id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
241,700
makinacorpus/tif2geojson
tif2geojson.py
_deep_value
def _deep_value(*args, **kwargs): """ Drills down into tree using the keys """ node, keys = args[0], args[1:] for key in keys: node = node.get(key, {}) default = kwargs.get('default', {}) if node in ({}, [], None): node = default return node
python
def _deep_value(*args, **kwargs): """ Drills down into tree using the keys """ node, keys = args[0], args[1:] for key in keys: node = node.get(key, {}) default = kwargs.get('default', {}) if node in ({}, [], None): node = default return node
[ "def", "_deep_value", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "node", ",", "keys", "=", "args", "[", "0", "]", ",", "args", "[", "1", ":", "]", "for", "key", "in", "keys", ":", "node", "=", "node", ".", "get", "(", "key", ",", ...
Drills down into tree using the keys
[ "Drills", "down", "into", "tree", "using", "the", "keys" ]
071b26cea6e23a3ec87a5cd1f73cc800612021b9
https://github.com/makinacorpus/tif2geojson/blob/071b26cea6e23a3ec87a5cd1f73cc800612021b9/tif2geojson.py#L162-L171
241,701
MacHu-GWU/angora-project
angora/dataIO/pk.py
load_pk
def load_pk(abspath, compress=False, enable_verbose=True): """Load Python Object from Pickle file. :param abspath: File path. Use absolute path as much as you can. File extension has to be ``.pickle`` or ``.gz``. (for compressed Pickle) :type abspath: string :param compress: (default False) Lo...
python
def load_pk(abspath, compress=False, enable_verbose=True): """Load Python Object from Pickle file. :param abspath: File path. Use absolute path as much as you can. File extension has to be ``.pickle`` or ``.gz``. (for compressed Pickle) :type abspath: string :param compress: (default False) Lo...
[ "def", "load_pk", "(", "abspath", ",", "compress", "=", "False", ",", "enable_verbose", "=", "True", ")", ":", "abspath", "=", "str", "(", "abspath", ")", "# try stringlize", "msg", "=", "Messenger", "(", "enable_verbose", "=", "enable_verbose", ")", "if", ...
Load Python Object from Pickle file. :param abspath: File path. Use absolute path as much as you can. File extension has to be ``.pickle`` or ``.gz``. (for compressed Pickle) :type abspath: string :param compress: (default False) Load from a gzip compressed Pickle file. Check :func:`dump_p...
[ "Load", "Python", "Object", "from", "Pickle", "file", "." ]
689a60da51cd88680ddbe26e28dbe81e6b01d275
https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/dataIO/pk.py#L73-L135
241,702
MacHu-GWU/angora-project
angora/dataIO/pk.py
dump_pk
def dump_pk(obj, abspath, pk_protocol=pk_protocol, replace=False, compress=False, enable_verbose=True): """Dump Picklable Python Object to file. Provides multiple choice to customize the behavior. :param obj: Picklable Python Object. :param abspath: ``save as`` path, file exten...
python
def dump_pk(obj, abspath, pk_protocol=pk_protocol, replace=False, compress=False, enable_verbose=True): """Dump Picklable Python Object to file. Provides multiple choice to customize the behavior. :param obj: Picklable Python Object. :param abspath: ``save as`` path, file exten...
[ "def", "dump_pk", "(", "obj", ",", "abspath", ",", "pk_protocol", "=", "pk_protocol", ",", "replace", "=", "False", ",", "compress", "=", "False", ",", "enable_verbose", "=", "True", ")", ":", "abspath", "=", "str", "(", "abspath", ")", "# try stringlize",...
Dump Picklable Python Object to file. Provides multiple choice to customize the behavior. :param obj: Picklable Python Object. :param abspath: ``save as`` path, file extension has to be ``.pickle`` or ``.gz`` (for compressed Pickle). :type abspath: string :param pk_protocol: (default your...
[ "Dump", "Picklable", "Python", "Object", "to", "file", ".", "Provides", "multiple", "choice", "to", "customize", "the", "behavior", "." ]
689a60da51cd88680ddbe26e28dbe81e6b01d275
https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/dataIO/pk.py#L138-L250
241,703
MacHu-GWU/angora-project
angora/dataIO/pk.py
safe_dump_pk
def safe_dump_pk(obj, abspath, pk_protocol=pk_protocol, compress=False, enable_verbose=True): """A stable version of dump_pk, silently overwrite existing file. When your program been interrupted, you lose nothing. Typically if your program is interrupted by any reason, it only leaves a inc...
python
def safe_dump_pk(obj, abspath, pk_protocol=pk_protocol, compress=False, enable_verbose=True): """A stable version of dump_pk, silently overwrite existing file. When your program been interrupted, you lose nothing. Typically if your program is interrupted by any reason, it only leaves a inc...
[ "def", "safe_dump_pk", "(", "obj", ",", "abspath", ",", "pk_protocol", "=", "pk_protocol", ",", "compress", "=", "False", ",", "enable_verbose", "=", "True", ")", ":", "abspath", "=", "str", "(", "abspath", ")", "# try stringlize", "temp_abspath", "=", "\"%s...
A stable version of dump_pk, silently overwrite existing file. When your program been interrupted, you lose nothing. Typically if your program is interrupted by any reason, it only leaves a incomplete file. If you use replace=True, then you also lose your old file. So a bettr way is to: 1. dump p...
[ "A", "stable", "version", "of", "dump_pk", "silently", "overwrite", "existing", "file", "." ]
689a60da51cd88680ddbe26e28dbe81e6b01d275
https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/dataIO/pk.py#L253-L326
241,704
MacHu-GWU/angora-project
angora/dataIO/pk.py
obj2str
def obj2str(obj, pk_protocol=pk_protocol): """Convert arbitrary object to utf-8 string, using base64encode algorithm. Usage:: >>> from weatherlab.lib.dataIO.pk import obj2str >>> data = {"a": 1, "b": 2} >>> obj2str(data, pk_protocol=2) 'gAJ9cQAoWAEAAABhcQFLAVgBAAAAYnECSwJ1L...
python
def obj2str(obj, pk_protocol=pk_protocol): """Convert arbitrary object to utf-8 string, using base64encode algorithm. Usage:: >>> from weatherlab.lib.dataIO.pk import obj2str >>> data = {"a": 1, "b": 2} >>> obj2str(data, pk_protocol=2) 'gAJ9cQAoWAEAAABhcQFLAVgBAAAAYnECSwJ1L...
[ "def", "obj2str", "(", "obj", ",", "pk_protocol", "=", "pk_protocol", ")", ":", "return", "base64", ".", "b64encode", "(", "pickle", ".", "dumps", "(", "obj", ",", "protocol", "=", "pk_protocol", ")", ")", ".", "decode", "(", "\"utf-8\"", ")" ]
Convert arbitrary object to utf-8 string, using base64encode algorithm. Usage:: >>> from weatherlab.lib.dataIO.pk import obj2str >>> data = {"a": 1, "b": 2} >>> obj2str(data, pk_protocol=2) 'gAJ9cQAoWAEAAABhcQFLAVgBAAAAYnECSwJ1Lg==' **中文文档** 将可Pickle化的Python对象转化为utf-8...
[ "Convert", "arbitrary", "object", "to", "utf", "-", "8", "string", "using", "base64encode", "algorithm", "." ]
689a60da51cd88680ddbe26e28dbe81e6b01d275
https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/dataIO/pk.py#L363-L379
241,705
MacHu-GWU/angora-project
angora/gadget/codestats.py
CodeStats.run
def run(self): """Run analysis. The basic idea is to recursively find all script files in specific programming language, and analyze each file then sum it up. """ n_target_file, n_other_file = 0, 0 code, comment, docstr, purecode = 0, 0, 0, 0 fc = FileCollecti...
python
def run(self): """Run analysis. The basic idea is to recursively find all script files in specific programming language, and analyze each file then sum it up. """ n_target_file, n_other_file = 0, 0 code, comment, docstr, purecode = 0, 0, 0, 0 fc = FileCollecti...
[ "def", "run", "(", "self", ")", ":", "n_target_file", ",", "n_other_file", "=", "0", ",", "0", "code", ",", "comment", ",", "docstr", ",", "purecode", "=", "0", ",", "0", ",", "0", ",", "0", "fc", "=", "FileCollection", ".", "from_path_except", "(", ...
Run analysis. The basic idea is to recursively find all script files in specific programming language, and analyze each file then sum it up.
[ "Run", "analysis", "." ]
689a60da51cd88680ddbe26e28dbe81e6b01d275
https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/gadget/codestats.py#L97-L137
241,706
MacHu-GWU/angora-project
angora/gadget/codestats.py
CodeStats.analyzePython
def analyzePython(code_text): """Count how many line of code, comment, dosstr, purecode in one Python script file. """ code, comment, docstr = 0, 0, 0 p1 = r"""(?<=%s)[\s\S]*?(?=%s)""" % ('"""', '"""') p2 = r"""(?<=%s)[\s\S]*?(?=%s)""" % ("'''", "'''") # count ...
python
def analyzePython(code_text): """Count how many line of code, comment, dosstr, purecode in one Python script file. """ code, comment, docstr = 0, 0, 0 p1 = r"""(?<=%s)[\s\S]*?(?=%s)""" % ('"""', '"""') p2 = r"""(?<=%s)[\s\S]*?(?=%s)""" % ("'''", "'''") # count ...
[ "def", "analyzePython", "(", "code_text", ")", ":", "code", ",", "comment", ",", "docstr", "=", "0", ",", "0", ",", "0", "p1", "=", "r\"\"\"(?<=%s)[\\s\\S]*?(?=%s)\"\"\"", "%", "(", "'\"\"\"'", ",", "'\"\"\"'", ")", "p2", "=", "r\"\"\"(?<=%s)[\\s\\S]*?(?=%s)\"...
Count how many line of code, comment, dosstr, purecode in one Python script file.
[ "Count", "how", "many", "line", "of", "code", "comment", "dosstr", "purecode", "in", "one", "Python", "script", "file", "." ]
689a60da51cd88680ddbe26e28dbe81e6b01d275
https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/gadget/codestats.py#L147-L170
241,707
JNRowe/jnrbase
jnrbase/cmdline.py
get_default
def get_default(__func: Callable, __arg: str) -> str: """Fetch default value for a function argument Args: __func: Function to inspect __arg: Argument to extract default value for """ return signature(__func).parameters[__arg].default
python
def get_default(__func: Callable, __arg: str) -> str: """Fetch default value for a function argument Args: __func: Function to inspect __arg: Argument to extract default value for """ return signature(__func).parameters[__arg].default
[ "def", "get_default", "(", "__func", ":", "Callable", ",", "__arg", ":", "str", ")", "->", "str", ":", "return", "signature", "(", "__func", ")", ".", "parameters", "[", "__arg", "]", ".", "default" ]
Fetch default value for a function argument Args: __func: Function to inspect __arg: Argument to extract default value for
[ "Fetch", "default", "value", "for", "a", "function", "argument" ]
ae505ef69a9feb739b5f4e62c5a8e6533104d3ea
https://github.com/JNRowe/jnrbase/blob/ae505ef69a9feb739b5f4e62c5a8e6533104d3ea/jnrbase/cmdline.py#L38-L45
241,708
JNRowe/jnrbase
jnrbase/cmdline.py
config_
def config_(name: str, local: bool, package: str, section: str, key: Optional[str]): """Extract or list values from config.""" cfg = config.read_configs(package, name, local=local) if key: with suppress(NoOptionError, NoSectionError): echo(cfg.get(section, key)) else: ...
python
def config_(name: str, local: bool, package: str, section: str, key: Optional[str]): """Extract or list values from config.""" cfg = config.read_configs(package, name, local=local) if key: with suppress(NoOptionError, NoSectionError): echo(cfg.get(section, key)) else: ...
[ "def", "config_", "(", "name", ":", "str", ",", "local", ":", "bool", ",", "package", ":", "str", ",", "section", ":", "str", ",", "key", ":", "Optional", "[", "str", "]", ")", ":", "cfg", "=", "config", ".", "read_configs", "(", "package", ",", ...
Extract or list values from config.
[ "Extract", "or", "list", "values", "from", "config", "." ]
ae505ef69a9feb739b5f4e62c5a8e6533104d3ea
https://github.com/JNRowe/jnrbase/blob/ae505ef69a9feb739b5f4e62c5a8e6533104d3ea/jnrbase/cmdline.py#L97-L108
241,709
JNRowe/jnrbase
jnrbase/cmdline.py
find_tag
def find_tag(match: str, strict: bool, directory: str): """Find tag for git repository.""" with suppress(CalledProcessError): echo(git.find_tag(match, strict=strict, git_dir=directory))
python
def find_tag(match: str, strict: bool, directory: str): """Find tag for git repository.""" with suppress(CalledProcessError): echo(git.find_tag(match, strict=strict, git_dir=directory))
[ "def", "find_tag", "(", "match", ":", "str", ",", "strict", ":", "bool", ",", "directory", ":", "str", ")", ":", "with", "suppress", "(", "CalledProcessError", ")", ":", "echo", "(", "git", ".", "find_tag", "(", "match", ",", "strict", "=", "strict", ...
Find tag for git repository.
[ "Find", "tag", "for", "git", "repository", "." ]
ae505ef69a9feb739b5f4e62c5a8e6533104d3ea
https://github.com/JNRowe/jnrbase/blob/ae505ef69a9feb739b5f4e62c5a8e6533104d3ea/jnrbase/cmdline.py#L117-L120
241,710
JNRowe/jnrbase
jnrbase/cmdline.py
pretty_time
def pretty_time(timestamp: str): """Format timestamp for human consumption.""" try: parsed = iso_8601.parse_datetime(timestamp) except ValueError: now = datetime.utcnow().replace(tzinfo=timezone.utc) try: delta = iso_8601.parse_delta(timestamp) except ValueError: ...
python
def pretty_time(timestamp: str): """Format timestamp for human consumption.""" try: parsed = iso_8601.parse_datetime(timestamp) except ValueError: now = datetime.utcnow().replace(tzinfo=timezone.utc) try: delta = iso_8601.parse_delta(timestamp) except ValueError: ...
[ "def", "pretty_time", "(", "timestamp", ":", "str", ")", ":", "try", ":", "parsed", "=", "iso_8601", ".", "parse_datetime", "(", "timestamp", ")", "except", "ValueError", ":", "now", "=", "datetime", ".", "utcnow", "(", ")", ".", "replace", "(", "tzinfo"...
Format timestamp for human consumption.
[ "Format", "timestamp", "for", "human", "consumption", "." ]
ae505ef69a9feb739b5f4e62c5a8e6533104d3ea
https://github.com/JNRowe/jnrbase/blob/ae505ef69a9feb739b5f4e62c5a8e6533104d3ea/jnrbase/cmdline.py#L131-L143
241,711
JNRowe/jnrbase
jnrbase/cmdline.py
gen_text
def gen_text(env: TextIOBase, package: str, tmpl: str): """Create output from Jinja template.""" if env: env_args = json_datetime.load(env) else: env_args = {} jinja_env = template.setup(package) echo(jinja_env.get_template(tmpl).render(**env_args))
python
def gen_text(env: TextIOBase, package: str, tmpl: str): """Create output from Jinja template.""" if env: env_args = json_datetime.load(env) else: env_args = {} jinja_env = template.setup(package) echo(jinja_env.get_template(tmpl).render(**env_args))
[ "def", "gen_text", "(", "env", ":", "TextIOBase", ",", "package", ":", "str", ",", "tmpl", ":", "str", ")", ":", "if", "env", ":", "env_args", "=", "json_datetime", ".", "load", "(", "env", ")", "else", ":", "env_args", "=", "{", "}", "jinja_env", ...
Create output from Jinja template.
[ "Create", "output", "from", "Jinja", "template", "." ]
ae505ef69a9feb739b5f4e62c5a8e6533104d3ea
https://github.com/JNRowe/jnrbase/blob/ae505ef69a9feb739b5f4e62c5a8e6533104d3ea/jnrbase/cmdline.py#L160-L167
241,712
JNRowe/jnrbase
jnrbase/cmdline.py
time
def time(ctx: Context, command: str): """Time the output of a command.""" with timer.Timing(verbose=True): proc = run(command, shell=True) ctx.exit(proc.returncode)
python
def time(ctx: Context, command: str): """Time the output of a command.""" with timer.Timing(verbose=True): proc = run(command, shell=True) ctx.exit(proc.returncode)
[ "def", "time", "(", "ctx", ":", "Context", ",", "command", ":", "str", ")", ":", "with", "timer", ".", "Timing", "(", "verbose", "=", "True", ")", ":", "proc", "=", "run", "(", "command", ",", "shell", "=", "True", ")", "ctx", ".", "exit", "(", ...
Time the output of a command.
[ "Time", "the", "output", "of", "a", "command", "." ]
ae505ef69a9feb739b5f4e62c5a8e6533104d3ea
https://github.com/JNRowe/jnrbase/blob/ae505ef69a9feb739b5f4e62c5a8e6533104d3ea/jnrbase/cmdline.py#L173-L177
241,713
zerok/zs.bibtex
src/zs/bibtex/structures.py
TypeRegistry.register
def register(cls, name, type_): """ Register a new type for an entry-type. The 2nd argument has to be a subclass of structures.Entry. """ if not issubclass(type_, Entry): raise exceptions.InvalidEntryType("%s is not a subclass of Entry" % str(type_)) cls._reg...
python
def register(cls, name, type_): """ Register a new type for an entry-type. The 2nd argument has to be a subclass of structures.Entry. """ if not issubclass(type_, Entry): raise exceptions.InvalidEntryType("%s is not a subclass of Entry" % str(type_)) cls._reg...
[ "def", "register", "(", "cls", ",", "name", ",", "type_", ")", ":", "if", "not", "issubclass", "(", "type_", ",", "Entry", ")", ":", "raise", "exceptions", ".", "InvalidEntryType", "(", "\"%s is not a subclass of Entry\"", "%", "str", "(", "type_", ")", ")...
Register a new type for an entry-type. The 2nd argument has to be a subclass of structures.Entry.
[ "Register", "a", "new", "type", "for", "an", "entry", "-", "type", ".", "The", "2nd", "argument", "has", "to", "be", "a", "subclass", "of", "structures", ".", "Entry", "." ]
ac9594b36b9d4ec9a3593c0dc7c1a35e5aea04d9
https://github.com/zerok/zs.bibtex/blob/ac9594b36b9d4ec9a3593c0dc7c1a35e5aea04d9/src/zs/bibtex/structures.py#L51-L59
241,714
zerok/zs.bibtex
src/zs/bibtex/structures.py
Bibliography.validate
def validate(self, **kwargs): """ Validates each entry (passing the provided arguments down to them and also tries to resolve all cross-references between the entries. """ self.check_crossrefs() for value in self.values(): value.validate(**kwargs)
python
def validate(self, **kwargs): """ Validates each entry (passing the provided arguments down to them and also tries to resolve all cross-references between the entries. """ self.check_crossrefs() for value in self.values(): value.validate(**kwargs)
[ "def", "validate", "(", "self", ",", "*", "*", "kwargs", ")", ":", "self", ".", "check_crossrefs", "(", ")", "for", "value", "in", "self", ".", "values", "(", ")", ":", "value", ".", "validate", "(", "*", "*", "kwargs", ")" ]
Validates each entry (passing the provided arguments down to them and also tries to resolve all cross-references between the entries.
[ "Validates", "each", "entry", "(", "passing", "the", "provided", "arguments", "down", "to", "them", "and", "also", "tries", "to", "resolve", "all", "cross", "-", "references", "between", "the", "entries", "." ]
ac9594b36b9d4ec9a3593c0dc7c1a35e5aea04d9
https://github.com/zerok/zs.bibtex/blob/ac9594b36b9d4ec9a3593c0dc7c1a35e5aea04d9/src/zs/bibtex/structures.py#L79-L86
241,715
zerok/zs.bibtex
src/zs/bibtex/structures.py
Entry.validate
def validate(self, raise_unsupported=False): """ Checks if the Entry instance includes all the required fields of its type. If ``raise_unsupported`` is set to ``True`` it will also check for potentially unsupported types. If a problem is found, an InvalidStructure exception is r...
python
def validate(self, raise_unsupported=False): """ Checks if the Entry instance includes all the required fields of its type. If ``raise_unsupported`` is set to ``True`` it will also check for potentially unsupported types. If a problem is found, an InvalidStructure exception is r...
[ "def", "validate", "(", "self", ",", "raise_unsupported", "=", "False", ")", ":", "fields", "=", "set", "(", "self", ".", "keys", "(", ")", ")", "flattened_required_fields", "=", "set", "(", ")", "required_errors", "=", "[", "]", "for", "field", "in", ...
Checks if the Entry instance includes all the required fields of its type. If ``raise_unsupported`` is set to ``True`` it will also check for potentially unsupported types. If a problem is found, an InvalidStructure exception is raised.
[ "Checks", "if", "the", "Entry", "instance", "includes", "all", "the", "required", "fields", "of", "its", "type", ".", "If", "raise_unsupported", "is", "set", "to", "True", "it", "will", "also", "check", "for", "potentially", "unsupported", "types", "." ]
ac9594b36b9d4ec9a3593c0dc7c1a35e5aea04d9
https://github.com/zerok/zs.bibtex/blob/ac9594b36b9d4ec9a3593c0dc7c1a35e5aea04d9/src/zs/bibtex/structures.py#L125-L156
241,716
nsavch/python-xonotic-db
xon_db/cli.py
get
def get(file_name, key): """ Print a value for the specified key. If key is not found xon_db exists with code 1. """ db = XonoticDB.load_path(file_name) value = db.get(key) if value is None: sys.exit(1) else: click.echo(value)
python
def get(file_name, key): """ Print a value for the specified key. If key is not found xon_db exists with code 1. """ db = XonoticDB.load_path(file_name) value = db.get(key) if value is None: sys.exit(1) else: click.echo(value)
[ "def", "get", "(", "file_name", ",", "key", ")", ":", "db", "=", "XonoticDB", ".", "load_path", "(", "file_name", ")", "value", "=", "db", ".", "get", "(", "key", ")", "if", "value", "is", "None", ":", "sys", ".", "exit", "(", "1", ")", "else", ...
Print a value for the specified key. If key is not found xon_db exists with code 1.
[ "Print", "a", "value", "for", "the", "specified", "key", ".", "If", "key", "is", "not", "found", "xon_db", "exists", "with", "code", "1", "." ]
339fe4c2c74880fd66712ae32789d7e9ae3e8f02
https://github.com/nsavch/python-xonotic-db/blob/339fe4c2c74880fd66712ae32789d7e9ae3e8f02/xon_db/cli.py#L31-L40
241,717
nsavch/python-xonotic-db
xon_db/cli.py
set
def set(file_name, key, value, new): """ Set a new value for the specified key. """ db = XonoticDB.load_path(file_name) if key not in db and not new: click.echo('Key %s is not found in the database' % key, file=sys.stderr) sys.exit(1) else: db[key] = value db.save...
python
def set(file_name, key, value, new): """ Set a new value for the specified key. """ db = XonoticDB.load_path(file_name) if key not in db and not new: click.echo('Key %s is not found in the database' % key, file=sys.stderr) sys.exit(1) else: db[key] = value db.save...
[ "def", "set", "(", "file_name", ",", "key", ",", "value", ",", "new", ")", ":", "db", "=", "XonoticDB", ".", "load_path", "(", "file_name", ")", "if", "key", "not", "in", "db", "and", "not", "new", ":", "click", ".", "echo", "(", "'Key %s is not foun...
Set a new value for the specified key.
[ "Set", "a", "new", "value", "for", "the", "specified", "key", "." ]
339fe4c2c74880fd66712ae32789d7e9ae3e8f02
https://github.com/nsavch/python-xonotic-db/blob/339fe4c2c74880fd66712ae32789d7e9ae3e8f02/xon_db/cli.py#L48-L58
241,718
nsavch/python-xonotic-db
xon_db/cli.py
remove_cts_record
def remove_cts_record(file_name, map, position): """ Remove cts record on MAP and POSITION """ db = XonoticDB.load_path(file_name) db.remove_cts_record(map, position) db.save(file_name)
python
def remove_cts_record(file_name, map, position): """ Remove cts record on MAP and POSITION """ db = XonoticDB.load_path(file_name) db.remove_cts_record(map, position) db.save(file_name)
[ "def", "remove_cts_record", "(", "file_name", ",", "map", ",", "position", ")", ":", "db", "=", "XonoticDB", ".", "load_path", "(", "file_name", ")", "db", ".", "remove_cts_record", "(", "map", ",", "position", ")", "db", ".", "save", "(", "file_name", "...
Remove cts record on MAP and POSITION
[ "Remove", "cts", "record", "on", "MAP", "and", "POSITION" ]
339fe4c2c74880fd66712ae32789d7e9ae3e8f02
https://github.com/nsavch/python-xonotic-db/blob/339fe4c2c74880fd66712ae32789d7e9ae3e8f02/xon_db/cli.py#L65-L71
241,719
nsavch/python-xonotic-db
xon_db/cli.py
remove_all_cts_records_by
def remove_all_cts_records_by(file_name, crypto_idfp): """ Remove all cts records set by player with CRYPTO_IDFP """ db = XonoticDB.load_path(file_name) db.remove_all_cts_records_by(crypto_idfp) db.save(file_name)
python
def remove_all_cts_records_by(file_name, crypto_idfp): """ Remove all cts records set by player with CRYPTO_IDFP """ db = XonoticDB.load_path(file_name) db.remove_all_cts_records_by(crypto_idfp) db.save(file_name)
[ "def", "remove_all_cts_records_by", "(", "file_name", ",", "crypto_idfp", ")", ":", "db", "=", "XonoticDB", ".", "load_path", "(", "file_name", ")", "db", ".", "remove_all_cts_records_by", "(", "crypto_idfp", ")", "db", ".", "save", "(", "file_name", ")" ]
Remove all cts records set by player with CRYPTO_IDFP
[ "Remove", "all", "cts", "records", "set", "by", "player", "with", "CRYPTO_IDFP" ]
339fe4c2c74880fd66712ae32789d7e9ae3e8f02
https://github.com/nsavch/python-xonotic-db/blob/339fe4c2c74880fd66712ae32789d7e9ae3e8f02/xon_db/cli.py#L77-L83
241,720
nsavch/python-xonotic-db
xon_db/cli.py
merge_cts_records
def merge_cts_records(file_name, crypto_idfp, crypto_idfps): """ Merge cts records made by CRYPTO_IDFPS to CRYPTO_IDFP """ db = XonoticDB.load_path(file_name) db.merge_cts_records(crypto_idfp, crypto_idfps) db.save(file_name)
python
def merge_cts_records(file_name, crypto_idfp, crypto_idfps): """ Merge cts records made by CRYPTO_IDFPS to CRYPTO_IDFP """ db = XonoticDB.load_path(file_name) db.merge_cts_records(crypto_idfp, crypto_idfps) db.save(file_name)
[ "def", "merge_cts_records", "(", "file_name", ",", "crypto_idfp", ",", "crypto_idfps", ")", ":", "db", "=", "XonoticDB", ".", "load_path", "(", "file_name", ")", "db", ".", "merge_cts_records", "(", "crypto_idfp", ",", "crypto_idfps", ")", "db", ".", "save", ...
Merge cts records made by CRYPTO_IDFPS to CRYPTO_IDFP
[ "Merge", "cts", "records", "made", "by", "CRYPTO_IDFPS", "to", "CRYPTO_IDFP" ]
339fe4c2c74880fd66712ae32789d7e9ae3e8f02
https://github.com/nsavch/python-xonotic-db/blob/339fe4c2c74880fd66712ae32789d7e9ae3e8f02/xon_db/cli.py#L90-L96
241,721
Arvedui/picuplib
picuplib/checks.py
check_rotation
def check_rotation(rotation): """checks rotation parameter if illegal value raises exception""" if rotation not in ALLOWED_ROTATION: allowed_rotation = ', '.join(ALLOWED_ROTATION) raise UnsupportedRotation('Rotation %s is not allwoed. Allowed are %s' % (rotatio...
python
def check_rotation(rotation): """checks rotation parameter if illegal value raises exception""" if rotation not in ALLOWED_ROTATION: allowed_rotation = ', '.join(ALLOWED_ROTATION) raise UnsupportedRotation('Rotation %s is not allwoed. Allowed are %s' % (rotatio...
[ "def", "check_rotation", "(", "rotation", ")", ":", "if", "rotation", "not", "in", "ALLOWED_ROTATION", ":", "allowed_rotation", "=", "', '", ".", "join", "(", "ALLOWED_ROTATION", ")", "raise", "UnsupportedRotation", "(", "'Rotation %s is not allwoed. Allowed are %s'", ...
checks rotation parameter if illegal value raises exception
[ "checks", "rotation", "parameter", "if", "illegal", "value", "raises", "exception" ]
c8a5d1542dbd421e84afd5ee81fe76efec89fb95
https://github.com/Arvedui/picuplib/blob/c8a5d1542dbd421e84afd5ee81fe76efec89fb95/picuplib/checks.py#L31-L37
241,722
Arvedui/picuplib
picuplib/checks.py
check_resize
def check_resize(resize): """checks resize parameter if illegal value raises exception""" if resize is None: return resize = resize.lower().strip() if 'x' in resize: tmp = resize.lower().split('x') tmp = [x.strip() for x in resize.split('x')] if len(tmp) == 2 and tmp[0]...
python
def check_resize(resize): """checks resize parameter if illegal value raises exception""" if resize is None: return resize = resize.lower().strip() if 'x' in resize: tmp = resize.lower().split('x') tmp = [x.strip() for x in resize.split('x')] if len(tmp) == 2 and tmp[0]...
[ "def", "check_resize", "(", "resize", ")", ":", "if", "resize", "is", "None", ":", "return", "resize", "=", "resize", ".", "lower", "(", ")", ".", "strip", "(", ")", "if", "'x'", "in", "resize", ":", "tmp", "=", "resize", ".", "lower", "(", ")", ...
checks resize parameter if illegal value raises exception
[ "checks", "resize", "parameter", "if", "illegal", "value", "raises", "exception" ]
c8a5d1542dbd421e84afd5ee81fe76efec89fb95
https://github.com/Arvedui/picuplib/blob/c8a5d1542dbd421e84afd5ee81fe76efec89fb95/picuplib/checks.py#L40-L62
241,723
Arvedui/picuplib
picuplib/checks.py
check_response
def check_response(response): """ checks the response if the server returned an error raises an exception. """ if response.status_code < 200 or response.status_code > 300: raise ServerError('API requests returned with error: %s' % response.status_code) try: ...
python
def check_response(response): """ checks the response if the server returned an error raises an exception. """ if response.status_code < 200 or response.status_code > 300: raise ServerError('API requests returned with error: %s' % response.status_code) try: ...
[ "def", "check_response", "(", "response", ")", ":", "if", "response", ".", "status_code", "<", "200", "or", "response", ".", "status_code", ">", "300", ":", "raise", "ServerError", "(", "'API requests returned with error: %s'", "%", "response", ".", "status_code",...
checks the response if the server returned an error raises an exception.
[ "checks", "the", "response", "if", "the", "server", "returned", "an", "error", "raises", "an", "exception", "." ]
c8a5d1542dbd421e84afd5ee81fe76efec89fb95
https://github.com/Arvedui/picuplib/blob/c8a5d1542dbd421e84afd5ee81fe76efec89fb95/picuplib/checks.py#L77-L98
241,724
Arvedui/picuplib
picuplib/checks.py
check_if_redirect
def check_if_redirect(url): """ checks if server redirects url """ response = head(url, headers={'User-Agent': USER_AGENT}) if response.status_code >= 300 and response.status_code < 400: return response.headers['location'] return None
python
def check_if_redirect(url): """ checks if server redirects url """ response = head(url, headers={'User-Agent': USER_AGENT}) if response.status_code >= 300 and response.status_code < 400: return response.headers['location'] return None
[ "def", "check_if_redirect", "(", "url", ")", ":", "response", "=", "head", "(", "url", ",", "headers", "=", "{", "'User-Agent'", ":", "USER_AGENT", "}", ")", "if", "response", ".", "status_code", ">=", "300", "and", "response", ".", "status_code", "<", "...
checks if server redirects url
[ "checks", "if", "server", "redirects", "url" ]
c8a5d1542dbd421e84afd5ee81fe76efec89fb95
https://github.com/Arvedui/picuplib/blob/c8a5d1542dbd421e84afd5ee81fe76efec89fb95/picuplib/checks.py#L101-L109
241,725
deviantony/valigator
valigator/scheduler.py
validate_backup
def validate_backup(configuration, backup_data): """Celery task. It will extract the backup archive into a unique folder in the temporary directory specified in the configuration. Once extracted, a Docker container will be started and will start a restoration procedure. The worker will wait for the...
python
def validate_backup(configuration, backup_data): """Celery task. It will extract the backup archive into a unique folder in the temporary directory specified in the configuration. Once extracted, a Docker container will be started and will start a restoration procedure. The worker will wait for the...
[ "def", "validate_backup", "(", "configuration", ",", "backup_data", ")", ":", "extract_archive", "(", "backup_data", "[", "'archive_path'", "]", ",", "backup_data", "[", "'workdir'", "]", ")", "docker_client", "=", "Client", "(", "configuration", "[", "'docker'", ...
Celery task. It will extract the backup archive into a unique folder in the temporary directory specified in the configuration. Once extracted, a Docker container will be started and will start a restoration procedure. The worker will wait for the container to exit and retrieve its return code. ...
[ "Celery", "task", ".", "It", "will", "extract", "the", "backup", "archive", "into", "a", "unique", "folder", "in", "the", "temporary", "directory", "specified", "in", "the", "configuration", "." ]
0557029bc58ea1270e358c14ca382d3807ed5b6f
https://github.com/deviantony/valigator/blob/0557029bc58ea1270e358c14ca382d3807ed5b6f/valigator/scheduler.py#L11-L38
241,726
codecobblers/modified
modified.py
module_files
def module_files(module, dependencies_dict=None): """ Scan a module and its entire dependency tree to create a dict of all files and their modified time. @param module: A <module> object @param dependencies_dict: Pass an existing dict to add only unscanned files or None to create a new file...
python
def module_files(module, dependencies_dict=None): """ Scan a module and its entire dependency tree to create a dict of all files and their modified time. @param module: A <module> object @param dependencies_dict: Pass an existing dict to add only unscanned files or None to create a new file...
[ "def", "module_files", "(", "module", ",", "dependencies_dict", "=", "None", ")", ":", "if", "dependencies_dict", "is", "None", ":", "dependencies_dict", "=", "dict", "(", ")", "if", "hasattr", "(", "module", ",", "'__file__'", ")", ":", "filename", "=", "...
Scan a module and its entire dependency tree to create a dict of all files and their modified time. @param module: A <module> object @param dependencies_dict: Pass an existing dict to add only unscanned files or None to create a new file dict @return: A dict containing filenames as keys with th...
[ "Scan", "a", "module", "and", "its", "entire", "dependency", "tree", "to", "create", "a", "dict", "of", "all", "files", "and", "their", "modified", "time", "." ]
1cca9337d4de44fa660d1601ed43b71e00d8b6f5
https://github.com/codecobblers/modified/blob/1cca9337d4de44fa660d1601ed43b71e00d8b6f5/modified.py#L82-L112
241,727
codecobblers/modified
modified.py
files
def files(): """ Scan all modules in the currently running app to create a dict of all files and their modified time. @note The scan only occurs the first time this function is called. Subsequent calls simply return the global dict. @return: A dict containing filenames as keys with their m...
python
def files(): """ Scan all modules in the currently running app to create a dict of all files and their modified time. @note The scan only occurs the first time this function is called. Subsequent calls simply return the global dict. @return: A dict containing filenames as keys with their m...
[ "def", "files", "(", ")", ":", "if", "not", "_scanned", ":", "if", "not", "module_files", "(", "sys", ".", "modules", "[", "'__main__'", "]", ",", "_process_files", ")", ":", "for", "module", "in", "sys", ".", "modules", ".", "values", "(", ")", ":",...
Scan all modules in the currently running app to create a dict of all files and their modified time. @note The scan only occurs the first time this function is called. Subsequent calls simply return the global dict. @return: A dict containing filenames as keys with their modified time as v...
[ "Scan", "all", "modules", "in", "the", "currently", "running", "app", "to", "create", "a", "dict", "of", "all", "files", "and", "their", "modified", "time", "." ]
1cca9337d4de44fa660d1601ed43b71e00d8b6f5
https://github.com/codecobblers/modified/blob/1cca9337d4de44fa660d1601ed43b71e00d8b6f5/modified.py#L115-L135
241,728
codecobblers/modified
modified.py
hup_hook
def hup_hook(signal_or_callable=signal.SIGTERM, verbose=False): """ Register a signal handler for `signal.SIGHUP` that checks for modified files and only acts if at least one modified file is found. @type signal_or_callable: str, int or callable @param signal_or_callable: You can pass either a sign...
python
def hup_hook(signal_or_callable=signal.SIGTERM, verbose=False): """ Register a signal handler for `signal.SIGHUP` that checks for modified files and only acts if at least one modified file is found. @type signal_or_callable: str, int or callable @param signal_or_callable: You can pass either a sign...
[ "def", "hup_hook", "(", "signal_or_callable", "=", "signal", ".", "SIGTERM", ",", "verbose", "=", "False", ")", ":", "#noinspection PyUnusedLocal", "def", "handle_hup", "(", "signum", ",", "frame", ")", ":", "changed", "=", "modified", "(", ")", "if", "chang...
Register a signal handler for `signal.SIGHUP` that checks for modified files and only acts if at least one modified file is found. @type signal_or_callable: str, int or callable @param signal_or_callable: You can pass either a signal or a callable. The signal can be specified by name or number. If ...
[ "Register", "a", "signal", "handler", "for", "signal", ".", "SIGHUP", "that", "checks", "for", "modified", "files", "and", "only", "acts", "if", "at", "least", "one", "modified", "file", "is", "found", "." ]
1cca9337d4de44fa660d1601ed43b71e00d8b6f5
https://github.com/codecobblers/modified/blob/1cca9337d4de44fa660d1601ed43b71e00d8b6f5/modified.py#L167-L225
241,729
salimm/msgpack-pystream
msgpackstream/backend/python/stream.py
StreamUnpacker.handle_segment_ended
def handle_segment_ended(self): ''' process end of the segment based on template ''' if self._state[1].value.endevent is not None: self.events.append((self._state[1].value.endevent, self._state[0], None)) if self._state[1].value.multiplier is 2: self.p...
python
def handle_segment_ended(self): ''' process end of the segment based on template ''' if self._state[1].value.endevent is not None: self.events.append((self._state[1].value.endevent, self._state[0], None)) if self._state[1].value.multiplier is 2: self.p...
[ "def", "handle_segment_ended", "(", "self", ")", ":", "if", "self", ".", "_state", "[", "1", "]", ".", "value", ".", "endevent", "is", "not", "None", ":", "self", ".", "events", ".", "append", "(", "(", "self", ".", "_state", "[", "1", "]", ".", ...
process end of the segment based on template
[ "process", "end", "of", "the", "segment", "based", "on", "template" ]
676158a5a8dd8ff56dca080d597943f67fc4325e
https://github.com/salimm/msgpack-pystream/blob/676158a5a8dd8ff56dca080d597943f67fc4325e/msgpackstream/backend/python/stream.py#L267-L292
241,730
davidmiller/letter
letter/__main__.py
main
def main(): """ Do the things! Return: 0 Exceptions: """ description = 'Letter - a commandline interface' parser = argparse.ArgumentParser(description=description) parser.add_argument('--gmail', action='store_true', help='Send via Gmail', ) args = parser.parse_args() to ...
python
def main(): """ Do the things! Return: 0 Exceptions: """ description = 'Letter - a commandline interface' parser = argparse.ArgumentParser(description=description) parser.add_argument('--gmail', action='store_true', help='Send via Gmail', ) args = parser.parse_args() to ...
[ "def", "main", "(", ")", ":", "description", "=", "'Letter - a commandline interface'", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "description", ")", "parser", ".", "add_argument", "(", "'--gmail'", ",", "action", "=", "'store_true...
Do the things! Return: 0 Exceptions:
[ "Do", "the", "things!" ]
c0c66ae2c6a792106e9a8374a01421817c8a8ae0
https://github.com/davidmiller/letter/blob/c0c66ae2c6a792106e9a8374a01421817c8a8ae0/letter/__main__.py#L10-L44
241,731
langloisjp/pysvclog
servicelog.py
UDPLogger.send
def send(self, jsonstr): """ Send jsonstr to the UDP collector >>> logger = UDPLogger() >>> logger.send('{"key": "value"}') """ udp_sock = socket(AF_INET, SOCK_DGRAM) udp_sock.sendto(jsonstr.encode('utf-8'), self.addr)
python
def send(self, jsonstr): """ Send jsonstr to the UDP collector >>> logger = UDPLogger() >>> logger.send('{"key": "value"}') """ udp_sock = socket(AF_INET, SOCK_DGRAM) udp_sock.sendto(jsonstr.encode('utf-8'), self.addr)
[ "def", "send", "(", "self", ",", "jsonstr", ")", ":", "udp_sock", "=", "socket", "(", "AF_INET", ",", "SOCK_DGRAM", ")", "udp_sock", ".", "sendto", "(", "jsonstr", ".", "encode", "(", "'utf-8'", ")", ",", "self", ".", "addr", ")" ]
Send jsonstr to the UDP collector >>> logger = UDPLogger() >>> logger.send('{"key": "value"}')
[ "Send", "jsonstr", "to", "the", "UDP", "collector" ]
ab429bb12e13dca63ffce082e633d8879b6e3854
https://github.com/langloisjp/pysvclog/blob/ab429bb12e13dca63ffce082e633d8879b6e3854/servicelog.py#L66-L74
241,732
NegativeMjark/mockingmirror
setup.py
read_file
def read_file(path): """Read a UTF-8 file from the package. Takes a list of strings to join to make the path""" file_path = os.path.join(here, *path) with open(file_path, encoding="utf-8") as f: return f.read()
python
def read_file(path): """Read a UTF-8 file from the package. Takes a list of strings to join to make the path""" file_path = os.path.join(here, *path) with open(file_path, encoding="utf-8") as f: return f.read()
[ "def", "read_file", "(", "path", ")", ":", "file_path", "=", "os", ".", "path", ".", "join", "(", "here", ",", "*", "path", ")", "with", "open", "(", "file_path", ",", "encoding", "=", "\"utf-8\"", ")", "as", "f", ":", "return", "f", ".", "read", ...
Read a UTF-8 file from the package. Takes a list of strings to join to make the path
[ "Read", "a", "UTF", "-", "8", "file", "from", "the", "package", ".", "Takes", "a", "list", "of", "strings", "to", "join", "to", "make", "the", "path" ]
75cf7d56ab18922394db89725ae9b37f1d4b3711
https://github.com/NegativeMjark/mockingmirror/blob/75cf7d56ab18922394db89725ae9b37f1d4b3711/setup.py#L8-L13
241,733
NegativeMjark/mockingmirror
setup.py
exec_file
def exec_file(path, name): """Extract a constant from a python file by looking for a line defining the constant and executing it.""" result = {} code = read_file(path) lines = [line for line in code.split('\n') if line.startswith(name)] exec("\n".join(lines), result) return result[name]
python
def exec_file(path, name): """Extract a constant from a python file by looking for a line defining the constant and executing it.""" result = {} code = read_file(path) lines = [line for line in code.split('\n') if line.startswith(name)] exec("\n".join(lines), result) return result[name]
[ "def", "exec_file", "(", "path", ",", "name", ")", ":", "result", "=", "{", "}", "code", "=", "read_file", "(", "path", ")", "lines", "=", "[", "line", "for", "line", "in", "code", ".", "split", "(", "'\\n'", ")", "if", "line", ".", "startswith", ...
Extract a constant from a python file by looking for a line defining the constant and executing it.
[ "Extract", "a", "constant", "from", "a", "python", "file", "by", "looking", "for", "a", "line", "defining", "the", "constant", "and", "executing", "it", "." ]
75cf7d56ab18922394db89725ae9b37f1d4b3711
https://github.com/NegativeMjark/mockingmirror/blob/75cf7d56ab18922394db89725ae9b37f1d4b3711/setup.py#L16-L23
241,734
GreenBankObservatory/django-resetdb
django_resetdb/dbops.py
pg_dump
def pg_dump(db_name, backup_path): """Dump db_name to backup_path""" logger.info("Dumping %s to %s", repr(db_name), repr(backup_path)) return shell( 'pg_dump "{db_name}" -U "{USER}" -h "{HOST}" ' "--schema=public --file={backup_path}".format( db_name=db_name, backup_path=backup_...
python
def pg_dump(db_name, backup_path): """Dump db_name to backup_path""" logger.info("Dumping %s to %s", repr(db_name), repr(backup_path)) return shell( 'pg_dump "{db_name}" -U "{USER}" -h "{HOST}" ' "--schema=public --file={backup_path}".format( db_name=db_name, backup_path=backup_...
[ "def", "pg_dump", "(", "db_name", ",", "backup_path", ")", ":", "logger", ".", "info", "(", "\"Dumping %s to %s\"", ",", "repr", "(", "db_name", ")", ",", "repr", "(", "backup_path", ")", ")", "return", "shell", "(", "'pg_dump \"{db_name}\" -U \"{USER}\" -h \"{H...
Dump db_name to backup_path
[ "Dump", "db_name", "to", "backup_path" ]
767bddacb53823bb003e2abebfe8139a14b843f7
https://github.com/GreenBankObservatory/django-resetdb/blob/767bddacb53823bb003e2abebfe8139a14b843f7/django_resetdb/dbops.py#L50-L59
241,735
mrstephenneal/dirutility
dirutility/backup.py
ZipBackup._resolve_file_name
def _resolve_file_name(source, destination): """Create a filename for the destination zip file.""" number = 1 if os.path.exists(os.path.join(destination, os.path.basename(source) + '.zip')): while True: zip_filename = os.path.join(destination, os.path.basename(source)...
python
def _resolve_file_name(source, destination): """Create a filename for the destination zip file.""" number = 1 if os.path.exists(os.path.join(destination, os.path.basename(source) + '.zip')): while True: zip_filename = os.path.join(destination, os.path.basename(source)...
[ "def", "_resolve_file_name", "(", "source", ",", "destination", ")", ":", "number", "=", "1", "if", "os", ".", "path", ".", "exists", "(", "os", ".", "path", ".", "join", "(", "destination", ",", "os", ".", "path", ".", "basename", "(", "source", ")"...
Create a filename for the destination zip file.
[ "Create", "a", "filename", "for", "the", "destination", "zip", "file", "." ]
339378659e2d7e09c53acfc51c5df745bb0cd517
https://github.com/mrstephenneal/dirutility/blob/339378659e2d7e09c53acfc51c5df745bb0cd517/dirutility/backup.py#L38-L49
241,736
mrstephenneal/dirutility
dirutility/backup.py
ZipBackup._backup_compresslevel
def _backup_compresslevel(self, dirs): """Create a backup file with a compresslevel parameter.""" # Only supported in Python 3.7+ with ZipFile(self.zip_filename, 'w', compresslevel=self.compress_level) as backup_zip: for path in tqdm(dirs, desc='Writing Zip Files', total=len(dirs)): ...
python
def _backup_compresslevel(self, dirs): """Create a backup file with a compresslevel parameter.""" # Only supported in Python 3.7+ with ZipFile(self.zip_filename, 'w', compresslevel=self.compress_level) as backup_zip: for path in tqdm(dirs, desc='Writing Zip Files', total=len(dirs)): ...
[ "def", "_backup_compresslevel", "(", "self", ",", "dirs", ")", ":", "# Only supported in Python 3.7+", "with", "ZipFile", "(", "self", ".", "zip_filename", ",", "'w'", ",", "compresslevel", "=", "self", ".", "compress_level", ")", "as", "backup_zip", ":", "for",...
Create a backup file with a compresslevel parameter.
[ "Create", "a", "backup", "file", "with", "a", "compresslevel", "parameter", "." ]
339378659e2d7e09c53acfc51c5df745bb0cd517
https://github.com/mrstephenneal/dirutility/blob/339378659e2d7e09c53acfc51c5df745bb0cd517/dirutility/backup.py#L72-L77
241,737
mrstephenneal/dirutility
dirutility/backup.py
ZipBackup._backup_pb_gui
def _backup_pb_gui(self, dirs): """Create a zip backup with a GUI progress bar.""" import PySimpleGUI as sg # Legacy support with ZipFile(self.zip_filename, 'w') as backup_zip: for count, path in enumerate(dirs): backup_zip.write(path, path[len(self.source):le...
python
def _backup_pb_gui(self, dirs): """Create a zip backup with a GUI progress bar.""" import PySimpleGUI as sg # Legacy support with ZipFile(self.zip_filename, 'w') as backup_zip: for count, path in enumerate(dirs): backup_zip.write(path, path[len(self.source):le...
[ "def", "_backup_pb_gui", "(", "self", ",", "dirs", ")", ":", "import", "PySimpleGUI", "as", "sg", "# Legacy support", "with", "ZipFile", "(", "self", ".", "zip_filename", ",", "'w'", ")", "as", "backup_zip", ":", "for", "count", ",", "path", "in", "enumera...
Create a zip backup with a GUI progress bar.
[ "Create", "a", "zip", "backup", "with", "a", "GUI", "progress", "bar", "." ]
339378659e2d7e09c53acfc51c5df745bb0cd517
https://github.com/mrstephenneal/dirutility/blob/339378659e2d7e09c53acfc51c5df745bb0cd517/dirutility/backup.py#L79-L87
241,738
mrstephenneal/dirutility
dirutility/backup.py
ZipBackup._backup_pb_tqdm
def _backup_pb_tqdm(self, dirs): """Create a backup with a tqdm progress bar.""" with ZipFile(self.zip_filename, 'w') as backup_zip: for path in tqdm(dirs, desc='Writing Zip Files', total=len(dirs)): backup_zip.write(path, path[len(self.source):len(path)])
python
def _backup_pb_tqdm(self, dirs): """Create a backup with a tqdm progress bar.""" with ZipFile(self.zip_filename, 'w') as backup_zip: for path in tqdm(dirs, desc='Writing Zip Files', total=len(dirs)): backup_zip.write(path, path[len(self.source):len(path)])
[ "def", "_backup_pb_tqdm", "(", "self", ",", "dirs", ")", ":", "with", "ZipFile", "(", "self", ".", "zip_filename", ",", "'w'", ")", "as", "backup_zip", ":", "for", "path", "in", "tqdm", "(", "dirs", ",", "desc", "=", "'Writing Zip Files'", ",", "total", ...
Create a backup with a tqdm progress bar.
[ "Create", "a", "backup", "with", "a", "tqdm", "progress", "bar", "." ]
339378659e2d7e09c53acfc51c5df745bb0cd517
https://github.com/mrstephenneal/dirutility/blob/339378659e2d7e09c53acfc51c5df745bb0cd517/dirutility/backup.py#L89-L93
241,739
mrstephenneal/dirutility
dirutility/backup.py
ZipBackup.backup
def backup(self, paths=None): """Backup method driver.""" if not paths: paths = self._get_paths() try: self._backup_compresslevel(paths) except TypeError: try: self._backup_pb_gui(paths) except ImportError: ...
python
def backup(self, paths=None): """Backup method driver.""" if not paths: paths = self._get_paths() try: self._backup_compresslevel(paths) except TypeError: try: self._backup_pb_gui(paths) except ImportError: ...
[ "def", "backup", "(", "self", ",", "paths", "=", "None", ")", ":", "if", "not", "paths", ":", "paths", "=", "self", ".", "_get_paths", "(", ")", "try", ":", "self", ".", "_backup_compresslevel", "(", "paths", ")", "except", "TypeError", ":", "try", "...
Backup method driver.
[ "Backup", "method", "driver", "." ]
339378659e2d7e09c53acfc51c5df745bb0cd517
https://github.com/mrstephenneal/dirutility/blob/339378659e2d7e09c53acfc51c5df745bb0cd517/dirutility/backup.py#L95-L111
241,740
50onRed/smr
smr/uri.py
get_uris
def get_uris(config): """ returns a tuple of total file size in bytes, and the list of files """ file_names = [] if config.INPUT_DATA is None: sys.stderr.write("you need to provide INPUT_DATA in config\n") sys.exit(1) if isinstance(config.INPUT_DATA, basestring): config.INPUT_DAT...
python
def get_uris(config): """ returns a tuple of total file size in bytes, and the list of files """ file_names = [] if config.INPUT_DATA is None: sys.stderr.write("you need to provide INPUT_DATA in config\n") sys.exit(1) if isinstance(config.INPUT_DATA, basestring): config.INPUT_DAT...
[ "def", "get_uris", "(", "config", ")", ":", "file_names", "=", "[", "]", "if", "config", ".", "INPUT_DATA", "is", "None", ":", "sys", ".", "stderr", ".", "write", "(", "\"you need to provide INPUT_DATA in config\\n\"", ")", "sys", ".", "exit", "(", "1", ")...
returns a tuple of total file size in bytes, and the list of files
[ "returns", "a", "tuple", "of", "total", "file", "size", "in", "bytes", "and", "the", "list", "of", "files" ]
999b33d86b6a900d7c4aadf03cf4a661acba9f1b
https://github.com/50onRed/smr/blob/999b33d86b6a900d7c4aadf03cf4a661acba9f1b/smr/uri.py#L84-L100
241,741
b3j0f/schema
b3j0f/schema/lang/python.py
buildschema
def buildschema(_cls=None, **kwargs): """Class decorator used to build a schema from the decorate class. :param type _cls: class to decorate. :param kwargs: schema attributes to set. :rtype: type :return: schema class. """ if _cls is None: return lambda _cls: buildschema(_cls=_cls, ...
python
def buildschema(_cls=None, **kwargs): """Class decorator used to build a schema from the decorate class. :param type _cls: class to decorate. :param kwargs: schema attributes to set. :rtype: type :return: schema class. """ if _cls is None: return lambda _cls: buildschema(_cls=_cls, ...
[ "def", "buildschema", "(", "_cls", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "_cls", "is", "None", ":", "return", "lambda", "_cls", ":", "buildschema", "(", "_cls", "=", "_cls", ",", "*", "*", "kwargs", ")", "result", "=", "build", "(",...
Class decorator used to build a schema from the decorate class. :param type _cls: class to decorate. :param kwargs: schema attributes to set. :rtype: type :return: schema class.
[ "Class", "decorator", "used", "to", "build", "a", "schema", "from", "the", "decorate", "class", "." ]
1c88c23337f5fef50254e65bd407112c43396dd9
https://github.com/b3j0f/schema/blob/1c88c23337f5fef50254e65bd407112c43396dd9/b3j0f/schema/lang/python.py#L108-L121
241,742
b3j0f/schema
b3j0f/schema/lang/python.py
funcschema
def funcschema(default=None, *args, **kwargs): """Decorator to use in order to transform a function into a schema.""" if default is None: return lambda default: funcschema(default=default, *args, **kwargs) return FunctionSchema(default=default, *args, **kwargs)
python
def funcschema(default=None, *args, **kwargs): """Decorator to use in order to transform a function into a schema.""" if default is None: return lambda default: funcschema(default=default, *args, **kwargs) return FunctionSchema(default=default, *args, **kwargs)
[ "def", "funcschema", "(", "default", "=", "None", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "default", "is", "None", ":", "return", "lambda", "default", ":", "funcschema", "(", "default", "=", "default", ",", "*", "args", ",", "*", ...
Decorator to use in order to transform a function into a schema.
[ "Decorator", "to", "use", "in", "order", "to", "transform", "a", "function", "into", "a", "schema", "." ]
1c88c23337f5fef50254e65bd407112c43396dd9
https://github.com/b3j0f/schema/blob/1c88c23337f5fef50254e65bd407112c43396dd9/b3j0f/schema/lang/python.py#L488-L493
241,743
hobson/pug-dj
pug/dj/crawler/models.py
import_wiki_json
def import_wiki_json(path='wikipedia_crawler_data.json', model=WikiItem, batch_len=100, db_alias='default', verbosity=2): """Read json file and create the appropriate records according to the given database model.""" return djdb.import_json(path=path, model=model, batch_len=batch_len, db_alias=db_alias, verbos...
python
def import_wiki_json(path='wikipedia_crawler_data.json', model=WikiItem, batch_len=100, db_alias='default', verbosity=2): """Read json file and create the appropriate records according to the given database model.""" return djdb.import_json(path=path, model=model, batch_len=batch_len, db_alias=db_alias, verbos...
[ "def", "import_wiki_json", "(", "path", "=", "'wikipedia_crawler_data.json'", ",", "model", "=", "WikiItem", ",", "batch_len", "=", "100", ",", "db_alias", "=", "'default'", ",", "verbosity", "=", "2", ")", ":", "return", "djdb", ".", "import_json", "(", "pa...
Read json file and create the appropriate records according to the given database model.
[ "Read", "json", "file", "and", "create", "the", "appropriate", "records", "according", "to", "the", "given", "database", "model", "." ]
55678b08755a55366ce18e7d3b8ea8fa4491ab04
https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/crawler/models.py#L81-L83
241,744
hobson/pug-dj
pug/dj/crawler/models.py
WikiItem.import_item
def import_item(self, item, crawler='wiki', truncate_strings=True, verbosity=0): """Import a single record from a Scrapy Item dict >> WikiItem().import_item({'url': 'http://test.com', 'modified': '13 January 2014 00:15', 'crawler': 'more than thirty characters in this silly name'}) # doctest: +ELLIPSI...
python
def import_item(self, item, crawler='wiki', truncate_strings=True, verbosity=0): """Import a single record from a Scrapy Item dict >> WikiItem().import_item({'url': 'http://test.com', 'modified': '13 January 2014 00:15', 'crawler': 'more than thirty characters in this silly name'}) # doctest: +ELLIPSI...
[ "def", "import_item", "(", "self", ",", "item", ",", "crawler", "=", "'wiki'", ",", "truncate_strings", "=", "True", ",", "verbosity", "=", "0", ")", ":", "item", "=", "dict", "(", "item", ")", "self", ".", "crawler", "=", "str", "(", "crawler", ")",...
Import a single record from a Scrapy Item dict >> WikiItem().import_item({'url': 'http://test.com', 'modified': '13 January 2014 00:15', 'crawler': 'more than thirty characters in this silly name'}) # doctest: +ELLIPSIS <WikiItem: WikiItem('more than thirty characters in', u'http://test.com', '', date...
[ "Import", "a", "single", "record", "from", "a", "Scrapy", "Item", "dict" ]
55678b08755a55366ce18e7d3b8ea8fa4491ab04
https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/crawler/models.py#L41-L71
241,745
ministryofjustice/django-form-error-reporting
form_error_reporting.py
OrderedQueryDict.urlencode
def urlencode(self): """ Convert dictionary into a query string; keys are assumed to always be str """ output = ('%s=%s' % (k, quote(v)) for k, v in self.items()) return '&'.join(output)
python
def urlencode(self): """ Convert dictionary into a query string; keys are assumed to always be str """ output = ('%s=%s' % (k, quote(v)) for k, v in self.items()) return '&'.join(output)
[ "def", "urlencode", "(", "self", ")", ":", "output", "=", "(", "'%s=%s'", "%", "(", "k", ",", "quote", "(", "v", ")", ")", "for", "k", ",", "v", "in", "self", ".", "items", "(", ")", ")", "return", "'&'", ".", "join", "(", "output", ")" ]
Convert dictionary into a query string; keys are assumed to always be str
[ "Convert", "dictionary", "into", "a", "query", "string", ";", "keys", "are", "assumed", "to", "always", "be", "str" ]
2d08dd5cc4321e1abf49241c515ccd7050d9f828
https://github.com/ministryofjustice/django-form-error-reporting/blob/2d08dd5cc4321e1abf49241c515ccd7050d9f828/form_error_reporting.py#L24-L30
241,746
ministryofjustice/django-form-error-reporting
form_error_reporting.py
GAErrorReportingMixin.is_valid
def is_valid(self): """ Error reporting is triggered when a form is checked for validity """ is_valid = super(GAErrorReportingMixin, self).is_valid() if self.is_bound and not is_valid: try: self.report_errors_to_ga(self.errors) except: # n...
python
def is_valid(self): """ Error reporting is triggered when a form is checked for validity """ is_valid = super(GAErrorReportingMixin, self).is_valid() if self.is_bound and not is_valid: try: self.report_errors_to_ga(self.errors) except: # n...
[ "def", "is_valid", "(", "self", ")", ":", "is_valid", "=", "super", "(", "GAErrorReportingMixin", ",", "self", ")", ".", "is_valid", "(", ")", "if", "self", ".", "is_bound", "and", "not", "is_valid", ":", "try", ":", "self", ".", "report_errors_to_ga", "...
Error reporting is triggered when a form is checked for validity
[ "Error", "reporting", "is", "triggered", "when", "a", "form", "is", "checked", "for", "validity" ]
2d08dd5cc4321e1abf49241c515ccd7050d9f828
https://github.com/ministryofjustice/django-form-error-reporting/blob/2d08dd5cc4321e1abf49241c515ccd7050d9f828/form_error_reporting.py#L44-L54
241,747
ministryofjustice/django-form-error-reporting
form_error_reporting.py
GAErrorReportingMixin.get_ga_event_category
def get_ga_event_category(self): """ Event category, defaults to form class name """ return self.ga_event_category or '%s.%s' % (self.__class__.__module__, self.__class__.__name__)
python
def get_ga_event_category(self): """ Event category, defaults to form class name """ return self.ga_event_category or '%s.%s' % (self.__class__.__module__, self.__class__.__name__)
[ "def", "get_ga_event_category", "(", "self", ")", ":", "return", "self", ".", "ga_event_category", "or", "'%s.%s'", "%", "(", "self", ".", "__class__", ".", "__module__", ",", "self", ".", "__class__", ".", "__name__", ")" ]
Event category, defaults to form class name
[ "Event", "category", "defaults", "to", "form", "class", "name" ]
2d08dd5cc4321e1abf49241c515ccd7050d9f828
https://github.com/ministryofjustice/django-form-error-reporting/blob/2d08dd5cc4321e1abf49241c515ccd7050d9f828/form_error_reporting.py#L80-L84
241,748
ministryofjustice/django-form-error-reporting
form_error_reporting.py
GAErrorReportingMixin.format_ga_hit
def format_ga_hit(self, field_name, error_message): """ Format a single hit """ tracking_id = self.get_ga_tracking_id() if not tracking_id: warnings.warn('Google Analytics tracking ID is not set') return None query_dict = self.get_ga_query_dict() ...
python
def format_ga_hit(self, field_name, error_message): """ Format a single hit """ tracking_id = self.get_ga_tracking_id() if not tracking_id: warnings.warn('Google Analytics tracking ID is not set') return None query_dict = self.get_ga_query_dict() ...
[ "def", "format_ga_hit", "(", "self", ",", "field_name", ",", "error_message", ")", ":", "tracking_id", "=", "self", ".", "get_ga_tracking_id", "(", ")", "if", "not", "tracking_id", ":", "warnings", ".", "warn", "(", "'Google Analytics tracking ID is not set'", ")"...
Format a single hit
[ "Format", "a", "single", "hit" ]
2d08dd5cc4321e1abf49241c515ccd7050d9f828
https://github.com/ministryofjustice/django-form-error-reporting/blob/2d08dd5cc4321e1abf49241c515ccd7050d9f828/form_error_reporting.py#L100-L114
241,749
ministryofjustice/django-form-error-reporting
form_error_reporting.py
GARequestErrorReportingMixin.get_ga_tracking_id
def get_ga_tracking_id(self): """ Retrieve tracking ID from settings """ if hasattr(settings, self.ga_tracking_id_settings_key): return getattr(settings, self.ga_tracking_id_settings_key) return super(GARequestErrorReportingMixin, self).get_ga_tracking_id()
python
def get_ga_tracking_id(self): """ Retrieve tracking ID from settings """ if hasattr(settings, self.ga_tracking_id_settings_key): return getattr(settings, self.ga_tracking_id_settings_key) return super(GARequestErrorReportingMixin, self).get_ga_tracking_id()
[ "def", "get_ga_tracking_id", "(", "self", ")", ":", "if", "hasattr", "(", "settings", ",", "self", ".", "ga_tracking_id_settings_key", ")", ":", "return", "getattr", "(", "settings", ",", "self", ".", "ga_tracking_id_settings_key", ")", "return", "super", "(", ...
Retrieve tracking ID from settings
[ "Retrieve", "tracking", "ID", "from", "settings" ]
2d08dd5cc4321e1abf49241c515ccd7050d9f828
https://github.com/ministryofjustice/django-form-error-reporting/blob/2d08dd5cc4321e1abf49241c515ccd7050d9f828/form_error_reporting.py#L150-L156
241,750
ministryofjustice/django-form-error-reporting
form_error_reporting.py
GARequestErrorReportingMixin.get_ga_client_id
def get_ga_client_id(self): """ Retrieve the client ID from the Google Analytics cookie, if available, and save in the current session """ request = self.get_ga_request() if not request or not hasattr(request, 'session'): return super(GARequestErrorReportingMi...
python
def get_ga_client_id(self): """ Retrieve the client ID from the Google Analytics cookie, if available, and save in the current session """ request = self.get_ga_request() if not request or not hasattr(request, 'session'): return super(GARequestErrorReportingMi...
[ "def", "get_ga_client_id", "(", "self", ")", ":", "request", "=", "self", ".", "get_ga_request", "(", ")", "if", "not", "request", "or", "not", "hasattr", "(", "request", ",", "'session'", ")", ":", "return", "super", "(", "GARequestErrorReportingMixin", ","...
Retrieve the client ID from the Google Analytics cookie, if available, and save in the current session
[ "Retrieve", "the", "client", "ID", "from", "the", "Google", "Analytics", "cookie", "if", "available", "and", "save", "in", "the", "current", "session" ]
2d08dd5cc4321e1abf49241c515ccd7050d9f828
https://github.com/ministryofjustice/django-form-error-reporting/blob/2d08dd5cc4321e1abf49241c515ccd7050d9f828/form_error_reporting.py#L165-L177
241,751
ministryofjustice/django-form-error-reporting
form_error_reporting.py
GARequestErrorReportingMixin.get_ga_query_dict
def get_ga_query_dict(self): """ Adds user agent and IP to the default hit parameters """ query_dict = super(GARequestErrorReportingMixin, self).get_ga_query_dict() request = self.get_ga_request() if not request: return query_dict user_ip = request.MET...
python
def get_ga_query_dict(self): """ Adds user agent and IP to the default hit parameters """ query_dict = super(GARequestErrorReportingMixin, self).get_ga_query_dict() request = self.get_ga_request() if not request: return query_dict user_ip = request.MET...
[ "def", "get_ga_query_dict", "(", "self", ")", ":", "query_dict", "=", "super", "(", "GARequestErrorReportingMixin", ",", "self", ")", ".", "get_ga_query_dict", "(", ")", "request", "=", "self", ".", "get_ga_request", "(", ")", "if", "not", "request", ":", "r...
Adds user agent and IP to the default hit parameters
[ "Adds", "user", "agent", "and", "IP", "to", "the", "default", "hit", "parameters" ]
2d08dd5cc4321e1abf49241c515ccd7050d9f828
https://github.com/ministryofjustice/django-form-error-reporting/blob/2d08dd5cc4321e1abf49241c515ccd7050d9f828/form_error_reporting.py#L179-L197
241,752
datakortet/dkfileutils
tasks.py
build_js
def build_js(ctx, force=False): """Build all javascript files. """ for fname in JSX_FILENAMES: jstools.babel( ctx, '{pkg.source_js}/' + fname, '{pkg.django_static}/{pkg.name}/js/' + fname + '.js', force=force )
python
def build_js(ctx, force=False): """Build all javascript files. """ for fname in JSX_FILENAMES: jstools.babel( ctx, '{pkg.source_js}/' + fname, '{pkg.django_static}/{pkg.name}/js/' + fname + '.js', force=force )
[ "def", "build_js", "(", "ctx", ",", "force", "=", "False", ")", ":", "for", "fname", "in", "JSX_FILENAMES", ":", "jstools", ".", "babel", "(", "ctx", ",", "'{pkg.source_js}/'", "+", "fname", ",", "'{pkg.django_static}/{pkg.name}/js/'", "+", "fname", "+", "'....
Build all javascript files.
[ "Build", "all", "javascript", "files", "." ]
924098d6e2edf88ad9b3ffdec9c74530f80a7d77
https://github.com/datakortet/dkfileutils/blob/924098d6e2edf88ad9b3ffdec9c74530f80a7d77/tasks.py#L79-L88
241,753
datakortet/dkfileutils
tasks.py
build
def build(ctx, less=False, docs=False, js=False, force=False): """Build everything and collectstatic. """ specified = any([less, docs, js]) buildall = not specified if buildall or less: less_fname = ctx.pkg.source_less / ctx.pkg.name + '.less' if less_fname.exists(): les...
python
def build(ctx, less=False, docs=False, js=False, force=False): """Build everything and collectstatic. """ specified = any([less, docs, js]) buildall = not specified if buildall or less: less_fname = ctx.pkg.source_less / ctx.pkg.name + '.less' if less_fname.exists(): les...
[ "def", "build", "(", "ctx", ",", "less", "=", "False", ",", "docs", "=", "False", ",", "js", "=", "False", ",", "force", "=", "False", ")", ":", "specified", "=", "any", "(", "[", "less", ",", "docs", ",", "js", "]", ")", "buildall", "=", "not"...
Build everything and collectstatic.
[ "Build", "everything", "and", "collectstatic", "." ]
924098d6e2edf88ad9b3ffdec9c74530f80a7d77
https://github.com/datakortet/dkfileutils/blob/924098d6e2edf88ad9b3ffdec9c74530f80a7d77/tasks.py#L92-L123
241,754
datakortet/dkfileutils
tasks.py
watch
def watch(ctx): """Automatically run build whenever a relevant file changes. """ watcher = Watcher(ctx) watcher.watch_directory( path='{pkg.source_less}', ext='.less', action=lambda e: build(ctx, less=True) ) watcher.watch_directory( path='{pkg.source_js}', ext='.jsx', ...
python
def watch(ctx): """Automatically run build whenever a relevant file changes. """ watcher = Watcher(ctx) watcher.watch_directory( path='{pkg.source_less}', ext='.less', action=lambda e: build(ctx, less=True) ) watcher.watch_directory( path='{pkg.source_js}', ext='.jsx', ...
[ "def", "watch", "(", "ctx", ")", ":", "watcher", "=", "Watcher", "(", "ctx", ")", "watcher", ".", "watch_directory", "(", "path", "=", "'{pkg.source_less}'", ",", "ext", "=", "'.less'", ",", "action", "=", "lambda", "e", ":", "build", "(", "ctx", ",", ...
Automatically run build whenever a relevant file changes.
[ "Automatically", "run", "build", "whenever", "a", "relevant", "file", "changes", "." ]
924098d6e2edf88ad9b3ffdec9c74530f80a7d77
https://github.com/datakortet/dkfileutils/blob/924098d6e2edf88ad9b3ffdec9c74530f80a7d77/tasks.py#L127-L143
241,755
Metatab/tableintuit
tableintuit/stats.py
_force_float
def _force_float(v): """ Converts given argument to float. On fail logs warning and returns 0.0. Args: v (any): value to convert to float Returns: float: converted v or 0.0 if conversion failed. """ try: return float(v) except Exception as exc: return float('na...
python
def _force_float(v): """ Converts given argument to float. On fail logs warning and returns 0.0. Args: v (any): value to convert to float Returns: float: converted v or 0.0 if conversion failed. """ try: return float(v) except Exception as exc: return float('na...
[ "def", "_force_float", "(", "v", ")", ":", "try", ":", "return", "float", "(", "v", ")", "except", "Exception", "as", "exc", ":", "return", "float", "(", "'nan'", ")", "logger", ".", "warning", "(", "'Failed to convert {} to float with {} error. Using 0 instead....
Converts given argument to float. On fail logs warning and returns 0.0. Args: v (any): value to convert to float Returns: float: converted v or 0.0 if conversion failed.
[ "Converts", "given", "argument", "to", "float", ".", "On", "fail", "logs", "warning", "and", "returns", "0", ".", "0", "." ]
9a3d500d5d90e44e6637dd17ca4c8dae474d6d4c
https://github.com/Metatab/tableintuit/blob/9a3d500d5d90e44e6637dd17ca4c8dae474d6d4c/tableintuit/stats.py#L509-L523
241,756
Metatab/tableintuit
tableintuit/stats.py
StatSet.dict
def dict(self): """Return a dict that can be passed into the ColumnStats constructor""" try: skewness = self.skewness kurtosis = self.kurtosis except ZeroDivisionError: skewness = kurtosis = float('nan') base_cols = [ ('name', self.colum...
python
def dict(self): """Return a dict that can be passed into the ColumnStats constructor""" try: skewness = self.skewness kurtosis = self.kurtosis except ZeroDivisionError: skewness = kurtosis = float('nan') base_cols = [ ('name', self.colum...
[ "def", "dict", "(", "self", ")", ":", "try", ":", "skewness", "=", "self", ".", "skewness", "kurtosis", "=", "self", ".", "kurtosis", "except", "ZeroDivisionError", ":", "skewness", "=", "kurtosis", "=", "float", "(", "'nan'", ")", "base_cols", "=", "[",...
Return a dict that can be passed into the ColumnStats constructor
[ "Return", "a", "dict", "that", "can", "be", "passed", "into", "the", "ColumnStats", "constructor" ]
9a3d500d5d90e44e6637dd17ca4c8dae474d6d4c
https://github.com/Metatab/tableintuit/blob/9a3d500d5d90e44e6637dd17ca4c8dae474d6d4c/tableintuit/stats.py#L306-L351
241,757
Metatab/tableintuit
tableintuit/stats.py
Stats.run
def run(self): """ Run the stats. The source must yield Row proxies. """ self._func, self._func_code = self.build() def process_row(row): try: self._func(self._stats, row) except TypeError as e: raise TypeError("Failed for '{}'; ...
python
def run(self): """ Run the stats. The source must yield Row proxies. """ self._func, self._func_code = self.build() def process_row(row): try: self._func(self._stats, row) except TypeError as e: raise TypeError("Failed for '{}'; ...
[ "def", "run", "(", "self", ")", ":", "self", ".", "_func", ",", "self", ".", "_func_code", "=", "self", ".", "build", "(", ")", "def", "process_row", "(", "row", ")", ":", "try", ":", "self", ".", "_func", "(", "self", ".", "_stats", ",", "row", ...
Run the stats. The source must yield Row proxies.
[ "Run", "the", "stats", ".", "The", "source", "must", "yield", "Row", "proxies", "." ]
9a3d500d5d90e44e6637dd17ca4c8dae474d6d4c
https://github.com/Metatab/tableintuit/blob/9a3d500d5d90e44e6637dd17ca4c8dae474d6d4c/tableintuit/stats.py#L427-L470
241,758
openp2pdesign/makerlabs
makerlabs/hackaday_io.py
get_labs
def get_labs(format): """Gets Hackerspaces data from hackaday.io.""" hackerspaces_json = data_from_hackaday_io(hackaday_io_labs_map_url) hackerspaces = {} # Load all the Hackerspaces for i in hackerspaces_json: current_lab = Hackerspace() current_lab.id = i["id"] current_la...
python
def get_labs(format): """Gets Hackerspaces data from hackaday.io.""" hackerspaces_json = data_from_hackaday_io(hackaday_io_labs_map_url) hackerspaces = {} # Load all the Hackerspaces for i in hackerspaces_json: current_lab = Hackerspace() current_lab.id = i["id"] current_la...
[ "def", "get_labs", "(", "format", ")", ":", "hackerspaces_json", "=", "data_from_hackaday_io", "(", "hackaday_io_labs_map_url", ")", "hackerspaces", "=", "{", "}", "# Load all the Hackerspaces", "for", "i", "in", "hackerspaces_json", ":", "current_lab", "=", "Hackersp...
Gets Hackerspaces data from hackaday.io.
[ "Gets", "Hackerspaces", "data", "from", "hackaday", ".", "io", "." ]
b5838440174f10d370abb671358db9a99d7739fd
https://github.com/openp2pdesign/makerlabs/blob/b5838440174f10d370abb671358db9a99d7739fd/makerlabs/hackaday_io.py#L57-L137
241,759
shreyaspotnis/rampage
rampage/server.py
check_ramp_for_errors
def check_ramp_for_errors(ramp_data): """Checks ramp for errors. This is experiment specific checklist.""" error_list = [] keyframe_list = ramps.KeyFrameList(ramp_data['keyframes']) sorted_key_list = keyframe_list.sorted_key_list() channel_list = [ramps.Channel(ch_name, ramp_data['channels'][ch_name...
python
def check_ramp_for_errors(ramp_data): """Checks ramp for errors. This is experiment specific checklist.""" error_list = [] keyframe_list = ramps.KeyFrameList(ramp_data['keyframes']) sorted_key_list = keyframe_list.sorted_key_list() channel_list = [ramps.Channel(ch_name, ramp_data['channels'][ch_name...
[ "def", "check_ramp_for_errors", "(", "ramp_data", ")", ":", "error_list", "=", "[", "]", "keyframe_list", "=", "ramps", ".", "KeyFrameList", "(", "ramp_data", "[", "'keyframes'", "]", ")", "sorted_key_list", "=", "keyframe_list", ".", "sorted_key_list", "(", ")"...
Checks ramp for errors. This is experiment specific checklist.
[ "Checks", "ramp", "for", "errors", ".", "This", "is", "experiment", "specific", "checklist", "." ]
e2565aef7ee16ee06523de975e8aa41aca14e3b2
https://github.com/shreyaspotnis/rampage/blob/e2565aef7ee16ee06523de975e8aa41aca14e3b2/rampage/server.py#L713-L763
241,760
JNRowe/jnrbase
jnrbase/colourise.py
_colourise
def _colourise(text: str, colour: str) -> str: """Colour text, if possible. Args: text: Text to colourise colour: Colour to display text in Returns: Colourised text, if possible """ if COLOUR: text = style(text, fg=colour, bold=True) return text
python
def _colourise(text: str, colour: str) -> str: """Colour text, if possible. Args: text: Text to colourise colour: Colour to display text in Returns: Colourised text, if possible """ if COLOUR: text = style(text, fg=colour, bold=True) return text
[ "def", "_colourise", "(", "text", ":", "str", ",", "colour", ":", "str", ")", "->", "str", ":", "if", "COLOUR", ":", "text", "=", "style", "(", "text", ",", "fg", "=", "colour", ",", "bold", "=", "True", ")", "return", "text" ]
Colour text, if possible. Args: text: Text to colourise colour: Colour to display text in Returns: Colourised text, if possible
[ "Colour", "text", "if", "possible", "." ]
ae505ef69a9feb739b5f4e62c5a8e6533104d3ea
https://github.com/JNRowe/jnrbase/blob/ae505ef69a9feb739b5f4e62c5a8e6533104d3ea/jnrbase/colourise.py#L31-L42
241,761
HazardDede/dictmentor
dictmentor/extensions.py
ExternalResource._apply
def _apply(self, ctx: ExtensionContext) -> AugmentedDict: """ Performs the actual loading of an external resource into the current model. Args: ctx: The processing context. Returns: Returns a dictionary that gets incorporated into the actual model. """ ...
python
def _apply(self, ctx: ExtensionContext) -> AugmentedDict: """ Performs the actual loading of an external resource into the current model. Args: ctx: The processing context. Returns: Returns a dictionary that gets incorporated into the actual model. """ ...
[ "def", "_apply", "(", "self", ",", "ctx", ":", "ExtensionContext", ")", "->", "AugmentedDict", ":", "def", "process", "(", "pattern", ":", "Pattern", "[", "str", "]", ",", "_str", ":", "str", ")", "->", "Any", ":", "_match", "=", "pattern", ".", "mat...
Performs the actual loading of an external resource into the current model. Args: ctx: The processing context. Returns: Returns a dictionary that gets incorporated into the actual model.
[ "Performs", "the", "actual", "loading", "of", "an", "external", "resource", "into", "the", "current", "model", "." ]
f50ca26ed04f7a924cde6e4d464c4f6ccba4e320
https://github.com/HazardDede/dictmentor/blob/f50ca26ed04f7a924cde6e4d464c4f6ccba4e320/dictmentor/extensions.py#L144-L172
241,762
HazardDede/dictmentor
dictmentor/extensions.py
ExternalYamlResource._apply
def _apply(self, ctx: ExtensionContext) -> Any: """ Loads a yaml fragment from an external file. Args: ctx: The processing context. Returns: The external resource as a python dictionary. The fragment is already send through the processor as well. ...
python
def _apply(self, ctx: ExtensionContext) -> Any: """ Loads a yaml fragment from an external file. Args: ctx: The processing context. Returns: The external resource as a python dictionary. The fragment is already send through the processor as well. ...
[ "def", "_apply", "(", "self", ",", "ctx", ":", "ExtensionContext", ")", "->", "Any", ":", "_", ",", "external_path", "=", "ctx", ".", "node", "return", "ctx", ".", "mentor", ".", "load_yaml", "(", "self", ".", "locator", "(", "external_path", ",", "cas...
Loads a yaml fragment from an external file. Args: ctx: The processing context. Returns: The external resource as a python dictionary. The fragment is already send through the processor as well.
[ "Loads", "a", "yaml", "fragment", "from", "an", "external", "file", "." ]
f50ca26ed04f7a924cde6e4d464c4f6ccba4e320
https://github.com/HazardDede/dictmentor/blob/f50ca26ed04f7a924cde6e4d464c4f6ccba4e320/dictmentor/extensions.py#L227-L242
241,763
OpenGov/carpenter
carpenter/blocks/tableanalyzer.py
TableAnalyzer.preprocess
def preprocess(self): ''' Performs initial cell conversions to standard types. This will strip units, scale numbers, and identify numeric data where it's convertible. ''' self.processed_tables = [] self.flags_by_table = [] self.units_by_table = [] for work...
python
def preprocess(self): ''' Performs initial cell conversions to standard types. This will strip units, scale numbers, and identify numeric data where it's convertible. ''' self.processed_tables = [] self.flags_by_table = [] self.units_by_table = [] for work...
[ "def", "preprocess", "(", "self", ")", ":", "self", ".", "processed_tables", "=", "[", "]", "self", ".", "flags_by_table", "=", "[", "]", "self", ".", "units_by_table", "=", "[", "]", "for", "worksheet", ",", "rtable", "in", "enumerate", "(", "self", "...
Performs initial cell conversions to standard types. This will strip units, scale numbers, and identify numeric data where it's convertible.
[ "Performs", "initial", "cell", "conversions", "to", "standard", "types", ".", "This", "will", "strip", "units", "scale", "numbers", "and", "identify", "numeric", "data", "where", "it", "s", "convertible", "." ]
0ab3c54c05133b9b0468c63e834a7ce3a6fb575b
https://github.com/OpenGov/carpenter/blob/0ab3c54c05133b9b0468c63e834a7ce3a6fb575b/carpenter/blocks/tableanalyzer.py#L45-L59
241,764
OpenGov/carpenter
carpenter/blocks/tableanalyzer.py
TableAnalyzer.generate_blocks
def generate_blocks(self, assume_complete_blocks=None): ''' Identifies and extracts all blocks from the input tables. These blocks are logical identifiers for where related information resides in the original table. Any block can be converted into a row-titled table which can then be sti...
python
def generate_blocks(self, assume_complete_blocks=None): ''' Identifies and extracts all blocks from the input tables. These blocks are logical identifiers for where related information resides in the original table. Any block can be converted into a row-titled table which can then be sti...
[ "def", "generate_blocks", "(", "self", ",", "assume_complete_blocks", "=", "None", ")", ":", "# Store this value to restore object settings later", "_track_assume_blocks", "=", "self", ".", "assume_complete_blocks", "try", ":", "if", "assume_complete_blocks", "!=", "None", ...
Identifies and extracts all blocks from the input tables. These blocks are logical identifiers for where related information resides in the original table. Any block can be converted into a row-titled table which can then be stitched together with other tables from other blocks to form a fully c...
[ "Identifies", "and", "extracts", "all", "blocks", "from", "the", "input", "tables", ".", "These", "blocks", "are", "logical", "identifiers", "for", "where", "related", "information", "resides", "in", "the", "original", "table", ".", "Any", "block", "can", "be"...
0ab3c54c05133b9b0468c63e834a7ce3a6fb575b
https://github.com/OpenGov/carpenter/blob/0ab3c54c05133b9b0468c63e834a7ce3a6fb575b/carpenter/blocks/tableanalyzer.py#L61-L96
241,765
OpenGov/carpenter
carpenter/blocks/tableanalyzer.py
TableAnalyzer.preprocess_worksheet
def preprocess_worksheet(self, table, worksheet): ''' Performs a preprocess pass of the table to attempt naive conversions of data and to record the initial types of each cell. ''' table_conversion = [] flags = {} units = {} for rind, row in enumerate(tabl...
python
def preprocess_worksheet(self, table, worksheet): ''' Performs a preprocess pass of the table to attempt naive conversions of data and to record the initial types of each cell. ''' table_conversion = [] flags = {} units = {} for rind, row in enumerate(tabl...
[ "def", "preprocess_worksheet", "(", "self", ",", "table", ",", "worksheet", ")", ":", "table_conversion", "=", "[", "]", "flags", "=", "{", "}", "units", "=", "{", "}", "for", "rind", ",", "row", "in", "enumerate", "(", "table", ")", ":", "conversion_r...
Performs a preprocess pass of the table to attempt naive conversions of data and to record the initial types of each cell.
[ "Performs", "a", "preprocess", "pass", "of", "the", "table", "to", "attempt", "naive", "conversions", "of", "data", "and", "to", "record", "the", "initial", "types", "of", "each", "cell", "." ]
0ab3c54c05133b9b0468c63e834a7ce3a6fb575b
https://github.com/OpenGov/carpenter/blob/0ab3c54c05133b9b0468c63e834a7ce3a6fb575b/carpenter/blocks/tableanalyzer.py#L98-L123
241,766
OpenGov/carpenter
carpenter/blocks/tableanalyzer.py
TableAnalyzer.fill_in_table
def fill_in_table(self, table, worksheet, flags): ''' Fills in any rows with missing right hand side data with empty cells. ''' max_row = 0 min_row = sys.maxint for row in table: if len(row) > max_row: max_row = len(row) if len(row)...
python
def fill_in_table(self, table, worksheet, flags): ''' Fills in any rows with missing right hand side data with empty cells. ''' max_row = 0 min_row = sys.maxint for row in table: if len(row) > max_row: max_row = len(row) if len(row)...
[ "def", "fill_in_table", "(", "self", ",", "table", ",", "worksheet", ",", "flags", ")", ":", "max_row", "=", "0", "min_row", "=", "sys", ".", "maxint", "for", "row", "in", "table", ":", "if", "len", "(", "row", ")", ">", "max_row", ":", "max_row", ...
Fills in any rows with missing right hand side data with empty cells.
[ "Fills", "in", "any", "rows", "with", "missing", "right", "hand", "side", "data", "with", "empty", "cells", "." ]
0ab3c54c05133b9b0468c63e834a7ce3a6fb575b
https://github.com/OpenGov/carpenter/blob/0ab3c54c05133b9b0468c63e834a7ce3a6fb575b/carpenter/blocks/tableanalyzer.py#L125-L139
241,767
OpenGov/carpenter
carpenter/blocks/tableanalyzer.py
TableAnalyzer._find_valid_block
def _find_valid_block(self, table, worksheet, flags, units, used_cells, start_pos, end_pos): ''' Searches for the next location where a valid block could reside and constructs the block object representing that location. ''' for row_index in range(len(table)): if row_...
python
def _find_valid_block(self, table, worksheet, flags, units, used_cells, start_pos, end_pos): ''' Searches for the next location where a valid block could reside and constructs the block object representing that location. ''' for row_index in range(len(table)): if row_...
[ "def", "_find_valid_block", "(", "self", ",", "table", ",", "worksheet", ",", "flags", ",", "units", ",", "used_cells", ",", "start_pos", ",", "end_pos", ")", ":", "for", "row_index", "in", "range", "(", "len", "(", "table", ")", ")", ":", "if", "row_i...
Searches for the next location where a valid block could reside and constructs the block object representing that location.
[ "Searches", "for", "the", "next", "location", "where", "a", "valid", "block", "could", "reside", "and", "constructs", "the", "block", "object", "representing", "that", "location", "." ]
0ab3c54c05133b9b0468c63e834a7ce3a6fb575b
https://github.com/OpenGov/carpenter/blob/0ab3c54c05133b9b0468c63e834a7ce3a6fb575b/carpenter/blocks/tableanalyzer.py#L198-L223
241,768
OpenGov/carpenter
carpenter/blocks/tableanalyzer.py
TableAnalyzer._find_block_bounds
def _find_block_bounds(self, table, used_cells, possible_block_start, start_pos, end_pos): ''' First walk the rows, checking for the farthest left column belonging to the block and the bottom most row belonging to the block. If a blank cell is hit and the column started with a blank cell...
python
def _find_block_bounds(self, table, used_cells, possible_block_start, start_pos, end_pos): ''' First walk the rows, checking for the farthest left column belonging to the block and the bottom most row belonging to the block. If a blank cell is hit and the column started with a blank cell...
[ "def", "_find_block_bounds", "(", "self", ",", "table", ",", "used_cells", ",", "possible_block_start", ",", "start_pos", ",", "end_pos", ")", ":", "# If we're only looking for complete blocks, then just walk", "# until we hit a blank cell", "if", "self", ".", "assume_compl...
First walk the rows, checking for the farthest left column belonging to the block and the bottom most row belonging to the block. If a blank cell is hit and the column started with a blank cell or has length < self.blank_repeat_threshold, then restart one row to the right. Alternatively, if assu...
[ "First", "walk", "the", "rows", "checking", "for", "the", "farthest", "left", "column", "belonging", "to", "the", "block", "and", "the", "bottom", "most", "row", "belonging", "to", "the", "block", ".", "If", "a", "blank", "cell", "is", "hit", "and", "the...
0ab3c54c05133b9b0468c63e834a7ce3a6fb575b
https://github.com/OpenGov/carpenter/blob/0ab3c54c05133b9b0468c63e834a7ce3a6fb575b/carpenter/blocks/tableanalyzer.py#L225-L252
241,769
OpenGov/carpenter
carpenter/blocks/tableanalyzer.py
TableAnalyzer._single_length_title
def _single_length_title(self, table, row_index, current_col): ''' Returns true if the row is a single length title element with no other row titles. Useful for tracking pre-data titles that belong in their own block. ''' if len(table[row_index]) - current_col <= 0: r...
python
def _single_length_title(self, table, row_index, current_col): ''' Returns true if the row is a single length title element with no other row titles. Useful for tracking pre-data titles that belong in their own block. ''' if len(table[row_index]) - current_col <= 0: r...
[ "def", "_single_length_title", "(", "self", ",", "table", ",", "row_index", ",", "current_col", ")", ":", "if", "len", "(", "table", "[", "row_index", "]", ")", "-", "current_col", "<=", "0", ":", "return", "False", "return", "(", "is_text_cell", "(", "t...
Returns true if the row is a single length title element with no other row titles. Useful for tracking pre-data titles that belong in their own block.
[ "Returns", "true", "if", "the", "row", "is", "a", "single", "length", "title", "element", "with", "no", "other", "row", "titles", ".", "Useful", "for", "tracking", "pre", "-", "data", "titles", "that", "belong", "in", "their", "own", "block", "." ]
0ab3c54c05133b9b0468c63e834a7ce3a6fb575b
https://github.com/OpenGov/carpenter/blob/0ab3c54c05133b9b0468c63e834a7ce3a6fb575b/carpenter/blocks/tableanalyzer.py#L287-L296
241,770
OpenGov/carpenter
carpenter/blocks/tableanalyzer.py
TableAnalyzer._find_block_start
def _find_block_start(self, table, used_cells, possible_block_start, start_pos, end_pos): ''' Finds the start of a block from a suggested start location. This location can be at a lower column but not a lower row. The function traverses columns until it finds a stopping condition or a re...
python
def _find_block_start(self, table, used_cells, possible_block_start, start_pos, end_pos): ''' Finds the start of a block from a suggested start location. This location can be at a lower column but not a lower row. The function traverses columns until it finds a stopping condition or a re...
[ "def", "_find_block_start", "(", "self", ",", "table", ",", "used_cells", ",", "possible_block_start", ",", "start_pos", ",", "end_pos", ")", ":", "current_col", "=", "possible_block_start", "[", "1", "]", "block_start", "=", "list", "(", "possible_block_start", ...
Finds the start of a block from a suggested start location. This location can be at a lower column but not a lower row. The function traverses columns until it finds a stopping condition or a repeat condition that restarts on the next column. Note this also finds the lowest row of block_end.
[ "Finds", "the", "start", "of", "a", "block", "from", "a", "suggested", "start", "location", ".", "This", "location", "can", "be", "at", "a", "lower", "column", "but", "not", "a", "lower", "row", ".", "The", "function", "traverses", "columns", "until", "i...
0ab3c54c05133b9b0468c63e834a7ce3a6fb575b
https://github.com/OpenGov/carpenter/blob/0ab3c54c05133b9b0468c63e834a7ce3a6fb575b/carpenter/blocks/tableanalyzer.py#L310-L377
241,771
veeti/decent
decent/error.py
Error.as_dict
def as_dict(self, join='.'): """ Returns the error as a path to message dictionary. Paths are joined with the ``join`` string. """ if self.path: path = [str(node) for node in self.path] else: path = '' return { join.join(path): self.message...
python
def as_dict(self, join='.'): """ Returns the error as a path to message dictionary. Paths are joined with the ``join`` string. """ if self.path: path = [str(node) for node in self.path] else: path = '' return { join.join(path): self.message...
[ "def", "as_dict", "(", "self", ",", "join", "=", "'.'", ")", ":", "if", "self", ".", "path", ":", "path", "=", "[", "str", "(", "node", ")", "for", "node", "in", "self", ".", "path", "]", "else", ":", "path", "=", "''", "return", "{", "join", ...
Returns the error as a path to message dictionary. Paths are joined with the ``join`` string.
[ "Returns", "the", "error", "as", "a", "path", "to", "message", "dictionary", ".", "Paths", "are", "joined", "with", "the", "join", "string", "." ]
07b11536953b9cf4402c65f241706ab717b90bff
https://github.com/veeti/decent/blob/07b11536953b9cf4402c65f241706ab717b90bff/decent/error.py#L28-L37
241,772
veeti/decent
decent/error.py
Invalid.as_dict
def as_dict(self, join='.'): """ Returns all the errors in this collection as a path to message dictionary. Paths are joined with the ``join`` string. """ result = {} for e in self.errors: result.update(e.as_dict(join)) return result
python
def as_dict(self, join='.'): """ Returns all the errors in this collection as a path to message dictionary. Paths are joined with the ``join`` string. """ result = {} for e in self.errors: result.update(e.as_dict(join)) return result
[ "def", "as_dict", "(", "self", ",", "join", "=", "'.'", ")", ":", "result", "=", "{", "}", "for", "e", "in", "self", ".", "errors", ":", "result", ".", "update", "(", "e", ".", "as_dict", "(", "join", ")", ")", "return", "result" ]
Returns all the errors in this collection as a path to message dictionary. Paths are joined with the ``join`` string.
[ "Returns", "all", "the", "errors", "in", "this", "collection", "as", "a", "path", "to", "message", "dictionary", ".", "Paths", "are", "joined", "with", "the", "join", "string", "." ]
07b11536953b9cf4402c65f241706ab717b90bff
https://github.com/veeti/decent/blob/07b11536953b9cf4402c65f241706ab717b90bff/decent/error.py#L64-L72
241,773
cdeboever3/cdpybio
cdpybio/gencode.py
load_gffutils_db
def load_gffutils_db(f): """ Load database for gffutils. Parameters ---------- f : str Path to database. Returns ------- db : gffutils.FeatureDB gffutils feature database. """ import gffutils db = gffutils.FeatureDB(f, keep_order=True) return db
python
def load_gffutils_db(f): """ Load database for gffutils. Parameters ---------- f : str Path to database. Returns ------- db : gffutils.FeatureDB gffutils feature database. """ import gffutils db = gffutils.FeatureDB(f, keep_order=True) return db
[ "def", "load_gffutils_db", "(", "f", ")", ":", "import", "gffutils", "db", "=", "gffutils", ".", "FeatureDB", "(", "f", ",", "keep_order", "=", "True", ")", "return", "db" ]
Load database for gffutils. Parameters ---------- f : str Path to database. Returns ------- db : gffutils.FeatureDB gffutils feature database.
[ "Load", "database", "for", "gffutils", "." ]
38efdf0e11d01bc00a135921cb91a19c03db5d5c
https://github.com/cdeboever3/cdpybio/blob/38efdf0e11d01bc00a135921cb91a19c03db5d5c/cdpybio/gencode.py#L18-L35
241,774
cdeboever3/cdpybio
cdpybio/gencode.py
make_gffutils_db
def make_gffutils_db(gtf, db): """ Make database for gffutils. Parameters ---------- gtf : str Path to Gencode gtf file. db : str Path to save database to. Returns ------- out_db : gffutils.FeatureDB gffutils feature database. """ import gffutils...
python
def make_gffutils_db(gtf, db): """ Make database for gffutils. Parameters ---------- gtf : str Path to Gencode gtf file. db : str Path to save database to. Returns ------- out_db : gffutils.FeatureDB gffutils feature database. """ import gffutils...
[ "def", "make_gffutils_db", "(", "gtf", ",", "db", ")", ":", "import", "gffutils", "out_db", "=", "gffutils", ".", "create_db", "(", "gtf", ",", "db", ",", "keep_order", "=", "True", ",", "infer_gene_extent", "=", "False", ")", "return", "out_db" ]
Make database for gffutils. Parameters ---------- gtf : str Path to Gencode gtf file. db : str Path to save database to. Returns ------- out_db : gffutils.FeatureDB gffutils feature database.
[ "Make", "database", "for", "gffutils", "." ]
38efdf0e11d01bc00a135921cb91a19c03db5d5c
https://github.com/cdeboever3/cdpybio/blob/38efdf0e11d01bc00a135921cb91a19c03db5d5c/cdpybio/gencode.py#L37-L60
241,775
cdeboever3/cdpybio
cdpybio/gencode.py
merge_bed_by_name
def merge_bed_by_name(bt): """ Merge intervals in a bed file when the intervals have the same name. Intervals with the same name must be adjacent in the bed file. """ name_lines = dict() for r in bt: name = r.name name_lines[name] = name_lines.get(name, []) + [[r.chrom, r.start,...
python
def merge_bed_by_name(bt): """ Merge intervals in a bed file when the intervals have the same name. Intervals with the same name must be adjacent in the bed file. """ name_lines = dict() for r in bt: name = r.name name_lines[name] = name_lines.get(name, []) + [[r.chrom, r.start,...
[ "def", "merge_bed_by_name", "(", "bt", ")", ":", "name_lines", "=", "dict", "(", ")", "for", "r", "in", "bt", ":", "name", "=", "r", ".", "name", "name_lines", "[", "name", "]", "=", "name_lines", ".", "get", "(", "name", ",", "[", "]", ")", "+",...
Merge intervals in a bed file when the intervals have the same name. Intervals with the same name must be adjacent in the bed file.
[ "Merge", "intervals", "in", "a", "bed", "file", "when", "the", "intervals", "have", "the", "same", "name", ".", "Intervals", "with", "the", "same", "name", "must", "be", "adjacent", "in", "the", "bed", "file", "." ]
38efdf0e11d01bc00a135921cb91a19c03db5d5c
https://github.com/cdeboever3/cdpybio/blob/38efdf0e11d01bc00a135921cb91a19c03db5d5c/cdpybio/gencode.py#L207-L223
241,776
cdeboever3/cdpybio
cdpybio/gencode.py
make_feature_bed
def make_feature_bed(gtf, feature, out=None): """ Make a bed file with the start and stop coordinates for all of a particular feature in Gencode. Valid features are the features present in the third column of the Gencode GTF file. Parameters ---------- gtf : str Filename of the Genc...
python
def make_feature_bed(gtf, feature, out=None): """ Make a bed file with the start and stop coordinates for all of a particular feature in Gencode. Valid features are the features present in the third column of the Gencode GTF file. Parameters ---------- gtf : str Filename of the Genc...
[ "def", "make_feature_bed", "(", "gtf", ",", "feature", ",", "out", "=", "None", ")", ":", "bed_lines", "=", "[", "]", "with", "open", "(", "gtf", ")", "as", "f", ":", "line", "=", "f", ".", "readline", "(", ")", ".", "strip", "(", ")", "while", ...
Make a bed file with the start and stop coordinates for all of a particular feature in Gencode. Valid features are the features present in the third column of the Gencode GTF file. Parameters ---------- gtf : str Filename of the Gencode gtf file. feature : str Feature from thir...
[ "Make", "a", "bed", "file", "with", "the", "start", "and", "stop", "coordinates", "for", "all", "of", "a", "particular", "feature", "in", "Gencode", ".", "Valid", "features", "are", "the", "features", "present", "in", "the", "third", "column", "of", "the",...
38efdf0e11d01bc00a135921cb91a19c03db5d5c
https://github.com/cdeboever3/cdpybio/blob/38efdf0e11d01bc00a135921cb91a19c03db5d5c/cdpybio/gencode.py#L225-L275
241,777
cdeboever3/cdpybio
cdpybio/gencode.py
make_transcript_gene_se
def make_transcript_gene_se(fn): """ Make a Pandas Series with transcript ID's as the index and values as the gene ID containing that transcript. Parameters ---------- fn : str Filename of the Gencode gtf file. Returns ------- se : pandas.Series Make a Pandas Series...
python
def make_transcript_gene_se(fn): """ Make a Pandas Series with transcript ID's as the index and values as the gene ID containing that transcript. Parameters ---------- fn : str Filename of the Gencode gtf file. Returns ------- se : pandas.Series Make a Pandas Series...
[ "def", "make_transcript_gene_se", "(", "fn", ")", ":", "import", "itertools", "as", "it", "import", "HTSeq", "gtf", "=", "it", ".", "islice", "(", "HTSeq", ".", "GFF_Reader", "(", "fn", ")", ",", "None", ")", "transcripts", "=", "[", "]", "genes", "=",...
Make a Pandas Series with transcript ID's as the index and values as the gene ID containing that transcript. Parameters ---------- fn : str Filename of the Gencode gtf file. Returns ------- se : pandas.Series Make a Pandas Series with transcript ID's as the index and values...
[ "Make", "a", "Pandas", "Series", "with", "transcript", "ID", "s", "as", "the", "index", "and", "values", "as", "the", "gene", "ID", "containing", "that", "transcript", "." ]
38efdf0e11d01bc00a135921cb91a19c03db5d5c
https://github.com/cdeboever3/cdpybio/blob/38efdf0e11d01bc00a135921cb91a19c03db5d5c/cdpybio/gencode.py#L320-L354
241,778
cdeboever3/cdpybio
cdpybio/gencode.py
make_gene_info_df
def make_gene_info_df(fn): """ Make a Pandas dataframe with gene information Parameters ---------- fn : str of filename Filename of the Gencode gtf file Returns ------- df : pandas.DataFrame Pandas dataframe indexed by gene id with the following columns: gene_...
python
def make_gene_info_df(fn): """ Make a Pandas dataframe with gene information Parameters ---------- fn : str of filename Filename of the Gencode gtf file Returns ------- df : pandas.DataFrame Pandas dataframe indexed by gene id with the following columns: gene_...
[ "def", "make_gene_info_df", "(", "fn", ")", ":", "import", "itertools", "as", "it", "import", "HTSeq", "gff_iter", "=", "it", ".", "islice", "(", "HTSeq", ".", "GFF_Reader", "(", "fn", ")", ",", "None", ")", "convD", "=", "dict", "(", ")", "eof", "="...
Make a Pandas dataframe with gene information Parameters ---------- fn : str of filename Filename of the Gencode gtf file Returns ------- df : pandas.DataFrame Pandas dataframe indexed by gene id with the following columns: gene_type, gene_status, gene_name.
[ "Make", "a", "Pandas", "dataframe", "with", "gene", "information" ]
38efdf0e11d01bc00a135921cb91a19c03db5d5c
https://github.com/cdeboever3/cdpybio/blob/38efdf0e11d01bc00a135921cb91a19c03db5d5c/cdpybio/gencode.py#L356-L400
241,779
cdeboever3/cdpybio
cdpybio/gencode.py
make_splice_junction_df
def make_splice_junction_df(fn, type='gene'): """Read the Gencode gtf file and make a pandas dataframe describing the splice junctions Parameters ---------- filename : str of filename Filename of the Gencode gtf file Returns ------- df : pandas.DataFrame Dataframe of ...
python
def make_splice_junction_df(fn, type='gene'): """Read the Gencode gtf file and make a pandas dataframe describing the splice junctions Parameters ---------- filename : str of filename Filename of the Gencode gtf file Returns ------- df : pandas.DataFrame Dataframe of ...
[ "def", "make_splice_junction_df", "(", "fn", ",", "type", "=", "'gene'", ")", ":", "import", "itertools", "as", "it", "import", "HTSeq", "import", "numpy", "as", "np", "# GFF_Reader has an option for end_included. However, I think it is", "# backwards. So if your gtf is en...
Read the Gencode gtf file and make a pandas dataframe describing the splice junctions Parameters ---------- filename : str of filename Filename of the Gencode gtf file Returns ------- df : pandas.DataFrame Dataframe of splice junctions with the following columns 'gene', ...
[ "Read", "the", "Gencode", "gtf", "file", "and", "make", "a", "pandas", "dataframe", "describing", "the", "splice", "junctions" ]
38efdf0e11d01bc00a135921cb91a19c03db5d5c
https://github.com/cdeboever3/cdpybio/blob/38efdf0e11d01bc00a135921cb91a19c03db5d5c/cdpybio/gencode.py#L402-L489
241,780
rsalmaso/django-fluo
fluo/views/decorators.py
login_required
def login_required(function=None, required=False, redirect_field_name=REDIRECT_FIELD_NAME): """ Decorator for views that, if required, checks that the user is logged in and redirect to the log-in page if necessary. """ if required: if django.VERSION < (1, 11): actual_decorator = ...
python
def login_required(function=None, required=False, redirect_field_name=REDIRECT_FIELD_NAME): """ Decorator for views that, if required, checks that the user is logged in and redirect to the log-in page if necessary. """ if required: if django.VERSION < (1, 11): actual_decorator = ...
[ "def", "login_required", "(", "function", "=", "None", ",", "required", "=", "False", ",", "redirect_field_name", "=", "REDIRECT_FIELD_NAME", ")", ":", "if", "required", ":", "if", "django", ".", "VERSION", "<", "(", "1", ",", "11", ")", ":", "actual_decor...
Decorator for views that, if required, checks that the user is logged in and redirect to the log-in page if necessary.
[ "Decorator", "for", "views", "that", "if", "required", "checks", "that", "the", "user", "is", "logged", "in", "and", "redirect", "to", "the", "log", "-", "in", "page", "if", "necessary", "." ]
1321c1e7d6a912108f79be02a9e7f2108c57f89f
https://github.com/rsalmaso/django-fluo/blob/1321c1e7d6a912108f79be02a9e7f2108c57f89f/fluo/views/decorators.py#L54-L78
241,781
firstprayer/monsql
monsql/db.py
Database.is_table_existed
def is_table_existed(self, tablename): """ Check whether the given table name exists in this database. Return boolean. """ all_tablenames = self.list_tables() tablename = tablename.lower() if tablename in all_tablenames: return True else: ...
python
def is_table_existed(self, tablename): """ Check whether the given table name exists in this database. Return boolean. """ all_tablenames = self.list_tables() tablename = tablename.lower() if tablename in all_tablenames: return True else: ...
[ "def", "is_table_existed", "(", "self", ",", "tablename", ")", ":", "all_tablenames", "=", "self", ".", "list_tables", "(", ")", "tablename", "=", "tablename", ".", "lower", "(", ")", "if", "tablename", "in", "all_tablenames", ":", "return", "True", "else", ...
Check whether the given table name exists in this database. Return boolean.
[ "Check", "whether", "the", "given", "table", "name", "exists", "in", "this", "database", ".", "Return", "boolean", "." ]
6285c15b574c8664046eae2edfeb548c7b173efd
https://github.com/firstprayer/monsql/blob/6285c15b574c8664046eae2edfeb548c7b173efd/monsql/db.py#L97-L107
241,782
firstprayer/monsql
monsql/db.py
Database.drop_table
def drop_table(self, tablename, silent=False): """ Drop a table :Parameters: - tablename: string - slient: boolean. If false and the table doesn't exists an exception will be raised; Otherwise it will be ignored :Return: Nothing """ i...
python
def drop_table(self, tablename, silent=False): """ Drop a table :Parameters: - tablename: string - slient: boolean. If false and the table doesn't exists an exception will be raised; Otherwise it will be ignored :Return: Nothing """ i...
[ "def", "drop_table", "(", "self", ",", "tablename", ",", "silent", "=", "False", ")", ":", "if", "not", "silent", "and", "not", "self", ".", "is_table_existed", "(", "tablename", ")", ":", "raise", "MonSQLException", "(", "'TABLE %s DOES NOT EXIST'", "%", "t...
Drop a table :Parameters: - tablename: string - slient: boolean. If false and the table doesn't exists an exception will be raised; Otherwise it will be ignored :Return: Nothing
[ "Drop", "a", "table" ]
6285c15b574c8664046eae2edfeb548c7b173efd
https://github.com/firstprayer/monsql/blob/6285c15b574c8664046eae2edfeb548c7b173efd/monsql/db.py#L138-L155
241,783
pyvec/pyvodb
pyvodb/cli/calendar.py
calendar
def calendar(ctx, date, agenda, year): """Show a 3-month calendar of meetups. \b date: The date around which the calendar is centered. May be: - YYYY-MM-DD, YY-MM-DD, YYYY-MM or YY-MM (e.g. 2015-08) - MM (e.g. 08): the given month in the current year - pN (e.g. p1): N-th last month ...
python
def calendar(ctx, date, agenda, year): """Show a 3-month calendar of meetups. \b date: The date around which the calendar is centered. May be: - YYYY-MM-DD, YY-MM-DD, YYYY-MM or YY-MM (e.g. 2015-08) - MM (e.g. 08): the given month in the current year - pN (e.g. p1): N-th last month ...
[ "def", "calendar", "(", "ctx", ",", "date", ",", "agenda", ",", "year", ")", ":", "do_full_year", "=", "year", "today", "=", "ctx", ".", "obj", "[", "'now'", "]", ".", "date", "(", ")", "db", "=", "ctx", ".", "obj", "[", "'db'", "]", "term", "=...
Show a 3-month calendar of meetups. \b date: The date around which the calendar is centered. May be: - YYYY-MM-DD, YY-MM-DD, YYYY-MM or YY-MM (e.g. 2015-08) - MM (e.g. 08): the given month in the current year - pN (e.g. p1): N-th last month - +N (e.g. +2): N-th next month ...
[ "Show", "a", "3", "-", "month", "calendar", "of", "meetups", "." ]
07183333df26eb12c5c2b98802cde3fb3a6c1339
https://github.com/pyvec/pyvodb/blob/07183333df26eb12c5c2b98802cde3fb3a6c1339/pyvodb/cli/calendar.py#L15-L57
241,784
Noneus/slojsonrpc
slojsonrpc/__init__.py
SLOJSONRPC.register
def register(self, obj): ''' register all methods for of an object as json rpc methods obj - object with methods ''' for method in dir(obj): #ignore private methods if not method.startswith('_'): fct = getattr(obj, method) ...
python
def register(self, obj): ''' register all methods for of an object as json rpc methods obj - object with methods ''' for method in dir(obj): #ignore private methods if not method.startswith('_'): fct = getattr(obj, method) ...
[ "def", "register", "(", "self", ",", "obj", ")", ":", "for", "method", "in", "dir", "(", "obj", ")", ":", "#ignore private methods", "if", "not", "method", ".", "startswith", "(", "'_'", ")", ":", "fct", "=", "getattr", "(", "obj", ",", "method", ")"...
register all methods for of an object as json rpc methods obj - object with methods
[ "register", "all", "methods", "for", "of", "an", "object", "as", "json", "rpc", "methods" ]
33b5d79486e1562fe4fc7b73b8f3014535168b03
https://github.com/Noneus/slojsonrpc/blob/33b5d79486e1562fe4fc7b73b8f3014535168b03/slojsonrpc/__init__.py#L139-L159
241,785
Noneus/slojsonrpc
slojsonrpc/__init__.py
SLOJSONRPC._validate_format
def _validate_format(req): ''' Validate jsonrpc compliance of a jsonrpc-dict. req - the request as a jsonrpc-dict raises SLOJSONRPCError on validation error ''' #check for all required keys for key in SLOJSONRPC._min_keys: if not key in req: ...
python
def _validate_format(req): ''' Validate jsonrpc compliance of a jsonrpc-dict. req - the request as a jsonrpc-dict raises SLOJSONRPCError on validation error ''' #check for all required keys for key in SLOJSONRPC._min_keys: if not key in req: ...
[ "def", "_validate_format", "(", "req", ")", ":", "#check for all required keys", "for", "key", "in", "SLOJSONRPC", ".", "_min_keys", ":", "if", "not", "key", "in", "req", ":", "logging", ".", "debug", "(", "'JSONRPC: Fmt Error: Need key \"%s\"'", "%", "key", ")"...
Validate jsonrpc compliance of a jsonrpc-dict. req - the request as a jsonrpc-dict raises SLOJSONRPCError on validation error
[ "Validate", "jsonrpc", "compliance", "of", "a", "jsonrpc", "-", "dict", "." ]
33b5d79486e1562fe4fc7b73b8f3014535168b03
https://github.com/Noneus/slojsonrpc/blob/33b5d79486e1562fe4fc7b73b8f3014535168b03/slojsonrpc/__init__.py#L169-L192
241,786
Noneus/slojsonrpc
slojsonrpc/__init__.py
SLOJSONRPC._validate_params
def _validate_params(self, req): ''' Validate parameters of a jsonrpc-request. req - request as a jsonrpc-dict raises SLOJSONRPCError on validation error ''' #does the method exist? method = req['method'] if not method in self._methods: rais...
python
def _validate_params(self, req): ''' Validate parameters of a jsonrpc-request. req - request as a jsonrpc-dict raises SLOJSONRPCError on validation error ''' #does the method exist? method = req['method'] if not method in self._methods: rais...
[ "def", "_validate_params", "(", "self", ",", "req", ")", ":", "#does the method exist?", "method", "=", "req", "[", "'method'", "]", "if", "not", "method", "in", "self", ".", "_methods", ":", "raise", "SLOJSONRPCError", "(", "-", "32601", ")", "fct", "=", ...
Validate parameters of a jsonrpc-request. req - request as a jsonrpc-dict raises SLOJSONRPCError on validation error
[ "Validate", "parameters", "of", "a", "jsonrpc", "-", "request", "." ]
33b5d79486e1562fe4fc7b73b8f3014535168b03
https://github.com/Noneus/slojsonrpc/blob/33b5d79486e1562fe4fc7b73b8f3014535168b03/slojsonrpc/__init__.py#L194-L259
241,787
Noneus/slojsonrpc
slojsonrpc/__init__.py
SLOJSONRPC.handle_request
def handle_request(self, req, validate=True): ''' handle a jsonrpc request req - request as jsonrpc-dict validate - validate the request? (default: True) returns jsonrpc-dict with result or error ''' #result that will be filled and returned res = {'json...
python
def handle_request(self, req, validate=True): ''' handle a jsonrpc request req - request as jsonrpc-dict validate - validate the request? (default: True) returns jsonrpc-dict with result or error ''' #result that will be filled and returned res = {'json...
[ "def", "handle_request", "(", "self", ",", "req", ",", "validate", "=", "True", ")", ":", "#result that will be filled and returned", "res", "=", "{", "'jsonrpc'", ":", "'2.0'", ",", "'id'", ":", "-", "1", ",", "'result'", ":", "None", "}", "logging", ".",...
handle a jsonrpc request req - request as jsonrpc-dict validate - validate the request? (default: True) returns jsonrpc-dict with result or error
[ "handle", "a", "jsonrpc", "request" ]
33b5d79486e1562fe4fc7b73b8f3014535168b03
https://github.com/Noneus/slojsonrpc/blob/33b5d79486e1562fe4fc7b73b8f3014535168b03/slojsonrpc/__init__.py#L261-L334
241,788
Noneus/slojsonrpc
slojsonrpc/__init__.py
SLOJSONRPC.handle_string
def handle_string(self, strreq): ''' Handle a string representing a jsonrpc-request strreq - jsonrpc-request as a string returns jsonrpc-response as a string ''' #convert to jsonrpc-dict req = None try: req = json.loads(strreq) excep...
python
def handle_string(self, strreq): ''' Handle a string representing a jsonrpc-request strreq - jsonrpc-request as a string returns jsonrpc-response as a string ''' #convert to jsonrpc-dict req = None try: req = json.loads(strreq) excep...
[ "def", "handle_string", "(", "self", ",", "strreq", ")", ":", "#convert to jsonrpc-dict", "req", "=", "None", "try", ":", "req", "=", "json", ".", "loads", "(", "strreq", ")", "except", ":", "logging", ".", "debug", "(", "'JSONRPC: Format Exception:'", ")", ...
Handle a string representing a jsonrpc-request strreq - jsonrpc-request as a string returns jsonrpc-response as a string
[ "Handle", "a", "string", "representing", "a", "jsonrpc", "-", "request" ]
33b5d79486e1562fe4fc7b73b8f3014535168b03
https://github.com/Noneus/slojsonrpc/blob/33b5d79486e1562fe4fc7b73b8f3014535168b03/slojsonrpc/__init__.py#L336-L376
241,789
sunlightlabs/django-locksmith
locksmith/hub/views.py
report_calls
def report_calls(request): ''' POST endpoint for APIs to report their statistics requires parameters: api, key, calls, date, endpoint & signature if 'api' or 'key' parameter is invalid returns a 404 if signature is bad returns a 400 returns a 200 with content 'OK' if call s...
python
def report_calls(request): ''' POST endpoint for APIs to report their statistics requires parameters: api, key, calls, date, endpoint & signature if 'api' or 'key' parameter is invalid returns a 404 if signature is bad returns a 400 returns a 200 with content 'OK' if call s...
[ "def", "report_calls", "(", "request", ")", ":", "api_obj", "=", "get_object_or_404", "(", "Api", ",", "name", "=", "request", ".", "POST", "[", "'api'", "]", ")", "# check the signature", "if", "get_signature", "(", "request", ".", "POST", ",", "api_obj", ...
POST endpoint for APIs to report their statistics requires parameters: api, key, calls, date, endpoint & signature if 'api' or 'key' parameter is invalid returns a 404 if signature is bad returns a 400 returns a 200 with content 'OK' if call succeeds
[ "POST", "endpoint", "for", "APIs", "to", "report", "their", "statistics" ]
eef5b7c25404560aaad50b6e622594f89239b74b
https://github.com/sunlightlabs/django-locksmith/blob/eef5b7c25404560aaad50b6e622594f89239b74b/locksmith/hub/views.py#L23-L55
241,790
sunlightlabs/django-locksmith
locksmith/hub/views.py
check_key
def check_key(request): ''' POST endpoint determining whether or not a key exists and is valid ''' api_objs = list(Api.objects.filter(name=request.POST['api'])) if not api_objs: return HttpResponseBadRequest('Must specify valid API') # check the signature if get_signature(reques...
python
def check_key(request): ''' POST endpoint determining whether or not a key exists and is valid ''' api_objs = list(Api.objects.filter(name=request.POST['api'])) if not api_objs: return HttpResponseBadRequest('Must specify valid API') # check the signature if get_signature(reques...
[ "def", "check_key", "(", "request", ")", ":", "api_objs", "=", "list", "(", "Api", ".", "objects", ".", "filter", "(", "name", "=", "request", ".", "POST", "[", "'api'", "]", ")", ")", "if", "not", "api_objs", ":", "return", "HttpResponseBadRequest", "...
POST endpoint determining whether or not a key exists and is valid
[ "POST", "endpoint", "determining", "whether", "or", "not", "a", "key", "exists", "and", "is", "valid" ]
eef5b7c25404560aaad50b6e622594f89239b74b
https://github.com/sunlightlabs/django-locksmith/blob/eef5b7c25404560aaad50b6e622594f89239b74b/locksmith/hub/views.py#L81-L95
241,791
sunlightlabs/django-locksmith
locksmith/hub/views.py
register
def register(request, email_template='locksmith/registration_email.txt', registration_template=getattr(settings, 'LOCKSMITH_REGISTER_TEMPLATE', 'locksmith/register.html'), registered_template=getattr(settings, 'LOCKSMITH_REGISTERED_TEMPLATE', 'locksmith/registered.html'), ...
python
def register(request, email_template='locksmith/registration_email.txt', registration_template=getattr(settings, 'LOCKSMITH_REGISTER_TEMPLATE', 'locksmith/register.html'), registered_template=getattr(settings, 'LOCKSMITH_REGISTERED_TEMPLATE', 'locksmith/registered.html'), ...
[ "def", "register", "(", "request", ",", "email_template", "=", "'locksmith/registration_email.txt'", ",", "registration_template", "=", "getattr", "(", "settings", ",", "'LOCKSMITH_REGISTER_TEMPLATE'", ",", "'locksmith/register.html'", ")", ",", "registered_template", "=", ...
API registration view displays/validates form and sends email on successful submission
[ "API", "registration", "view" ]
eef5b7c25404560aaad50b6e622594f89239b74b
https://github.com/sunlightlabs/django-locksmith/blob/eef5b7c25404560aaad50b6e622594f89239b74b/locksmith/hub/views.py#L98-L120
241,792
sunlightlabs/django-locksmith
locksmith/hub/views.py
confirm_registration
def confirm_registration(request, key, template="locksmith/confirmed.html"): ''' API key confirmation visiting this URL marks a Key as ready for use ''' context = {'LOCKSMITH_BASE_TEMPLATE': settings.LOCKSMITH_BASE_TEMPLATE} try: context['key'] = key_obj = Key.objects.get(key=ke...
python
def confirm_registration(request, key, template="locksmith/confirmed.html"): ''' API key confirmation visiting this URL marks a Key as ready for use ''' context = {'LOCKSMITH_BASE_TEMPLATE': settings.LOCKSMITH_BASE_TEMPLATE} try: context['key'] = key_obj = Key.objects.get(key=ke...
[ "def", "confirm_registration", "(", "request", ",", "key", ",", "template", "=", "\"locksmith/confirmed.html\"", ")", ":", "context", "=", "{", "'LOCKSMITH_BASE_TEMPLATE'", ":", "settings", ".", "LOCKSMITH_BASE_TEMPLATE", "}", "try", ":", "context", "[", "'key'", ...
API key confirmation visiting this URL marks a Key as ready for use
[ "API", "key", "confirmation" ]
eef5b7c25404560aaad50b6e622594f89239b74b
https://github.com/sunlightlabs/django-locksmith/blob/eef5b7c25404560aaad50b6e622594f89239b74b/locksmith/hub/views.py#L158-L176
241,793
sunlightlabs/django-locksmith
locksmith/hub/views.py
profile
def profile(request): ''' Viewing of signup details and editing of password ''' context = {} if request.method == 'POST': form = PasswordChangeForm(request.user, request.POST) if form.is_valid(): form.save() messages.info(request, 'Password Changed.') ...
python
def profile(request): ''' Viewing of signup details and editing of password ''' context = {} if request.method == 'POST': form = PasswordChangeForm(request.user, request.POST) if form.is_valid(): form.save() messages.info(request, 'Password Changed.') ...
[ "def", "profile", "(", "request", ")", ":", "context", "=", "{", "}", "if", "request", ".", "method", "==", "'POST'", ":", "form", "=", "PasswordChangeForm", "(", "request", ".", "user", ",", "request", ".", "POST", ")", "if", "form", ".", "is_valid", ...
Viewing of signup details and editing of password
[ "Viewing", "of", "signup", "details", "and", "editing", "of", "password" ]
eef5b7c25404560aaad50b6e622594f89239b74b
https://github.com/sunlightlabs/django-locksmith/blob/eef5b7c25404560aaad50b6e622594f89239b74b/locksmith/hub/views.py#L180-L208
241,794
sunlightlabs/django-locksmith
locksmith/hub/views.py
_dictlist_to_lists
def _dictlist_to_lists(dl, *keys): ''' convert a list of dictionaries to a dictionary of lists >>> dl = [{'a': 'test', 'b': 3}, {'a': 'zaz', 'b': 444}, {'a': 'wow', 'b': 300}] >>> _dictlist_to_lists(dl) (['test', 'zaz', 'wow'], [3, 444, 300]) ''' lists = [] for k in keys: ...
python
def _dictlist_to_lists(dl, *keys): ''' convert a list of dictionaries to a dictionary of lists >>> dl = [{'a': 'test', 'b': 3}, {'a': 'zaz', 'b': 444}, {'a': 'wow', 'b': 300}] >>> _dictlist_to_lists(dl) (['test', 'zaz', 'wow'], [3, 444, 300]) ''' lists = [] for k in keys: ...
[ "def", "_dictlist_to_lists", "(", "dl", ",", "*", "keys", ")", ":", "lists", "=", "[", "]", "for", "k", "in", "keys", ":", "lists", ".", "append", "(", "[", "]", ")", "for", "item", "in", "dl", ":", "for", "i", ",", "key", "in", "enumerate", "(...
convert a list of dictionaries to a dictionary of lists >>> dl = [{'a': 'test', 'b': 3}, {'a': 'zaz', 'b': 444}, {'a': 'wow', 'b': 300}] >>> _dictlist_to_lists(dl) (['test', 'zaz', 'wow'], [3, 444, 300])
[ "convert", "a", "list", "of", "dictionaries", "to", "a", "dictionary", "of", "lists" ]
eef5b7c25404560aaad50b6e622594f89239b74b
https://github.com/sunlightlabs/django-locksmith/blob/eef5b7c25404560aaad50b6e622594f89239b74b/locksmith/hub/views.py#L212-L229
241,795
sunlightlabs/django-locksmith
locksmith/hub/views.py
_cumulative_by_date
def _cumulative_by_date(model, datefield): ''' Given a model and date field, generate monthly cumulative totals. ''' monthly_counts = defaultdict(int) for obj in model.objects.all().order_by(datefield): datevalue = getattr(obj, datefield) monthkey = (datevalue.year, datevalue.mon...
python
def _cumulative_by_date(model, datefield): ''' Given a model and date field, generate monthly cumulative totals. ''' monthly_counts = defaultdict(int) for obj in model.objects.all().order_by(datefield): datevalue = getattr(obj, datefield) monthkey = (datevalue.year, datevalue.mon...
[ "def", "_cumulative_by_date", "(", "model", ",", "datefield", ")", ":", "monthly_counts", "=", "defaultdict", "(", "int", ")", "for", "obj", "in", "model", ".", "objects", ".", "all", "(", ")", ".", "order_by", "(", "datefield", ")", ":", "datevalue", "=...
Given a model and date field, generate monthly cumulative totals.
[ "Given", "a", "model", "and", "date", "field", "generate", "monthly", "cumulative", "totals", "." ]
eef5b7c25404560aaad50b6e622594f89239b74b
https://github.com/sunlightlabs/django-locksmith/blob/eef5b7c25404560aaad50b6e622594f89239b74b/locksmith/hub/views.py#L231-L254
241,796
luismasuelli/python-cantrips
cantrips/types/exception.py
factory
def factory(codes, base=_Exception): """ Creates a custom exception class with arbitrary error codes and arguments. """ if not issubclass(base, _Exception): raise FactoryException("Invalid class passed as parent: Must be a subclass of an Exception class created with this function", ...
python
def factory(codes, base=_Exception): """ Creates a custom exception class with arbitrary error codes and arguments. """ if not issubclass(base, _Exception): raise FactoryException("Invalid class passed as parent: Must be a subclass of an Exception class created with this function", ...
[ "def", "factory", "(", "codes", ",", "base", "=", "_Exception", ")", ":", "if", "not", "issubclass", "(", "base", ",", "_Exception", ")", ":", "raise", "FactoryException", "(", "\"Invalid class passed as parent: Must be a subclass of an Exception class created with this f...
Creates a custom exception class with arbitrary error codes and arguments.
[ "Creates", "a", "custom", "exception", "class", "with", "arbitrary", "error", "codes", "and", "arguments", "." ]
dba2742c1d1a60863bb65f4a291464f6e68eb2ee
https://github.com/luismasuelli/python-cantrips/blob/dba2742c1d1a60863bb65f4a291464f6e68eb2ee/cantrips/types/exception.py#L11-L37
241,797
hactar-is/frink
frink/orm.py
InstanceLayerMixin.save
def save(self): """ Save the current instance to the DB """ with rconnect() as conn: try: self.validate() except ValidationError as e: log.warn(e.messages) raise except ModelValidationError as e: ...
python
def save(self): """ Save the current instance to the DB """ with rconnect() as conn: try: self.validate() except ValidationError as e: log.warn(e.messages) raise except ModelValidationError as e: ...
[ "def", "save", "(", "self", ")", ":", "with", "rconnect", "(", ")", "as", "conn", ":", "try", ":", "self", ".", "validate", "(", ")", "except", "ValidationError", "as", "e", ":", "log", ".", "warn", "(", "e", ".", "messages", ")", "raise", "except"...
Save the current instance to the DB
[ "Save", "the", "current", "instance", "to", "the", "DB" ]
0d2c11daca8ef6d4365e98914bdc0bc65478ae72
https://github.com/hactar-is/frink/blob/0d2c11daca8ef6d4365e98914bdc0bc65478ae72/frink/orm.py#L33-L90
241,798
hactar-is/frink
frink/orm.py
InstanceLayerMixin.delete
def delete(self): """ Delete the current instance from the DB. """ with rconnect() as conn: # Can't delete an object without an ID. if self.id is None: raise FrinkError("You can't delete an object with no ID") else: ...
python
def delete(self): """ Delete the current instance from the DB. """ with rconnect() as conn: # Can't delete an object without an ID. if self.id is None: raise FrinkError("You can't delete an object with no ID") else: ...
[ "def", "delete", "(", "self", ")", ":", "with", "rconnect", "(", ")", "as", "conn", ":", "# Can't delete an object without an ID.", "if", "self", ".", "id", "is", "None", ":", "raise", "FrinkError", "(", "\"You can't delete an object with no ID\"", ")", "else", ...
Delete the current instance from the DB.
[ "Delete", "the", "current", "instance", "from", "the", "DB", "." ]
0d2c11daca8ef6d4365e98914bdc0bc65478ae72
https://github.com/hactar-is/frink/blob/0d2c11daca8ef6d4365e98914bdc0bc65478ae72/frink/orm.py#L92-L118
241,799
hactar-is/frink
frink/orm.py
ORMLayer.get
def get(self, id): """ Get a single instance by pk id. :param id: The UUID of the instance you want to retrieve. """ with rconnect() as conn: if id is None: raise ValueError if isinstance(id, uuid.UUID): id = str(...
python
def get(self, id): """ Get a single instance by pk id. :param id: The UUID of the instance you want to retrieve. """ with rconnect() as conn: if id is None: raise ValueError if isinstance(id, uuid.UUID): id = str(...
[ "def", "get", "(", "self", ",", "id", ")", ":", "with", "rconnect", "(", ")", "as", "conn", ":", "if", "id", "is", "None", ":", "raise", "ValueError", "if", "isinstance", "(", "id", ",", "uuid", ".", "UUID", ")", ":", "id", "=", "str", "(", "id...
Get a single instance by pk id. :param id: The UUID of the instance you want to retrieve.
[ "Get", "a", "single", "instance", "by", "pk", "id", "." ]
0d2c11daca8ef6d4365e98914bdc0bc65478ae72
https://github.com/hactar-is/frink/blob/0d2c11daca8ef6d4365e98914bdc0bc65478ae72/frink/orm.py#L148-L178