repository_name stringlengths 7 55 | func_path_in_repository stringlengths 4 223 | func_name stringlengths 1 134 | whole_func_string stringlengths 75 104k | language stringclasses 1
value | func_code_string stringlengths 75 104k | func_code_tokens listlengths 19 28.4k | func_documentation_string stringlengths 1 46.9k | func_documentation_tokens listlengths 1 1.97k | split_name stringclasses 1
value | func_code_url stringlengths 87 315 |
|---|---|---|---|---|---|---|---|---|---|---|
inveniosoftware-attic/invenio-knowledge | invenio_knowledge/manage.py | main | def main():
"""Run manager."""
from invenio_base.factory import create_app
app = create_app()
manager.app = app
manager.run() | python | def main():
"""Run manager."""
from invenio_base.factory import create_app
app = create_app()
manager.app = app
manager.run() | [
"def",
"main",
"(",
")",
":",
"from",
"invenio_base",
".",
"factory",
"import",
"create_app",
"app",
"=",
"create_app",
"(",
")",
"manager",
".",
"app",
"=",
"app",
"manager",
".",
"run",
"(",
")"
] | Run manager. | [
"Run",
"manager",
"."
] | train | https://github.com/inveniosoftware-attic/invenio-knowledge/blob/b31722dc14243ca8f626f8b3bce9718d0119de55/invenio_knowledge/manage.py#L86-L91 |
FlorianLudwig/rueckenwind | rw/cli.py | command | def command(func):
"""Decorator for CLI exposed functions"""
func.parser = SUB_PARSER.add_parser(func.__name__, help=func.__doc__)
func.parser.set_defaults(func=func)
return func | python | def command(func):
"""Decorator for CLI exposed functions"""
func.parser = SUB_PARSER.add_parser(func.__name__, help=func.__doc__)
func.parser.set_defaults(func=func)
return func | [
"def",
"command",
"(",
"func",
")",
":",
"func",
".",
"parser",
"=",
"SUB_PARSER",
".",
"add_parser",
"(",
"func",
".",
"__name__",
",",
"help",
"=",
"func",
".",
"__doc__",
")",
"func",
".",
"parser",
".",
"set_defaults",
"(",
"func",
"=",
"func",
"... | Decorator for CLI exposed functions | [
"Decorator",
"for",
"CLI",
"exposed",
"functions"
] | train | https://github.com/FlorianLudwig/rueckenwind/blob/47fec7af05ea10b3cf6d59b9f7bf4d12c02dddea/rw/cli.py#L45-L49 |
FlorianLudwig/rueckenwind | rw/cli.py | serv | def serv(args):
"""Serve a rueckenwind application"""
if not args.no_debug:
tornado.autoreload.start()
extra = []
if sys.stdout.isatty():
# set terminal title
sys.stdout.write('\x1b]2;rw: {}\x07'.format(' '.join(sys.argv[2:])))
if args.cfg:
extra.append(os.path.abs... | python | def serv(args):
"""Serve a rueckenwind application"""
if not args.no_debug:
tornado.autoreload.start()
extra = []
if sys.stdout.isatty():
# set terminal title
sys.stdout.write('\x1b]2;rw: {}\x07'.format(' '.join(sys.argv[2:])))
if args.cfg:
extra.append(os.path.abs... | [
"def",
"serv",
"(",
"args",
")",
":",
"if",
"not",
"args",
".",
"no_debug",
":",
"tornado",
".",
"autoreload",
".",
"start",
"(",
")",
"extra",
"=",
"[",
"]",
"if",
"sys",
".",
"stdout",
".",
"isatty",
"(",
")",
":",
"# set terminal title",
"sys",
... | Serve a rueckenwind application | [
"Serve",
"a",
"rueckenwind",
"application"
] | train | https://github.com/FlorianLudwig/rueckenwind/blob/47fec7af05ea10b3cf6d59b9f7bf4d12c02dddea/rw/cli.py#L53-L71 |
FlorianLudwig/rueckenwind | rw/cli.py | main | def main():
"""Entry point of rw cli"""
# check logging
log_level = os.environ.get('LOG_LEVEL', 'INFO')
logging.basicConfig(level=getattr(logging, log_level),
format='%(asctime)s %(name)s[%(levelname)s] %(message)s',
datefmt='%Y-%m-%d %H:%M:%S')
curre... | python | def main():
"""Entry point of rw cli"""
# check logging
log_level = os.environ.get('LOG_LEVEL', 'INFO')
logging.basicConfig(level=getattr(logging, log_level),
format='%(asctime)s %(name)s[%(levelname)s] %(message)s',
datefmt='%Y-%m-%d %H:%M:%S')
curre... | [
"def",
"main",
"(",
")",
":",
"# check logging",
"log_level",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'LOG_LEVEL'",
",",
"'INFO'",
")",
"logging",
".",
"basicConfig",
"(",
"level",
"=",
"getattr",
"(",
"logging",
",",
"log_level",
")",
",",
"format"... | Entry point of rw cli | [
"Entry",
"point",
"of",
"rw",
"cli"
] | train | https://github.com/FlorianLudwig/rueckenwind/blob/47fec7af05ea10b3cf6d59b9f7bf4d12c02dddea/rw/cli.py#L113-L126 |
jkawamoto/dsargparse | dsargparse.py | _checker | def _checker(keywords):
"""Generate a checker which tests a given value not starts with keywords."""
def _(v):
"""Check a given value matches to keywords."""
for k in keywords:
if k in v:
return False
return True
return _ | python | def _checker(keywords):
"""Generate a checker which tests a given value not starts with keywords."""
def _(v):
"""Check a given value matches to keywords."""
for k in keywords:
if k in v:
return False
return True
return _ | [
"def",
"_checker",
"(",
"keywords",
")",
":",
"def",
"_",
"(",
"v",
")",
":",
"\"\"\"Check a given value matches to keywords.\"\"\"",
"for",
"k",
"in",
"keywords",
":",
"if",
"k",
"in",
"v",
":",
"return",
"False",
"return",
"True",
"return",
"_"
] | Generate a checker which tests a given value not starts with keywords. | [
"Generate",
"a",
"checker",
"which",
"tests",
"a",
"given",
"value",
"not",
"starts",
"with",
"keywords",
"."
] | train | https://github.com/jkawamoto/dsargparse/blob/dbbcea11ff1ae7b84bdfccb9f97d1947574e4126/dsargparse.py#L37-L45 |
jkawamoto/dsargparse | dsargparse.py | _parse_doc | def _parse_doc(doc):
"""Parse a docstring.
Parse a docstring and extract three components; headline, description,
and map of arguments to help texts.
Args:
doc: docstring.
Returns:
a dictionary.
"""
lines = doc.split("\n")
descriptions = list(itertools.takewhile(_checker(_... | python | def _parse_doc(doc):
"""Parse a docstring.
Parse a docstring and extract three components; headline, description,
and map of arguments to help texts.
Args:
doc: docstring.
Returns:
a dictionary.
"""
lines = doc.split("\n")
descriptions = list(itertools.takewhile(_checker(_... | [
"def",
"_parse_doc",
"(",
"doc",
")",
":",
"lines",
"=",
"doc",
".",
"split",
"(",
"\"\\n\"",
")",
"descriptions",
"=",
"list",
"(",
"itertools",
".",
"takewhile",
"(",
"_checker",
"(",
"_KEYWORDS",
")",
",",
"lines",
")",
")",
"if",
"len",
"(",
"des... | Parse a docstring.
Parse a docstring and extract three components; headline, description,
and map of arguments to help texts.
Args:
doc: docstring.
Returns:
a dictionary. | [
"Parse",
"a",
"docstring",
"."
] | train | https://github.com/jkawamoto/dsargparse/blob/dbbcea11ff1ae7b84bdfccb9f97d1947574e4126/dsargparse.py#L48-L79 |
jkawamoto/dsargparse | dsargparse.py | _SubparsersWrapper.add_parser | def add_parser(self, func=None, name=None, **kwargs):
"""Add parser.
This method makes a new sub command parser. It takes same arguments
as add_parser() of the action class made by
argparse.ArgumentParser.add_subparsers.
In addition to, it takes one positional argument `func`, ... | python | def add_parser(self, func=None, name=None, **kwargs):
"""Add parser.
This method makes a new sub command parser. It takes same arguments
as add_parser() of the action class made by
argparse.ArgumentParser.add_subparsers.
In addition to, it takes one positional argument `func`, ... | [
"def",
"add_parser",
"(",
"self",
",",
"func",
"=",
"None",
",",
"name",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"func",
":",
"if",
"not",
"func",
".",
"__doc__",
":",
"raise",
"ValueError",
"(",
"\"No docstrings given in {0}\"",
".",
"fo... | Add parser.
This method makes a new sub command parser. It takes same arguments
as add_parser() of the action class made by
argparse.ArgumentParser.add_subparsers.
In addition to, it takes one positional argument `func`, which is the
function implements process of this sub comm... | [
"Add",
"parser",
"."
] | train | https://github.com/jkawamoto/dsargparse/blob/dbbcea11ff1ae7b84bdfccb9f97d1947574e4126/dsargparse.py#L93-L140 |
jkawamoto/dsargparse | dsargparse.py | ArgumentParser.add_argument | def add_argument(self, *args, **kwargs):
"""Add an argument.
This method adds a new argument to the current parser. The function is
same as ``argparse.ArgumentParser.add_argument``. However, this method
tries to determine help messages for the adding argument from some
docstring... | python | def add_argument(self, *args, **kwargs):
"""Add an argument.
This method adds a new argument to the current parser. The function is
same as ``argparse.ArgumentParser.add_argument``. However, this method
tries to determine help messages for the adding argument from some
docstring... | [
"def",
"add_argument",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"_HELP",
"not",
"in",
"kwargs",
":",
"for",
"name",
"in",
"args",
":",
"name",
"=",
"name",
".",
"replace",
"(",
"\"-\"",
",",
"\"\"",
")",
"if",
"name... | Add an argument.
This method adds a new argument to the current parser. The function is
same as ``argparse.ArgumentParser.add_argument``. However, this method
tries to determine help messages for the adding argument from some
docstrings.
If the new arguments belong to some sub ... | [
"Add",
"an",
"argument",
"."
] | train | https://github.com/jkawamoto/dsargparse/blob/dbbcea11ff1ae7b84bdfccb9f97d1947574e4126/dsargparse.py#L183-L208 |
MacHu-GWU/angora-project | angora/markup/html.py | HtmlConstructor.input_ratio | def input_ratio(self, name, choices, labels, multi_line=False):
"""
{% for value, label in [('choice1', '选项1'), ('choice2', '选项2')] %}
{% if ratio == value %}
{% set checked = "checked" %}
{% else %}
{% set checked = "" %}
{% en... | python | def input_ratio(self, name, choices, labels, multi_line=False):
"""
{% for value, label in [('choice1', '选项1'), ('choice2', '选项2')] %}
{% if ratio == value %}
{% set checked = "checked" %}
{% else %}
{% set checked = "" %}
{% en... | [
"def",
"input_ratio",
"(",
"self",
",",
"name",
",",
"choices",
",",
"labels",
",",
"multi_line",
"=",
"False",
")",
":",
"if",
"len",
"(",
"choices",
")",
"!=",
"len",
"(",
"labels",
")",
":",
"raise",
"ValueError",
"(",
"\"The size of 'choices' and 'labe... | {% for value, label in [('choice1', '选项1'), ('choice2', '选项2')] %}
{% if ratio == value %}
{% set checked = "checked" %}
{% else %}
{% set checked = "" %}
{% endif %}
<input type="radio" name="ratio" value="{{value}}" {{checked}} /> {{label... | [
"{",
"%",
"for",
"value",
"label",
"in",
"[",
"(",
"choice1",
"选项1",
")",
"(",
"choice2",
"选项2",
")",
"]",
"%",
"}",
"{",
"%",
"if",
"ratio",
"==",
"value",
"%",
"}",
"{",
"%",
"set",
"checked",
"=",
"checked",
"%",
"}",
"{",
"%",
"else",
"%"... | train | https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/markup/html.py#L54-L83 |
MacHu-GWU/angora-project | angora/markup/html.py | HtmlConstructor.input_check | def input_check(self, name, label, multi_line=False):
"""
{% if multiple_choice_1 %}
{% set checked = "checked" %}
{% else %}
{% set checked = "" %}
{% endif %}
<input type="checkbox" name="multiple_choice_1" value="multiple_choice_1" {{checked}}> multiple... | python | def input_check(self, name, label, multi_line=False):
"""
{% if multiple_choice_1 %}
{% set checked = "checked" %}
{% else %}
{% set checked = "" %}
{% endif %}
<input type="checkbox" name="multiple_choice_1" value="multiple_choice_1" {{checked}}> multiple... | [
"def",
"input_check",
"(",
"self",
",",
"name",
",",
"label",
",",
"multi_line",
"=",
"False",
")",
":",
"lines",
"=",
"list",
"(",
")",
"lines",
".",
"append",
"(",
"'{%% if %s %%}'",
"%",
"name",
")",
"lines",
".",
"append",
"(",
"self",
".",
"tab"... | {% if multiple_choice_1 %}
{% set checked = "checked" %}
{% else %}
{% set checked = "" %}
{% endif %}
<input type="checkbox" name="multiple_choice_1" value="multiple_choice_1" {{checked}}> multiple_choice_1 | [
"{",
"%",
"if",
"multiple_choice_1",
"%",
"}",
"{",
"%",
"set",
"checked",
"=",
"checked",
"%",
"}",
"{",
"%",
"else",
"%",
"}",
"{",
"%",
"set",
"checked",
"=",
"%",
"}",
"{",
"%",
"endif",
"%",
"}",
"<input",
"type",
"=",
"checkbox",
"name",
... | train | https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/markup/html.py#L85-L105 |
JNRowe/jnrbase | jnrbase/xdg_basedir.py | __user_location | def __user_location(__pkg: str, type_) -> str:
"""Utility function to look up XDG basedir locations
Args:
__pkg: Package name
__type: Location type
"""
if ALLOW_DARWIN and sys.platform == 'darwin':
user_dir = '~/Library/{}'.format(__LOCATIONS[type_][0])
else:
user_di... | python | def __user_location(__pkg: str, type_) -> str:
"""Utility function to look up XDG basedir locations
Args:
__pkg: Package name
__type: Location type
"""
if ALLOW_DARWIN and sys.platform == 'darwin':
user_dir = '~/Library/{}'.format(__LOCATIONS[type_][0])
else:
user_di... | [
"def",
"__user_location",
"(",
"__pkg",
":",
"str",
",",
"type_",
")",
"->",
"str",
":",
"if",
"ALLOW_DARWIN",
"and",
"sys",
".",
"platform",
"==",
"'darwin'",
":",
"user_dir",
"=",
"'~/Library/{}'",
".",
"format",
"(",
"__LOCATIONS",
"[",
"type_",
"]",
... | Utility function to look up XDG basedir locations
Args:
__pkg: Package name
__type: Location type | [
"Utility",
"function",
"to",
"look",
"up",
"XDG",
"basedir",
"locations"
] | train | https://github.com/JNRowe/jnrbase/blob/ae505ef69a9feb739b5f4e62c5a8e6533104d3ea/jnrbase/xdg_basedir.py#L38-L51 |
JNRowe/jnrbase | jnrbase/xdg_basedir.py | get_configs | def get_configs(__pkg: str, __name: str = 'config') -> List[str]:
"""Return all configs for given package.
Args:
__pkg: Package name
__name: Configuration file name
"""
dirs = [user_config(__pkg), ]
dirs.extend(path.expanduser(path.sep.join([d, __pkg]))
for d in gete... | python | def get_configs(__pkg: str, __name: str = 'config') -> List[str]:
"""Return all configs for given package.
Args:
__pkg: Package name
__name: Configuration file name
"""
dirs = [user_config(__pkg), ]
dirs.extend(path.expanduser(path.sep.join([d, __pkg]))
for d in gete... | [
"def",
"get_configs",
"(",
"__pkg",
":",
"str",
",",
"__name",
":",
"str",
"=",
"'config'",
")",
"->",
"List",
"[",
"str",
"]",
":",
"dirs",
"=",
"[",
"user_config",
"(",
"__pkg",
")",
",",
"]",
"dirs",
".",
"extend",
"(",
"path",
".",
"expanduser"... | Return all configs for given package.
Args:
__pkg: Package name
__name: Configuration file name | [
"Return",
"all",
"configs",
"for",
"given",
"package",
"."
] | train | https://github.com/JNRowe/jnrbase/blob/ae505ef69a9feb739b5f4e62c5a8e6533104d3ea/jnrbase/xdg_basedir.py#L75-L90 |
JNRowe/jnrbase | jnrbase/xdg_basedir.py | get_data | def get_data(__pkg: str, __name: str) -> str:
"""Return top-most data file for given package.
Args:
__pkg: Package name
__name: Data file name
"""
for dname in get_data_dirs(__pkg):
test_path = path.join(dname, __name)
if path.exists(test_path):
return test_p... | python | def get_data(__pkg: str, __name: str) -> str:
"""Return top-most data file for given package.
Args:
__pkg: Package name
__name: Data file name
"""
for dname in get_data_dirs(__pkg):
test_path = path.join(dname, __name)
if path.exists(test_path):
return test_p... | [
"def",
"get_data",
"(",
"__pkg",
":",
"str",
",",
"__name",
":",
"str",
")",
"->",
"str",
":",
"for",
"dname",
"in",
"get_data_dirs",
"(",
"__pkg",
")",
":",
"test_path",
"=",
"path",
".",
"join",
"(",
"dname",
",",
"__name",
")",
"if",
"path",
"."... | Return top-most data file for given package.
Args:
__pkg: Package name
__name: Data file name | [
"Return",
"top",
"-",
"most",
"data",
"file",
"for",
"given",
"package",
"."
] | train | https://github.com/JNRowe/jnrbase/blob/ae505ef69a9feb739b5f4e62c5a8e6533104d3ea/jnrbase/xdg_basedir.py#L93-L104 |
JNRowe/jnrbase | jnrbase/xdg_basedir.py | get_data_dirs | def get_data_dirs(__pkg: str) -> List[str]:
"""Return all data directories for given package.
Args:
__pkg: Package name
"""
dirs = [user_data(__pkg), ]
dirs.extend(path.expanduser(path.sep.join([d, __pkg]))
for d in getenv('XDG_DATA_DIRS',
'/u... | python | def get_data_dirs(__pkg: str) -> List[str]:
"""Return all data directories for given package.
Args:
__pkg: Package name
"""
dirs = [user_data(__pkg), ]
dirs.extend(path.expanduser(path.sep.join([d, __pkg]))
for d in getenv('XDG_DATA_DIRS',
'/u... | [
"def",
"get_data_dirs",
"(",
"__pkg",
":",
"str",
")",
"->",
"List",
"[",
"str",
"]",
":",
"dirs",
"=",
"[",
"user_data",
"(",
"__pkg",
")",
",",
"]",
"dirs",
".",
"extend",
"(",
"path",
".",
"expanduser",
"(",
"path",
".",
"sep",
".",
"join",
"(... | Return all data directories for given package.
Args:
__pkg: Package name | [
"Return",
"all",
"data",
"directories",
"for",
"given",
"package",
"."
] | train | https://github.com/JNRowe/jnrbase/blob/ae505ef69a9feb739b5f4e62c5a8e6533104d3ea/jnrbase/xdg_basedir.py#L107-L117 |
armenzg/pulse_replay | replay/replay.py | create_consumer | def create_consumer(user, password, config_file_path, process_message, *args, **kwargs):
'''Create a pulse consumer. Call listen() to start listening.'''
queue_config = _read_json_file(filepath=config_file_path)
exchanges = map(lambda x: queue_config['sources'][x]['exchange'], queue_config['sources'].keys(... | python | def create_consumer(user, password, config_file_path, process_message, *args, **kwargs):
'''Create a pulse consumer. Call listen() to start listening.'''
queue_config = _read_json_file(filepath=config_file_path)
exchanges = map(lambda x: queue_config['sources'][x]['exchange'], queue_config['sources'].keys(... | [
"def",
"create_consumer",
"(",
"user",
",",
"password",
",",
"config_file_path",
",",
"process_message",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"queue_config",
"=",
"_read_json_file",
"(",
"filepath",
"=",
"config_file_path",
")",
"exchanges",
"=... | Create a pulse consumer. Call listen() to start listening. | [
"Create",
"a",
"pulse",
"consumer",
".",
"Call",
"listen",
"()",
"to",
"start",
"listening",
"."
] | train | https://github.com/armenzg/pulse_replay/blob/d3fae9f445aaaeb58d17898a597524375e9bf3ce/replay/replay.py#L30-L57 |
armenzg/pulse_replay | replay/replay.py | replay_messages | def replay_messages(filepath, process_message, *args, **kwargs):
''' Take pulse messages from a file and process each with process_message.
:param filepath: File containing dumped pulse messages
:type filepath: str
:param process_message: Function to process each pulse message with
:type process_me... | python | def replay_messages(filepath, process_message, *args, **kwargs):
''' Take pulse messages from a file and process each with process_message.
:param filepath: File containing dumped pulse messages
:type filepath: str
:param process_message: Function to process each pulse message with
:type process_me... | [
"def",
"replay_messages",
"(",
"filepath",
",",
"process_message",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"message",
"=",
"Mock",
"(",
")",
"file_contents",
"=",
"_read_file",
"(",
"filepath",
")",
"for",
"line",
"in",
"file_contents",
".",
... | Take pulse messages from a file and process each with process_message.
:param filepath: File containing dumped pulse messages
:type filepath: str
:param process_message: Function to process each pulse message with
:type process_message: function
:param *args: Arguments to be passed to process_messa... | [
"Take",
"pulse",
"messages",
"from",
"a",
"file",
"and",
"process",
"each",
"with",
"process_message",
"."
] | train | https://github.com/armenzg/pulse_replay/blob/d3fae9f445aaaeb58d17898a597524375e9bf3ce/replay/replay.py#L60-L81 |
robertchase/ergaleia | ergaleia/normalize_path.py | normalize_path | def normalize_path(path, filetype=None, has_filetype=True):
""" Convert dot-separated paths to directory paths
Allows non-python files to be placed in the PYTHONPATH and be referenced
using dot-notation instead of absolute or relative file-system paths.
If a text file, named test.txt was placed in a p... | python | def normalize_path(path, filetype=None, has_filetype=True):
""" Convert dot-separated paths to directory paths
Allows non-python files to be placed in the PYTHONPATH and be referenced
using dot-notation instead of absolute or relative file-system paths.
If a text file, named test.txt was placed in a p... | [
"def",
"normalize_path",
"(",
"path",
",",
"filetype",
"=",
"None",
",",
"has_filetype",
"=",
"True",
")",
":",
"if",
"not",
"isinstance",
"(",
"path",
",",
"str",
")",
":",
"return",
"path",
"if",
"'.'",
"in",
"path",
"and",
"os",
".",
"path",
".",
... | Convert dot-separated paths to directory paths
Allows non-python files to be placed in the PYTHONPATH and be referenced
using dot-notation instead of absolute or relative file-system paths.
If a text file, named test.txt was placed in a python repo named myprog in
the module named util, then:
... | [
"Convert",
"dot",
"-",
"separated",
"paths",
"to",
"directory",
"paths"
] | train | https://github.com/robertchase/ergaleia/blob/df8e9a4b18c563022a503faa27e822c9a5755490/ergaleia/normalize_path.py#L17-L65 |
HazardDede/dictmentor | dictmentor/utils.py | dict_find_pattern | def dict_find_pattern(_dict: Dict[Any, Any], pattern: str, search_in_keys: bool = True,
search_in_values: bool = True) -> PatternGenerator:
"""
Find keys and values in a (nested) dictionary with regular expression pattern.
Examples:
>>> from collections import OrderedDict
... | python | def dict_find_pattern(_dict: Dict[Any, Any], pattern: str, search_in_keys: bool = True,
search_in_values: bool = True) -> PatternGenerator:
"""
Find keys and values in a (nested) dictionary with regular expression pattern.
Examples:
>>> from collections import OrderedDict
... | [
"def",
"dict_find_pattern",
"(",
"_dict",
":",
"Dict",
"[",
"Any",
",",
"Any",
"]",
",",
"pattern",
":",
"str",
",",
"search_in_keys",
":",
"bool",
"=",
"True",
",",
"search_in_values",
":",
"bool",
"=",
"True",
")",
"->",
"PatternGenerator",
":",
"def",... | Find keys and values in a (nested) dictionary with regular expression pattern.
Examples:
>>> from collections import OrderedDict
>>> d = OrderedDict((
... ('foo', 'bar'),
... ('bar', 'baz'),
... ('nested', dict(p1=1, p2=2)),
... ('lst', ['bar', 'foo', ... | [
"Find",
"keys",
"and",
"values",
"in",
"a",
"(",
"nested",
")",
"dictionary",
"with",
"regular",
"expression",
"pattern",
".",
"Examples",
":",
">>>",
"from",
"collections",
"import",
"OrderedDict",
">>>",
"d",
"=",
"OrderedDict",
"((",
"...",
"(",
"foo",
... | train | https://github.com/HazardDede/dictmentor/blob/f50ca26ed04f7a924cde6e4d464c4f6ccba4e320/dictmentor/utils.py#L15-L66 |
HazardDede/dictmentor | dictmentor/utils.py | modified_environ | def modified_environ(*remove: str, **update: str) -> Iterator[None]:
"""
Temporarily updates the ``os.environ`` dictionary in-place and resets it to the original state
when finished.
(https://stackoverflow.com/questions/2059482/
python-temporarily-modify-the-current-processs-environment/34333710... | python | def modified_environ(*remove: str, **update: str) -> Iterator[None]:
"""
Temporarily updates the ``os.environ`` dictionary in-place and resets it to the original state
when finished.
(https://stackoverflow.com/questions/2059482/
python-temporarily-modify-the-current-processs-environment/34333710... | [
"def",
"modified_environ",
"(",
"*",
"remove",
":",
"str",
",",
"*",
"*",
"update",
":",
"str",
")",
"->",
"Iterator",
"[",
"None",
"]",
":",
"env",
"=",
"os",
".",
"environ",
"update",
"=",
"update",
"or",
"{",
"}",
"remove",
"=",
"remove",
"or",
... | Temporarily updates the ``os.environ`` dictionary in-place and resets it to the original state
when finished.
(https://stackoverflow.com/questions/2059482/
python-temporarily-modify-the-current-processs-environment/34333710#34333710)
The ``os.environ`` dictionary is updated in-place so that the mod... | [
"Temporarily",
"updates",
"the",
"os",
".",
"environ",
"dictionary",
"in",
"-",
"place",
"and",
"resets",
"it",
"to",
"the",
"original",
"state",
"when",
"finished",
".",
"(",
"https",
":",
"//",
"stackoverflow",
".",
"com",
"/",
"questions",
"/",
"2059482... | train | https://github.com/HazardDede/dictmentor/blob/f50ca26ed04f7a924cde6e4d464c4f6ccba4e320/dictmentor/utils.py#L70-L109 |
HazardDede/dictmentor | dictmentor/utils.py | eval_first_non_none | def eval_first_non_none(eval_list: Iterable[Callable[..., Any]], **kwargs: Any) -> Any:
"""
Executes a list of functions and returns the first non none result. All kwargs will be passed as
kwargs to each individual function. If all functions return None, None is the overall result.
Examples:
>... | python | def eval_first_non_none(eval_list: Iterable[Callable[..., Any]], **kwargs: Any) -> Any:
"""
Executes a list of functions and returns the first non none result. All kwargs will be passed as
kwargs to each individual function. If all functions return None, None is the overall result.
Examples:
>... | [
"def",
"eval_first_non_none",
"(",
"eval_list",
":",
"Iterable",
"[",
"Callable",
"[",
"...",
",",
"Any",
"]",
"]",
",",
"*",
"*",
"kwargs",
":",
"Any",
")",
"->",
"Any",
":",
"Validator",
".",
"is_real_iterable",
"(",
"raise_ex",
"=",
"True",
",",
"ev... | Executes a list of functions and returns the first non none result. All kwargs will be passed as
kwargs to each individual function. If all functions return None, None is the overall result.
Examples:
>>> eval_first_non_none((lambda: None, lambda: None, lambda: 3))
3
>>> print(eval_fir... | [
"Executes",
"a",
"list",
"of",
"functions",
"and",
"returns",
"the",
"first",
"non",
"none",
"result",
".",
"All",
"kwargs",
"will",
"be",
"passed",
"as",
"kwargs",
"to",
"each",
"individual",
"function",
".",
"If",
"all",
"functions",
"return",
"None",
"N... | train | https://github.com/HazardDede/dictmentor/blob/f50ca26ed04f7a924cde6e4d464c4f6ccba4e320/dictmentor/utils.py#L112-L136 |
the01/python-paps | paps/crowd/controller.py | CrowdController.on_person_new | def on_person_new(self, people):
"""
New people joined the audience
:param people: People that just joined the audience
:type people: list[paps.person.Person]
:rtype: None
"""
self.debug("()")
changed = []
with self._people_lock:
for p... | python | def on_person_new(self, people):
"""
New people joined the audience
:param people: People that just joined the audience
:type people: list[paps.person.Person]
:rtype: None
"""
self.debug("()")
changed = []
with self._people_lock:
for p... | [
"def",
"on_person_new",
"(",
"self",
",",
"people",
")",
":",
"self",
".",
"debug",
"(",
"\"()\"",
")",
"changed",
"=",
"[",
"]",
"with",
"self",
".",
"_people_lock",
":",
"for",
"p",
"in",
"people",
":",
"person",
"=",
"Person",
".",
"from_person",
... | New people joined the audience
:param people: People that just joined the audience
:type people: list[paps.person.Person]
:rtype: None | [
"New",
"people",
"joined",
"the",
"audience"
] | train | https://github.com/the01/python-paps/blob/2dde5a71913e4c7b22901cf05c6ecedd890919c4/paps/crowd/controller.py#L49-L74 |
the01/python-paps | paps/crowd/controller.py | CrowdController.on_person_update | def on_person_update(self, people):
"""
People have changed (e.g. a sensor value)
:param people: People whos state changed (may include unchanged)
:type people: list[paps.person.Person]
:rtype: None
"""
self.debug("()")
changed = []
with self._peo... | python | def on_person_update(self, people):
"""
People have changed (e.g. a sensor value)
:param people: People whos state changed (may include unchanged)
:type people: list[paps.person.Person]
:rtype: None
"""
self.debug("()")
changed = []
with self._peo... | [
"def",
"on_person_update",
"(",
"self",
",",
"people",
")",
":",
"self",
".",
"debug",
"(",
"\"()\"",
")",
"changed",
"=",
"[",
"]",
"with",
"self",
".",
"_people_lock",
":",
"for",
"p",
"in",
"people",
":",
"person",
"=",
"Person",
".",
"from_person",... | People have changed (e.g. a sensor value)
:param people: People whos state changed (may include unchanged)
:type people: list[paps.person.Person]
:rtype: None | [
"People",
"have",
"changed",
"(",
"e",
".",
"g",
".",
"a",
"sensor",
"value",
")"
] | train | https://github.com/the01/python-paps/blob/2dde5a71913e4c7b22901cf05c6ecedd890919c4/paps/crowd/controller.py#L102-L126 |
the01/python-paps | paps/crowd/controller.py | CrowdController.start | def start(self, blocking=False):
"""
Start the interface
:param blocking: Should the call block until stop() is called
(default: False)
:type blocking: bool
:rtype: None
"""
self.debug("()")
# Start the plugins
for plugin in self.plugi... | python | def start(self, blocking=False):
"""
Start the interface
:param blocking: Should the call block until stop() is called
(default: False)
:type blocking: bool
:rtype: None
"""
self.debug("()")
# Start the plugins
for plugin in self.plugi... | [
"def",
"start",
"(",
"self",
",",
"blocking",
"=",
"False",
")",
":",
"self",
".",
"debug",
"(",
"\"()\"",
")",
"# Start the plugins",
"for",
"plugin",
"in",
"self",
".",
"plugins",
":",
"try",
":",
"# Inject self into plugin",
"plugin",
".",
"controller",
... | Start the interface
:param blocking: Should the call block until stop() is called
(default: False)
:type blocking: bool
:rtype: None | [
"Start",
"the",
"interface"
] | train | https://github.com/the01/python-paps/blob/2dde5a71913e4c7b22901cf05c6ecedd890919c4/paps/crowd/controller.py#L139-L162 |
the01/python-paps | paps/crowd/controller.py | CrowdController.stop | def stop(self):
"""
Stop the interface
:rtype: None
"""
self.debug("()")
# Stop the plugins
for plugin in self.plugins:
try:
plugin.stop()
except:
self.exception(u"Failed to stop plugin {}".format(plugin.nam... | python | def stop(self):
"""
Stop the interface
:rtype: None
"""
self.debug("()")
# Stop the plugins
for plugin in self.plugins:
try:
plugin.stop()
except:
self.exception(u"Failed to stop plugin {}".format(plugin.nam... | [
"def",
"stop",
"(",
"self",
")",
":",
"self",
".",
"debug",
"(",
"\"()\"",
")",
"# Stop the plugins",
"for",
"plugin",
"in",
"self",
".",
"plugins",
":",
"try",
":",
"plugin",
".",
"stop",
"(",
")",
"except",
":",
"self",
".",
"exception",
"(",
"u\"F... | Stop the interface
:rtype: None | [
"Stop",
"the",
"interface"
] | train | https://github.com/the01/python-paps/blob/2dde5a71913e4c7b22901cf05c6ecedd890919c4/paps/crowd/controller.py#L164-L177 |
hobson/pug-dj | pug/dj/miner/management/commands/modeldb.py | Command.normalize_col_name | def normalize_col_name(self, col_name, used_column_names, is_relation):
"""
Modify the column name to make it Python-compatible as a field name
"""
field_params = {}
field_notes = []
new_name = col_name.lower()
if new_name != col_name:
field_notes.app... | python | def normalize_col_name(self, col_name, used_column_names, is_relation):
"""
Modify the column name to make it Python-compatible as a field name
"""
field_params = {}
field_notes = []
new_name = col_name.lower()
if new_name != col_name:
field_notes.app... | [
"def",
"normalize_col_name",
"(",
"self",
",",
"col_name",
",",
"used_column_names",
",",
"is_relation",
")",
":",
"field_params",
"=",
"{",
"}",
"field_notes",
"=",
"[",
"]",
"new_name",
"=",
"col_name",
".",
"lower",
"(",
")",
"if",
"new_name",
"!=",
"co... | Modify the column name to make it Python-compatible as a field name | [
"Modify",
"the",
"column",
"name",
"to",
"make",
"it",
"Python",
"-",
"compatible",
"as",
"a",
"field",
"name"
] | train | https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/miner/management/commands/modeldb.py#L129-L183 |
hobson/pug-dj | pug/dj/miner/management/commands/modeldb.py | Command.get_field_type | def get_field_type(self, connection, table_name, row):
"""
Given the database connection, the table name, and the cursor row
description, this routine will return the given field type name, as
well as any additional keyword parameters and notes for the field.
"""
field_pa... | python | def get_field_type(self, connection, table_name, row):
"""
Given the database connection, the table name, and the cursor row
description, this routine will return the given field type name, as
well as any additional keyword parameters and notes for the field.
"""
field_pa... | [
"def",
"get_field_type",
"(",
"self",
",",
"connection",
",",
"table_name",
",",
"row",
")",
":",
"field_params",
"=",
"{",
"}",
"field_notes",
"=",
"[",
"]",
"try",
":",
"field_type",
"=",
"connection",
".",
"introspection",
".",
"get_field_type",
"(",
"r... | Given the database connection, the table name, and the cursor row
description, this routine will return the given field type name, as
well as any additional keyword parameters and notes for the field. | [
"Given",
"the",
"database",
"connection",
"the",
"table",
"name",
"and",
"the",
"cursor",
"row",
"description",
"this",
"routine",
"will",
"return",
"the",
"given",
"field",
"type",
"name",
"as",
"well",
"as",
"any",
"additional",
"keyword",
"parameters",
"and... | train | https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/miner/management/commands/modeldb.py#L185-L214 |
firstprayer/monsql | monsql/__init__.py | MonSQL | def MonSQL(host=None, port=None, username=None, password=None, dbname=None, dbpath=None, dbtype=None):
"""
Initialize and return a Database instance
"""
if dbtype is None:
raise MonSQLException('Database type must be specified')
if dbtype == DB_TYPES.MYSQL:
return MySQLDatabase(host, port, username, password,... | python | def MonSQL(host=None, port=None, username=None, password=None, dbname=None, dbpath=None, dbtype=None):
"""
Initialize and return a Database instance
"""
if dbtype is None:
raise MonSQLException('Database type must be specified')
if dbtype == DB_TYPES.MYSQL:
return MySQLDatabase(host, port, username, password,... | [
"def",
"MonSQL",
"(",
"host",
"=",
"None",
",",
"port",
"=",
"None",
",",
"username",
"=",
"None",
",",
"password",
"=",
"None",
",",
"dbname",
"=",
"None",
",",
"dbpath",
"=",
"None",
",",
"dbtype",
"=",
"None",
")",
":",
"if",
"dbtype",
"is",
"... | Initialize and return a Database instance | [
"Initialize",
"and",
"return",
"a",
"Database",
"instance"
] | train | https://github.com/firstprayer/monsql/blob/6285c15b574c8664046eae2edfeb548c7b173efd/monsql/__init__.py#L26-L40 |
damienjones/sculpt-model-tools | sculpt/model_tools/mixins.py | PasswordMixin.check_password | def check_password(self, raw_password):
"""
Returns a boolean of whether the raw_password was correct. Handles
hashing formats behind the scenes.
"""
def setter(raw_password):
self.set_password(raw_password)
self.save(update_fields=[self.PASSWORD_FIELD])
... | python | def check_password(self, raw_password):
"""
Returns a boolean of whether the raw_password was correct. Handles
hashing formats behind the scenes.
"""
def setter(raw_password):
self.set_password(raw_password)
self.save(update_fields=[self.PASSWORD_FIELD])
... | [
"def",
"check_password",
"(",
"self",
",",
"raw_password",
")",
":",
"def",
"setter",
"(",
"raw_password",
")",
":",
"self",
".",
"set_password",
"(",
"raw_password",
")",
"self",
".",
"save",
"(",
"update_fields",
"=",
"[",
"self",
".",
"PASSWORD_FIELD",
... | Returns a boolean of whether the raw_password was correct. Handles
hashing formats behind the scenes. | [
"Returns",
"a",
"boolean",
"of",
"whether",
"the",
"raw_password",
"was",
"correct",
".",
"Handles",
"hashing",
"formats",
"behind",
"the",
"scenes",
"."
] | train | https://github.com/damienjones/sculpt-model-tools/blob/28d5a7d92bd73bcb1016b30736b6b07070e4cc98/sculpt/model_tools/mixins.py#L280-L288 |
s1s5/django_busybody | django_busybody/views.py | MultipleFormMixin.get_form | def get_form(self, key, form_class=None):
"""
Returns an instance of the form to be used in this view.
"""
if form_class is None:
form_class = self.get_form_class(key)
return form_class(**self.get_form_kwargs(key)) | python | def get_form(self, key, form_class=None):
"""
Returns an instance of the form to be used in this view.
"""
if form_class is None:
form_class = self.get_form_class(key)
return form_class(**self.get_form_kwargs(key)) | [
"def",
"get_form",
"(",
"self",
",",
"key",
",",
"form_class",
"=",
"None",
")",
":",
"if",
"form_class",
"is",
"None",
":",
"form_class",
"=",
"self",
".",
"get_form_class",
"(",
"key",
")",
"return",
"form_class",
"(",
"*",
"*",
"self",
".",
"get_for... | Returns an instance of the form to be used in this view. | [
"Returns",
"an",
"instance",
"of",
"the",
"form",
"to",
"be",
"used",
"in",
"this",
"view",
"."
] | train | https://github.com/s1s5/django_busybody/blob/5c6fd89824224f1de1be79ccd9a149f025af1b8f/django_busybody/views.py#L67-L73 |
s1s5/django_busybody | django_busybody/views.py | MultipleFormMixin.get_form_kwargs | def get_form_kwargs(self, key):
"""
Returns the keyword arguments for instantiating the form.
"""
kwargs = {
'initial': self.get_initial(key),
'prefix': self.get_prefix(key),
}
if self.request.method in ('POST', 'PUT'):
kwargs.update({... | python | def get_form_kwargs(self, key):
"""
Returns the keyword arguments for instantiating the form.
"""
kwargs = {
'initial': self.get_initial(key),
'prefix': self.get_prefix(key),
}
if self.request.method in ('POST', 'PUT'):
kwargs.update({... | [
"def",
"get_form_kwargs",
"(",
"self",
",",
"key",
")",
":",
"kwargs",
"=",
"{",
"'initial'",
":",
"self",
".",
"get_initial",
"(",
"key",
")",
",",
"'prefix'",
":",
"self",
".",
"get_prefix",
"(",
"key",
")",
",",
"}",
"if",
"self",
".",
"request",
... | Returns the keyword arguments for instantiating the form. | [
"Returns",
"the",
"keyword",
"arguments",
"for",
"instantiating",
"the",
"form",
"."
] | train | https://github.com/s1s5/django_busybody/blob/5c6fd89824224f1de1be79ccd9a149f025af1b8f/django_busybody/views.py#L75-L89 |
s1s5/django_busybody | django_busybody/views.py | MultipleFormMixin.get_context_data | def get_context_data(self, **kwargs):
"""
Insert the form into the context dict.
"""
for key in self.get_form_class_keys():
kwargs['{}_form'.format(key)] = self.get_form(key)
return super(FormMixin, self).get_context_data(**kwargs) | python | def get_context_data(self, **kwargs):
"""
Insert the form into the context dict.
"""
for key in self.get_form_class_keys():
kwargs['{}_form'.format(key)] = self.get_form(key)
return super(FormMixin, self).get_context_data(**kwargs) | [
"def",
"get_context_data",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"key",
"in",
"self",
".",
"get_form_class_keys",
"(",
")",
":",
"kwargs",
"[",
"'{}_form'",
".",
"format",
"(",
"key",
")",
"]",
"=",
"self",
".",
"get_form",
"(",
"key... | Insert the form into the context dict. | [
"Insert",
"the",
"form",
"into",
"the",
"context",
"dict",
"."
] | train | https://github.com/s1s5/django_busybody/blob/5c6fd89824224f1de1be79ccd9a149f025af1b8f/django_busybody/views.py#L100-L106 |
s1s5/django_busybody | django_busybody/views.py | MultipleModelFormMixin.get_form_kwargs | def get_form_kwargs(self, key):
"""
Returns the keyword arguments for instantiating the form.
"""
kwargs = super(MultipleModelFormMixin, self).get_form_kwargs(key)
if hasattr(self, '{}_object'.format(key)):
kwargs.update({'instance': getattr(self, '{}_object'.format(k... | python | def get_form_kwargs(self, key):
"""
Returns the keyword arguments for instantiating the form.
"""
kwargs = super(MultipleModelFormMixin, self).get_form_kwargs(key)
if hasattr(self, '{}_object'.format(key)):
kwargs.update({'instance': getattr(self, '{}_object'.format(k... | [
"def",
"get_form_kwargs",
"(",
"self",
",",
"key",
")",
":",
"kwargs",
"=",
"super",
"(",
"MultipleModelFormMixin",
",",
"self",
")",
".",
"get_form_kwargs",
"(",
"key",
")",
"if",
"hasattr",
"(",
"self",
",",
"'{}_object'",
".",
"format",
"(",
"key",
")... | Returns the keyword arguments for instantiating the form. | [
"Returns",
"the",
"keyword",
"arguments",
"for",
"instantiating",
"the",
"form",
"."
] | train | https://github.com/s1s5/django_busybody/blob/5c6fd89824224f1de1be79ccd9a149f025af1b8f/django_busybody/views.py#L141-L148 |
s1s5/django_busybody | django_busybody/views.py | MultipleModelFormMixin.form_valid | def form_valid(self, forms):
"""
If the form is valid, save the associated model.
"""
for key, form in forms.items():
setattr(self, '{}_object'.format(key), form.save())
return super(MultipleModelFormMixin, self).form_valid(forms) | python | def form_valid(self, forms):
"""
If the form is valid, save the associated model.
"""
for key, form in forms.items():
setattr(self, '{}_object'.format(key), form.save())
return super(MultipleModelFormMixin, self).form_valid(forms) | [
"def",
"form_valid",
"(",
"self",
",",
"forms",
")",
":",
"for",
"key",
",",
"form",
"in",
"forms",
".",
"items",
"(",
")",
":",
"setattr",
"(",
"self",
",",
"'{}_object'",
".",
"format",
"(",
"key",
")",
",",
"form",
".",
"save",
"(",
")",
")",
... | If the form is valid, save the associated model. | [
"If",
"the",
"form",
"is",
"valid",
"save",
"the",
"associated",
"model",
"."
] | train | https://github.com/s1s5/django_busybody/blob/5c6fd89824224f1de1be79ccd9a149f025af1b8f/django_busybody/views.py#L155-L161 |
casebeer/factual | factual/v2/requests.py | Read.within | def within(self, lat, lon, radius):
'''Convenience method to apply a $loc/$within/$center filter. Radius is in meters.'''
return self.filter(filter_helpers.within_(lat, lon, radius)) | python | def within(self, lat, lon, radius):
'''Convenience method to apply a $loc/$within/$center filter. Radius is in meters.'''
return self.filter(filter_helpers.within_(lat, lon, radius)) | [
"def",
"within",
"(",
"self",
",",
"lat",
",",
"lon",
",",
"radius",
")",
":",
"return",
"self",
".",
"filter",
"(",
"filter_helpers",
".",
"within_",
"(",
"lat",
",",
"lon",
",",
"radius",
")",
")"
] | Convenience method to apply a $loc/$within/$center filter. Radius is in meters. | [
"Convenience",
"method",
"to",
"apply",
"a",
"$loc",
"/",
"$within",
"/",
"$center",
"filter",
".",
"Radius",
"is",
"in",
"meters",
"."
] | train | https://github.com/casebeer/factual/blob/f2795a8c9fd447c5d62887ae0f960481ce13be84/factual/v2/requests.py#L13-L15 |
rsalmaso/django-fluo | fluo/admin/sites.py | AdminSite.view_on_site | def view_on_site(self, request, content_type_id, object_id):
"""
Redirect to an object's page based on a content-type ID and an object ID.
"""
# Look up the object, making sure it's got a get_absolute_url() function.
try:
content_type = ContentType.objects.get(pk=cont... | python | def view_on_site(self, request, content_type_id, object_id):
"""
Redirect to an object's page based on a content-type ID and an object ID.
"""
# Look up the object, making sure it's got a get_absolute_url() function.
try:
content_type = ContentType.objects.get(pk=cont... | [
"def",
"view_on_site",
"(",
"self",
",",
"request",
",",
"content_type_id",
",",
"object_id",
")",
":",
"# Look up the object, making sure it's got a get_absolute_url() function.",
"try",
":",
"content_type",
"=",
"ContentType",
".",
"objects",
".",
"get",
"(",
"pk",
... | Redirect to an object's page based on a content-type ID and an object ID. | [
"Redirect",
"to",
"an",
"object",
"s",
"page",
"based",
"on",
"a",
"content",
"-",
"type",
"ID",
"and",
"an",
"object",
"ID",
"."
] | train | https://github.com/rsalmaso/django-fluo/blob/1321c1e7d6a912108f79be02a9e7f2108c57f89f/fluo/admin/sites.py#L49-L75 |
uw-it-aca/uw-restclients-graderoster | uw_sws_graderoster/__init__.py | get_graderoster | def get_graderoster(section, instructor, requestor):
"""
Returns a restclients.GradeRoster for the passed Section model and
instructor Person.
"""
label = GradeRoster(section=section,
instructor=instructor).graderoster_label()
url = "{}/{}".format(graderoster_url, encode_... | python | def get_graderoster(section, instructor, requestor):
"""
Returns a restclients.GradeRoster for the passed Section model and
instructor Person.
"""
label = GradeRoster(section=section,
instructor=instructor).graderoster_label()
url = "{}/{}".format(graderoster_url, encode_... | [
"def",
"get_graderoster",
"(",
"section",
",",
"instructor",
",",
"requestor",
")",
":",
"label",
"=",
"GradeRoster",
"(",
"section",
"=",
"section",
",",
"instructor",
"=",
"instructor",
")",
".",
"graderoster_label",
"(",
")",
"url",
"=",
"\"{}/{}\"",
".",... | Returns a restclients.GradeRoster for the passed Section model and
instructor Person. | [
"Returns",
"a",
"restclients",
".",
"GradeRoster",
"for",
"the",
"passed",
"Section",
"model",
"and",
"instructor",
"Person",
"."
] | train | https://github.com/uw-it-aca/uw-restclients-graderoster/blob/1e41553eb7363765af60e87223ca9d22cf6c9187/uw_sws_graderoster/__init__.py#L10-L31 |
uw-it-aca/uw-restclients-graderoster | uw_sws_graderoster/__init__.py | update_graderoster | def update_graderoster(graderoster, requestor):
"""
Updates the graderoster resource for the passed restclients.GradeRoster
model. A new restclients.GradeRoster is returned, representing the
document returned from the update request.
"""
label = graderoster.graderoster_label()
url = "{}/{}".... | python | def update_graderoster(graderoster, requestor):
"""
Updates the graderoster resource for the passed restclients.GradeRoster
model. A new restclients.GradeRoster is returned, representing the
document returned from the update request.
"""
label = graderoster.graderoster_label()
url = "{}/{}".... | [
"def",
"update_graderoster",
"(",
"graderoster",
",",
"requestor",
")",
":",
"label",
"=",
"graderoster",
".",
"graderoster_label",
"(",
")",
"url",
"=",
"\"{}/{}\"",
".",
"format",
"(",
"graderoster_url",
",",
"encode_section_label",
"(",
"label",
")",
")",
"... | Updates the graderoster resource for the passed restclients.GradeRoster
model. A new restclients.GradeRoster is returned, representing the
document returned from the update request. | [
"Updates",
"the",
"graderoster",
"resource",
"for",
"the",
"passed",
"restclients",
".",
"GradeRoster",
"model",
".",
"A",
"new",
"restclients",
".",
"GradeRoster",
"is",
"returned",
"representing",
"the",
"document",
"returned",
"from",
"the",
"update",
"request"... | train | https://github.com/uw-it-aca/uw-restclients-graderoster/blob/1e41553eb7363765af60e87223ca9d22cf6c9187/uw_sws_graderoster/__init__.py#L34-L56 |
zenotech/SysScribe | sysscribe/__init__.py | cpuinfo | def cpuinfo():
''' Return the information in /proc/cpuinfo
as a dictionary in the following format:
cpu_info['proc0']={...}
cpu_info['proc1']={...}
'''
cpuinfo=OrderedDict()
procinfo=OrderedDict()
nprocs = 0
with open('/proc/cpuinfo') as f:
for line in f:
if no... | python | def cpuinfo():
''' Return the information in /proc/cpuinfo
as a dictionary in the following format:
cpu_info['proc0']={...}
cpu_info['proc1']={...}
'''
cpuinfo=OrderedDict()
procinfo=OrderedDict()
nprocs = 0
with open('/proc/cpuinfo') as f:
for line in f:
if no... | [
"def",
"cpuinfo",
"(",
")",
":",
"cpuinfo",
"=",
"OrderedDict",
"(",
")",
"procinfo",
"=",
"OrderedDict",
"(",
")",
"nprocs",
"=",
"0",
"with",
"open",
"(",
"'/proc/cpuinfo'",
")",
"as",
"f",
":",
"for",
"line",
"in",
"f",
":",
"if",
"not",
"line",
... | Return the information in /proc/cpuinfo
as a dictionary in the following format:
cpu_info['proc0']={...}
cpu_info['proc1']={...} | [
"Return",
"the",
"information",
"in",
"/",
"proc",
"/",
"cpuinfo",
"as",
"a",
"dictionary",
"in",
"the",
"following",
"format",
":",
"cpu_info",
"[",
"proc0",
"]",
"=",
"{",
"...",
"}",
"cpu_info",
"[",
"proc1",
"]",
"=",
"{",
"...",
"}"
] | train | https://github.com/zenotech/SysScribe/blob/8cabfc9718e7ccc6d217fbcfc158dd255b28c9b1/sysscribe/__init__.py#L10-L36 |
zenotech/SysScribe | sysscribe/__init__.py | meminfo | def meminfo():
''' Return the information in /proc/meminfo
as a dictionary '''
meminfo=OrderedDict()
with open('/proc/meminfo') as f:
for line in f:
meminfo[line.split(':')[0]] = line.split(':')[1].strip()
return meminfo | python | def meminfo():
''' Return the information in /proc/meminfo
as a dictionary '''
meminfo=OrderedDict()
with open('/proc/meminfo') as f:
for line in f:
meminfo[line.split(':')[0]] = line.split(':')[1].strip()
return meminfo | [
"def",
"meminfo",
"(",
")",
":",
"meminfo",
"=",
"OrderedDict",
"(",
")",
"with",
"open",
"(",
"'/proc/meminfo'",
")",
"as",
"f",
":",
"for",
"line",
"in",
"f",
":",
"meminfo",
"[",
"line",
".",
"split",
"(",
"':'",
")",
"[",
"0",
"]",
"]",
"=",
... | Return the information in /proc/meminfo
as a dictionary | [
"Return",
"the",
"information",
"in",
"/",
"proc",
"/",
"meminfo",
"as",
"a",
"dictionary"
] | train | https://github.com/zenotech/SysScribe/blob/8cabfc9718e7ccc6d217fbcfc158dd255b28c9b1/sysscribe/__init__.py#L46-L54 |
zenotech/SysScribe | sysscribe/__init__.py | netdevs | def netdevs():
''' RX and TX bytes for each of the network devices '''
with open('/proc/net/dev') as f:
net_dump = f.readlines()
device_data={}
data = namedtuple('data',['rx','tx'])
for line in net_dump[2:]:
line = line.split(':')
if line[0].strip() != 'lo':
... | python | def netdevs():
''' RX and TX bytes for each of the network devices '''
with open('/proc/net/dev') as f:
net_dump = f.readlines()
device_data={}
data = namedtuple('data',['rx','tx'])
for line in net_dump[2:]:
line = line.split(':')
if line[0].strip() != 'lo':
... | [
"def",
"netdevs",
"(",
")",
":",
"with",
"open",
"(",
"'/proc/net/dev'",
")",
"as",
"f",
":",
"net_dump",
"=",
"f",
".",
"readlines",
"(",
")",
"device_data",
"=",
"{",
"}",
"data",
"=",
"namedtuple",
"(",
"'data'",
",",
"[",
"'rx'",
",",
"'tx'",
"... | RX and TX bytes for each of the network devices | [
"RX",
"and",
"TX",
"bytes",
"for",
"each",
"of",
"the",
"network",
"devices"
] | train | https://github.com/zenotech/SysScribe/blob/8cabfc9718e7ccc6d217fbcfc158dd255b28c9b1/sysscribe/__init__.py#L58-L72 |
proversity-org/bibblio-api-python | bibbliothon/enrichment.py | create_content_item | def create_content_item(access_token, payload):
'''
Name: create_content_item
Parameters: access_token, payload (dict)
Return: dictionary
'''
headers = {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + str(access_token)
}
request = requests.post(enrichment_url, json=payload, headers=heade... | python | def create_content_item(access_token, payload):
'''
Name: create_content_item
Parameters: access_token, payload (dict)
Return: dictionary
'''
headers = {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + str(access_token)
}
request = requests.post(enrichment_url, json=payload, headers=heade... | [
"def",
"create_content_item",
"(",
"access_token",
",",
"payload",
")",
":",
"headers",
"=",
"{",
"'Content-Type'",
":",
"'application/json'",
",",
"'Authorization'",
":",
"'Bearer '",
"+",
"str",
"(",
"access_token",
")",
"}",
"request",
"=",
"requests",
".",
... | Name: create_content_item
Parameters: access_token, payload (dict)
Return: dictionary | [
"Name",
":",
"create_content_item",
"Parameters",
":",
"access_token",
"payload",
"(",
"dict",
")",
"Return",
":",
"dictionary"
] | train | https://github.com/proversity-org/bibblio-api-python/blob/d619223ad80a4bcd32f90ba64d93370260601b60/bibbliothon/enrichment.py#L15-L33 |
proversity-org/bibblio-api-python | bibbliothon/enrichment.py | get_content_items | def get_content_items(access_token, limit, page):
'''
Name: get_content_items
Parameters: access_token, limit (optional), page (optional)
Return: dictionary
'''
headers = {'Authorization': 'Bearer ' + str(access_token)}
content_items_url =\
construct_content_items_url(enrichment_url, limit, page)
request = ... | python | def get_content_items(access_token, limit, page):
'''
Name: get_content_items
Parameters: access_token, limit (optional), page (optional)
Return: dictionary
'''
headers = {'Authorization': 'Bearer ' + str(access_token)}
content_items_url =\
construct_content_items_url(enrichment_url, limit, page)
request = ... | [
"def",
"get_content_items",
"(",
"access_token",
",",
"limit",
",",
"page",
")",
":",
"headers",
"=",
"{",
"'Authorization'",
":",
"'Bearer '",
"+",
"str",
"(",
"access_token",
")",
"}",
"content_items_url",
"=",
"construct_content_items_url",
"(",
"enrichment_url... | Name: get_content_items
Parameters: access_token, limit (optional), page (optional)
Return: dictionary | [
"Name",
":",
"get_content_items",
"Parameters",
":",
"access_token",
"limit",
"(",
"optional",
")",
"page",
"(",
"optional",
")",
"Return",
":",
"dictionary"
] | train | https://github.com/proversity-org/bibblio-api-python/blob/d619223ad80a4bcd32f90ba64d93370260601b60/bibbliothon/enrichment.py#L36-L53 |
proversity-org/bibblio-api-python | bibbliothon/enrichment.py | get_content_item | def get_content_item(access_token, content_item_id):
'''
Name: get_content_item
Parameters: access_token, content_item_id
Return: dictionary
'''
headers = {'Authorization': 'Bearer ' + str(access_token)}
content_item_url =\
construct_content_item_url(enrichment_url, content_item_id)
request = requests.get(c... | python | def get_content_item(access_token, content_item_id):
'''
Name: get_content_item
Parameters: access_token, content_item_id
Return: dictionary
'''
headers = {'Authorization': 'Bearer ' + str(access_token)}
content_item_url =\
construct_content_item_url(enrichment_url, content_item_id)
request = requests.get(c... | [
"def",
"get_content_item",
"(",
"access_token",
",",
"content_item_id",
")",
":",
"headers",
"=",
"{",
"'Authorization'",
":",
"'Bearer '",
"+",
"str",
"(",
"access_token",
")",
"}",
"content_item_url",
"=",
"construct_content_item_url",
"(",
"enrichment_url",
",",
... | Name: get_content_item
Parameters: access_token, content_item_id
Return: dictionary | [
"Name",
":",
"get_content_item",
"Parameters",
":",
"access_token",
"content_item_id",
"Return",
":",
"dictionary"
] | train | https://github.com/proversity-org/bibblio-api-python/blob/d619223ad80a4bcd32f90ba64d93370260601b60/bibbliothon/enrichment.py#L56-L73 |
proversity-org/bibblio-api-python | bibbliothon/enrichment.py | update_content_item | def update_content_item(access_token, content_item_id, payload):
'''
Name: update_content_item
Parameters: access_token, content_item_id, payload (dict)
Return: dictionary
'''
headers = {'Authorization': 'Bearer ' + str(access_token)}
content_item_url =\
construct_content_item_url(enrichment_url, content_item... | python | def update_content_item(access_token, content_item_id, payload):
'''
Name: update_content_item
Parameters: access_token, content_item_id, payload (dict)
Return: dictionary
'''
headers = {'Authorization': 'Bearer ' + str(access_token)}
content_item_url =\
construct_content_item_url(enrichment_url, content_item... | [
"def",
"update_content_item",
"(",
"access_token",
",",
"content_item_id",
",",
"payload",
")",
":",
"headers",
"=",
"{",
"'Authorization'",
":",
"'Bearer '",
"+",
"str",
"(",
"access_token",
")",
"}",
"content_item_url",
"=",
"construct_content_item_url",
"(",
"e... | Name: update_content_item
Parameters: access_token, content_item_id, payload (dict)
Return: dictionary | [
"Name",
":",
"update_content_item",
"Parameters",
":",
"access_token",
"content_item_id",
"payload",
"(",
"dict",
")",
"Return",
":",
"dictionary"
] | train | https://github.com/proversity-org/bibblio-api-python/blob/d619223ad80a4bcd32f90ba64d93370260601b60/bibbliothon/enrichment.py#L76-L95 |
proversity-org/bibblio-api-python | bibbliothon/enrichment.py | delete_content_item | def delete_content_item(access_token, content_item_id):
'''
Name: delete_content_item
Parameters: access_token, content_item_id
Return: dictionary
'''
headers = {'Authorization': 'Bearer ' + str(access_token)}
content_item_url =\
construct_content_item_url(enrichment_url, content_item_id)
request = requests... | python | def delete_content_item(access_token, content_item_id):
'''
Name: delete_content_item
Parameters: access_token, content_item_id
Return: dictionary
'''
headers = {'Authorization': 'Bearer ' + str(access_token)}
content_item_url =\
construct_content_item_url(enrichment_url, content_item_id)
request = requests... | [
"def",
"delete_content_item",
"(",
"access_token",
",",
"content_item_id",
")",
":",
"headers",
"=",
"{",
"'Authorization'",
":",
"'Bearer '",
"+",
"str",
"(",
"access_token",
")",
"}",
"content_item_url",
"=",
"construct_content_item_url",
"(",
"enrichment_url",
",... | Name: delete_content_item
Parameters: access_token, content_item_id
Return: dictionary | [
"Name",
":",
"delete_content_item",
"Parameters",
":",
"access_token",
"content_item_id",
"Return",
":",
"dictionary"
] | train | https://github.com/proversity-org/bibblio-api-python/blob/d619223ad80a4bcd32f90ba64d93370260601b60/bibbliothon/enrichment.py#L98-L110 |
proversity-org/bibblio-api-python | bibbliothon/enrichment.py | metadata | def metadata(access_token, text): # (Legacy)
'''
Name: metadata_only
Parameters: access_token, text (string)
Return: dictionary
'''
headers = {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + str(access_token)
}
payload = {'text': text}
request = requests.post(met... | python | def metadata(access_token, text): # (Legacy)
'''
Name: metadata_only
Parameters: access_token, text (string)
Return: dictionary
'''
headers = {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + str(access_token)
}
payload = {'text': text}
request = requests.post(met... | [
"def",
"metadata",
"(",
"access_token",
",",
"text",
")",
":",
"# (Legacy)",
"headers",
"=",
"{",
"'Content-Type'",
":",
"'application/json'",
",",
"'Authorization'",
":",
"'Bearer '",
"+",
"str",
"(",
"access_token",
")",
"}",
"payload",
"=",
"{",
"'text'",
... | Name: metadata_only
Parameters: access_token, text (string)
Return: dictionary | [
"Name",
":",
"metadata_only",
"Parameters",
":",
"access_token",
"text",
"(",
"string",
")",
"Return",
":",
"dictionary"
] | train | https://github.com/proversity-org/bibblio-api-python/blob/d619223ad80a4bcd32f90ba64d93370260601b60/bibbliothon/enrichment.py#L113-L131 |
almcc/cinder-data | robot/libs/CinderDataLibrary.py | CinderDataLibrary.get_model | def get_model(self, model, model_id):
"""Get a single model from the server.
Args:
model (string): The class as a string.
model_id (string): The integer ID as a string.
Returns:
:class:`cinder_data.model.CinderModel`: A instance of the model.
"""
... | python | def get_model(self, model, model_id):
"""Get a single model from the server.
Args:
model (string): The class as a string.
model_id (string): The integer ID as a string.
Returns:
:class:`cinder_data.model.CinderModel`: A instance of the model.
"""
... | [
"def",
"get_model",
"(",
"self",
",",
"model",
",",
"model_id",
")",
":",
"return",
"self",
".",
"_store",
".",
"find_record",
"(",
"self",
".",
"_get_model_class",
"(",
"model",
")",
",",
"int",
"(",
"model_id",
")",
")"
] | Get a single model from the server.
Args:
model (string): The class as a string.
model_id (string): The integer ID as a string.
Returns:
:class:`cinder_data.model.CinderModel`: A instance of the model. | [
"Get",
"a",
"single",
"model",
"from",
"the",
"server",
"."
] | train | https://github.com/almcc/cinder-data/blob/4159a5186c4b4fc32354749892e86130530f6ec5/robot/libs/CinderDataLibrary.py#L38-L48 |
almcc/cinder-data | robot/libs/CinderDataLibrary.py | CinderDataLibrary.get_models | def get_models(self, model, page=None):
"""Get all the models from the server.
Args:
model (string): The class as a string.
page (string, optional): The page number as a string
Returns:
list: A list of instances of the requested model.
"""
if... | python | def get_models(self, model, page=None):
"""Get all the models from the server.
Args:
model (string): The class as a string.
page (string, optional): The page number as a string
Returns:
list: A list of instances of the requested model.
"""
if... | [
"def",
"get_models",
"(",
"self",
",",
"model",
",",
"page",
"=",
"None",
")",
":",
"if",
"page",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_store",
".",
"find_all",
"(",
"self",
".",
"_get_model_class",
"(",
"model",
")",
",",
"params",
"=",... | Get all the models from the server.
Args:
model (string): The class as a string.
page (string, optional): The page number as a string
Returns:
list: A list of instances of the requested model. | [
"Get",
"all",
"the",
"models",
"from",
"the",
"server",
"."
] | train | https://github.com/almcc/cinder-data/blob/4159a5186c4b4fc32354749892e86130530f6ec5/robot/libs/CinderDataLibrary.py#L50-L63 |
dicaso/leopard | leopard/utils.py | makeFigFromFile | def makeFigFromFile(filename,*args,**kwargs):
"""
Renders an image in a matplotlib figure, so it can be added to reports
args and kwargs are passed to plt.subplots
"""
import matplotlib.pyplot as plt
img = plt.imread(filename)
fig,ax = plt.subplots(*args,**kwargs)
ax.axis('off')
ax.... | python | def makeFigFromFile(filename,*args,**kwargs):
"""
Renders an image in a matplotlib figure, so it can be added to reports
args and kwargs are passed to plt.subplots
"""
import matplotlib.pyplot as plt
img = plt.imread(filename)
fig,ax = plt.subplots(*args,**kwargs)
ax.axis('off')
ax.... | [
"def",
"makeFigFromFile",
"(",
"filename",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"import",
"matplotlib",
".",
"pyplot",
"as",
"plt",
"img",
"=",
"plt",
".",
"imread",
"(",
"filename",
")",
"fig",
",",
"ax",
"=",
"plt",
".",
"subplots",... | Renders an image in a matplotlib figure, so it can be added to reports
args and kwargs are passed to plt.subplots | [
"Renders",
"an",
"image",
"in",
"a",
"matplotlib",
"figure",
"so",
"it",
"can",
"be",
"added",
"to",
"reports",
"args",
"and",
"kwargs",
"are",
"passed",
"to",
"plt",
".",
"subplots"
] | train | https://github.com/dicaso/leopard/blob/ee9f45251aaacd1e453b135b419f4f0b50fb036e/leopard/utils.py#L8-L18 |
Raynes/quarantine | quarantine/cdc.py | CDC.list_exes | def list_exes(self):
"""List the installed executables by this project."""
return [path.join(self.env_bin, f)
for f
in os.listdir(self.env_bin)] | python | def list_exes(self):
"""List the installed executables by this project."""
return [path.join(self.env_bin, f)
for f
in os.listdir(self.env_bin)] | [
"def",
"list_exes",
"(",
"self",
")",
":",
"return",
"[",
"path",
".",
"join",
"(",
"self",
".",
"env_bin",
",",
"f",
")",
"for",
"f",
"in",
"os",
".",
"listdir",
"(",
"self",
".",
"env_bin",
")",
"]"
] | List the installed executables by this project. | [
"List",
"the",
"installed",
"executables",
"by",
"this",
"project",
"."
] | train | https://github.com/Raynes/quarantine/blob/742a318fcb7d34dbdf4fac388daff03a36872d8b/quarantine/cdc.py#L32-L36 |
Raynes/quarantine | quarantine/cdc.py | CDC.create_env | def create_env(self):
"""Create a virtual environment."""
virtualenv(self.env, _err=sys.stderr)
os.mkdir(self.env_bin) | python | def create_env(self):
"""Create a virtual environment."""
virtualenv(self.env, _err=sys.stderr)
os.mkdir(self.env_bin) | [
"def",
"create_env",
"(",
"self",
")",
":",
"virtualenv",
"(",
"self",
".",
"env",
",",
"_err",
"=",
"sys",
".",
"stderr",
")",
"os",
".",
"mkdir",
"(",
"self",
".",
"env_bin",
")"
] | Create a virtual environment. | [
"Create",
"a",
"virtual",
"environment",
"."
] | train | https://github.com/Raynes/quarantine/blob/742a318fcb7d34dbdf4fac388daff03a36872d8b/quarantine/cdc.py#L38-L41 |
Raynes/quarantine | quarantine/cdc.py | CDC.install_program | def install_program(self, extra_args):
"""Install the app to the virtualenv"""
pip = Command(path.join(self.env, 'bin', 'pip'))
args = ['install', self.raw_name,
'--install-option', '--install-scripts={}'
.format(self.env_bin)] + list(extra_args)
print_pre... | python | def install_program(self, extra_args):
"""Install the app to the virtualenv"""
pip = Command(path.join(self.env, 'bin', 'pip'))
args = ['install', self.raw_name,
'--install-option', '--install-scripts={}'
.format(self.env_bin)] + list(extra_args)
print_pre... | [
"def",
"install_program",
"(",
"self",
",",
"extra_args",
")",
":",
"pip",
"=",
"Command",
"(",
"path",
".",
"join",
"(",
"self",
".",
"env",
",",
"'bin'",
",",
"'pip'",
")",
")",
"args",
"=",
"[",
"'install'",
",",
"self",
".",
"raw_name",
",",
"'... | Install the app to the virtualenv | [
"Install",
"the",
"app",
"to",
"the",
"virtualenv"
] | train | https://github.com/Raynes/quarantine/blob/742a318fcb7d34dbdf4fac388daff03a36872d8b/quarantine/cdc.py#L47-L55 |
Raynes/quarantine | quarantine/cdc.py | CDC.create_links | def create_links(self):
"""Create links to installed scripts in the virtualenv's
bin directory to our bin directory.
"""
for link in self.list_exes():
print_pretty("<FG_BLUE>Creating link for {}...<END>".format(link))
os.symlink(link, path.join(ENV_BIN, path.base... | python | def create_links(self):
"""Create links to installed scripts in the virtualenv's
bin directory to our bin directory.
"""
for link in self.list_exes():
print_pretty("<FG_BLUE>Creating link for {}...<END>".format(link))
os.symlink(link, path.join(ENV_BIN, path.base... | [
"def",
"create_links",
"(",
"self",
")",
":",
"for",
"link",
"in",
"self",
".",
"list_exes",
"(",
")",
":",
"print_pretty",
"(",
"\"<FG_BLUE>Creating link for {}...<END>\"",
".",
"format",
"(",
"link",
")",
")",
"os",
".",
"symlink",
"(",
"link",
",",
"pat... | Create links to installed scripts in the virtualenv's
bin directory to our bin directory. | [
"Create",
"links",
"to",
"installed",
"scripts",
"in",
"the",
"virtualenv",
"s",
"bin",
"directory",
"to",
"our",
"bin",
"directory",
"."
] | train | https://github.com/Raynes/quarantine/blob/742a318fcb7d34dbdf4fac388daff03a36872d8b/quarantine/cdc.py#L57-L64 |
Raynes/quarantine | quarantine/cdc.py | CDC.remove_links | def remove_links(self):
"""Remove links from our bin."""
for link in self.list_exes():
link = path.join(ENV_BIN, path.basename(link))
print_pretty("<FG_BLUE>Removing link {}...<END>".format(link))
os.remove(link) | python | def remove_links(self):
"""Remove links from our bin."""
for link in self.list_exes():
link = path.join(ENV_BIN, path.basename(link))
print_pretty("<FG_BLUE>Removing link {}...<END>".format(link))
os.remove(link) | [
"def",
"remove_links",
"(",
"self",
")",
":",
"for",
"link",
"in",
"self",
".",
"list_exes",
"(",
")",
":",
"link",
"=",
"path",
".",
"join",
"(",
"ENV_BIN",
",",
"path",
".",
"basename",
"(",
"link",
")",
")",
"print_pretty",
"(",
"\"<FG_BLUE>Removing... | Remove links from our bin. | [
"Remove",
"links",
"from",
"our",
"bin",
"."
] | train | https://github.com/Raynes/quarantine/blob/742a318fcb7d34dbdf4fac388daff03a36872d8b/quarantine/cdc.py#L66-L71 |
Raynes/quarantine | quarantine/cdc.py | CDC.uninstall | def uninstall(self):
"""Uninstall the environment and links."""
if path.isdir(self.env_bin):
self.remove_links()
if path.isdir(self.env):
print_pretty("<FG_BLUE>Removing env {}...<END>".format(self.env))
shutil.rmtree(self.env) | python | def uninstall(self):
"""Uninstall the environment and links."""
if path.isdir(self.env_bin):
self.remove_links()
if path.isdir(self.env):
print_pretty("<FG_BLUE>Removing env {}...<END>".format(self.env))
shutil.rmtree(self.env) | [
"def",
"uninstall",
"(",
"self",
")",
":",
"if",
"path",
".",
"isdir",
"(",
"self",
".",
"env_bin",
")",
":",
"self",
".",
"remove_links",
"(",
")",
"if",
"path",
".",
"isdir",
"(",
"self",
".",
"env",
")",
":",
"print_pretty",
"(",
"\"<FG_BLUE>Remov... | Uninstall the environment and links. | [
"Uninstall",
"the",
"environment",
"and",
"links",
"."
] | train | https://github.com/Raynes/quarantine/blob/742a318fcb7d34dbdf4fac388daff03a36872d8b/quarantine/cdc.py#L73-L79 |
Raynes/quarantine | quarantine/cdc.py | CDC.install | def install(self, pip_args=None):
"""Install the program and put links in place."""
if path.isdir(self.env):
print_pretty("<FG_RED>This seems to already be installed.<END>")
else:
print_pretty("<FG_BLUE>Creating environment {}...<END>\n".format(self.env))
self... | python | def install(self, pip_args=None):
"""Install the program and put links in place."""
if path.isdir(self.env):
print_pretty("<FG_RED>This seems to already be installed.<END>")
else:
print_pretty("<FG_BLUE>Creating environment {}...<END>\n".format(self.env))
self... | [
"def",
"install",
"(",
"self",
",",
"pip_args",
"=",
"None",
")",
":",
"if",
"path",
".",
"isdir",
"(",
"self",
".",
"env",
")",
":",
"print_pretty",
"(",
"\"<FG_RED>This seems to already be installed.<END>\"",
")",
"else",
":",
"print_pretty",
"(",
"\"<FG_BLU... | Install the program and put links in place. | [
"Install",
"the",
"program",
"and",
"put",
"links",
"in",
"place",
"."
] | train | https://github.com/Raynes/quarantine/blob/742a318fcb7d34dbdf4fac388daff03a36872d8b/quarantine/cdc.py#L81-L89 |
dev-pipeline/dev-pipeline-git | lib/devpipeline_git/git.py | _make_git | def _make_git(config_info):
"""This function initializes and Git SCM tool object."""
git_args = {}
def _add_value(value, key):
args_key, args_value = _GIT_ARG_FNS[key](value)
git_args[args_key] = args_value
devpipeline_core.toolsupport.args_builder("git", config_info, _GIT_ARGS, _add_v... | python | def _make_git(config_info):
"""This function initializes and Git SCM tool object."""
git_args = {}
def _add_value(value, key):
args_key, args_value = _GIT_ARG_FNS[key](value)
git_args[args_key] = args_value
devpipeline_core.toolsupport.args_builder("git", config_info, _GIT_ARGS, _add_v... | [
"def",
"_make_git",
"(",
"config_info",
")",
":",
"git_args",
"=",
"{",
"}",
"def",
"_add_value",
"(",
"value",
",",
"key",
")",
":",
"args_key",
",",
"args_value",
"=",
"_GIT_ARG_FNS",
"[",
"key",
"]",
"(",
"value",
")",
"git_args",
"[",
"args_key",
"... | This function initializes and Git SCM tool object. | [
"This",
"function",
"initializes",
"and",
"Git",
"SCM",
"tool",
"object",
"."
] | train | https://github.com/dev-pipeline/dev-pipeline-git/blob/b604f1f89402502b8ad858f4f834baa9467ef380/lib/devpipeline_git/git.py#L143-L155 |
dev-pipeline/dev-pipeline-git | lib/devpipeline_git/git.py | Git.checkout | def checkout(self, repo_dir, shared_dir, **kwargs):
"""This function checks out code from a Git SCM server."""
del kwargs
args = []
for checkout_fn in _CHECKOUT_ARG_BUILDERS:
args.extend(checkout_fn(shared_dir, repo_dir, self._args))
return args | python | def checkout(self, repo_dir, shared_dir, **kwargs):
"""This function checks out code from a Git SCM server."""
del kwargs
args = []
for checkout_fn in _CHECKOUT_ARG_BUILDERS:
args.extend(checkout_fn(shared_dir, repo_dir, self._args))
return args | [
"def",
"checkout",
"(",
"self",
",",
"repo_dir",
",",
"shared_dir",
",",
"*",
"*",
"kwargs",
")",
":",
"del",
"kwargs",
"args",
"=",
"[",
"]",
"for",
"checkout_fn",
"in",
"_CHECKOUT_ARG_BUILDERS",
":",
"args",
".",
"extend",
"(",
"checkout_fn",
"(",
"sha... | This function checks out code from a Git SCM server. | [
"This",
"function",
"checks",
"out",
"code",
"from",
"a",
"Git",
"SCM",
"server",
"."
] | train | https://github.com/dev-pipeline/dev-pipeline-git/blob/b604f1f89402502b8ad858f4f834baa9467ef380/lib/devpipeline_git/git.py#L118-L124 |
dev-pipeline/dev-pipeline-git | lib/devpipeline_git/git.py | Git.update | def update(self, repo_dir, **kwargs):
"""This function updates an existing checkout of source code."""
del kwargs
rev = self._args.get("revision")
if rev:
return [{"args": ["git", "checkout", rev], "cwd": repo_dir}] + _ff_command(
rev, repo_dir
)
... | python | def update(self, repo_dir, **kwargs):
"""This function updates an existing checkout of source code."""
del kwargs
rev = self._args.get("revision")
if rev:
return [{"args": ["git", "checkout", rev], "cwd": repo_dir}] + _ff_command(
rev, repo_dir
)
... | [
"def",
"update",
"(",
"self",
",",
"repo_dir",
",",
"*",
"*",
"kwargs",
")",
":",
"del",
"kwargs",
"rev",
"=",
"self",
".",
"_args",
".",
"get",
"(",
"\"revision\"",
")",
"if",
"rev",
":",
"return",
"[",
"{",
"\"args\"",
":",
"[",
"\"git\"",
",",
... | This function updates an existing checkout of source code. | [
"This",
"function",
"updates",
"an",
"existing",
"checkout",
"of",
"source",
"code",
"."
] | train | https://github.com/dev-pipeline/dev-pipeline-git/blob/b604f1f89402502b8ad858f4f834baa9467ef380/lib/devpipeline_git/git.py#L126-L134 |
CitrineInformatics/dftparse | dftparse/wien2k/absorp_parser.py | _parse_absorption | def _parse_absorption(line, lines):
"""Parse Energy, Re sigma xx, Re sigma zz, absorp xx, absorp zz"""
split_line = line.split()
energy = float(split_line[0])
re_sigma_xx = float(split_line[1])
re_sigma_zz = float(split_line[2])
absorp_xx = float(split_line[3])
absorp_zz = float(split_line... | python | def _parse_absorption(line, lines):
"""Parse Energy, Re sigma xx, Re sigma zz, absorp xx, absorp zz"""
split_line = line.split()
energy = float(split_line[0])
re_sigma_xx = float(split_line[1])
re_sigma_zz = float(split_line[2])
absorp_xx = float(split_line[3])
absorp_zz = float(split_line... | [
"def",
"_parse_absorption",
"(",
"line",
",",
"lines",
")",
":",
"split_line",
"=",
"line",
".",
"split",
"(",
")",
"energy",
"=",
"float",
"(",
"split_line",
"[",
"0",
"]",
")",
"re_sigma_xx",
"=",
"float",
"(",
"split_line",
"[",
"1",
"]",
")",
"re... | Parse Energy, Re sigma xx, Re sigma zz, absorp xx, absorp zz | [
"Parse",
"Energy",
"Re",
"sigma",
"xx",
"Re",
"sigma",
"zz",
"absorp",
"xx",
"absorp",
"zz"
] | train | https://github.com/CitrineInformatics/dftparse/blob/53a1bf19945cf1c195d6af9beccb3d1b7f4a4c1d/dftparse/wien2k/absorp_parser.py#L4-L16 |
jalanb/pysyte | pysyte/text_streams.py | parse_args | def parse_args():
"""Parse out command line arguments"""
parser = arguments.parser(__doc__)
parser.args('streams', help='streams to use')
parser.opt('-p', '--paste', 'paste text from clipboard')
parser.opt('-i', '--stdin', 'wait for text from stdin')
return parser.parse_args() | python | def parse_args():
"""Parse out command line arguments"""
parser = arguments.parser(__doc__)
parser.args('streams', help='streams to use')
parser.opt('-p', '--paste', 'paste text from clipboard')
parser.opt('-i', '--stdin', 'wait for text from stdin')
return parser.parse_args() | [
"def",
"parse_args",
"(",
")",
":",
"parser",
"=",
"arguments",
".",
"parser",
"(",
"__doc__",
")",
"parser",
".",
"args",
"(",
"'streams'",
",",
"help",
"=",
"'streams to use'",
")",
"parser",
".",
"opt",
"(",
"'-p'",
",",
"'--paste'",
",",
"'paste text... | Parse out command line arguments | [
"Parse",
"out",
"command",
"line",
"arguments"
] | train | https://github.com/jalanb/pysyte/blob/4e278101943d1ceb1a6bcaf6ddc72052ecf13114/pysyte/text_streams.py#L14-L20 |
jalanb/pysyte | pysyte/text_streams.py | args | def args(parsed_args, name=None):
"""Interpret parsed args to streams"""
strings = parsed_args.arg_strings(name)
files = [s for s in strings if os.path.isfile(s)]
if files:
streams = [open(f) for f in files]
else:
streams = []
if getattr(parsed_args, 'paste', not files):
... | python | def args(parsed_args, name=None):
"""Interpret parsed args to streams"""
strings = parsed_args.arg_strings(name)
files = [s for s in strings if os.path.isfile(s)]
if files:
streams = [open(f) for f in files]
else:
streams = []
if getattr(parsed_args, 'paste', not files):
... | [
"def",
"args",
"(",
"parsed_args",
",",
"name",
"=",
"None",
")",
":",
"strings",
"=",
"parsed_args",
".",
"arg_strings",
"(",
"name",
")",
"files",
"=",
"[",
"s",
"for",
"s",
"in",
"strings",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"s",
")",
... | Interpret parsed args to streams | [
"Interpret",
"parsed",
"args",
"to",
"streams"
] | train | https://github.com/jalanb/pysyte/blob/4e278101943d1ceb1a6bcaf6ddc72052ecf13114/pysyte/text_streams.py#L23-L37 |
MacHu-GWU/angora-project | angora/hashes/fingerprint.py | FingerPrint.use | def use(self, algorithm):
"""Change the hash algorithm you gonna use.
"""
algorithm = algorithm.lower()
if algorithm == "md5":
self.default_hash_method = hashlib.md5
elif algorithm == "sha1":
self.default_hash_method = hashlib.sha1
elif algorithm =... | python | def use(self, algorithm):
"""Change the hash algorithm you gonna use.
"""
algorithm = algorithm.lower()
if algorithm == "md5":
self.default_hash_method = hashlib.md5
elif algorithm == "sha1":
self.default_hash_method = hashlib.sha1
elif algorithm =... | [
"def",
"use",
"(",
"self",
",",
"algorithm",
")",
":",
"algorithm",
"=",
"algorithm",
".",
"lower",
"(",
")",
"if",
"algorithm",
"==",
"\"md5\"",
":",
"self",
".",
"default_hash_method",
"=",
"hashlib",
".",
"md5",
"elif",
"algorithm",
"==",
"\"sha1\"",
... | Change the hash algorithm you gonna use. | [
"Change",
"the",
"hash",
"algorithm",
"you",
"gonna",
"use",
"."
] | train | https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/hashes/fingerprint.py#L72-L91 |
MacHu-GWU/angora-project | angora/hashes/fingerprint.py | FingerPrint.of_file | def of_file(self, abspath, nbytes=0):
"""Use default hash method to return hash value of a piece of a file
Estimate processing time on:
:param abspath: the absolute path to the file
:param nbytes: only has first N bytes of the file. if 0, hash all file
CPU = i7-4600U 2.10GHz -... | python | def of_file(self, abspath, nbytes=0):
"""Use default hash method to return hash value of a piece of a file
Estimate processing time on:
:param abspath: the absolute path to the file
:param nbytes: only has first N bytes of the file. if 0, hash all file
CPU = i7-4600U 2.10GHz -... | [
"def",
"of_file",
"(",
"self",
",",
"abspath",
",",
"nbytes",
"=",
"0",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"abspath",
")",
":",
"raise",
"FileNotFoundError",
"(",
"\"[Errno 2] No such file or directory: '%s'\"",
"%",
"abspath",
")"... | Use default hash method to return hash value of a piece of a file
Estimate processing time on:
:param abspath: the absolute path to the file
:param nbytes: only has first N bytes of the file. if 0, hash all file
CPU = i7-4600U 2.10GHz - 2.70GHz, RAM = 8.00 GB
1 second can proc... | [
"Use",
"default",
"hash",
"method",
"to",
"return",
"hash",
"value",
"of",
"a",
"piece",
"of",
"a",
"file"
] | train | https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/hashes/fingerprint.py#L131-L172 |
MacHu-GWU/angora-project | angora/gadget/controlflow.py | try_until_succeed | def try_until_succeed(_warning_period, func, *argv, **kwarg):
"""Try a function until it successfully returns.
Print current exception every ``_warning_period`` times try.
**中文文档**
尝试一个函数直到其成功为止。不适用于会出现死循环的函数。
每隔``_warning_period``次失败, 就会打印当前异常和尝试次数。
"""
if (not isinstanc... | python | def try_until_succeed(_warning_period, func, *argv, **kwarg):
"""Try a function until it successfully returns.
Print current exception every ``_warning_period`` times try.
**中文文档**
尝试一个函数直到其成功为止。不适用于会出现死循环的函数。
每隔``_warning_period``次失败, 就会打印当前异常和尝试次数。
"""
if (not isinstanc... | [
"def",
"try_until_succeed",
"(",
"_warning_period",
",",
"func",
",",
"*",
"argv",
",",
"*",
"*",
"kwarg",
")",
":",
"if",
"(",
"not",
"isinstance",
"(",
"_warning_period",
",",
"int",
")",
")",
"or",
"(",
"_warning_period",
"<",
"1",
")",
":",
"raise"... | Try a function until it successfully returns.
Print current exception every ``_warning_period`` times try.
**中文文档**
尝试一个函数直到其成功为止。不适用于会出现死循环的函数。
每隔``_warning_period``次失败, 就会打印当前异常和尝试次数。 | [
"Try",
"a",
"function",
"until",
"it",
"successfully",
"returns",
".",
"Print",
"current",
"exception",
"every",
"_warning_period",
"times",
"try",
".",
"**",
"中文文档",
"**",
"尝试一个函数直到其成功为止。不适用于会出现死循环的函数。",
"每隔",
"_warning_period",
"次失败",
"就会打印当前异常和尝试次数。"
] | train | https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/gadget/controlflow.py#L27-L51 |
MacHu-GWU/angora-project | angora/gadget/controlflow.py | try_ntimes | def try_ntimes(_howmany, func, *argv, **kwarg):
"""Try a function n times.
Try to execute func(*argv, **kwarg) ``_howmany`` times. If it successfully run
one time, then return as normal. If it fails N times, then raise the
exception in the last run.
**中文文档**
反复尝试一个函数或方法``_howman... | python | def try_ntimes(_howmany, func, *argv, **kwarg):
"""Try a function n times.
Try to execute func(*argv, **kwarg) ``_howmany`` times. If it successfully run
one time, then return as normal. If it fails N times, then raise the
exception in the last run.
**中文文档**
反复尝试一个函数或方法``_howman... | [
"def",
"try_ntimes",
"(",
"_howmany",
",",
"func",
",",
"*",
"argv",
",",
"*",
"*",
"kwarg",
")",
":",
"if",
"(",
"not",
"isinstance",
"(",
"_howmany",
",",
"int",
")",
")",
"or",
"(",
"_howmany",
"<",
"1",
")",
":",
"raise",
"Exception",
"(",
"\... | Try a function n times.
Try to execute func(*argv, **kwarg) ``_howmany`` times. If it successfully run
one time, then return as normal. If it fails N times, then raise the
exception in the last run.
**中文文档**
反复尝试一个函数或方法``_howmany``次。
对func函数使用try, except, pass 若干次, 期间只要有一次成... | [
"Try",
"a",
"function",
"n",
"times",
".",
"Try",
"to",
"execute",
"func",
"(",
"*",
"argv",
"**",
"kwarg",
")",
"_howmany",
"times",
".",
"If",
"it",
"successfully",
"run",
"one",
"time",
"then",
"return",
"as",
"normal",
".",
"If",
"it",
"fails",
"... | train | https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/gadget/controlflow.py#L53-L81 |
brycepg/mand | mand/mand.py | main | def main(argv=None):
"""Execute each module in the same interpreter.
Args:
argv: Each item of argv will be treated as a separate
module with potential arguments
each item may be a string or a sequence of strings.
If a given argument is a string, then treat string as
... | python | def main(argv=None):
"""Execute each module in the same interpreter.
Args:
argv: Each item of argv will be treated as a separate
module with potential arguments
each item may be a string or a sequence of strings.
If a given argument is a string, then treat string as
... | [
"def",
"main",
"(",
"argv",
"=",
"None",
")",
":",
"if",
"argv",
"is",
"None",
":",
"argv",
"=",
"sys",
".",
"argv",
"[",
"1",
":",
"]",
"args",
"=",
"_get_parser",
"(",
")",
".",
"parse_args",
"(",
"argv",
")",
"mand",
"(",
"args",
".",
"modul... | Execute each module in the same interpreter.
Args:
argv: Each item of argv will be treated as a separate
module with potential arguments
each item may be a string or a sequence of strings.
If a given argument is a string, then treat string as
shell arguments ... | [
"Execute",
"each",
"module",
"in",
"the",
"same",
"interpreter",
"."
] | train | https://github.com/brycepg/mand/blob/3a8f9c1cc1bbe217aaca8c805113285ab02ecb7c/mand/mand.py#L12-L28 |
brycepg/mand | mand/mand.py | call_multiple_modules | def call_multiple_modules(module_gen):
"""Call each module
module_gen should be a iterator
"""
for args_seq in module_gen:
module_name_or_path = args_seq[0]
with replace_sys_args(args_seq):
if re.match(VALID_PACKAGE_RE, module_name_or_path):
runpy.run_module(... | python | def call_multiple_modules(module_gen):
"""Call each module
module_gen should be a iterator
"""
for args_seq in module_gen:
module_name_or_path = args_seq[0]
with replace_sys_args(args_seq):
if re.match(VALID_PACKAGE_RE, module_name_or_path):
runpy.run_module(... | [
"def",
"call_multiple_modules",
"(",
"module_gen",
")",
":",
"for",
"args_seq",
"in",
"module_gen",
":",
"module_name_or_path",
"=",
"args_seq",
"[",
"0",
"]",
"with",
"replace_sys_args",
"(",
"args_seq",
")",
":",
"if",
"re",
".",
"match",
"(",
"VALID_PACKAGE... | Call each module
module_gen should be a iterator | [
"Call",
"each",
"module"
] | train | https://github.com/brycepg/mand/blob/3a8f9c1cc1bbe217aaca8c805113285ab02ecb7c/mand/mand.py#L50-L63 |
brycepg/mand | mand/mand.py | replace_sys_args | def replace_sys_args(new_args):
"""Temporarily replace sys.argv with current arguments
Restores sys.argv upon exit of the context manager.
"""
# Replace sys.argv arguments
# for module import
old_args = sys.argv
sys.argv = new_args
try:
yield
finally:
sys.argv = old_... | python | def replace_sys_args(new_args):
"""Temporarily replace sys.argv with current arguments
Restores sys.argv upon exit of the context manager.
"""
# Replace sys.argv arguments
# for module import
old_args = sys.argv
sys.argv = new_args
try:
yield
finally:
sys.argv = old_... | [
"def",
"replace_sys_args",
"(",
"new_args",
")",
":",
"# Replace sys.argv arguments",
"# for module import",
"old_args",
"=",
"sys",
".",
"argv",
"sys",
".",
"argv",
"=",
"new_args",
"try",
":",
"yield",
"finally",
":",
"sys",
".",
"argv",
"=",
"old_args"
] | Temporarily replace sys.argv with current arguments
Restores sys.argv upon exit of the context manager. | [
"Temporarily",
"replace",
"sys",
".",
"argv",
"with",
"current",
"arguments"
] | train | https://github.com/brycepg/mand/blob/3a8f9c1cc1bbe217aaca8c805113285ab02ecb7c/mand/mand.py#L66-L78 |
edwards-lab/libGWAS | libgwas/bed_parser.py | Parser.ReportConfiguration | def ReportConfiguration(self, file):
""" Report configuration for logging purposes.
:param file: Destination for report details
:return: None
"""
print >> file, BuildReportLine("BED_FILE", self.bed_file)
print >> file, BuildReportLine("BIM_FILE", self.bim_file)
... | python | def ReportConfiguration(self, file):
""" Report configuration for logging purposes.
:param file: Destination for report details
:return: None
"""
print >> file, BuildReportLine("BED_FILE", self.bed_file)
print >> file, BuildReportLine("BIM_FILE", self.bim_file)
... | [
"def",
"ReportConfiguration",
"(",
"self",
",",
"file",
")",
":",
"print",
">>",
"file",
",",
"BuildReportLine",
"(",
"\"BED_FILE\"",
",",
"self",
".",
"bed_file",
")",
"print",
">>",
"file",
",",
"BuildReportLine",
"(",
"\"BIM_FILE\"",
",",
"self",
".",
"... | Report configuration for logging purposes.
:param file: Destination for report details
:return: None | [
"Report",
"configuration",
"for",
"logging",
"purposes",
"."
] | train | https://github.com/edwards-lab/libGWAS/blob/d68c9a083d443dfa5d7c5112de29010909cfe23f/libgwas/bed_parser.py#L106-L115 |
edwards-lab/libGWAS | libgwas/bed_parser.py | Parser.load_fam | def load_fam(self, pheno_covar=None):
"""Load contents from the .fam file, updating the pheno_covar with \
family ids found.
:param pheno_covar: Phenotype/covariate object
:return: None
"""
logging.info("Loading file: %s" % (self.fam_file))
pheno_col = 5
... | python | def load_fam(self, pheno_covar=None):
"""Load contents from the .fam file, updating the pheno_covar with \
family ids found.
:param pheno_covar: Phenotype/covariate object
:return: None
"""
logging.info("Loading file: %s" % (self.fam_file))
pheno_col = 5
... | [
"def",
"load_fam",
"(",
"self",
",",
"pheno_covar",
"=",
"None",
")",
":",
"logging",
".",
"info",
"(",
"\"Loading file: %s\"",
"%",
"(",
"self",
".",
"fam_file",
")",
")",
"pheno_col",
"=",
"5",
"if",
"not",
"DataParser",
".",
"has_sex",
":",
"pheno_col... | Load contents from the .fam file, updating the pheno_covar with \
family ids found.
:param pheno_covar: Phenotype/covariate object
:return: None | [
"Load",
"contents",
"from",
"the",
".",
"fam",
"file",
"updating",
"the",
"pheno_covar",
"with",
"\\",
"family",
"ids",
"found",
"."
] | train | https://github.com/edwards-lab/libGWAS/blob/d68c9a083d443dfa5d7c5112de29010909cfe23f/libgwas/bed_parser.py#L117-L159 |
edwards-lab/libGWAS | libgwas/bed_parser.py | Parser.load_bim | def load_bim(self, map3=False):
"""Basic marker details loading.
(chr, rsid, gen. dist, pos, allelel 1, allele2)
:param map3: When true, ignore the genetic distance column
:return: None
"""
cols = [0, 1, 3, 4, 5]
if map3:
cols = [0, 1, 2, 3, 4]
... | python | def load_bim(self, map3=False):
"""Basic marker details loading.
(chr, rsid, gen. dist, pos, allelel 1, allele2)
:param map3: When true, ignore the genetic distance column
:return: None
"""
cols = [0, 1, 3, 4, 5]
if map3:
cols = [0, 1, 2, 3, 4]
... | [
"def",
"load_bim",
"(",
"self",
",",
"map3",
"=",
"False",
")",
":",
"cols",
"=",
"[",
"0",
",",
"1",
",",
"3",
",",
"4",
",",
"5",
"]",
"if",
"map3",
":",
"cols",
"=",
"[",
"0",
",",
"1",
",",
"2",
",",
"3",
",",
"4",
"]",
"logging",
"... | Basic marker details loading.
(chr, rsid, gen. dist, pos, allelel 1, allele2)
:param map3: When true, ignore the genetic distance column
:return: None | [
"Basic",
"marker",
"details",
"loading",
"."
] | train | https://github.com/edwards-lab/libGWAS/blob/d68c9a083d443dfa5d7c5112de29010909cfe23f/libgwas/bed_parser.py#L162-L192 |
edwards-lab/libGWAS | libgwas/bed_parser.py | Parser.init_genotype_file | def init_genotype_file(self):
"""Resets the bed file and preps it for starting at the start of the \
genotype data
Returns to beginning of file and reads the version so that it points \
to first marker's info
:return: None
"""
self.genotype_file.seek(0)
... | python | def init_genotype_file(self):
"""Resets the bed file and preps it for starting at the start of the \
genotype data
Returns to beginning of file and reads the version so that it points \
to first marker's info
:return: None
"""
self.genotype_file.seek(0)
... | [
"def",
"init_genotype_file",
"(",
"self",
")",
":",
"self",
".",
"genotype_file",
".",
"seek",
"(",
"0",
")",
"buff",
"=",
"self",
".",
"genotype_file",
".",
"read",
"(",
"3",
")",
"version",
"=",
"0",
"magic",
",",
"data_format",
"=",
"buff",
".",
"... | Resets the bed file and preps it for starting at the start of the \
genotype data
Returns to beginning of file and reads the version so that it points \
to first marker's info
:return: None | [
"Resets",
"the",
"bed",
"file",
"and",
"preps",
"it",
"for",
"starting",
"at",
"the",
"start",
"of",
"the",
"\\",
"genotype",
"data"
] | train | https://github.com/edwards-lab/libGWAS/blob/d68c9a083d443dfa5d7c5112de29010909cfe23f/libgwas/bed_parser.py#L194-L208 |
edwards-lab/libGWAS | libgwas/bed_parser.py | Parser.extract_genotypes | def extract_genotypes(self, bytes):
"""Extracts encoded genotype data from binary formatted file.
:param bytes: array of bytes pulled from the .bed file
:return: standard python list containing the genotype data
Only ind_count genotypes will be returned (even if there are
a ha... | python | def extract_genotypes(self, bytes):
"""Extracts encoded genotype data from binary formatted file.
:param bytes: array of bytes pulled from the .bed file
:return: standard python list containing the genotype data
Only ind_count genotypes will be returned (even if there are
a ha... | [
"def",
"extract_genotypes",
"(",
"self",
",",
"bytes",
")",
":",
"genotypes",
"=",
"[",
"]",
"for",
"b",
"in",
"bytes",
":",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"4",
")",
":",
"v",
"=",
"(",
"(",
"b",
">>",
"(",
"i",
"*",
"2",
")",
")... | Extracts encoded genotype data from binary formatted file.
:param bytes: array of bytes pulled from the .bed file
:return: standard python list containing the genotype data
Only ind_count genotypes will be returned (even if there are
a handful of extra pairs present). | [
"Extracts",
"encoded",
"genotype",
"data",
"from",
"binary",
"formatted",
"file",
"."
] | train | https://github.com/edwards-lab/libGWAS/blob/d68c9a083d443dfa5d7c5112de29010909cfe23f/libgwas/bed_parser.py#L210-L226 |
edwards-lab/libGWAS | libgwas/bed_parser.py | Parser.filter_missing | def filter_missing(self):
"""Filter out individuals and SNPs that have too many missing to be \
considered
:return: None
This must be run prior to actually parsing the genotypes because it
initializes the following instance members:
* ind_mask
* tota... | python | def filter_missing(self):
"""Filter out individuals and SNPs that have too many missing to be \
considered
:return: None
This must be run prior to actually parsing the genotypes because it
initializes the following instance members:
* ind_mask
* tota... | [
"def",
"filter_missing",
"(",
"self",
")",
":",
"missing",
"=",
"None",
"locus_count",
"=",
"0",
"logging",
".",
"info",
"(",
"\"Sorting out missing data from genotype data\"",
")",
"# Filter out individuals according to missingness",
"self",
".",
"genotype_file",
".",
... | Filter out individuals and SNPs that have too many missing to be \
considered
:return: None
This must be run prior to actually parsing the genotypes because it
initializes the following instance members:
* ind_mask
* total_locus_count
* locus_cou... | [
"Filter",
"out",
"individuals",
"and",
"SNPs",
"that",
"have",
"too",
"many",
"missing",
"to",
"be",
"\\",
"considered"
] | train | https://github.com/edwards-lab/libGWAS/blob/d68c9a083d443dfa5d7c5112de29010909cfe23f/libgwas/bed_parser.py#L229-L313 |
edwards-lab/libGWAS | libgwas/bed_parser.py | Parser.populate_iteration | def populate_iteration(self, iteration):
"""Parse genotypes from the file and iteration with relevant marker \
details.
:param iteration: ParseLocus object which is returned per iteration
:return: True indicates current locus is valid.
StopIteration is thrown if the marker ... | python | def populate_iteration(self, iteration):
"""Parse genotypes from the file and iteration with relevant marker \
details.
:param iteration: ParseLocus object which is returned per iteration
:return: True indicates current locus is valid.
StopIteration is thrown if the marker ... | [
"def",
"populate_iteration",
"(",
"self",
",",
"iteration",
")",
":",
"cur_idx",
"=",
"iteration",
".",
"cur_idx",
"if",
"cur_idx",
"<",
"self",
".",
"total_locus_count",
":",
"buffer",
"=",
"struct",
".",
"unpack",
"(",
"self",
".",
"fmt_string",
",",
"se... | Parse genotypes from the file and iteration with relevant marker \
details.
:param iteration: ParseLocus object which is returned per iteration
:return: True indicates current locus is valid.
StopIteration is thrown if the marker reaches the end of the file or
the valid gen... | [
"Parse",
"genotypes",
"from",
"the",
"file",
"and",
"iteration",
"with",
"relevant",
"marker",
"\\",
"details",
"."
] | train | https://github.com/edwards-lab/libGWAS/blob/d68c9a083d443dfa5d7c5112de29010909cfe23f/libgwas/bed_parser.py#L323-L369 |
jalanb/pysyte | pysyte/bash/shell.py | _get_path | def _get_path():
"""Guarantee that /usr/local/bin and /usr/bin are in PATH"""
if _path:
return _path[0]
environ_paths = set(os.environ['PATH'].split(':'))
environ_paths.add('/usr/local/bin')
environ_paths.add('/usr/bin')
_path.append(':'.join(environ_paths))
logger.debug('PATH = %s',... | python | def _get_path():
"""Guarantee that /usr/local/bin and /usr/bin are in PATH"""
if _path:
return _path[0]
environ_paths = set(os.environ['PATH'].split(':'))
environ_paths.add('/usr/local/bin')
environ_paths.add('/usr/bin')
_path.append(':'.join(environ_paths))
logger.debug('PATH = %s',... | [
"def",
"_get_path",
"(",
")",
":",
"if",
"_path",
":",
"return",
"_path",
"[",
"0",
"]",
"environ_paths",
"=",
"set",
"(",
"os",
".",
"environ",
"[",
"'PATH'",
"]",
".",
"split",
"(",
"':'",
")",
")",
"environ_paths",
".",
"add",
"(",
"'/usr/local/bi... | Guarantee that /usr/local/bin and /usr/bin are in PATH | [
"Guarantee",
"that",
"/",
"usr",
"/",
"local",
"/",
"bin",
"and",
"/",
"usr",
"/",
"bin",
"are",
"in",
"PATH"
] | train | https://github.com/jalanb/pysyte/blob/4e278101943d1ceb1a6bcaf6ddc72052ecf13114/pysyte/bash/shell.py#L36-L45 |
jalanb/pysyte | pysyte/bash/shell.py | full_path | def full_path(path):
"""Get the real path, expanding links and bashisms"""
return os.path.realpath(os.path.expanduser(os.path.expandvars(path))) | python | def full_path(path):
"""Get the real path, expanding links and bashisms"""
return os.path.realpath(os.path.expanduser(os.path.expandvars(path))) | [
"def",
"full_path",
"(",
"path",
")",
":",
"return",
"os",
".",
"path",
".",
"realpath",
"(",
"os",
".",
"path",
".",
"expanduser",
"(",
"os",
".",
"path",
".",
"expandvars",
"(",
"path",
")",
")",
")"
] | Get the real path, expanding links and bashisms | [
"Get",
"the",
"real",
"path",
"expanding",
"links",
"and",
"bashisms"
] | train | https://github.com/jalanb/pysyte/blob/4e278101943d1ceb1a6bcaf6ddc72052ecf13114/pysyte/bash/shell.py#L69-L71 |
CitrineInformatics/dftparse | dftparse/core.py | BlockParser.parse | def parse(self, generator):
"""Parse an iterable source of strings into a generator"""
gen = iter(generator)
for line in gen:
block = {}
for rule in self.rules:
if rule[0](line):
block = rule[1](line, gen)
break
... | python | def parse(self, generator):
"""Parse an iterable source of strings into a generator"""
gen = iter(generator)
for line in gen:
block = {}
for rule in self.rules:
if rule[0](line):
block = rule[1](line, gen)
break
... | [
"def",
"parse",
"(",
"self",
",",
"generator",
")",
":",
"gen",
"=",
"iter",
"(",
"generator",
")",
"for",
"line",
"in",
"gen",
":",
"block",
"=",
"{",
"}",
"for",
"rule",
"in",
"self",
".",
"rules",
":",
"if",
"rule",
"[",
"0",
"]",
"(",
"line... | Parse an iterable source of strings into a generator | [
"Parse",
"an",
"iterable",
"source",
"of",
"strings",
"into",
"a",
"generator"
] | train | https://github.com/CitrineInformatics/dftparse/blob/53a1bf19945cf1c195d6af9beccb3d1b7f4a4c1d/dftparse/core.py#L15-L24 |
edwards-lab/libGWAS | libgwas/mach_parser.py | Parser.ReportConfiguration | def ReportConfiguration(self, file):
"""Report the configuration details for logging purposes.
:param file: Destination for report details
:return: None
"""
global encodingpar
print >> file, libgwas.BuildReportLine("MACH_ARCHIVES", "")
if self.chrpos_encoding:
... | python | def ReportConfiguration(self, file):
"""Report the configuration details for logging purposes.
:param file: Destination for report details
:return: None
"""
global encodingpar
print >> file, libgwas.BuildReportLine("MACH_ARCHIVES", "")
if self.chrpos_encoding:
... | [
"def",
"ReportConfiguration",
"(",
"self",
",",
"file",
")",
":",
"global",
"encodingpar",
"print",
">>",
"file",
",",
"libgwas",
".",
"BuildReportLine",
"(",
"\"MACH_ARCHIVES\"",
",",
"\"\"",
")",
"if",
"self",
".",
"chrpos_encoding",
":",
"print",
">>",
"f... | Report the configuration details for logging purposes.
:param file: Destination for report details
:return: None | [
"Report",
"the",
"configuration",
"details",
"for",
"logging",
"purposes",
"."
] | train | https://github.com/edwards-lab/libGWAS/blob/d68c9a083d443dfa5d7c5112de29010909cfe23f/libgwas/mach_parser.py#L147-L167 |
edwards-lab/libGWAS | libgwas/mach_parser.py | Parser.load_family_details | def load_family_details(self, pheno_covar):
"""Load contents from the .fam file, updating the pheno_covar with \
family ids found.
:param pheno_covar: Phenotype/covariate object
:return: None
"""
self.file_index = 0
# 1s indicate an individual is to be masked... | python | def load_family_details(self, pheno_covar):
"""Load contents from the .fam file, updating the pheno_covar with \
family ids found.
:param pheno_covar: Phenotype/covariate object
:return: None
"""
self.file_index = 0
# 1s indicate an individual is to be masked... | [
"def",
"load_family_details",
"(",
"self",
",",
"pheno_covar",
")",
":",
"self",
".",
"file_index",
"=",
"0",
"# 1s indicate an individual is to be masked out",
"mask_components",
"=",
"[",
"]",
"file",
"=",
"self",
".",
"family_details",
"if",
"DataParser",
".",
... | Load contents from the .fam file, updating the pheno_covar with \
family ids found.
:param pheno_covar: Phenotype/covariate object
:return: None | [
"Load",
"contents",
"from",
"the",
".",
"fam",
"file",
"updating",
"the",
"pheno_covar",
"with",
"\\",
"family",
"ids",
"found",
"."
] | train | https://github.com/edwards-lab/libGWAS/blob/d68c9a083d443dfa5d7c5112de29010909cfe23f/libgwas/mach_parser.py#L170-L207 |
edwards-lab/libGWAS | libgwas/mach_parser.py | Parser.parse_genotypes | def parse_genotypes(self, lb, ub):
"""Extracts a fraction of the file (current chunk of loci) loading
the genotypes into memoery.
:param lb: Lower bound of the current chunk
:param ub: Upper bound of the current chunk
:return: Dosage dosages for current chunk
"""
... | python | def parse_genotypes(self, lb, ub):
"""Extracts a fraction of the file (current chunk of loci) loading
the genotypes into memoery.
:param lb: Lower bound of the current chunk
:param ub: Upper bound of the current chunk
:return: Dosage dosages for current chunk
"""
... | [
"def",
"parse_genotypes",
"(",
"self",
",",
"lb",
",",
"ub",
")",
":",
"file",
"=",
"self",
".",
"openfile",
"(",
"self",
".",
"current_file",
")",
"words",
"=",
"file",
".",
"readline",
"(",
")",
".",
"strip",
"(",
")",
".",
"split",
"(",
")",
"... | Extracts a fraction of the file (current chunk of loci) loading
the genotypes into memoery.
:param lb: Lower bound of the current chunk
:param ub: Upper bound of the current chunk
:return: Dosage dosages for current chunk | [
"Extracts",
"a",
"fraction",
"of",
"the",
"file",
"(",
"current",
"chunk",
"of",
"loci",
")",
"loading",
"the",
"genotypes",
"into",
"memoery",
"."
] | train | https://github.com/edwards-lab/libGWAS/blob/d68c9a083d443dfa5d7c5112de29010909cfe23f/libgwas/mach_parser.py#L214-L239 |
edwards-lab/libGWAS | libgwas/mach_parser.py | Parser.load_genotypes | def load_genotypes(self):
"""Actually loads the first chunk of genotype data into memory due to \
the individual oriented format of MACH data.
Due to the fragmented approach to data loading necessary to avoid
running out of RAM, this function will initialize the data structures
... | python | def load_genotypes(self):
"""Actually loads the first chunk of genotype data into memory due to \
the individual oriented format of MACH data.
Due to the fragmented approach to data loading necessary to avoid
running out of RAM, this function will initialize the data structures
... | [
"def",
"load_genotypes",
"(",
"self",
")",
":",
"lb",
"=",
"self",
".",
"chunk",
"*",
"Parser",
".",
"chunk_stride",
"+",
"2",
"ub",
"=",
"(",
"self",
".",
"chunk",
"+",
"1",
")",
"*",
"Parser",
".",
"chunk_stride",
"+",
"2",
"buff",
"=",
"None",
... | Actually loads the first chunk of genotype data into memory due to \
the individual oriented format of MACH data.
Due to the fragmented approach to data loading necessary to avoid
running out of RAM, this function will initialize the data structures
with the first chunk of loci and prep... | [
"Actually",
"loads",
"the",
"first",
"chunk",
"of",
"genotype",
"data",
"into",
"memory",
"due",
"to",
"\\",
"the",
"individual",
"oriented",
"format",
"of",
"MACH",
"data",
"."
] | train | https://github.com/edwards-lab/libGWAS/blob/d68c9a083d443dfa5d7c5112de29010909cfe23f/libgwas/mach_parser.py#L241-L327 |
edwards-lab/libGWAS | libgwas/mach_parser.py | Parser.populate_iteration | def populate_iteration(self, iteration):
"""Parse genotypes from the file and iteration with relevant marker \
details.
:param iteration: ParseLocus object which is returned per iteration
:return: True indicates current locus is valid.
StopIteration is thrown if the marker ... | python | def populate_iteration(self, iteration):
"""Parse genotypes from the file and iteration with relevant marker \
details.
:param iteration: ParseLocus object which is returned per iteration
:return: True indicates current locus is valid.
StopIteration is thrown if the marker ... | [
"def",
"populate_iteration",
"(",
"self",
",",
"iteration",
")",
":",
"global",
"encoding",
"# We never have to worry about iteration exceptions...that is taken",
"# care of in load_genotypes",
"cur_idx",
"=",
"iteration",
".",
"cur_idx",
"if",
"cur_idx",
"<",
"0",
"or",
... | Parse genotypes from the file and iteration with relevant marker \
details.
:param iteration: ParseLocus object which is returned per iteration
:return: True indicates current locus is valid.
StopIteration is thrown if the marker reaches the end of the file or
the valid gen... | [
"Parse",
"genotypes",
"from",
"the",
"file",
"and",
"iteration",
"with",
"relevant",
"marker",
"\\",
"details",
"."
] | train | https://github.com/edwards-lab/libGWAS/blob/d68c9a083d443dfa5d7c5112de29010909cfe23f/libgwas/mach_parser.py#L334-L370 |
QualiSystems/qpm | qpm/packaging/driver_packager.py | zip_dir | def zip_dir(path, zip_handler, include_dir=True, use_arc_name=False):
"""
zip all files and items in dir
:param only_init:
:param path:
:param zip_handler: zip file handler
:param boolean include_dir: specify if we want the archive with or without the directory
"""
for root, dirs, files... | python | def zip_dir(path, zip_handler, include_dir=True, use_arc_name=False):
"""
zip all files and items in dir
:param only_init:
:param path:
:param zip_handler: zip file handler
:param boolean include_dir: specify if we want the archive with or without the directory
"""
for root, dirs, files... | [
"def",
"zip_dir",
"(",
"path",
",",
"zip_handler",
",",
"include_dir",
"=",
"True",
",",
"use_arc_name",
"=",
"False",
")",
":",
"for",
"root",
",",
"dirs",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"path",
")",
":",
"for",
"file_to_zip",
"in",
"fi... | zip all files and items in dir
:param only_init:
:param path:
:param zip_handler: zip file handler
:param boolean include_dir: specify if we want the archive with or without the directory | [
"zip",
"all",
"files",
"and",
"items",
"in",
"dir",
":",
"param",
"only_init",
":",
":",
"param",
"path",
":",
":",
"param",
"zip_handler",
":",
"zip",
"file",
"handler",
":",
"param",
"boolean",
"include_dir",
":",
"specify",
"if",
"we",
"want",
"the",
... | train | https://github.com/QualiSystems/qpm/blob/25d5b2a2edf05db9e0ae91fcd80f10da2cab778f/qpm/packaging/driver_packager.py#L17-L34 |
QualiSystems/qpm | qpm/packaging/driver_packager.py | add_init_files | def add_init_files(path, zip_handler):
"""
adds init files to the included folder
:param path: str
"""
paths = path.split('\\')
paths = paths[:len(paths) - 1]
for sub_path in paths:
for root, dirs, files in os.walk(sub_path):
for file_to_zip in [x for x in files if '__in... | python | def add_init_files(path, zip_handler):
"""
adds init files to the included folder
:param path: str
"""
paths = path.split('\\')
paths = paths[:len(paths) - 1]
for sub_path in paths:
for root, dirs, files in os.walk(sub_path):
for file_to_zip in [x for x in files if '__in... | [
"def",
"add_init_files",
"(",
"path",
",",
"zip_handler",
")",
":",
"paths",
"=",
"path",
".",
"split",
"(",
"'\\\\'",
")",
"paths",
"=",
"paths",
"[",
":",
"len",
"(",
"paths",
")",
"-",
"1",
"]",
"for",
"sub_path",
"in",
"paths",
":",
"for",
"roo... | adds init files to the included folder
:param path: str | [
"adds",
"init",
"files",
"to",
"the",
"included",
"folder",
":",
"param",
"path",
":",
"str"
] | train | https://github.com/QualiSystems/qpm/blob/25d5b2a2edf05db9e0ae91fcd80f10da2cab778f/qpm/packaging/driver_packager.py#L37-L54 |
vex1023/vxUtils | vxUtils/decorator.py | retry | def retry(tries, CatchExceptions=(Exception,), delay=0.01, backoff=2):
'''
错误重试的修饰器
:param tries: 重试次数
:param CatchExceptions: 需要重试的exception列表
:param delay: 重试前等待
:param backoff: 重试n次后,需要等待delay * n * backoff
:return:
@retry(5,ValueError)
def test():
raise ValueError
... | python | def retry(tries, CatchExceptions=(Exception,), delay=0.01, backoff=2):
'''
错误重试的修饰器
:param tries: 重试次数
:param CatchExceptions: 需要重试的exception列表
:param delay: 重试前等待
:param backoff: 重试n次后,需要等待delay * n * backoff
:return:
@retry(5,ValueError)
def test():
raise ValueError
... | [
"def",
"retry",
"(",
"tries",
",",
"CatchExceptions",
"=",
"(",
"Exception",
",",
")",
",",
"delay",
"=",
"0.01",
",",
"backoff",
"=",
"2",
")",
":",
"if",
"backoff",
"<=",
"1",
":",
"raise",
"ValueError",
"(",
"\"backoff must be greater than 1\"",
")",
... | 错误重试的修饰器
:param tries: 重试次数
:param CatchExceptions: 需要重试的exception列表
:param delay: 重试前等待
:param backoff: 重试n次后,需要等待delay * n * backoff
:return:
@retry(5,ValueError)
def test():
raise ValueError | [
"错误重试的修饰器",
":",
"param",
"tries",
":",
"重试次数",
":",
"param",
"CatchExceptions",
":",
"需要重试的exception列表",
":",
"param",
"delay",
":",
"重试前等待",
":",
"param",
"backoff",
":",
"重试n次后,需要等待delay",
"*",
"n",
"*",
"backoff",
":",
"return",
":"
] | train | https://github.com/vex1023/vxUtils/blob/58120a206cf96c4231d1e63d271c9d533d5f0a89/vxUtils/decorator.py#L26-L70 |
vex1023/vxUtils | vxUtils/decorator.py | timeit | def timeit(func):
'''
计算运行消耗时间
@timeit
def test():
time.sleep(1)
'''
def wapper(*args, **kwargs):
_start = time.time()
retval = func(*args, **kwargs)
_end = time.time()
logger.info('function %s() used : %.6f s' % (func.__name__, _end - _start))
re... | python | def timeit(func):
'''
计算运行消耗时间
@timeit
def test():
time.sleep(1)
'''
def wapper(*args, **kwargs):
_start = time.time()
retval = func(*args, **kwargs)
_end = time.time()
logger.info('function %s() used : %.6f s' % (func.__name__, _end - _start))
re... | [
"def",
"timeit",
"(",
"func",
")",
":",
"def",
"wapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"_start",
"=",
"time",
".",
"time",
"(",
")",
"retval",
"=",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"_end",
"=",
"t... | 计算运行消耗时间
@timeit
def test():
time.sleep(1) | [
"计算运行消耗时间"
] | train | https://github.com/vex1023/vxUtils/blob/58120a206cf96c4231d1e63d271c9d533d5f0a89/vxUtils/decorator.py#L77-L92 |
vex1023/vxUtils | vxUtils/decorator.py | singleton | def singleton(cls):
'''
单例实现
@singleton
class test():
pass
'''
cls.__new_original__ = cls.__new__
@wraps(cls.__new__)
def singleton_new(cls, *args, **kw):
it = cls.__dict__.get('__it__')
if it is not None:
return it
cls.__it__ = it = cls.__n... | python | def singleton(cls):
'''
单例实现
@singleton
class test():
pass
'''
cls.__new_original__ = cls.__new__
@wraps(cls.__new__)
def singleton_new(cls, *args, **kw):
it = cls.__dict__.get('__it__')
if it is not None:
return it
cls.__it__ = it = cls.__n... | [
"def",
"singleton",
"(",
"cls",
")",
":",
"cls",
".",
"__new_original__",
"=",
"cls",
".",
"__new__",
"@",
"wraps",
"(",
"cls",
".",
"__new__",
")",
"def",
"singleton_new",
"(",
"cls",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"it",
"=",
"... | 单例实现
@singleton
class test():
pass | [
"单例实现"
] | train | https://github.com/vex1023/vxUtils/blob/58120a206cf96c4231d1e63d271c9d533d5f0a89/vxUtils/decorator.py#L99-L123 |
salimm/msgpack-pystream | msgpackstream/backend/python/format.py | FormatUtil._empty_value | def _empty_value(self, formattype):
'''
returns default empty value
:param formattype:
:param buff:
:param start:
:param end:
'''
if formattype.value.idx <= FormatType.BIN_32.value.idx: # @UndefinedVariable
return b''
elif formatt... | python | def _empty_value(self, formattype):
'''
returns default empty value
:param formattype:
:param buff:
:param start:
:param end:
'''
if formattype.value.idx <= FormatType.BIN_32.value.idx: # @UndefinedVariable
return b''
elif formatt... | [
"def",
"_empty_value",
"(",
"self",
",",
"formattype",
")",
":",
"if",
"formattype",
".",
"value",
".",
"idx",
"<=",
"FormatType",
".",
"BIN_32",
".",
"value",
".",
"idx",
":",
"# @UndefinedVariable",
"return",
"b''",
"elif",
"formattype",
".",
"value",
".... | returns default empty value
:param formattype:
:param buff:
:param start:
:param end: | [
"returns",
"default",
"empty",
"value",
":",
"param",
"formattype",
":",
":",
"param",
"buff",
":",
":",
"param",
"start",
":",
":",
"param",
"end",
":"
] | train | https://github.com/salimm/msgpack-pystream/blob/676158a5a8dd8ff56dca080d597943f67fc4325e/msgpackstream/backend/python/format.py#L83-L102 |
asyncdef/interfaces | asyncdef/interfaces/engine/icoroutine.py | ICoroutine.cancel | def cancel(
self,
identifier: typing.Any,
exc_type: typing.Optional[type]=None,
) -> bool:
"""Cancel an active coroutine and remove it from the schedule.
Args:
identifier (typing.Any): The identifier returned from add.
exc_type (typing.Opt... | python | def cancel(
self,
identifier: typing.Any,
exc_type: typing.Optional[type]=None,
) -> bool:
"""Cancel an active coroutine and remove it from the schedule.
Args:
identifier (typing.Any): The identifier returned from add.
exc_type (typing.Opt... | [
"def",
"cancel",
"(",
"self",
",",
"identifier",
":",
"typing",
".",
"Any",
",",
"exc_type",
":",
"typing",
".",
"Optional",
"[",
"type",
"]",
"=",
"None",
",",
")",
"->",
"bool",
":",
"raise",
"NotImplementedError",
"(",
")"
] | Cancel an active coroutine and remove it from the schedule.
Args:
identifier (typing.Any): The identifier returned from add.
exc_type (typing.Optional[type]): The exception type to throw into
the coroutine on cancel. No exception is thrown if nothing is
g... | [
"Cancel",
"an",
"active",
"coroutine",
"and",
"remove",
"it",
"from",
"the",
"schedule",
"."
] | train | https://github.com/asyncdef/interfaces/blob/17c589c6ab158e3d9977a6d9da6d5ecd44844285/asyncdef/interfaces/engine/icoroutine.py#L29-L46 |
mayfield/shellish | shellish/command/supplement.py | ShellishHelpFormatter._fill_text | def _fill_text(self, text, width=None, indent=None):
""" Reflow text width while maintaining certain formatting
characteristics like double newlines and indented statements. """
assert isinstance(text, str)
if indent is None:
indent = NBSP * self._current_indent
asser... | python | def _fill_text(self, text, width=None, indent=None):
""" Reflow text width while maintaining certain formatting
characteristics like double newlines and indented statements. """
assert isinstance(text, str)
if indent is None:
indent = NBSP * self._current_indent
asser... | [
"def",
"_fill_text",
"(",
"self",
",",
"text",
",",
"width",
"=",
"None",
",",
"indent",
"=",
"None",
")",
":",
"assert",
"isinstance",
"(",
"text",
",",
"str",
")",
"if",
"indent",
"is",
"None",
":",
"indent",
"=",
"NBSP",
"*",
"self",
".",
"_curr... | Reflow text width while maintaining certain formatting
characteristics like double newlines and indented statements. | [
"Reflow",
"text",
"width",
"while",
"maintaining",
"certain",
"formatting",
"characteristics",
"like",
"double",
"newlines",
"and",
"indented",
"statements",
"."
] | train | https://github.com/mayfield/shellish/blob/df0f0e4612d138c34d8cb99b66ab5b8e47f1414a/shellish/command/supplement.py#L61-L99 |
mayfield/shellish | shellish/command/supplement.py | ShellishParser.bind_env | def bind_env(self, action, env):
""" Bind an environment variable to an argument action. The env
value will traditionally be something uppercase like `MYAPP_FOO_ARG`.
Note that the ENV value is assigned using `set_defaults()` and as such
it will be overridden if the argument is set via... | python | def bind_env(self, action, env):
""" Bind an environment variable to an argument action. The env
value will traditionally be something uppercase like `MYAPP_FOO_ARG`.
Note that the ENV value is assigned using `set_defaults()` and as such
it will be overridden if the argument is set via... | [
"def",
"bind_env",
"(",
"self",
",",
"action",
",",
"env",
")",
":",
"if",
"env",
"in",
"self",
".",
"_env_actions",
":",
"raise",
"ValueError",
"(",
"'Duplicate ENV variable: %s'",
"%",
"env",
")",
"self",
".",
"_env_actions",
"[",
"env",
"]",
"=",
"act... | Bind an environment variable to an argument action. The env
value will traditionally be something uppercase like `MYAPP_FOO_ARG`.
Note that the ENV value is assigned using `set_defaults()` and as such
it will be overridden if the argument is set via `parse_args()` | [
"Bind",
"an",
"environment",
"variable",
"to",
"an",
"argument",
"action",
".",
"The",
"env",
"value",
"will",
"traditionally",
"be",
"something",
"uppercase",
"like",
"MYAPP_FOO_ARG",
"."
] | train | https://github.com/mayfield/shellish/blob/df0f0e4612d138c34d8cb99b66ab5b8e47f1414a/shellish/command/supplement.py#L278-L287 |
mayfield/shellish | shellish/command/supplement.py | ShellishParser.print_help | def print_help(self, *args, **kwargs):
""" Add pager support to help output. """
if self._command is not None and self._command.session.allow_pager:
desc = 'Help\: %s' % '-'.join(self.prog.split())
pager_kwargs = self._command.get_pager_spec()
with paging.pager_redire... | python | def print_help(self, *args, **kwargs):
""" Add pager support to help output. """
if self._command is not None and self._command.session.allow_pager:
desc = 'Help\: %s' % '-'.join(self.prog.split())
pager_kwargs = self._command.get_pager_spec()
with paging.pager_redire... | [
"def",
"print_help",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"_command",
"is",
"not",
"None",
"and",
"self",
".",
"_command",
".",
"session",
".",
"allow_pager",
":",
"desc",
"=",
"'Help\\: %s'",
"%",
"'-'... | Add pager support to help output. | [
"Add",
"pager",
"support",
"to",
"help",
"output",
"."
] | train | https://github.com/mayfield/shellish/blob/df0f0e4612d138c34d8cb99b66ab5b8e47f1414a/shellish/command/supplement.py#L329-L337 |
mayfield/shellish | shellish/command/supplement.py | ShellishParser.add_subparsers | def add_subparsers(self, prog=None, **kwargs):
""" Supplement a proper `prog` keyword argument for the subprocessor.
The superclass technique for getting the `prog` value breaks because
of our VT100 escape codes injected by `format_help`. """
if prog is None:
# Use a non-shel... | python | def add_subparsers(self, prog=None, **kwargs):
""" Supplement a proper `prog` keyword argument for the subprocessor.
The superclass technique for getting the `prog` value breaks because
of our VT100 escape codes injected by `format_help`. """
if prog is None:
# Use a non-shel... | [
"def",
"add_subparsers",
"(",
"self",
",",
"prog",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"prog",
"is",
"None",
":",
"# Use a non-shellish help formatter to avoid vt100 codes.",
"f",
"=",
"argparse",
".",
"HelpFormatter",
"(",
"prog",
"=",
"self... | Supplement a proper `prog` keyword argument for the subprocessor.
The superclass technique for getting the `prog` value breaks because
of our VT100 escape codes injected by `format_help`. | [
"Supplement",
"a",
"proper",
"prog",
"keyword",
"argument",
"for",
"the",
"subprocessor",
".",
"The",
"superclass",
"technique",
"for",
"getting",
"the",
"prog",
"value",
"breaks",
"because",
"of",
"our",
"VT100",
"escape",
"codes",
"injected",
"by",
"format_hel... | train | https://github.com/mayfield/shellish/blob/df0f0e4612d138c34d8cb99b66ab5b8e47f1414a/shellish/command/supplement.py#L351-L361 |
ThreshingFloor/libtf | libtf/logparsers/tf_generic_log.py | TFGenericLog._analyze | def _analyze(self):
"""
Apply the filter to the log file
"""
for parsed_line in self.parsed_lines:
if 'ip' in parsed_line:
if parsed_line['ip'] in self.filter['ips']:
self.noisy_logs.append(parsed_line)
else:
... | python | def _analyze(self):
"""
Apply the filter to the log file
"""
for parsed_line in self.parsed_lines:
if 'ip' in parsed_line:
if parsed_line['ip'] in self.filter['ips']:
self.noisy_logs.append(parsed_line)
else:
... | [
"def",
"_analyze",
"(",
"self",
")",
":",
"for",
"parsed_line",
"in",
"self",
".",
"parsed_lines",
":",
"if",
"'ip'",
"in",
"parsed_line",
":",
"if",
"parsed_line",
"[",
"'ip'",
"]",
"in",
"self",
".",
"filter",
"[",
"'ips'",
"]",
":",
"self",
".",
"... | Apply the filter to the log file | [
"Apply",
"the",
"filter",
"to",
"the",
"log",
"file"
] | train | https://github.com/ThreshingFloor/libtf/blob/f1a8710f750639c9b9e2a468ece0d2923bf8c3df/libtf/logparsers/tf_generic_log.py#L16-L27 |
ThreshingFloor/libtf | libtf/logparsers/tf_generic_log.py | TFGenericLog._extract_line_features | def _extract_line_features(self):
"""
Parse raw log lines and convert it to a dictionary with extracted features.
"""
for line in self.line_iterator:
m = re.search(GENERIC_IPV4_REGEX, line)
data = {
'raw': line
}
if m:
... | python | def _extract_line_features(self):
"""
Parse raw log lines and convert it to a dictionary with extracted features.
"""
for line in self.line_iterator:
m = re.search(GENERIC_IPV4_REGEX, line)
data = {
'raw': line
}
if m:
... | [
"def",
"_extract_line_features",
"(",
"self",
")",
":",
"for",
"line",
"in",
"self",
".",
"line_iterator",
":",
"m",
"=",
"re",
".",
"search",
"(",
"GENERIC_IPV4_REGEX",
",",
"line",
")",
"data",
"=",
"{",
"'raw'",
":",
"line",
"}",
"if",
"m",
":",
"... | Parse raw log lines and convert it to a dictionary with extracted features. | [
"Parse",
"raw",
"log",
"lines",
"and",
"convert",
"it",
"to",
"a",
"dictionary",
"with",
"extracted",
"features",
"."
] | train | https://github.com/ThreshingFloor/libtf/blob/f1a8710f750639c9b9e2a468ece0d2923bf8c3df/libtf/logparsers/tf_generic_log.py#L29-L43 |
ThreshingFloor/libtf | libtf/logparsers/tf_generic_log.py | TFGenericLog._extract_features | def _extract_features(self):
"""
Get the feature data from the log file necessary for a reduction
"""
for parsed_line in self.parsed_lines:
result = {'raw': parsed_line}
if 'ip' in parsed_line:
result['ip'] = parsed_line['ip']
if r... | python | def _extract_features(self):
"""
Get the feature data from the log file necessary for a reduction
"""
for parsed_line in self.parsed_lines:
result = {'raw': parsed_line}
if 'ip' in parsed_line:
result['ip'] = parsed_line['ip']
if r... | [
"def",
"_extract_features",
"(",
"self",
")",
":",
"for",
"parsed_line",
"in",
"self",
".",
"parsed_lines",
":",
"result",
"=",
"{",
"'raw'",
":",
"parsed_line",
"}",
"if",
"'ip'",
"in",
"parsed_line",
":",
"result",
"[",
"'ip'",
"]",
"=",
"parsed_line",
... | Get the feature data from the log file necessary for a reduction | [
"Get",
"the",
"feature",
"data",
"from",
"the",
"log",
"file",
"necessary",
"for",
"a",
"reduction"
] | train | https://github.com/ThreshingFloor/libtf/blob/f1a8710f750639c9b9e2a468ece0d2923bf8c3df/libtf/logparsers/tf_generic_log.py#L45-L55 |
the01/python-paps | paps/si/app/sensor.py | Sensor._get_local_ip | def _get_local_ip():
"""
Get the local ip of this device
:return: Ip of this computer
:rtype: str
"""
return set([x[4][0] for x in socket.getaddrinfo(
socket.gethostname(),
80,
socket.AF_INET
)]).pop() | python | def _get_local_ip():
"""
Get the local ip of this device
:return: Ip of this computer
:rtype: str
"""
return set([x[4][0] for x in socket.getaddrinfo(
socket.gethostname(),
80,
socket.AF_INET
)]).pop() | [
"def",
"_get_local_ip",
"(",
")",
":",
"return",
"set",
"(",
"[",
"x",
"[",
"4",
"]",
"[",
"0",
"]",
"for",
"x",
"in",
"socket",
".",
"getaddrinfo",
"(",
"socket",
".",
"gethostname",
"(",
")",
",",
"80",
",",
"socket",
".",
"AF_INET",
")",
"]",
... | Get the local ip of this device
:return: Ip of this computer
:rtype: str | [
"Get",
"the",
"local",
"ip",
"of",
"this",
"device"
] | train | https://github.com/the01/python-paps/blob/2dde5a71913e4c7b22901cf05c6ecedd890919c4/paps/si/app/sensor.py#L96-L107 |
the01/python-paps | paps/si/app/sensor.py | Sensor._init_listen_socket | def _init_listen_socket(self):
"""
Init listen socket
:rtype: None
"""
self.debug("()")
self._listen_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self._listen_socket.setsockopt(
socket.SOL_SOCKET,
socket.SO_REUSEADDR,
... | python | def _init_listen_socket(self):
"""
Init listen socket
:rtype: None
"""
self.debug("()")
self._listen_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self._listen_socket.setsockopt(
socket.SOL_SOCKET,
socket.SO_REUSEADDR,
... | [
"def",
"_init_listen_socket",
"(",
"self",
")",
":",
"self",
".",
"debug",
"(",
"\"()\"",
")",
"self",
".",
"_listen_socket",
"=",
"socket",
".",
"socket",
"(",
"socket",
".",
"AF_INET",
",",
"socket",
".",
"SOCK_DGRAM",
")",
"self",
".",
"_listen_socket",... | Init listen socket
:rtype: None | [
"Init",
"listen",
"socket"
] | train | https://github.com/the01/python-paps/blob/2dde5a71913e4c7b22901cf05c6ecedd890919c4/paps/si/app/sensor.py#L109-L123 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.