repo
stringlengths
7
55
path
stringlengths
4
223
func_name
stringlengths
1
134
original_string
stringlengths
75
104k
language
stringclasses
1 value
code
stringlengths
75
104k
code_tokens
listlengths
19
28.4k
docstring
stringlengths
1
46.9k
docstring_tokens
listlengths
1
1.97k
sha
stringlengths
40
40
url
stringlengths
87
315
partition
stringclasses
3 values
summary
stringlengths
4
350
tjcsl/cslbot
cslbot/commands/ping.py
cmd
def cmd(send, msg, args): """Ping something. Syntax: {command} <target> """ if not msg: send("Ping what?") return channel = args['target'] if args['target'] != 'private' else args['nick'] # CTCP PING if "." not in msg and ":" not in msg: targets = set(msg.split()) ...
python
def cmd(send, msg, args): """Ping something. Syntax: {command} <target> """ if not msg: send("Ping what?") return channel = args['target'] if args['target'] != 'private' else args['nick'] # CTCP PING if "." not in msg and ":" not in msg: targets = set(msg.split()) ...
[ "def", "cmd", "(", "send", ",", "msg", ",", "args", ")", ":", "if", "not", "msg", ":", "send", "(", "\"Ping what?\"", ")", "return", "channel", "=", "args", "[", "'target'", "]", "if", "args", "[", "'target'", "]", "!=", "'private'", "else", "args", ...
Ping something. Syntax: {command} <target>
[ "Ping", "something", "." ]
aebe07be47141f61d7c180706bddfb707f19b2b5
https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/ping.py#L26-L58
train
Ping something.
shapiromatron/bmds
bmds/models/base.py
BMDModel.execute_job
async def execute_job(self): """ Execute the BMDS model and parse outputs if successful. """ self.execution_start = datetime.now() # exit early if execution is not possible if not self.can_be_executed: return self._set_job_outputs(RunStatus.DID_NOT_RUN) ...
python
async def execute_job(self): """ Execute the BMDS model and parse outputs if successful. """ self.execution_start = datetime.now() # exit early if execution is not possible if not self.can_be_executed: return self._set_job_outputs(RunStatus.DID_NOT_RUN) ...
[ "async", "def", "execute_job", "(", "self", ")", ":", "self", ".", "execution_start", "=", "datetime", ".", "now", "(", ")", "# exit early if execution is not possible", "if", "not", "self", ".", "can_be_executed", ":", "return", "self", ".", "_set_job_outputs", ...
Execute the BMDS model and parse outputs if successful.
[ "Execute", "the", "BMDS", "model", "and", "parse", "outputs", "if", "successful", "." ]
395c6ce84ad82876fd9fa4a89a3497fb61616de0
https://github.com/shapiromatron/bmds/blob/395c6ce84ad82876fd9fa4a89a3497fb61616de0/bmds/models/base.py#L91-L143
train
Execute the BMDS model and parse outputs if successful.
shapiromatron/bmds
bmds/models/base.py
BMDModel.execution_duration
def execution_duration(self): """ Returns total BMDS execution time, in seconds. """ duration = None if self.execution_start and self.execution_end: delta = self.execution_end - self.execution_start duration = delta.total_seconds() return duration
python
def execution_duration(self): """ Returns total BMDS execution time, in seconds. """ duration = None if self.execution_start and self.execution_end: delta = self.execution_end - self.execution_start duration = delta.total_seconds() return duration
[ "def", "execution_duration", "(", "self", ")", ":", "duration", "=", "None", "if", "self", ".", "execution_start", "and", "self", ".", "execution_end", ":", "delta", "=", "self", ".", "execution_end", "-", "self", ".", "execution_start", "duration", "=", "de...
Returns total BMDS execution time, in seconds.
[ "Returns", "total", "BMDS", "execution", "time", "in", "seconds", "." ]
395c6ce84ad82876fd9fa4a89a3497fb61616de0
https://github.com/shapiromatron/bmds/blob/395c6ce84ad82876fd9fa4a89a3497fb61616de0/bmds/models/base.py#L155-L163
train
Returns total execution time in seconds.
shapiromatron/bmds
bmds/models/base.py
BMDModel.get_exe_path
def get_exe_path(cls): """ Return the full path to the executable. """ return os.path.abspath(os.path.join(ROOT, cls.bmds_version_dir, cls.exe + ".exe"))
python
def get_exe_path(cls): """ Return the full path to the executable. """ return os.path.abspath(os.path.join(ROOT, cls.bmds_version_dir, cls.exe + ".exe"))
[ "def", "get_exe_path", "(", "cls", ")", ":", "return", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "join", "(", "ROOT", ",", "cls", ".", "bmds_version_dir", ",", "cls", ".", "exe", "+", "\".exe\"", ")", ")" ]
Return the full path to the executable.
[ "Return", "the", "full", "path", "to", "the", "executable", "." ]
395c6ce84ad82876fd9fa4a89a3497fb61616de0
https://github.com/shapiromatron/bmds/blob/395c6ce84ad82876fd9fa4a89a3497fb61616de0/bmds/models/base.py#L173-L177
train
Returns the full path to the executable.
shapiromatron/bmds
bmds/models/base.py
BMDModel.plot
def plot(self): """ After model execution, print the dataset, curve-fit, BMD, and BMDL. Example ------- >>> import os >>> fn = os.path.expanduser('~/Desktop/image.png') >>> fig = model.plot() >>> fig.savefig(fn) >>> fig.clear() .. figure...
python
def plot(self): """ After model execution, print the dataset, curve-fit, BMD, and BMDL. Example ------- >>> import os >>> fn = os.path.expanduser('~/Desktop/image.png') >>> fig = model.plot() >>> fig.savefig(fn) >>> fig.clear() .. figure...
[ "def", "plot", "(", "self", ")", ":", "fig", "=", "self", ".", "dataset", ".", "plot", "(", ")", "ax", "=", "fig", ".", "gca", "(", ")", "ax", ".", "set_title", "(", "\"{}\\n{}, {}\"", ".", "format", "(", "self", ".", "dataset", ".", "_get_dataset_...
After model execution, print the dataset, curve-fit, BMD, and BMDL. Example ------- >>> import os >>> fn = os.path.expanduser('~/Desktop/image.png') >>> fig = model.plot() >>> fig.savefig(fn) >>> fig.clear() .. figure:: ../tests/resources/test_exponenti...
[ "After", "model", "execution", "print", "the", "dataset", "curve", "-", "fit", "BMD", "and", "BMDL", "." ]
395c6ce84ad82876fd9fa4a89a3497fb61616de0
https://github.com/shapiromatron/bmds/blob/395c6ce84ad82876fd9fa4a89a3497fb61616de0/bmds/models/base.py#L215-L251
train
Plot the dataset curve - fit BMD and BMDL.
shapiromatron/bmds
bmds/models/base.py
BMDModel.write_dfile
def write_dfile(self): """ Write the generated d_file to a temporary file. """ f_in = self.tempfiles.get_tempfile(prefix="bmds-", suffix=".(d)") with open(f_in, "w") as f: f.write(self.as_dfile()) return f_in
python
def write_dfile(self): """ Write the generated d_file to a temporary file. """ f_in = self.tempfiles.get_tempfile(prefix="bmds-", suffix=".(d)") with open(f_in, "w") as f: f.write(self.as_dfile()) return f_in
[ "def", "write_dfile", "(", "self", ")", ":", "f_in", "=", "self", ".", "tempfiles", ".", "get_tempfile", "(", "prefix", "=", "\"bmds-\"", ",", "suffix", "=", "\".(d)\"", ")", "with", "open", "(", "f_in", ",", "\"w\"", ")", "as", "f", ":", "f", ".", ...
Write the generated d_file to a temporary file.
[ "Write", "the", "generated", "d_file", "to", "a", "temporary", "file", "." ]
395c6ce84ad82876fd9fa4a89a3497fb61616de0
https://github.com/shapiromatron/bmds/blob/395c6ce84ad82876fd9fa4a89a3497fb61616de0/bmds/models/base.py#L316-L323
train
Write the generated d_file to a temporary file.
shapiromatron/bmds
bmds/models/base.py
BMDModel._get_option_value
def _get_option_value(self, key): """ Get option value(s), or use default value if no override value. Two output values for 'p' type values (parameters), else one. Returns a single value or tuple of two values """ fn_name = "set_{}_value".format(key) if key in se...
python
def _get_option_value(self, key): """ Get option value(s), or use default value if no override value. Two output values for 'p' type values (parameters), else one. Returns a single value or tuple of two values """ fn_name = "set_{}_value".format(key) if key in se...
[ "def", "_get_option_value", "(", "self", ",", "key", ")", ":", "fn_name", "=", "\"set_{}_value\"", ".", "format", "(", "key", ")", "if", "key", "in", "self", ".", "overrides", ":", "val", "=", "self", ".", "overrides", "[", "key", "]", "elif", "hasattr...
Get option value(s), or use default value if no override value. Two output values for 'p' type values (parameters), else one. Returns a single value or tuple of two values
[ "Get", "option", "value", "(", "s", ")", "or", "use", "default", "value", "if", "no", "override", "value", "." ]
395c6ce84ad82876fd9fa4a89a3497fb61616de0
https://github.com/shapiromatron/bmds/blob/395c6ce84ad82876fd9fa4a89a3497fb61616de0/bmds/models/base.py#L333-L351
train
Get option value or use default value.
shapiromatron/bmds
bmds/models/base.py
BMDModel.to_dict
def to_dict(self, model_index): """ Return a summary of the model in a dictionary format for serialization. Parameters ---------- model_index : int The index of the model in a list of models, should be unique Returns ------- out : dictionary ...
python
def to_dict(self, model_index): """ Return a summary of the model in a dictionary format for serialization. Parameters ---------- model_index : int The index of the model in a list of models, should be unique Returns ------- out : dictionary ...
[ "def", "to_dict", "(", "self", ",", "model_index", ")", ":", "return", "dict", "(", "name", "=", "self", ".", "name", ",", "model_index", "=", "model_index", ",", "model_name", "=", "self", ".", "model_name", ",", "model_version", "=", "self", ".", "vers...
Return a summary of the model in a dictionary format for serialization. Parameters ---------- model_index : int The index of the model in a list of models, should be unique Returns ------- out : dictionary A dictionary of model inputs, and raw an...
[ "Return", "a", "summary", "of", "the", "model", "in", "a", "dictionary", "format", "for", "serialization", "." ]
395c6ce84ad82876fd9fa4a89a3497fb61616de0
https://github.com/shapiromatron/bmds/blob/395c6ce84ad82876fd9fa4a89a3497fb61616de0/bmds/models/base.py#L395-L425
train
Returns a dictionary representation of the current state of the current model.
jlesquembre/autopilot
src/autopilot/utils.py
merge_config
def merge_config(d1, d2): '''Merges to config dicts. Key values are case insensitive for merging, but the value of d1 is remembered. ''' result = deepcopy(d1) elements = deque() elements.append((result, d2)) while elements: old, new = elements.popleft() new = OrderedDict([(...
python
def merge_config(d1, d2): '''Merges to config dicts. Key values are case insensitive for merging, but the value of d1 is remembered. ''' result = deepcopy(d1) elements = deque() elements.append((result, d2)) while elements: old, new = elements.popleft() new = OrderedDict([(...
[ "def", "merge_config", "(", "d1", ",", "d2", ")", ":", "result", "=", "deepcopy", "(", "d1", ")", "elements", "=", "deque", "(", ")", "elements", ".", "append", "(", "(", "result", ",", "d2", ")", ")", "while", "elements", ":", "old", ",", "new", ...
Merges to config dicts. Key values are case insensitive for merging, but the value of d1 is remembered.
[ "Merges", "to", "config", "dicts", ".", "Key", "values", "are", "case", "insensitive", "for", "merging", "but", "the", "value", "of", "d1", "is", "remembered", "." ]
ca5f36269ba0173bd29c39db6971dac57a58513d
https://github.com/jlesquembre/autopilot/blob/ca5f36269ba0173bd29c39db6971dac57a58513d/src/autopilot/utils.py#L74-L102
train
Merges two config dicts.
jlesquembre/autopilot
src/autopilot/utils.py
set_if_none
def set_if_none(user_config, config, key, value): ''' If the value of the key in is None, and doesn't exist on the user config, set it to a different value ''' keys = key.split('.') for k in keys[:-1]: try: user_config = user_config[k] except KeyError: us...
python
def set_if_none(user_config, config, key, value): ''' If the value of the key in is None, and doesn't exist on the user config, set it to a different value ''' keys = key.split('.') for k in keys[:-1]: try: user_config = user_config[k] except KeyError: us...
[ "def", "set_if_none", "(", "user_config", ",", "config", ",", "key", ",", "value", ")", ":", "keys", "=", "key", ".", "split", "(", "'.'", ")", "for", "k", "in", "keys", "[", ":", "-", "1", "]", ":", "try", ":", "user_config", "=", "user_config", ...
If the value of the key in is None, and doesn't exist on the user config, set it to a different value
[ "If", "the", "value", "of", "the", "key", "in", "is", "None", "and", "doesn", "t", "exist", "on", "the", "user", "config", "set", "it", "to", "a", "different", "value" ]
ca5f36269ba0173bd29c39db6971dac57a58513d
https://github.com/jlesquembre/autopilot/blob/ca5f36269ba0173bd29c39db6971dac57a58513d/src/autopilot/utils.py#L116-L134
train
Set the value of the key in config to value if the value of the key in is None.
jlesquembre/autopilot
src/autopilot/utils.py
get_header
def get_header(changelog): """Return line number of the first version-like header. We check for patterns like '2.10 (unreleased)', so with either 'unreleased' or a date between parenthesis as that's the format we're using. As an alternative, we support an alternative format used by some zope/plone pas...
python
def get_header(changelog): """Return line number of the first version-like header. We check for patterns like '2.10 (unreleased)', so with either 'unreleased' or a date between parenthesis as that's the format we're using. As an alternative, we support an alternative format used by some zope/plone pas...
[ "def", "get_header", "(", "changelog", ")", ":", "pattern", "=", "re", ".", "compile", "(", "r\"\"\"\n (?P<version>.+) # Version string\n \\( # Opening (\n (?P<date>.+) # Date\n \\) # Closing )\n \\W*$ # Possible whitespace at end o...
Return line number of the first version-like header. We check for patterns like '2.10 (unreleased)', so with either 'unreleased' or a date between parenthesis as that's the format we're using. As an alternative, we support an alternative format used by some zope/plone paster templates: '2.10 - unrelea...
[ "Return", "line", "number", "of", "the", "first", "version", "-", "like", "header", ".", "We", "check", "for", "patterns", "like", "2", ".", "10", "(", "unreleased", ")", "so", "with", "either", "unreleased", "or", "a", "date", "between", "parenthesis", ...
ca5f36269ba0173bd29c39db6971dac57a58513d
https://github.com/jlesquembre/autopilot/blob/ca5f36269ba0173bd29c39db6971dac57a58513d/src/autopilot/utils.py#L297-L324
train
Return the line number of the first version - like header in the changelog file.
tjcsl/cslbot
cslbot/helpers/acl.py
set_admin
def set_admin(msg, handler): """Handle admin verification responses from NickServ. | If NickServ tells us that the nick is authed, mark it as verified. """ if handler.config['feature']['servicestype'] == "ircservices": match = re.match("STATUS (.*) ([0-3])", msg) elif handler.config['featu...
python
def set_admin(msg, handler): """Handle admin verification responses from NickServ. | If NickServ tells us that the nick is authed, mark it as verified. """ if handler.config['feature']['servicestype'] == "ircservices": match = re.match("STATUS (.*) ([0-3])", msg) elif handler.config['featu...
[ "def", "set_admin", "(", "msg", ",", "handler", ")", ":", "if", "handler", ".", "config", "[", "'feature'", "]", "[", "'servicestype'", "]", "==", "\"ircservices\"", ":", "match", "=", "re", ".", "match", "(", "\"STATUS (.*) ([0-3])\"", ",", "msg", ")", ...
Handle admin verification responses from NickServ. | If NickServ tells us that the nick is authed, mark it as verified.
[ "Handle", "admin", "verification", "responses", "from", "NickServ", "." ]
aebe07be47141f61d7c180706bddfb707f19b2b5
https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/helpers/acl.py#L24-L45
train
Handle admin verification responses from NickServ.
Xion/taipan
taipan/collections/tuples.py
is_tuple
def is_tuple(obj, len_=None): """Checks whether given object is a tuple. :param len_: Optional expected length of the tuple :return: ``True`` if argument is a tuple (of given length, if any), ``False`` otherwise """ if not isinstance(obj, tuple): return False if len_ is N...
python
def is_tuple(obj, len_=None): """Checks whether given object is a tuple. :param len_: Optional expected length of the tuple :return: ``True`` if argument is a tuple (of given length, if any), ``False`` otherwise """ if not isinstance(obj, tuple): return False if len_ is N...
[ "def", "is_tuple", "(", "obj", ",", "len_", "=", "None", ")", ":", "if", "not", "isinstance", "(", "obj", ",", "tuple", ")", ":", "return", "False", "if", "len_", "is", "None", ":", "return", "True", "if", "not", "isinstance", "(", "len_", ",", "In...
Checks whether given object is a tuple. :param len_: Optional expected length of the tuple :return: ``True`` if argument is a tuple (of given length, if any), ``False`` otherwise
[ "Checks", "whether", "given", "object", "is", "a", "tuple", "." ]
f333f0287c8bd0915182c7d5308e5f05ef0cca78
https://github.com/Xion/taipan/blob/f333f0287c8bd0915182c7d5308e5f05ef0cca78/taipan/collections/tuples.py#L30-L49
train
Checks whether given object is a tuple.
Xion/taipan
taipan/collections/tuples.py
ensure_tuple
def ensure_tuple(arg, len_=None): """Checks whether argument is a tuple. :param len_: Optional expected length of the tuple :return: Argument, if it's a tuple (of given length, if any) :raise TypeError: When argument is not a tuple (of given length, if any) """ if not is_tuple(arg, len_=len_): ...
python
def ensure_tuple(arg, len_=None): """Checks whether argument is a tuple. :param len_: Optional expected length of the tuple :return: Argument, if it's a tuple (of given length, if any) :raise TypeError: When argument is not a tuple (of given length, if any) """ if not is_tuple(arg, len_=len_): ...
[ "def", "ensure_tuple", "(", "arg", ",", "len_", "=", "None", ")", ":", "if", "not", "is_tuple", "(", "arg", ",", "len_", "=", "len_", ")", ":", "len_part", "=", "\"\"", "if", "len_", "is", "None", "else", "\" of length %s\"", "%", "len_", "raise", "T...
Checks whether argument is a tuple. :param len_: Optional expected length of the tuple :return: Argument, if it's a tuple (of given length, if any) :raise TypeError: When argument is not a tuple (of given length, if any)
[ "Checks", "whether", "argument", "is", "a", "tuple", ".", ":", "param", "len_", ":", "Optional", "expected", "length", "of", "the", "tuple", ":", "return", ":", "Argument", "if", "it", "s", "a", "tuple", "(", "of", "given", "length", "if", "any", ")", ...
f333f0287c8bd0915182c7d5308e5f05ef0cca78
https://github.com/Xion/taipan/blob/f333f0287c8bd0915182c7d5308e5f05ef0cca78/taipan/collections/tuples.py#L89-L99
train
Checks whether argument is a tuple.
Xion/taipan
taipan/collections/tuples.py
select
def select(indices, from_, strict=False): """Selects a subsequence of given tuple, including only specified indices. :param indices: Iterable of indices to include :param strict: Whether ``indices`` are required to exist in the tuple. :return: Tuple with selected elements, in the order corresponding ...
python
def select(indices, from_, strict=False): """Selects a subsequence of given tuple, including only specified indices. :param indices: Iterable of indices to include :param strict: Whether ``indices`` are required to exist in the tuple. :return: Tuple with selected elements, in the order corresponding ...
[ "def", "select", "(", "indices", ",", "from_", ",", "strict", "=", "False", ")", ":", "ensure_iterable", "(", "indices", ")", "ensure_sequence", "(", "from_", ")", "if", "strict", ":", "return", "from_", ".", "__class__", "(", "from_", "[", "index", "]",...
Selects a subsequence of given tuple, including only specified indices. :param indices: Iterable of indices to include :param strict: Whether ``indices`` are required to exist in the tuple. :return: Tuple with selected elements, in the order corresponding to the order of ``indices``. :ra...
[ "Selects", "a", "subsequence", "of", "given", "tuple", "including", "only", "specified", "indices", "." ]
f333f0287c8bd0915182c7d5308e5f05ef0cca78
https://github.com/Xion/taipan/blob/f333f0287c8bd0915182c7d5308e5f05ef0cca78/taipan/collections/tuples.py#L189-L209
train
Selects a subsequence of given tuple including only specified indices.
Xion/taipan
taipan/collections/tuples.py
omit
def omit(indices, from_, strict=False): """Returns a subsequence from given tuple, omitting specified indices. :param indices: Iterable of indices to exclude :param strict: Whether ``indices`` are required to exist in the tuple :return: Tuple without elements of specified indices :raise IndexErro...
python
def omit(indices, from_, strict=False): """Returns a subsequence from given tuple, omitting specified indices. :param indices: Iterable of indices to exclude :param strict: Whether ``indices`` are required to exist in the tuple :return: Tuple without elements of specified indices :raise IndexErro...
[ "def", "omit", "(", "indices", ",", "from_", ",", "strict", "=", "False", ")", ":", "from", "taipan", ".", "collections", ".", "sets", "import", "remove_subset", "ensure_iterable", "(", "indices", ")", "ensure_sequence", "(", "from_", ")", "if", "strict", ...
Returns a subsequence from given tuple, omitting specified indices. :param indices: Iterable of indices to exclude :param strict: Whether ``indices`` are required to exist in the tuple :return: Tuple without elements of specified indices :raise IndexError: If ``strict`` is True and one of ``indices``...
[ "Returns", "a", "subsequence", "from", "given", "tuple", "omitting", "specified", "indices", "." ]
f333f0287c8bd0915182c7d5308e5f05ef0cca78
https://github.com/Xion/taipan/blob/f333f0287c8bd0915182c7d5308e5f05ef0cca78/taipan/collections/tuples.py#L217-L244
train
Returns a subsequence from given tuple omitting specified indices.
Xion/taipan
taipan/collections/tuples.py
_describe_type
def _describe_type(arg): """Describe given argument, including length if it's a tuple. The purpose is to prevent nonsensical exception messages such as:: expected a tuple of length 2, got tuple expected a tuple, got tuple by turning them into:: expected a tuple of length 3, got t...
python
def _describe_type(arg): """Describe given argument, including length if it's a tuple. The purpose is to prevent nonsensical exception messages such as:: expected a tuple of length 2, got tuple expected a tuple, got tuple by turning them into:: expected a tuple of length 3, got t...
[ "def", "_describe_type", "(", "arg", ")", ":", "if", "isinstance", "(", "arg", ",", "tuple", ")", ":", "return", "\"tuple of length %s\"", "%", "len", "(", "arg", ")", "else", ":", "return", "type", "(", "arg", ")", ".", "__name__" ]
Describe given argument, including length if it's a tuple. The purpose is to prevent nonsensical exception messages such as:: expected a tuple of length 2, got tuple expected a tuple, got tuple by turning them into:: expected a tuple of length 3, got tuple of length 2
[ "Describe", "given", "argument", "including", "length", "if", "it", "s", "a", "tuple", "." ]
f333f0287c8bd0915182c7d5308e5f05ef0cca78
https://github.com/Xion/taipan/blob/f333f0287c8bd0915182c7d5308e5f05ef0cca78/taipan/collections/tuples.py#L249-L264
train
Describe given argument including length if it s a tuple.
textbook/atmdb
atmdb/models.py
BaseModel._create_image_url
def _create_image_url(self, file_path, type_, target_size): """The the closest available size for specified image type. Arguments: file_path (:py:class:`str`): The image file path. type_ (:py:class:`str`): The type of image to create a URL for, (``'poster'`` or ``'profil...
python
def _create_image_url(self, file_path, type_, target_size): """The the closest available size for specified image type. Arguments: file_path (:py:class:`str`): The image file path. type_ (:py:class:`str`): The type of image to create a URL for, (``'poster'`` or ``'profil...
[ "def", "_create_image_url", "(", "self", ",", "file_path", ",", "type_", ",", "target_size", ")", ":", "if", "self", ".", "image_config", "is", "None", ":", "logger", ".", "warning", "(", "'no image configuration available'", ")", "return", "return", "''", "."...
The the closest available size for specified image type. Arguments: file_path (:py:class:`str`): The image file path. type_ (:py:class:`str`): The type of image to create a URL for, (``'poster'`` or ``'profile'``). target_size (:py:class:`int`): The size of image to ai...
[ "The", "the", "closest", "available", "size", "for", "specified", "image", "type", "." ]
cab14547d2e777a1e26c2560266365c484855789
https://github.com/textbook/atmdb/blob/cab14547d2e777a1e26c2560266365c484855789/atmdb/models.py#L65-L83
train
Creates a URL to the image file for the specified type and size.
textbook/atmdb
atmdb/models.py
BaseModel.from_json
def from_json(cls, json, image_config=None): """Create a model instance Arguments: json (:py:class:`dict`): The parsed JSON data. image_config (:py:class:`dict`): The API image configuration data. Returns: :py:class:`BaseModel`: The model instance. ...
python
def from_json(cls, json, image_config=None): """Create a model instance Arguments: json (:py:class:`dict`): The parsed JSON data. image_config (:py:class:`dict`): The API image configuration data. Returns: :py:class:`BaseModel`: The model instance. ...
[ "def", "from_json", "(", "cls", ",", "json", ",", "image_config", "=", "None", ")", ":", "cls", ".", "image_config", "=", "image_config", "return", "cls", "(", "*", "*", "{", "attr", ":", "json", ".", "get", "(", "attr", "if", "key", "is", "None", ...
Create a model instance Arguments: json (:py:class:`dict`): The parsed JSON data. image_config (:py:class:`dict`): The API image configuration data. Returns: :py:class:`BaseModel`: The model instance.
[ "Create", "a", "model", "instance" ]
cab14547d2e777a1e26c2560266365c484855789
https://github.com/textbook/atmdb/blob/cab14547d2e777a1e26c2560266365c484855789/atmdb/models.py#L86-L102
train
Create a new instance of the class from a JSON dict.
textbook/atmdb
atmdb/models.py
BaseModel._image_size
def _image_size(image_config, type_, target_size): """Find the closest available size for specified image type. Arguments: image_config (:py:class:`dict`): The image config data. type_ (:py:class:`str`): The type of image to create a URL for, (``'poster'`` or ``'profile'...
python
def _image_size(image_config, type_, target_size): """Find the closest available size for specified image type. Arguments: image_config (:py:class:`dict`): The image config data. type_ (:py:class:`str`): The type of image to create a URL for, (``'poster'`` or ``'profile'...
[ "def", "_image_size", "(", "image_config", ",", "type_", ",", "target_size", ")", ":", "return", "min", "(", "image_config", "[", "'{}_sizes'", ".", "format", "(", "type_", ")", "]", ",", "key", "=", "lambda", "size", ":", "(", "abs", "(", "target_size",...
Find the closest available size for specified image type. Arguments: image_config (:py:class:`dict`): The image config data. type_ (:py:class:`str`): The type of image to create a URL for, (``'poster'`` or ``'profile'``). target_size (:py:class:`int`): The size of imag...
[ "Find", "the", "closest", "available", "size", "for", "specified", "image", "type", "." ]
cab14547d2e777a1e26c2560266365c484855789
https://github.com/textbook/atmdb/blob/cab14547d2e777a1e26c2560266365c484855789/atmdb/models.py#L105-L121
train
Find the closest available size for the specified image type.
rchatterjee/pwmodels
src/pwmodel/helper.py
gen_n_random_num
def gen_n_random_num(n, MAX_NUM=MAX_INT, unique=True): """ Returns @n @unique random unsigned integers (4 bytes) \ between 0 and @MAX_NUM. """ fmt = "<%dI" % n t = struct.calcsize(fmt) D = [d % MAX_NUM for d in struct.unpack(fmt, os.urandom(t))] if unique: D = set(D) asse...
python
def gen_n_random_num(n, MAX_NUM=MAX_INT, unique=True): """ Returns @n @unique random unsigned integers (4 bytes) \ between 0 and @MAX_NUM. """ fmt = "<%dI" % n t = struct.calcsize(fmt) D = [d % MAX_NUM for d in struct.unpack(fmt, os.urandom(t))] if unique: D = set(D) asse...
[ "def", "gen_n_random_num", "(", "n", ",", "MAX_NUM", "=", "MAX_INT", ",", "unique", "=", "True", ")", ":", "fmt", "=", "\"<%dI\"", "%", "n", "t", "=", "struct", ".", "calcsize", "(", "fmt", ")", "D", "=", "[", "d", "%", "MAX_NUM", "for", "d", "in...
Returns @n @unique random unsigned integers (4 bytes) \ between 0 and @MAX_NUM.
[ "Returns" ]
e277411f8ebaf4ad1c208d2b035b4b68f7471517
https://github.com/rchatterjee/pwmodels/blob/e277411f8ebaf4ad1c208d2b035b4b68f7471517/src/pwmodel/helper.py#L123-L142
train
Generate a random number of n unsigned integers.
rchatterjee/pwmodels
src/pwmodel/helper.py
sample_following_dist
def sample_following_dist(handle_iter, n, totalf): """Samples n passwords following the distribution from the handle @handle_iter is an iterator that gives (pw,f) @n is the total number of samle asked for @totalf is the total number of users, which is euqal to sum(f for pw,f in handle_iter) As, hand...
python
def sample_following_dist(handle_iter, n, totalf): """Samples n passwords following the distribution from the handle @handle_iter is an iterator that gives (pw,f) @n is the total number of samle asked for @totalf is the total number of users, which is euqal to sum(f for pw,f in handle_iter) As, hand...
[ "def", "sample_following_dist", "(", "handle_iter", ",", "n", ",", "totalf", ")", ":", "multiplier", "=", "1.0", "if", "totalf", "==", "1.0", ":", "multiplier", "=", "1e8", "# print \"WARNING!! I don't except probabilities\"", "totalf", "=", "totalf", "*", "multip...
Samples n passwords following the distribution from the handle @handle_iter is an iterator that gives (pw,f) @n is the total number of samle asked for @totalf is the total number of users, which is euqal to sum(f for pw,f in handle_iter) As, handle_iterator is an iterator and can only traverse once. ...
[ "Samples", "n", "passwords", "following", "the", "distribution", "from", "the", "handle", "@handle_iter", "is", "an", "iterator", "that", "gives", "(", "pw", "f", ")", "@n", "is", "the", "total", "number", "of", "samle", "asked", "for", "@totalf", "is", "t...
e277411f8ebaf4ad1c208d2b035b4b68f7471517
https://github.com/rchatterjee/pwmodels/blob/e277411f8ebaf4ad1c208d2b035b4b68f7471517/src/pwmodel/helper.py#L145-L199
train
Generates n random passwords following the distribution from the handle_iter.
rchatterjee/pwmodels
src/pwmodel/helper.py
file_type
def file_type(filename, param='rb'): """returns the type of file, e.g., gz, bz2, normal""" magic_dict = { b"\x1f\x8b\x08": "gz", b"\x42\x5a\x68": "bz2", b"\x50\x4b\x03\x04": "zip" } if param.startswith('w'): return filename.split('.')[-1] max_len = max(len(x) for x in...
python
def file_type(filename, param='rb'): """returns the type of file, e.g., gz, bz2, normal""" magic_dict = { b"\x1f\x8b\x08": "gz", b"\x42\x5a\x68": "bz2", b"\x50\x4b\x03\x04": "zip" } if param.startswith('w'): return filename.split('.')[-1] max_len = max(len(x) for x in...
[ "def", "file_type", "(", "filename", ",", "param", "=", "'rb'", ")", ":", "magic_dict", "=", "{", "b\"\\x1f\\x8b\\x08\"", ":", "\"gz\"", ",", "b\"\\x42\\x5a\\x68\"", ":", "\"bz2\"", ",", "b\"\\x50\\x4b\\x03\\x04\"", ":", "\"zip\"", "}", "if", "param", ".", "st...
returns the type of file, e.g., gz, bz2, normal
[ "returns", "the", "type", "of", "file", "e", ".", "g", ".", "gz", "bz2", "normal" ]
e277411f8ebaf4ad1c208d2b035b4b68f7471517
https://github.com/rchatterjee/pwmodels/blob/e277411f8ebaf4ad1c208d2b035b4b68f7471517/src/pwmodel/helper.py#L227-L242
train
returns the type of file e. g. gz bz2 normal
rchatterjee/pwmodels
src/pwmodel/helper.py
getallgroups
def getallgroups(arr, k=-1): """ returns all the subset of @arr of size less than equalto @k the return array will be of size \sum_{i=1}^k nCi, n = len(arr) """ if k < 0: k = len(arr) return itertools.chain.from_iterable(itertools.combinations(set(arr), j) ...
python
def getallgroups(arr, k=-1): """ returns all the subset of @arr of size less than equalto @k the return array will be of size \sum_{i=1}^k nCi, n = len(arr) """ if k < 0: k = len(arr) return itertools.chain.from_iterable(itertools.combinations(set(arr), j) ...
[ "def", "getallgroups", "(", "arr", ",", "k", "=", "-", "1", ")", ":", "if", "k", "<", "0", ":", "k", "=", "len", "(", "arr", ")", "return", "itertools", ".", "chain", ".", "from_iterable", "(", "itertools", ".", "combinations", "(", "set", "(", "...
returns all the subset of @arr of size less than equalto @k the return array will be of size \sum_{i=1}^k nCi, n = len(arr)
[ "returns", "all", "the", "subset", "of" ]
e277411f8ebaf4ad1c208d2b035b4b68f7471517
https://github.com/rchatterjee/pwmodels/blob/e277411f8ebaf4ad1c208d2b035b4b68f7471517/src/pwmodel/helper.py#L273-L281
train
Returns all the groups of the given array.
rchatterjee/pwmodels
src/pwmodel/helper.py
open_get_line
def open_get_line(filename, limit=-1, **kwargs): """Opens the password file named @filename and reads first @limit passwords. @kwargs are passed to get_line for further processing. For example, pw_filter etc. @fielname: string @limit: integer """ allowed_keys_for_get_line = {'sep', 'pw_filte...
python
def open_get_line(filename, limit=-1, **kwargs): """Opens the password file named @filename and reads first @limit passwords. @kwargs are passed to get_line for further processing. For example, pw_filter etc. @fielname: string @limit: integer """ allowed_keys_for_get_line = {'sep', 'pw_filte...
[ "def", "open_get_line", "(", "filename", ",", "limit", "=", "-", "1", ",", "*", "*", "kwargs", ")", ":", "allowed_keys_for_get_line", "=", "{", "'sep'", ",", "'pw_filter'", ",", "'errors'", "}", "for", "k", "in", "list", "(", "kwargs", ".", "keys", "("...
Opens the password file named @filename and reads first @limit passwords. @kwargs are passed to get_line for further processing. For example, pw_filter etc. @fielname: string @limit: integer
[ "Opens", "the", "password", "file", "named" ]
e277411f8ebaf4ad1c208d2b035b4b68f7471517
https://github.com/rchatterjee/pwmodels/blob/e277411f8ebaf4ad1c208d2b035b4b68f7471517/src/pwmodel/helper.py#L317-L331
train
Opens the password file named filename and reads first limit passwords.
rchatterjee/pwmodels
src/pwmodel/helper.py
random.randints
def randints(s, e, n=1): """ returns n uniform random numbers from [s, e] """ assert e >= s, "Wrong range: [{}, {})".format(s, e) n = max(1, n) arr = [s + a % (e - s) for a in struct.unpack('<%dL' % n, os.urandom(4 * n))] return arr
python
def randints(s, e, n=1): """ returns n uniform random numbers from [s, e] """ assert e >= s, "Wrong range: [{}, {})".format(s, e) n = max(1, n) arr = [s + a % (e - s) for a in struct.unpack('<%dL' % n, os.urandom(4 * n))] return arr
[ "def", "randints", "(", "s", ",", "e", ",", "n", "=", "1", ")", ":", "assert", "e", ">=", "s", ",", "\"Wrong range: [{}, {})\"", ".", "format", "(", "s", ",", "e", ")", "n", "=", "max", "(", "1", ",", "n", ")", "arr", "=", "[", "s", "+", "a...
returns n uniform random numbers from [s, e]
[ "returns", "n", "uniform", "random", "numbers", "from", "[", "s", "e", "]" ]
e277411f8ebaf4ad1c208d2b035b4b68f7471517
https://github.com/rchatterjee/pwmodels/blob/e277411f8ebaf4ad1c208d2b035b4b68f7471517/src/pwmodel/helper.py#L79-L86
train
returns n uniform random numbers from [ s e )
tjcsl/cslbot
cslbot/helpers/workers.py
Workers.stop_workers
def stop_workers(self, clean): """Stop workers and deferred events.""" with executor_lock: self.executor.shutdown(clean) del self.executor with self.worker_lock: if clean: self.pool.close() else: self.pool.terminate(...
python
def stop_workers(self, clean): """Stop workers and deferred events.""" with executor_lock: self.executor.shutdown(clean) del self.executor with self.worker_lock: if clean: self.pool.close() else: self.pool.terminate(...
[ "def", "stop_workers", "(", "self", ",", "clean", ")", ":", "with", "executor_lock", ":", "self", ".", "executor", ".", "shutdown", "(", "clean", ")", "del", "self", ".", "executor", "with", "self", ".", "worker_lock", ":", "if", "clean", ":", "self", ...
Stop workers and deferred events.
[ "Stop", "workers", "and", "deferred", "events", "." ]
aebe07be47141f61d7c180706bddfb707f19b2b5
https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/helpers/workers.py#L108-L122
train
Stop workers and deferred events.
adamziel/python_translate
python_translate/extractors/python.py
PythonExtractor.extract_translations
def extract_translations(self, string): """Extract messages from Python string.""" tree = ast.parse(string) # ast_visit(tree) visitor = TransVisitor( self.tranz_functions, self.tranzchoice_functions) visitor.visit(tree) return visitor.translation...
python
def extract_translations(self, string): """Extract messages from Python string.""" tree = ast.parse(string) # ast_visit(tree) visitor = TransVisitor( self.tranz_functions, self.tranzchoice_functions) visitor.visit(tree) return visitor.translation...
[ "def", "extract_translations", "(", "self", ",", "string", ")", ":", "tree", "=", "ast", ".", "parse", "(", "string", ")", "# ast_visit(tree)", "visitor", "=", "TransVisitor", "(", "self", ".", "tranz_functions", ",", "self", ".", "tranzchoice_functions", ")",...
Extract messages from Python string.
[ "Extract", "messages", "from", "Python", "string", "." ]
0aee83f434bd2d1b95767bcd63adb7ac7036c7df
https://github.com/adamziel/python_translate/blob/0aee83f434bd2d1b95767bcd63adb7ac7036c7df/python_translate/extractors/python.py#L34-L44
train
Extract messages from Python string.
tjcsl/cslbot
cslbot/commands/isup.py
cmd
def cmd(send, msg, args): """Checks if a website is up. Syntax: {command} <website> """ if not msg: send("What are you trying to get to?") return nick = args['nick'] isup = get("http://isup.me/%s" % msg).text if "looks down from here" in isup: send("%s: %s is down" ...
python
def cmd(send, msg, args): """Checks if a website is up. Syntax: {command} <website> """ if not msg: send("What are you trying to get to?") return nick = args['nick'] isup = get("http://isup.me/%s" % msg).text if "looks down from here" in isup: send("%s: %s is down" ...
[ "def", "cmd", "(", "send", ",", "msg", ",", "args", ")", ":", "if", "not", "msg", ":", "send", "(", "\"What are you trying to get to?\"", ")", "return", "nick", "=", "args", "[", "'nick'", "]", "isup", "=", "get", "(", "\"http://isup.me/%s\"", "%", "msg"...
Checks if a website is up. Syntax: {command} <website>
[ "Checks", "if", "a", "website", "is", "up", "." ]
aebe07be47141f61d7c180706bddfb707f19b2b5
https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/isup.py#L24-L40
train
Checks if a website is up.
tjcsl/cslbot
cslbot/commands/wisdom.py
cmd
def cmd(send, msg, args): """Gets words of wisdom Syntax: {command} (--author <author>|--search <topic>) Powered by STANDS4, www.stands4.com """ uid = args['config']['api']['stands4uid'] token = args['config']['api']['stands4token'] parser = arguments.ArgParser(args['config']) group = pa...
python
def cmd(send, msg, args): """Gets words of wisdom Syntax: {command} (--author <author>|--search <topic>) Powered by STANDS4, www.stands4.com """ uid = args['config']['api']['stands4uid'] token = args['config']['api']['stands4token'] parser = arguments.ArgParser(args['config']) group = pa...
[ "def", "cmd", "(", "send", ",", "msg", ",", "args", ")", ":", "uid", "=", "args", "[", "'config'", "]", "[", "'api'", "]", "[", "'stands4uid'", "]", "token", "=", "args", "[", "'config'", "]", "[", "'api'", "]", "[", "'stands4token'", "]", "parser"...
Gets words of wisdom Syntax: {command} (--author <author>|--search <topic>) Powered by STANDS4, www.stands4.com
[ "Gets", "words", "of", "wisdom", "Syntax", ":", "{", "command", "}", "(", "--", "author", "<author", ">", "|", "--", "search", "<topic", ">", ")", "Powered", "by", "STANDS4", "www", ".", "stands4", ".", "com" ]
aebe07be47141f61d7c180706bddfb707f19b2b5
https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/wisdom.py#L29-L77
train
Gets words of wisdom
tylerbutler/engineer
engineer/conf.py
EngineerConfiguration.create_required_directories
def create_required_directories(self): """Creates any directories required for Engineer to function if they don't already exist.""" required = (self.CACHE_DIR, self.LOG_DIR, self.OUTPUT_DIR, self.ENGINEER.JINJA_CACHE_DIR,) for folder i...
python
def create_required_directories(self): """Creates any directories required for Engineer to function if they don't already exist.""" required = (self.CACHE_DIR, self.LOG_DIR, self.OUTPUT_DIR, self.ENGINEER.JINJA_CACHE_DIR,) for folder i...
[ "def", "create_required_directories", "(", "self", ")", ":", "required", "=", "(", "self", ".", "CACHE_DIR", ",", "self", ".", "LOG_DIR", ",", "self", ".", "OUTPUT_DIR", ",", "self", ".", "ENGINEER", ".", "JINJA_CACHE_DIR", ",", ")", "for", "folder", "in",...
Creates any directories required for Engineer to function if they don't already exist.
[ "Creates", "any", "directories", "required", "for", "Engineer", "to", "function", "if", "they", "don", "t", "already", "exist", "." ]
8884f587297f37646c40e5553174852b444a4024
https://github.com/tylerbutler/engineer/blob/8884f587297f37646c40e5553174852b444a4024/engineer/conf.py#L432-L440
train
Creates any directories required for Engineer to function if they don t already exist.
tjcsl/cslbot
cslbot/commands/wiki.py
cmd
def cmd(send, msg, args): """Returns the first wikipedia result for the argument. Syntax: {command} [term] """ if 'livedoc' in args['name']: url = 'http://livedoc.tjhsst.edu/w' name = 'livedoc' else: url = 'http://en.wikipedia.org/w' name = 'wikipedia' if not ms...
python
def cmd(send, msg, args): """Returns the first wikipedia result for the argument. Syntax: {command} [term] """ if 'livedoc' in args['name']: url = 'http://livedoc.tjhsst.edu/w' name = 'livedoc' else: url = 'http://en.wikipedia.org/w' name = 'wikipedia' if not ms...
[ "def", "cmd", "(", "send", ",", "msg", ",", "args", ")", ":", "if", "'livedoc'", "in", "args", "[", "'name'", "]", ":", "url", "=", "'http://livedoc.tjhsst.edu/w'", "name", "=", "'livedoc'", "else", ":", "url", "=", "'http://en.wikipedia.org/w'", "name", "...
Returns the first wikipedia result for the argument. Syntax: {command} [term]
[ "Returns", "the", "first", "wikipedia", "result", "for", "the", "argument", "." ]
aebe07be47141f61d7c180706bddfb707f19b2b5
https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/wiki.py#L30-L54
train
Returns the first wikipedia result for the argument.
jmbeach/KEP.py
src/keppy/channel.py
Channel.parse_devices
def parse_devices(self): """Creates an array of Device objects from the channel""" devices = [] for device in self._channel_dict["devices"]: devices.append(Device(device, self._is_sixteen_bit, self._ignore_list)) return devices
python
def parse_devices(self): """Creates an array of Device objects from the channel""" devices = [] for device in self._channel_dict["devices"]: devices.append(Device(device, self._is_sixteen_bit, self._ignore_list)) return devices
[ "def", "parse_devices", "(", "self", ")", ":", "devices", "=", "[", "]", "for", "device", "in", "self", ".", "_channel_dict", "[", "\"devices\"", "]", ":", "devices", ".", "append", "(", "Device", "(", "device", ",", "self", ".", "_is_sixteen_bit", ",", ...
Creates an array of Device objects from the channel
[ "Creates", "an", "array", "of", "Device", "objects", "from", "the", "channel" ]
68cda64ab649640a486534867c81274c41e39446
https://github.com/jmbeach/KEP.py/blob/68cda64ab649640a486534867c81274c41e39446/src/keppy/channel.py#L19-L24
train
Creates an array of Device objects from the channel
jmbeach/KEP.py
src/keppy/channel.py
Channel.update
def update(self): """Updates the dictionary of the channel""" for device in self.devices: device.update() for i in range(len(self._channel_dict["devices"])): device_dict = self._channel_dict["devices"][i] for device in self._devices: if device....
python
def update(self): """Updates the dictionary of the channel""" for device in self.devices: device.update() for i in range(len(self._channel_dict["devices"])): device_dict = self._channel_dict["devices"][i] for device in self._devices: if device....
[ "def", "update", "(", "self", ")", ":", "for", "device", "in", "self", ".", "devices", ":", "device", ".", "update", "(", ")", "for", "i", "in", "range", "(", "len", "(", "self", ".", "_channel_dict", "[", "\"devices\"", "]", ")", ")", ":", "device...
Updates the dictionary of the channel
[ "Updates", "the", "dictionary", "of", "the", "channel" ]
68cda64ab649640a486534867c81274c41e39446
https://github.com/jmbeach/KEP.py/blob/68cda64ab649640a486534867c81274c41e39446/src/keppy/channel.py#L44-L52
train
Updates the dictionary of the channel
JNPRAutomate/pyJunosManager
pyJunosManager/pyJunosManager.py
JunosDevice.open_config
def open_config(self,type="shared"): """ Opens the configuration of the currently connected device Args: :type: The type of configuration you want to open. Any string can be provided, however the standard supported options are: **exclusive**, **private**, and **shared**. The default...
python
def open_config(self,type="shared"): """ Opens the configuration of the currently connected device Args: :type: The type of configuration you want to open. Any string can be provided, however the standard supported options are: **exclusive**, **private**, and **shared**. The default...
[ "def", "open_config", "(", "self", ",", "type", "=", "\"shared\"", ")", ":", "try", ":", "#attempt to open a configuration", "output", "=", "self", ".", "dev", ".", "rpc", "(", "\"<open-configuration><{0}/></open-configuration>\"", ".", "format", "(", "type", ")",...
Opens the configuration of the currently connected device Args: :type: The type of configuration you want to open. Any string can be provided, however the standard supported options are: **exclusive**, **private**, and **shared**. The default mode is **shared**. Examples: .. code-...
[ "Opens", "the", "configuration", "of", "the", "currently", "connected", "device" ]
cfbe87bb55488f44bad0b383771a88be7b2ccf2a
https://github.com/JNPRAutomate/pyJunosManager/blob/cfbe87bb55488f44bad0b383771a88be7b2ccf2a/pyJunosManager/pyJunosManager.py#L95-L131
train
Opens the configuration of the currently connected device.
JNPRAutomate/pyJunosManager
pyJunosManager/pyJunosManager.py
JunosDevice.close_config
def close_config(self): """ Closes the exiting opened configuration Example: .. code-block:: python from pyJunosManager import JunosDevice dev = JunosDevice(host="1.2.3.4",username="root",password="Juniper") dev.open() dev.open_config()...
python
def close_config(self): """ Closes the exiting opened configuration Example: .. code-block:: python from pyJunosManager import JunosDevice dev = JunosDevice(host="1.2.3.4",username="root",password="Juniper") dev.open() dev.open_config()...
[ "def", "close_config", "(", "self", ")", ":", "try", ":", "self", ".", "dev", ".", "rpc", ".", "close_configuration", "(", ")", "except", "Exception", "as", "err", ":", "print", "err" ]
Closes the exiting opened configuration Example: .. code-block:: python from pyJunosManager import JunosDevice dev = JunosDevice(host="1.2.3.4",username="root",password="Juniper") dev.open() dev.open_config() dev.close_config() ...
[ "Closes", "the", "exiting", "opened", "configuration" ]
cfbe87bb55488f44bad0b383771a88be7b2ccf2a
https://github.com/JNPRAutomate/pyJunosManager/blob/cfbe87bb55488f44bad0b383771a88be7b2ccf2a/pyJunosManager/pyJunosManager.py#L133-L153
train
Closes the exiting opened configuration and closes the exiting opened configuration.
JNPRAutomate/pyJunosManager
pyJunosManager/pyJunosManager.py
JunosDevice.load_config_template
def load_config_template(self,template,template_vars,type="text"): """ :template: A templated string using Jinja2 templates :template_vars: A dict containing the vars used in the :template: string :type: The type of configuration to load. The default is "text" or a standard Junos config ...
python
def load_config_template(self,template,template_vars,type="text"): """ :template: A templated string using Jinja2 templates :template_vars: A dict containing the vars used in the :template: string :type: The type of configuration to load. The default is "text" or a standard Junos config ...
[ "def", "load_config_template", "(", "self", ",", "template", ",", "template_vars", ",", "type", "=", "\"text\"", ")", ":", "new_template", "=", "Template", "(", "template", ")", "final_template", "=", "new_template", ".", "render", "(", "template_vars", ")", "...
:template: A templated string using Jinja2 templates :template_vars: A dict containing the vars used in the :template: string :type: The type of configuration to load. The default is "text" or a standard Junos config block. Other options are: "set" for set style commands, "xml" for xml configs ...
[ ":", "template", ":", "A", "templated", "string", "using", "Jinja2", "templates", ":", "template_vars", ":", "A", "dict", "containing", "the", "vars", "used", "in", "the", ":", "template", ":", "string", ":", "type", ":", "The", "type", "of", "configuratio...
cfbe87bb55488f44bad0b383771a88be7b2ccf2a
https://github.com/JNPRAutomate/pyJunosManager/blob/cfbe87bb55488f44bad0b383771a88be7b2ccf2a/pyJunosManager/pyJunosManager.py#L155-L187
train
Load a Junos config block from a template string.
JNPRAutomate/pyJunosManager
pyJunosManager/pyJunosManager.py
JunosDevice.commit_config
def commit_config(self): """ Commits exiting configuration Example: .. code-block:: python from pyJunosManager import JunosDevice dev = JunosDevice(host="1.2.3.4",username="root",password="Juniper") dev.open() dev.open_config() ...
python
def commit_config(self): """ Commits exiting configuration Example: .. code-block:: python from pyJunosManager import JunosDevice dev = JunosDevice(host="1.2.3.4",username="root",password="Juniper") dev.open() dev.open_config() ...
[ "def", "commit_config", "(", "self", ")", ":", "try", ":", "self", ".", "dev", ".", "rpc", ".", "commit_configuration", "(", ")", "except", "Exception", "as", "err", ":", "print", "err" ]
Commits exiting configuration Example: .. code-block:: python from pyJunosManager import JunosDevice dev = JunosDevice(host="1.2.3.4",username="root",password="Juniper") dev.open() dev.open_config() dev.commit_config() dev.close...
[ "Commits", "exiting", "configuration" ]
cfbe87bb55488f44bad0b383771a88be7b2ccf2a
https://github.com/JNPRAutomate/pyJunosManager/blob/cfbe87bb55488f44bad0b383771a88be7b2ccf2a/pyJunosManager/pyJunosManager.py#L189-L209
train
Commits exiting configuration
JNPRAutomate/pyJunosManager
pyJunosManager/pyJunosManager.py
JunosDevice.commit_and_quit
def commit_and_quit(self): """ Commits and closes the currently open configration. Saves a step by not needing to manually close the config. Example: .. code-block:: python from pyJunosManager import JunosDevice dev = JunosDevice(host="1.2.3.4",username="root"...
python
def commit_and_quit(self): """ Commits and closes the currently open configration. Saves a step by not needing to manually close the config. Example: .. code-block:: python from pyJunosManager import JunosDevice dev = JunosDevice(host="1.2.3.4",username="root"...
[ "def", "commit_and_quit", "(", "self", ")", ":", "try", ":", "self", ".", "dev", ".", "rpc", ".", "commit_configuration", "(", ")", "self", ".", "close_config", "(", ")", "except", "Exception", "as", "err", ":", "print", "err" ]
Commits and closes the currently open configration. Saves a step by not needing to manually close the config. Example: .. code-block:: python from pyJunosManager import JunosDevice dev = JunosDevice(host="1.2.3.4",username="root",password="Juniper") dev.open() ...
[ "Commits", "and", "closes", "the", "currently", "open", "configration", ".", "Saves", "a", "step", "by", "not", "needing", "to", "manually", "close", "the", "config", "." ]
cfbe87bb55488f44bad0b383771a88be7b2ccf2a
https://github.com/JNPRAutomate/pyJunosManager/blob/cfbe87bb55488f44bad0b383771a88be7b2ccf2a/pyJunosManager/pyJunosManager.py#L211-L232
train
Commits and closes the currently open configration.
Genida/archan
src/archan/config.py
Config.load_local_plugin
def load_local_plugin(name): """Import a local plugin accessible through Python path.""" try: module_name = '.'.join(name.split('.')[:-1]) module_obj = importlib.import_module(name=module_name) obj = getattr(module_obj, name.split('.')[-1]) return obj ...
python
def load_local_plugin(name): """Import a local plugin accessible through Python path.""" try: module_name = '.'.join(name.split('.')[:-1]) module_obj = importlib.import_module(name=module_name) obj = getattr(module_obj, name.split('.')[-1]) return obj ...
[ "def", "load_local_plugin", "(", "name", ")", ":", "try", ":", "module_name", "=", "'.'", ".", "join", "(", "name", ".", "split", "(", "'.'", ")", "[", ":", "-", "1", "]", ")", "module_obj", "=", "importlib", ".", "import_module", "(", "name", "=", ...
Import a local plugin accessible through Python path.
[ "Import", "a", "local", "plugin", "accessible", "through", "Python", "path", "." ]
a026d3105c7e86f30e6c9507b93ceb736684bfdc
https://github.com/Genida/archan/blob/a026d3105c7e86f30e6c9507b93ceb736684bfdc/src/archan/config.py#L68-L76
train
Import a local plugin accessible through Python path.
Genida/archan
src/archan/config.py
Config.load_installed_plugins
def load_installed_plugins(): """Search and load every installed plugin through entry points.""" providers = {} checkers = {} for entry_point in pkg_resources.iter_entry_points(group='archan'): obj = entry_point.load() if issubclass(obj, Provider): ...
python
def load_installed_plugins(): """Search and load every installed plugin through entry points.""" providers = {} checkers = {} for entry_point in pkg_resources.iter_entry_points(group='archan'): obj = entry_point.load() if issubclass(obj, Provider): ...
[ "def", "load_installed_plugins", "(", ")", ":", "providers", "=", "{", "}", "checkers", "=", "{", "}", "for", "entry_point", "in", "pkg_resources", ".", "iter_entry_points", "(", "group", "=", "'archan'", ")", ":", "obj", "=", "entry_point", ".", "load", "...
Search and load every installed plugin through entry points.
[ "Search", "and", "load", "every", "installed", "plugin", "through", "entry", "points", "." ]
a026d3105c7e86f30e6c9507b93ceb736684bfdc
https://github.com/Genida/archan/blob/a026d3105c7e86f30e6c9507b93ceb736684bfdc/src/archan/config.py#L79-L92
train
Search and load every installed plugin through entry points.
Genida/archan
src/archan/config.py
Config.from_file
def from_file(path): """Return a ``Config`` instance by reading a configuration file.""" with open(path) as stream: obj = yaml.safe_load(stream) Config.lint(obj) return Config(config_dict=obj)
python
def from_file(path): """Return a ``Config`` instance by reading a configuration file.""" with open(path) as stream: obj = yaml.safe_load(stream) Config.lint(obj) return Config(config_dict=obj)
[ "def", "from_file", "(", "path", ")", ":", "with", "open", "(", "path", ")", "as", "stream", ":", "obj", "=", "yaml", ".", "safe_load", "(", "stream", ")", "Config", ".", "lint", "(", "obj", ")", "return", "Config", "(", "config_dict", "=", "obj", ...
Return a ``Config`` instance by reading a configuration file.
[ "Return", "a", "Config", "instance", "by", "reading", "a", "configuration", "file", "." ]
a026d3105c7e86f30e6c9507b93ceb736684bfdc
https://github.com/Genida/archan/blob/a026d3105c7e86f30e6c9507b93ceb736684bfdc/src/archan/config.py#L103-L108
train
Return a Config instance by reading a configuration file.
Genida/archan
src/archan/config.py
Config.find
def find(): """Find the configuration file if any.""" names = ('archan.yml', 'archan.yaml', '.archan.yml', '.archan.yaml') current_dir = os.getcwd() configconfig_file = os.path.join(current_dir, '.configconfig') default_config_dir = os.path.join(current_dir, 'config') if ...
python
def find(): """Find the configuration file if any.""" names = ('archan.yml', 'archan.yaml', '.archan.yml', '.archan.yaml') current_dir = os.getcwd() configconfig_file = os.path.join(current_dir, '.configconfig') default_config_dir = os.path.join(current_dir, 'config') if ...
[ "def", "find", "(", ")", ":", "names", "=", "(", "'archan.yml'", ",", "'archan.yaml'", ",", "'.archan.yml'", ",", "'.archan.yaml'", ")", "current_dir", "=", "os", ".", "getcwd", "(", ")", "configconfig_file", "=", "os", ".", "path", ".", "join", "(", "cu...
Find the configuration file if any.
[ "Find", "the", "configuration", "file", "if", "any", "." ]
a026d3105c7e86f30e6c9507b93ceb736684bfdc
https://github.com/Genida/archan/blob/a026d3105c7e86f30e6c9507b93ceb736684bfdc/src/archan/config.py#L111-L134
train
Find the configuration file if any.
Genida/archan
src/archan/config.py
Config.inflate_plugin_list
def inflate_plugin_list(plugin_list, inflate_plugin): """ Inflate a list of strings/dictionaries to a list of plugin instances. Args: plugin_list (list): a list of str/dict. inflate_plugin (method): the method to inflate the plugin. Returns: list: a ...
python
def inflate_plugin_list(plugin_list, inflate_plugin): """ Inflate a list of strings/dictionaries to a list of plugin instances. Args: plugin_list (list): a list of str/dict. inflate_plugin (method): the method to inflate the plugin. Returns: list: a ...
[ "def", "inflate_plugin_list", "(", "plugin_list", ",", "inflate_plugin", ")", ":", "plugins", "=", "[", "]", "for", "plugin_def", "in", "plugin_list", ":", "if", "isinstance", "(", "plugin_def", ",", "str", ")", ":", "try", ":", "plugins", ".", "append", "...
Inflate a list of strings/dictionaries to a list of plugin instances. Args: plugin_list (list): a list of str/dict. inflate_plugin (method): the method to inflate the plugin. Returns: list: a plugin instances list. Raises: ValueError: when a dic...
[ "Inflate", "a", "list", "of", "strings", "/", "dictionaries", "to", "a", "list", "of", "plugin", "instances", "." ]
a026d3105c7e86f30e6c9507b93ceb736684bfdc
https://github.com/Genida/archan/blob/a026d3105c7e86f30e6c9507b93ceb736684bfdc/src/archan/config.py#L156-L191
train
Inflate a list of strings or dictionaries to a list of plugin instances.
Genida/archan
src/archan/config.py
Config.inflate_plugin_dict
def inflate_plugin_dict(plugin_dict, inflate_plugin): """ Inflate a list of strings/dictionaries to a list of plugin instances. Args: plugin_dict (dict): a dict of dict. inflate_plugin (method): the method to inflate the plugin. Returns: list: a plug...
python
def inflate_plugin_dict(plugin_dict, inflate_plugin): """ Inflate a list of strings/dictionaries to a list of plugin instances. Args: plugin_dict (dict): a dict of dict. inflate_plugin (method): the method to inflate the plugin. Returns: list: a plug...
[ "def", "inflate_plugin_dict", "(", "plugin_dict", ",", "inflate_plugin", ")", ":", "plugins", "=", "[", "]", "for", "identifier", ",", "definition", "in", "plugin_dict", ".", "items", "(", ")", ":", "try", ":", "plugins", ".", "append", "(", "inflate_plugin"...
Inflate a list of strings/dictionaries to a list of plugin instances. Args: plugin_dict (dict): a dict of dict. inflate_plugin (method): the method to inflate the plugin. Returns: list: a plugin instances list.
[ "Inflate", "a", "list", "of", "strings", "/", "dictionaries", "to", "a", "list", "of", "plugin", "instances", "." ]
a026d3105c7e86f30e6c9507b93ceb736684bfdc
https://github.com/Genida/archan/blob/a026d3105c7e86f30e6c9507b93ceb736684bfdc/src/archan/config.py#L194-L212
train
Inflate a list of strings / dictionaries to a list of plugin instances.
Genida/archan
src/archan/config.py
Config.inflate_nd_checker
def inflate_nd_checker(identifier, definition): """ Inflate a no-data checker from a basic definition. Args: identifier (str): the no-data checker identifier / name. definition (bool/dict): a boolean acting as "passes" or a full dict definition with "pass...
python
def inflate_nd_checker(identifier, definition): """ Inflate a no-data checker from a basic definition. Args: identifier (str): the no-data checker identifier / name. definition (bool/dict): a boolean acting as "passes" or a full dict definition with "pass...
[ "def", "inflate_nd_checker", "(", "identifier", ",", "definition", ")", ":", "if", "isinstance", "(", "definition", ",", "bool", ")", ":", "return", "Checker", "(", "name", "=", "identifier", ",", "passes", "=", "definition", ")", "elif", "isinstance", "(", ...
Inflate a no-data checker from a basic definition. Args: identifier (str): the no-data checker identifier / name. definition (bool/dict): a boolean acting as "passes" or a full dict definition with "passes" and "allow_failure". Returns: Checker: a ch...
[ "Inflate", "a", "no", "-", "data", "checker", "from", "a", "basic", "definition", "." ]
a026d3105c7e86f30e6c9507b93ceb736684bfdc
https://github.com/Genida/archan/blob/a026d3105c7e86f30e6c9507b93ceb736684bfdc/src/archan/config.py#L215-L236
train
Inflate a no - data checker from a basic definition.
Genida/archan
src/archan/config.py
Config.get_plugin
def get_plugin(self, identifier, cls=None): """ Return the plugin corresponding to the given identifier and type. Args: identifier (str): identifier of the plugin. cls (str): one of checker / provider. Returns: Checker/Provider: plugin class. ...
python
def get_plugin(self, identifier, cls=None): """ Return the plugin corresponding to the given identifier and type. Args: identifier (str): identifier of the plugin. cls (str): one of checker / provider. Returns: Checker/Provider: plugin class. ...
[ "def", "get_plugin", "(", "self", ",", "identifier", ",", "cls", "=", "None", ")", ":", "if", "(", "(", "cls", "is", "None", "or", "cls", "==", "'provider'", ")", "and", "identifier", "in", "self", ".", "available_providers", ")", ":", "return", "self"...
Return the plugin corresponding to the given identifier and type. Args: identifier (str): identifier of the plugin. cls (str): one of checker / provider. Returns: Checker/Provider: plugin class.
[ "Return", "the", "plugin", "corresponding", "to", "the", "given", "identifier", "and", "type", "." ]
a026d3105c7e86f30e6c9507b93ceb736684bfdc
https://github.com/Genida/archan/blob/a026d3105c7e86f30e6c9507b93ceb736684bfdc/src/archan/config.py#L255-L272
train
Returns the plugin corresponding to the given identifier and type.
Genida/archan
src/archan/config.py
Config.provider_from_dict
def provider_from_dict(self, dct): """Return a provider instance from a dict object.""" provider_identifier = list(dct.keys())[0] provider_class = self.get_provider(provider_identifier) if provider_class: return provider_class(**dct[provider_identifier]) return None
python
def provider_from_dict(self, dct): """Return a provider instance from a dict object.""" provider_identifier = list(dct.keys())[0] provider_class = self.get_provider(provider_identifier) if provider_class: return provider_class(**dct[provider_identifier]) return None
[ "def", "provider_from_dict", "(", "self", ",", "dct", ")", ":", "provider_identifier", "=", "list", "(", "dct", ".", "keys", "(", ")", ")", "[", "0", "]", "provider_class", "=", "self", ".", "get_provider", "(", "provider_identifier", ")", "if", "provider_...
Return a provider instance from a dict object.
[ "Return", "a", "provider", "instance", "from", "a", "dict", "object", "." ]
a026d3105c7e86f30e6c9507b93ceb736684bfdc
https://github.com/Genida/archan/blob/a026d3105c7e86f30e6c9507b93ceb736684bfdc/src/archan/config.py#L282-L288
train
Return a provider instance from a dict object.
Genida/archan
src/archan/config.py
Config.checker_from_dict
def checker_from_dict(self, dct): """Return a checker instance from a dict object.""" checker_identifier = list(dct.keys())[0] checker_class = self.get_checker(checker_identifier) if checker_class: return checker_class(**dct[checker_identifier]) return None
python
def checker_from_dict(self, dct): """Return a checker instance from a dict object.""" checker_identifier = list(dct.keys())[0] checker_class = self.get_checker(checker_identifier) if checker_class: return checker_class(**dct[checker_identifier]) return None
[ "def", "checker_from_dict", "(", "self", ",", "dct", ")", ":", "checker_identifier", "=", "list", "(", "dct", ".", "keys", "(", ")", ")", "[", "0", "]", "checker_class", "=", "self", ".", "get_checker", "(", "checker_identifier", ")", "if", "checker_class"...
Return a checker instance from a dict object.
[ "Return", "a", "checker", "instance", "from", "a", "dict", "object", "." ]
a026d3105c7e86f30e6c9507b93ceb736684bfdc
https://github.com/Genida/archan/blob/a026d3105c7e86f30e6c9507b93ceb736684bfdc/src/archan/config.py#L290-L296
train
Return a checker instance from a dict object.
Genida/archan
src/archan/config.py
Config.inflate_plugin
def inflate_plugin(self, identifier, definition=None, cls=None): """ Inflate a plugin thanks to it's identifier, definition and class. Args: identifier (str): the plugin identifier. definition (dict): the kwargs to instantiate the plugin with. cls (str): "pro...
python
def inflate_plugin(self, identifier, definition=None, cls=None): """ Inflate a plugin thanks to it's identifier, definition and class. Args: identifier (str): the plugin identifier. definition (dict): the kwargs to instantiate the plugin with. cls (str): "pro...
[ "def", "inflate_plugin", "(", "self", ",", "identifier", ",", "definition", "=", "None", ",", "cls", "=", "None", ")", ":", "cls", "=", "self", ".", "get_plugin", "(", "identifier", ",", "cls", ")", "# TODO: implement re-usability of plugins?", "# same instances...
Inflate a plugin thanks to it's identifier, definition and class. Args: identifier (str): the plugin identifier. definition (dict): the kwargs to instantiate the plugin with. cls (str): "provider", "checker", or None. Returns: Provider/Checker: instance ...
[ "Inflate", "a", "plugin", "thanks", "to", "it", "s", "identifier", "definition", "and", "class", "." ]
a026d3105c7e86f30e6c9507b93ceb736684bfdc
https://github.com/Genida/archan/blob/a026d3105c7e86f30e6c9507b93ceb736684bfdc/src/archan/config.py#L298-L313
train
Inflate a plugin thanks to it s identifier definition and class.
Genida/archan
src/archan/config.py
Config.inflate_plugins
def inflate_plugins(self, plugins_definition, inflate_method): """ Inflate multiple plugins based on a list/dict definition. Args: plugins_definition (list/dict): the plugins definitions. inflate_method (method): the method to indlate each plugin. Returns: ...
python
def inflate_plugins(self, plugins_definition, inflate_method): """ Inflate multiple plugins based on a list/dict definition. Args: plugins_definition (list/dict): the plugins definitions. inflate_method (method): the method to indlate each plugin. Returns: ...
[ "def", "inflate_plugins", "(", "self", ",", "plugins_definition", ",", "inflate_method", ")", ":", "if", "isinstance", "(", "plugins_definition", ",", "list", ")", ":", "return", "self", ".", "inflate_plugin_list", "(", "plugins_definition", ",", "inflate_method", ...
Inflate multiple plugins based on a list/dict definition. Args: plugins_definition (list/dict): the plugins definitions. inflate_method (method): the method to indlate each plugin. Returns: list: a list of plugin instances. Raises: ValueError: w...
[ "Inflate", "multiple", "plugins", "based", "on", "a", "list", "/", "dict", "definition", "." ]
a026d3105c7e86f30e6c9507b93ceb736684bfdc
https://github.com/Genida/archan/blob/a026d3105c7e86f30e6c9507b93ceb736684bfdc/src/archan/config.py#L315-L335
train
Inflate multiple plugins based on a list or dict definition.
Genida/archan
src/archan/config.py
Config.inflate_analysis_group
def inflate_analysis_group(self, identifier, definition): """ Inflate a whole analysis group. An analysis group is a section defined in the YAML file. Args: identifier (str): the group identifier. definition (list/dict): the group definition. Returns: ...
python
def inflate_analysis_group(self, identifier, definition): """ Inflate a whole analysis group. An analysis group is a section defined in the YAML file. Args: identifier (str): the group identifier. definition (list/dict): the group definition. Returns: ...
[ "def", "inflate_analysis_group", "(", "self", ",", "identifier", ",", "definition", ")", ":", "providers_definition", "=", "definition", ".", "pop", "(", "'providers'", ",", "None", ")", "checkers_definition", "=", "definition", ".", "pop", "(", "'checkers'", ",...
Inflate a whole analysis group. An analysis group is a section defined in the YAML file. Args: identifier (str): the group identifier. definition (list/dict): the group definition. Returns: AnalysisGroup: an instance of AnalysisGroup. Raises: ...
[ "Inflate", "a", "whole", "analysis", "group", "." ]
a026d3105c7e86f30e6c9507b93ceb736684bfdc
https://github.com/Genida/archan/blob/a026d3105c7e86f30e6c9507b93ceb736684bfdc/src/archan/config.py#L353-L431
train
Inflate an analysis group from a given definition.
Genida/archan
src/archan/config.py
Config.print_plugins
def print_plugins(self): """Print the available plugins.""" width = console_width() line = Style.BRIGHT + '=' * width + '\n' middle = int(width / 2) if self.available_providers: print(line + ' ' * middle + 'PROVIDERS') for provider in sorted(self.available...
python
def print_plugins(self): """Print the available plugins.""" width = console_width() line = Style.BRIGHT + '=' * width + '\n' middle = int(width / 2) if self.available_providers: print(line + ' ' * middle + 'PROVIDERS') for provider in sorted(self.available...
[ "def", "print_plugins", "(", "self", ")", ":", "width", "=", "console_width", "(", ")", "line", "=", "Style", ".", "BRIGHT", "+", "'='", "*", "width", "+", "'\\n'", "middle", "=", "int", "(", "width", "/", "2", ")", "if", "self", ".", "available_prov...
Print the available plugins.
[ "Print", "the", "available", "plugins", "." ]
a026d3105c7e86f30e6c9507b93ceb736684bfdc
https://github.com/Genida/archan/blob/a026d3105c7e86f30e6c9507b93ceb736684bfdc/src/archan/config.py#L433-L449
train
Print the available plugins.
tylerbutler/engineer
engineer/plugins/bundled.py
FinalizationPlugin.render_markdown
def render_markdown(post): """ Renders the post as Markdown using the template specified in :attr:`markdown_template_path`. """ from engineer.conf import settings # A hack to guarantee the YAML output is in a sensible order. # The order, assuming all metadata should be w...
python
def render_markdown(post): """ Renders the post as Markdown using the template specified in :attr:`markdown_template_path`. """ from engineer.conf import settings # A hack to guarantee the YAML output is in a sensible order. # The order, assuming all metadata should be w...
[ "def", "render_markdown", "(", "post", ")", ":", "from", "engineer", ".", "conf", "import", "settings", "# A hack to guarantee the YAML output is in a sensible order.", "# The order, assuming all metadata should be written, should be:", "# title", "# status", "# timestamp", "# link...
Renders the post as Markdown using the template specified in :attr:`markdown_template_path`.
[ "Renders", "the", "post", "as", "Markdown", "using", "the", "template", "specified", "in", ":", "attr", ":", "markdown_template_path", "." ]
8884f587297f37646c40e5553174852b444a4024
https://github.com/tylerbutler/engineer/blob/8884f587297f37646c40e5553174852b444a4024/engineer/plugins/bundled.py#L159-L222
train
Renders the post as Markdown using the template specified in markdown_template_path.
tjcsl/cslbot
cslbot/commands/random.py
cmd
def cmd(send, msg, args): """For when you don't have enough randomness in your life. Syntax: {command} [--int] [len] """ match = re.match(r'--(.+?)\b', msg) randtype = 'hex' if match: if match.group(1) == 'int': randtype = 'int' else: send("Invalid Flag....
python
def cmd(send, msg, args): """For when you don't have enough randomness in your life. Syntax: {command} [--int] [len] """ match = re.match(r'--(.+?)\b', msg) randtype = 'hex' if match: if match.group(1) == 'int': randtype = 'int' else: send("Invalid Flag....
[ "def", "cmd", "(", "send", ",", "msg", ",", "args", ")", ":", "match", "=", "re", ".", "match", "(", "r'--(.+?)\\b'", ",", "msg", ")", "randtype", "=", "'hex'", "if", "match", ":", "if", "match", ".", "group", "(", "1", ")", "==", "'int'", ":", ...
For when you don't have enough randomness in your life. Syntax: {command} [--int] [len]
[ "For", "when", "you", "don", "t", "have", "enough", "randomness", "in", "your", "life", "." ]
aebe07be47141f61d7c180706bddfb707f19b2b5
https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/random.py#L25-L50
train
For when you don t have enough randomness in your life.
VIVelev/PyDojoML
dojo/tree/utils/functions.py
split
def split(X, Y, question): """Partitions a dataset. For each row in the dataset, check if it matches the question. If so, add it to 'true rows', otherwise, add it to 'false rows'. """ true_X, false_X = [], [] true_Y, false_Y = [], [] for x, y in zip(X, Y): if question.match(x): ...
python
def split(X, Y, question): """Partitions a dataset. For each row in the dataset, check if it matches the question. If so, add it to 'true rows', otherwise, add it to 'false rows'. """ true_X, false_X = [], [] true_Y, false_Y = [], [] for x, y in zip(X, Y): if question.match(x): ...
[ "def", "split", "(", "X", ",", "Y", ",", "question", ")", ":", "true_X", ",", "false_X", "=", "[", "]", ",", "[", "]", "true_Y", ",", "false_Y", "=", "[", "]", ",", "[", "]", "for", "x", ",", "y", "in", "zip", "(", "X", ",", "Y", ")", ":"...
Partitions a dataset. For each row in the dataset, check if it matches the question. If so, add it to 'true rows', otherwise, add it to 'false rows'.
[ "Partitions", "a", "dataset", "." ]
773fdce6866aa6decd306a5a85f94129fed816eb
https://github.com/VIVelev/PyDojoML/blob/773fdce6866aa6decd306a5a85f94129fed816eb/dojo/tree/utils/functions.py#L17-L37
train
Partitions a dataset into two lists of true and false rows.
VIVelev/PyDojoML
dojo/tree/utils/functions.py
find_best_question
def find_best_question(X, y, criterion): """Find the best question to ask by iterating over every feature / value and calculating the information gain. """ measure_impurity = gini_impurity if criterion == "gini" else entropy current_impurity = measure_impurity(y) best_info_gain = 0 bes...
python
def find_best_question(X, y, criterion): """Find the best question to ask by iterating over every feature / value and calculating the information gain. """ measure_impurity = gini_impurity if criterion == "gini" else entropy current_impurity = measure_impurity(y) best_info_gain = 0 bes...
[ "def", "find_best_question", "(", "X", ",", "y", ",", "criterion", ")", ":", "measure_impurity", "=", "gini_impurity", "if", "criterion", "==", "\"gini\"", "else", "entropy", "current_impurity", "=", "measure_impurity", "(", "y", ")", "best_info_gain", "=", "0",...
Find the best question to ask by iterating over every feature / value and calculating the information gain.
[ "Find", "the", "best", "question", "to", "ask", "by", "iterating", "over", "every", "feature", "/", "value", "and", "calculating", "the", "information", "gain", "." ]
773fdce6866aa6decd306a5a85f94129fed816eb
https://github.com/VIVelev/PyDojoML/blob/773fdce6866aa6decd306a5a85f94129fed816eb/dojo/tree/utils/functions.py#L41-L62
train
Find the best question to ask by iterating over every feature and value and calculating the information gain.
VIVelev/PyDojoML
dojo/tree/utils/functions.py
build_tree
def build_tree(X, y, criterion, max_depth, current_depth=1): """Builds the decision tree. """ # check for max_depth accomplished if max_depth >= 0 and current_depth >= max_depth: return Leaf(y) # check for 0 gain gain, question = find_best_question(X, y, criterion) if gain == 0: ...
python
def build_tree(X, y, criterion, max_depth, current_depth=1): """Builds the decision tree. """ # check for max_depth accomplished if max_depth >= 0 and current_depth >= max_depth: return Leaf(y) # check for 0 gain gain, question = find_best_question(X, y, criterion) if gain == 0: ...
[ "def", "build_tree", "(", "X", ",", "y", ",", "criterion", ",", "max_depth", ",", "current_depth", "=", "1", ")", ":", "# check for max_depth accomplished", "if", "max_depth", ">=", "0", "and", "current_depth", ">=", "max_depth", ":", "return", "Leaf", "(", ...
Builds the decision tree.
[ "Builds", "the", "decision", "tree", "." ]
773fdce6866aa6decd306a5a85f94129fed816eb
https://github.com/VIVelev/PyDojoML/blob/773fdce6866aa6decd306a5a85f94129fed816eb/dojo/tree/utils/functions.py#L92-L129
train
Builds the decision tree.
VIVelev/PyDojoML
dojo/tree/utils/functions.py
tree_predict
def tree_predict(x, root, proba=False, regression=False): """Predicts a probabilities/value/label for the sample x. """ if isinstance(root, Leaf): if proba: return root.probabilities elif regression: return root.mean else: return root.most_frequen...
python
def tree_predict(x, root, proba=False, regression=False): """Predicts a probabilities/value/label for the sample x. """ if isinstance(root, Leaf): if proba: return root.probabilities elif regression: return root.mean else: return root.most_frequen...
[ "def", "tree_predict", "(", "x", ",", "root", ",", "proba", "=", "False", ",", "regression", "=", "False", ")", ":", "if", "isinstance", "(", "root", ",", "Leaf", ")", ":", "if", "proba", ":", "return", "root", ".", "probabilities", "elif", "regression...
Predicts a probabilities/value/label for the sample x.
[ "Predicts", "a", "probabilities", "/", "value", "/", "label", "for", "the", "sample", "x", "." ]
773fdce6866aa6decd306a5a85f94129fed816eb
https://github.com/VIVelev/PyDojoML/blob/773fdce6866aa6decd306a5a85f94129fed816eb/dojo/tree/utils/functions.py#L174-L189
train
Predicts a probabilities value or label for the sample x.
VIVelev/PyDojoML
dojo/tree/utils/functions.py
print_tree
def print_tree(root, space=' '): """Prints the Decision Tree in a pretty way. """ if isinstance(root, Leaf): print(space + "Prediction: " + str(root.most_frequent)) return print(space + str(root.question)) print(space + "--> True:") print_tree(root.true_branch, space+' ') ...
python
def print_tree(root, space=' '): """Prints the Decision Tree in a pretty way. """ if isinstance(root, Leaf): print(space + "Prediction: " + str(root.most_frequent)) return print(space + str(root.question)) print(space + "--> True:") print_tree(root.true_branch, space+' ') ...
[ "def", "print_tree", "(", "root", ",", "space", "=", "' '", ")", ":", "if", "isinstance", "(", "root", ",", "Leaf", ")", ":", "print", "(", "space", "+", "\"Prediction: \"", "+", "str", "(", "root", ".", "most_frequent", ")", ")", "return", "print", ...
Prints the Decision Tree in a pretty way.
[ "Prints", "the", "Decision", "Tree", "in", "a", "pretty", "way", "." ]
773fdce6866aa6decd306a5a85f94129fed816eb
https://github.com/VIVelev/PyDojoML/blob/773fdce6866aa6decd306a5a85f94129fed816eb/dojo/tree/utils/functions.py#L193-L207
train
Prints the Decision Tree in a pretty way.
levi-rs/explicit
explicit/waiter.py
find_element
def find_element(driver, elem_path, by=CSS, timeout=TIMEOUT, poll_frequency=0.5): """ Find and return an element once located find_element locates an element on the page, waiting for up to timeout seconds. The element, when located, is returned. If not located, a TimeoutException is raised. Args: ...
python
def find_element(driver, elem_path, by=CSS, timeout=TIMEOUT, poll_frequency=0.5): """ Find and return an element once located find_element locates an element on the page, waiting for up to timeout seconds. The element, when located, is returned. If not located, a TimeoutException is raised. Args: ...
[ "def", "find_element", "(", "driver", ",", "elem_path", ",", "by", "=", "CSS", ",", "timeout", "=", "TIMEOUT", ",", "poll_frequency", "=", "0.5", ")", ":", "wait", "=", "WebDriverWait", "(", "driver", ",", "timeout", ",", "poll_frequency", ")", "return", ...
Find and return an element once located find_element locates an element on the page, waiting for up to timeout seconds. The element, when located, is returned. If not located, a TimeoutException is raised. Args: driver (selenium webdriver or element): A driver or element elem_path (str...
[ "Find", "and", "return", "an", "element", "once", "located" ]
0ebdd4c8e74dae02fd92b914325e37e386694e4c
https://github.com/levi-rs/explicit/blob/0ebdd4c8e74dae02fd92b914325e37e386694e4c/explicit/waiter.py#L20-L41
train
Find an element on the page and return it once located.
levi-rs/explicit
explicit/waiter.py
find_elements
def find_elements(driver, elem_path, by=CSS, timeout=TIMEOUT, poll_frequency=0.5): """ Find and return all elements once located find_elements locates all elements on the page, waiting for up to timeout seconds. The elements, when located, are returned. If not located, a TimeoutException is raised. ...
python
def find_elements(driver, elem_path, by=CSS, timeout=TIMEOUT, poll_frequency=0.5): """ Find and return all elements once located find_elements locates all elements on the page, waiting for up to timeout seconds. The elements, when located, are returned. If not located, a TimeoutException is raised. ...
[ "def", "find_elements", "(", "driver", ",", "elem_path", ",", "by", "=", "CSS", ",", "timeout", "=", "TIMEOUT", ",", "poll_frequency", "=", "0.5", ")", ":", "wait", "=", "WebDriverWait", "(", "driver", ",", "timeout", ",", "poll_frequency", ")", "return", ...
Find and return all elements once located find_elements locates all elements on the page, waiting for up to timeout seconds. The elements, when located, are returned. If not located, a TimeoutException is raised. Args: driver (selenium webdriver or element): A driver or element elem_pa...
[ "Find", "and", "return", "all", "elements", "once", "located" ]
0ebdd4c8e74dae02fd92b914325e37e386694e4c
https://github.com/levi-rs/explicit/blob/0ebdd4c8e74dae02fd92b914325e37e386694e4c/explicit/waiter.py#L44-L65
train
Find and return all elements located on the page.
levi-rs/explicit
explicit/waiter.py
find_one
def find_one(driver, locator_list, elem_type=CSS, timeout=TIMEOUT): """ Args: driver (selenium webdriver): Selenium webdriver object locator_list (:obj: `list` of :obj: `str`): List of CSS selector strings elem_type (Selenium By types): Selenium By type (i.e. By.CSS_SELECTOR) tim...
python
def find_one(driver, locator_list, elem_type=CSS, timeout=TIMEOUT): """ Args: driver (selenium webdriver): Selenium webdriver object locator_list (:obj: `list` of :obj: `str`): List of CSS selector strings elem_type (Selenium By types): Selenium By type (i.e. By.CSS_SELECTOR) tim...
[ "def", "find_one", "(", "driver", ",", "locator_list", ",", "elem_type", "=", "CSS", ",", "timeout", "=", "TIMEOUT", ")", ":", "def", "_find_one", "(", "driver", ")", ":", "\"\"\" Expected Condition to find and return first located element \"\"\"", "finders", "=", "...
Args: driver (selenium webdriver): Selenium webdriver object locator_list (:obj: `list` of :obj: `str`): List of CSS selector strings elem_type (Selenium By types): Selenium By type (i.e. By.CSS_SELECTOR) timeout (int): Number of seconds to wait before timing out Returns: Se...
[ "Args", ":", "driver", "(", "selenium", "webdriver", ")", ":", "Selenium", "webdriver", "object", "locator_list", "(", ":", "obj", ":", "list", "of", ":", "obj", ":", "str", ")", ":", "List", "of", "CSS", "selector", "strings", "elem_type", "(", "Seleniu...
0ebdd4c8e74dae02fd92b914325e37e386694e4c
https://github.com/levi-rs/explicit/blob/0ebdd4c8e74dae02fd92b914325e37e386694e4c/explicit/waiter.py#L68-L107
train
Find one element in the list of CSS selectors.
levi-rs/explicit
explicit/waiter.py
find_write
def find_write(driver, elem_path, write_str, clear_first=True, send_enter=False, by=CSS, timeout=TIMEOUT, poll_frequency=0.5): """ Find a writable element and write to it find_write locates a writable element on the page, waiting for up to timeout seconds. Once found, it writes the string ...
python
def find_write(driver, elem_path, write_str, clear_first=True, send_enter=False, by=CSS, timeout=TIMEOUT, poll_frequency=0.5): """ Find a writable element and write to it find_write locates a writable element on the page, waiting for up to timeout seconds. Once found, it writes the string ...
[ "def", "find_write", "(", "driver", ",", "elem_path", ",", "write_str", ",", "clear_first", "=", "True", ",", "send_enter", "=", "False", ",", "by", "=", "CSS", ",", "timeout", "=", "TIMEOUT", ",", "poll_frequency", "=", "0.5", ")", ":", "elem", "=", "...
Find a writable element and write to it find_write locates a writable element on the page, waiting for up to timeout seconds. Once found, it writes the string to it. Args: driver (selenium webdriver or element): A driver or element elem_path (str): String used to located the element ...
[ "Find", "a", "writable", "element", "and", "write", "to", "it" ]
0ebdd4c8e74dae02fd92b914325e37e386694e4c
https://github.com/levi-rs/explicit/blob/0ebdd4c8e74dae02fd92b914325e37e386694e4c/explicit/waiter.py#L110-L145
train
Find a writable element and write to it
tjcsl/cslbot
cslbot/commands/intensify.py
cmd
def cmd(send, msg, args): """Intensifies text. Syntax: {command} [text] """ if not msg: msg = gen_word() send(gen_intensify(msg))
python
def cmd(send, msg, args): """Intensifies text. Syntax: {command} [text] """ if not msg: msg = gen_word() send(gen_intensify(msg))
[ "def", "cmd", "(", "send", ",", "msg", ",", "args", ")", ":", "if", "not", "msg", ":", "msg", "=", "gen_word", "(", ")", "send", "(", "gen_intensify", "(", "msg", ")", ")" ]
Intensifies text. Syntax: {command} [text]
[ "Intensifies", "text", "." ]
aebe07be47141f61d7c180706bddfb707f19b2b5
https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/intensify.py#L23-L31
train
Intensifies text. Syntax
VIVelev/PyDojoML
dojo/svm/libsvm/commonutil.py
svm_read_problem
def svm_read_problem(data_file_name, return_scipy=False): """ svm_read_problem(data_file_name, return_scipy=False) -> [y, x], y: list, x: list of dictionary svm_read_problem(data_file_name, return_scipy=True) -> [y, x], y: ndarray, x: csr_matrix Read LIBSVM-format data from data_file_name and return labels y and...
python
def svm_read_problem(data_file_name, return_scipy=False): """ svm_read_problem(data_file_name, return_scipy=False) -> [y, x], y: list, x: list of dictionary svm_read_problem(data_file_name, return_scipy=True) -> [y, x], y: ndarray, x: csr_matrix Read LIBSVM-format data from data_file_name and return labels y and...
[ "def", "svm_read_problem", "(", "data_file_name", ",", "return_scipy", "=", "False", ")", ":", "prob_y", "=", "[", "]", "prob_x", "=", "[", "]", "row_ptr", "=", "[", "0", "]", "col_idx", "=", "[", "]", "for", "i", ",", "line", "in", "enumerate", "(",...
svm_read_problem(data_file_name, return_scipy=False) -> [y, x], y: list, x: list of dictionary svm_read_problem(data_file_name, return_scipy=True) -> [y, x], y: ndarray, x: csr_matrix Read LIBSVM-format data from data_file_name and return labels y and data instances x.
[ "svm_read_problem", "(", "data_file_name", "return_scipy", "=", "False", ")", "-", ">", "[", "y", "x", "]", "y", ":", "list", "x", ":", "list", "of", "dictionary", "svm_read_problem", "(", "data_file_name", "return_scipy", "=", "True", ")", "-", ">", "[", ...
773fdce6866aa6decd306a5a85f94129fed816eb
https://github.com/VIVelev/PyDojoML/blob/773fdce6866aa6decd306a5a85f94129fed816eb/dojo/svm/libsvm/commonutil.py#L16-L56
train
Reads LIBSVM - format data from data_file_name and returns labels y and x.
VIVelev/PyDojoML
dojo/svm/libsvm/commonutil.py
evaluations_scipy
def evaluations_scipy(ty, pv): """ evaluations_scipy(ty, pv) -> (ACC, MSE, SCC) ty, pv: ndarray Calculate accuracy, mean squared error and squared correlation coefficient using the true values (ty) and predicted values (pv). """ if not (scipy != None and isinstance(ty, scipy.ndarray) and isinstance(pv, scipy.nd...
python
def evaluations_scipy(ty, pv): """ evaluations_scipy(ty, pv) -> (ACC, MSE, SCC) ty, pv: ndarray Calculate accuracy, mean squared error and squared correlation coefficient using the true values (ty) and predicted values (pv). """ if not (scipy != None and isinstance(ty, scipy.ndarray) and isinstance(pv, scipy.nd...
[ "def", "evaluations_scipy", "(", "ty", ",", "pv", ")", ":", "if", "not", "(", "scipy", "!=", "None", "and", "isinstance", "(", "ty", ",", "scipy", ".", "ndarray", ")", "and", "isinstance", "(", "pv", ",", "scipy", ".", "ndarray", ")", ")", ":", "ra...
evaluations_scipy(ty, pv) -> (ACC, MSE, SCC) ty, pv: ndarray Calculate accuracy, mean squared error and squared correlation coefficient using the true values (ty) and predicted values (pv).
[ "evaluations_scipy", "(", "ty", "pv", ")", "-", ">", "(", "ACC", "MSE", "SCC", ")", "ty", "pv", ":", "ndarray" ]
773fdce6866aa6decd306a5a85f94129fed816eb
https://github.com/VIVelev/PyDojoML/blob/773fdce6866aa6decd306a5a85f94129fed816eb/dojo/svm/libsvm/commonutil.py#L58-L83
train
Compute the evaluation of two arrays of values using scipy.
VIVelev/PyDojoML
dojo/svm/libsvm/commonutil.py
evaluations
def evaluations(ty, pv, useScipy = True): """ evaluations(ty, pv, useScipy) -> (ACC, MSE, SCC) ty, pv: list, tuple or ndarray useScipy: convert ty, pv to ndarray, and use scipy functions for the evaluation Calculate accuracy, mean squared error and squared correlation coefficient using the true values (ty) and p...
python
def evaluations(ty, pv, useScipy = True): """ evaluations(ty, pv, useScipy) -> (ACC, MSE, SCC) ty, pv: list, tuple or ndarray useScipy: convert ty, pv to ndarray, and use scipy functions for the evaluation Calculate accuracy, mean squared error and squared correlation coefficient using the true values (ty) and p...
[ "def", "evaluations", "(", "ty", ",", "pv", ",", "useScipy", "=", "True", ")", ":", "if", "scipy", "!=", "None", "and", "useScipy", ":", "return", "evaluations_scipy", "(", "scipy", ".", "asarray", "(", "ty", ")", ",", "scipy", ".", "asarray", "(", "...
evaluations(ty, pv, useScipy) -> (ACC, MSE, SCC) ty, pv: list, tuple or ndarray useScipy: convert ty, pv to ndarray, and use scipy functions for the evaluation Calculate accuracy, mean squared error and squared correlation coefficient using the true values (ty) and predicted values (pv).
[ "evaluations", "(", "ty", "pv", "useScipy", ")", "-", ">", "(", "ACC", "MSE", "SCC", ")", "ty", "pv", ":", "list", "tuple", "or", "ndarray", "useScipy", ":", "convert", "ty", "pv", "to", "ndarray", "and", "use", "scipy", "functions", "for", "the", "e...
773fdce6866aa6decd306a5a85f94129fed816eb
https://github.com/VIVelev/PyDojoML/blob/773fdce6866aa6decd306a5a85f94129fed816eb/dojo/svm/libsvm/commonutil.py#L85-L116
train
calculate the evaluations of the predicted values of the given type and pv
Xion/taipan
taipan/collections/__init__.py
is_ordered_mapping
def is_ordered_mapping(obj): """Checks whether given object is an ordered mapping, e.g. a :class:`OrderedDict`. :return: ``True`` if argument is an ordered mapping, ``False`` otherwise """ if not (is_mapping(obj) and hasattr(obj, '__reversed__')): return False # PyPy has a bug where the...
python
def is_ordered_mapping(obj): """Checks whether given object is an ordered mapping, e.g. a :class:`OrderedDict`. :return: ``True`` if argument is an ordered mapping, ``False`` otherwise """ if not (is_mapping(obj) and hasattr(obj, '__reversed__')): return False # PyPy has a bug where the...
[ "def", "is_ordered_mapping", "(", "obj", ")", ":", "if", "not", "(", "is_mapping", "(", "obj", ")", "and", "hasattr", "(", "obj", ",", "'__reversed__'", ")", ")", ":", "return", "False", "# PyPy has a bug where the standard :class:`dict` has the ``__reversed__``", "...
Checks whether given object is an ordered mapping, e.g. a :class:`OrderedDict`. :return: ``True`` if argument is an ordered mapping, ``False`` otherwise
[ "Checks", "whether", "given", "object", "is", "an", "ordered", "mapping", "e", ".", "g", ".", "a", ":", "class", ":", "OrderedDict", ".", ":", "return", ":", "True", "if", "argument", "is", "an", "ordered", "mapping", "False", "otherwise" ]
f333f0287c8bd0915182c7d5308e5f05ef0cca78
https://github.com/Xion/taipan/blob/f333f0287c8bd0915182c7d5308e5f05ef0cca78/taipan/collections/__init__.py#L40-L55
train
Checks whether given object is an ordered mapping.
The-Politico/politico-civic-election-night
electionnight/management/commands/bake_elections.py
Command.fetch_states
def fetch_states(self, elections): """ Returns the unique divisions for all elections on an election day. """ states = [] for election in elections: if election.division.level.name == DivisionLevel.DISTRICT: division = election.division.parent ...
python
def fetch_states(self, elections): """ Returns the unique divisions for all elections on an election day. """ states = [] for election in elections: if election.division.level.name == DivisionLevel.DISTRICT: division = election.division.parent ...
[ "def", "fetch_states", "(", "self", ",", "elections", ")", ":", "states", "=", "[", "]", "for", "election", "in", "elections", ":", "if", "election", ".", "division", ".", "level", ".", "name", "==", "DivisionLevel", ".", "DISTRICT", ":", "division", "="...
Returns the unique divisions for all elections on an election day.
[ "Returns", "the", "unique", "divisions", "for", "all", "elections", "on", "an", "election", "day", "." ]
a8aaf5be43872a7b84d2b0d7c2b6151d32d4d8b6
https://github.com/The-Politico/politico-civic-election-night/blob/a8aaf5be43872a7b84d2b0d7c2b6151d32d4d8b6/electionnight/management/commands/bake_elections.py#L25-L39
train
Returns the unique divisions for all elections on an election day.
ktdreyer/txkoji
txkoji/cache.py
Cache.get_name
def get_name(self, type_, id_): """ Read a cached name if available. :param type_: str, "owner" or "tag" :param id_: int, eg. 123456 :returns: str, or None """ cachefile = self.filename(type_, id_) try: with open(cachefile, 'r') as f: ...
python
def get_name(self, type_, id_): """ Read a cached name if available. :param type_: str, "owner" or "tag" :param id_: int, eg. 123456 :returns: str, or None """ cachefile = self.filename(type_, id_) try: with open(cachefile, 'r') as f: ...
[ "def", "get_name", "(", "self", ",", "type_", ",", "id_", ")", ":", "cachefile", "=", "self", ".", "filename", "(", "type_", ",", "id_", ")", "try", ":", "with", "open", "(", "cachefile", ",", "'r'", ")", "as", "f", ":", "return", "f", ".", "read...
Read a cached name if available. :param type_: str, "owner" or "tag" :param id_: int, eg. 123456 :returns: str, or None
[ "Read", "a", "cached", "name", "if", "available", "." ]
a7de380f29f745bf11730b27217208f6d4da7733
https://github.com/ktdreyer/txkoji/blob/a7de380f29f745bf11730b27217208f6d4da7733/txkoji/cache.py#L29-L43
train
Read a cached name if available.
ktdreyer/txkoji
txkoji/cache.py
Cache.put_name
def put_name(self, type_, id_, name): """ Write a cached name to disk. :param type_: str, "user" or "tag" :param id_: int, eg. 123456 :returns: None """ cachefile = self.filename(type_, id_) dirname = os.path.dirname(cachefile) try: os...
python
def put_name(self, type_, id_, name): """ Write a cached name to disk. :param type_: str, "user" or "tag" :param id_: int, eg. 123456 :returns: None """ cachefile = self.filename(type_, id_) dirname = os.path.dirname(cachefile) try: os...
[ "def", "put_name", "(", "self", ",", "type_", ",", "id_", ",", "name", ")", ":", "cachefile", "=", "self", ".", "filename", "(", "type_", ",", "id_", ")", "dirname", "=", "os", ".", "path", ".", "dirname", "(", "cachefile", ")", "try", ":", "os", ...
Write a cached name to disk. :param type_: str, "user" or "tag" :param id_: int, eg. 123456 :returns: None
[ "Write", "a", "cached", "name", "to", "disk", "." ]
a7de380f29f745bf11730b27217208f6d4da7733
https://github.com/ktdreyer/txkoji/blob/a7de380f29f745bf11730b27217208f6d4da7733/txkoji/cache.py#L45-L61
train
Write a name to disk.
ktdreyer/txkoji
txkoji/cache.py
Cache.filename
def filename(self, type_, id_): """ cache filename to read for this type/id. :param type_: str, "user" or "tag" :param id_: int, eg. 123456 :returns: str """ profile = self.connection.profile return os.path.join(self.directory, profile, type_, str(id_))
python
def filename(self, type_, id_): """ cache filename to read for this type/id. :param type_: str, "user" or "tag" :param id_: int, eg. 123456 :returns: str """ profile = self.connection.profile return os.path.join(self.directory, profile, type_, str(id_))
[ "def", "filename", "(", "self", ",", "type_", ",", "id_", ")", ":", "profile", "=", "self", ".", "connection", ".", "profile", "return", "os", ".", "path", ".", "join", "(", "self", ".", "directory", ",", "profile", ",", "type_", ",", "str", "(", "...
cache filename to read for this type/id. :param type_: str, "user" or "tag" :param id_: int, eg. 123456 :returns: str
[ "cache", "filename", "to", "read", "for", "this", "type", "/", "id", "." ]
a7de380f29f745bf11730b27217208f6d4da7733
https://github.com/ktdreyer/txkoji/blob/a7de380f29f745bf11730b27217208f6d4da7733/txkoji/cache.py#L63-L72
train
Returns the cache filename to read for this type and id.
ktdreyer/txkoji
txkoji/cache.py
Cache.get_or_load_name
def get_or_load_name(self, type_, id_, method): """ read-through cache for a type of object's name. If we don't have a cached name for this type/id, then we will query the live Koji server and store the value before returning. :param type_: str, "user" or "tag" :param i...
python
def get_or_load_name(self, type_, id_, method): """ read-through cache for a type of object's name. If we don't have a cached name for this type/id, then we will query the live Koji server and store the value before returning. :param type_: str, "user" or "tag" :param i...
[ "def", "get_or_load_name", "(", "self", ",", "type_", ",", "id_", ",", "method", ")", ":", "name", "=", "self", ".", "get_name", "(", "type_", ",", "id_", ")", "if", "name", "is", "not", "None", ":", "defer", ".", "returnValue", "(", "name", ")", "...
read-through cache for a type of object's name. If we don't have a cached name for this type/id, then we will query the live Koji server and store the value before returning. :param type_: str, "user" or "tag" :param id_: int, eg. 123456 :param method: function to call if this ...
[ "read", "-", "through", "cache", "for", "a", "type", "of", "object", "s", "name", "." ]
a7de380f29f745bf11730b27217208f6d4da7733
https://github.com/ktdreyer/txkoji/blob/a7de380f29f745bf11730b27217208f6d4da7733/txkoji/cache.py#L75-L96
train
Reads the cache for a type of object s name. If the cache is not available then we will load the name from the server and store it.
ktdreyer/txkoji
txkoji/multicall.py
MultiCall.call
def call(self, name, *args, **kwargs): """ Add a new call to the list that we will submit to the server. Similar to txkoji.Connection.call(), but this will store the call for later instead of sending it now. """ # Like txkoji.Connection, we always want the full request f...
python
def call(self, name, *args, **kwargs): """ Add a new call to the list that we will submit to the server. Similar to txkoji.Connection.call(), but this will store the call for later instead of sending it now. """ # Like txkoji.Connection, we always want the full request f...
[ "def", "call", "(", "self", ",", "name", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# Like txkoji.Connection, we always want the full request for tasks:", "if", "name", "in", "(", "'getTaskInfo'", ",", "'getTaskDescendants'", ")", ":", "kwargs", "[", ...
Add a new call to the list that we will submit to the server. Similar to txkoji.Connection.call(), but this will store the call for later instead of sending it now.
[ "Add", "a", "new", "call", "to", "the", "list", "that", "we", "will", "submit", "to", "the", "server", "." ]
a7de380f29f745bf11730b27217208f6d4da7733
https://github.com/ktdreyer/txkoji/blob/a7de380f29f745bf11730b27217208f6d4da7733/txkoji/multicall.py#L44-L58
train
Add a new call to the list of calls that we will send to the server.
ktdreyer/txkoji
txkoji/multicall.py
MultiCall._multicall_callback
def _multicall_callback(self, values, calls): """ Fires when we get information back from the XML-RPC server. This is processes the raw results of system.multicall into a usable iterator of values (and/or Faults). :param values: list of data txkoji.Connection.call() :pa...
python
def _multicall_callback(self, values, calls): """ Fires when we get information back from the XML-RPC server. This is processes the raw results of system.multicall into a usable iterator of values (and/or Faults). :param values: list of data txkoji.Connection.call() :pa...
[ "def", "_multicall_callback", "(", "self", ",", "values", ",", "calls", ")", ":", "result", "=", "KojiMultiCallIterator", "(", "values", ")", "result", ".", "connection", "=", "self", ".", "connection", "result", ".", "calls", "=", "calls", "return", "result...
Fires when we get information back from the XML-RPC server. This is processes the raw results of system.multicall into a usable iterator of values (and/or Faults). :param values: list of data txkoji.Connection.call() :param calls: list of calls we sent in this multicall RPC :re...
[ "Fires", "when", "we", "get", "information", "back", "from", "the", "XML", "-", "RPC", "server", "." ]
a7de380f29f745bf11730b27217208f6d4da7733
https://github.com/ktdreyer/txkoji/blob/a7de380f29f745bf11730b27217208f6d4da7733/txkoji/multicall.py#L60-L75
train
This is the callback that is called when we get information back from the XML - RPC server.
ktdreyer/txkoji
txkoji/multicall.py
KojiMultiCallIterator.rich_item
def rich_item(self, method_name, value): """ Convert this value into the rich txkoji objects (if applicable) """ if value is None: return None if method_name == 'getAverageBuildDuration': return timedelta(seconds=value) types = (Build, Channel, Pac...
python
def rich_item(self, method_name, value): """ Convert this value into the rich txkoji objects (if applicable) """ if value is None: return None if method_name == 'getAverageBuildDuration': return timedelta(seconds=value) types = (Build, Channel, Pac...
[ "def", "rich_item", "(", "self", ",", "method_name", ",", "value", ")", ":", "if", "value", "is", "None", ":", "return", "None", "if", "method_name", "==", "'getAverageBuildDuration'", ":", "return", "timedelta", "(", "seconds", "=", "value", ")", "types", ...
Convert this value into the rich txkoji objects (if applicable)
[ "Convert", "this", "value", "into", "the", "rich", "txkoji", "objects", "(", "if", "applicable", ")" ]
a7de380f29f745bf11730b27217208f6d4da7733
https://github.com/ktdreyer/txkoji/blob/a7de380f29f745bf11730b27217208f6d4da7733/txkoji/multicall.py#L104-L123
train
Convert this value into the rich txkoji objects
dkkline/EventManager
EventManager/EventManager.py
Event.add_handler
def add_handler(self, handler): """Adds a handler. Also checks if it is callable. To bypass checks, use Event.append() instead.""" if not callable(handler): raise TypeError("'%s' is not callable." % handler) self.append(handler)
python
def add_handler(self, handler): """Adds a handler. Also checks if it is callable. To bypass checks, use Event.append() instead.""" if not callable(handler): raise TypeError("'%s' is not callable." % handler) self.append(handler)
[ "def", "add_handler", "(", "self", ",", "handler", ")", ":", "if", "not", "callable", "(", "handler", ")", ":", "raise", "TypeError", "(", "\"'%s' is not callable.\"", "%", "handler", ")", "self", ".", "append", "(", "handler", ")" ]
Adds a handler. Also checks if it is callable. To bypass checks, use Event.append() instead.
[ "Adds", "a", "handler", ".", "Also", "checks", "if", "it", "is", "callable", ".", "To", "bypass", "checks", "use", "Event", ".", "append", "()", "instead", "." ]
39c722335e908ff28a3e4814e62db012ced211f2
https://github.com/dkkline/EventManager/blob/39c722335e908ff28a3e4814e62db012ced211f2/EventManager/EventManager.py#L28-L34
train
Adds a handler to the event list.
dkkline/EventManager
EventManager/EventManager.py
Event.fire
def fire(self, *args, **kwargs): """Fires an event, executing all it's handlers with given args and kwargs. You can also use Event() directly instead of Event.fire()""" if self.eventmanager: # Fire global event. Assuming we have an eventmanager. self.eventma...
python
def fire(self, *args, **kwargs): """Fires an event, executing all it's handlers with given args and kwargs. You can also use Event() directly instead of Event.fire()""" if self.eventmanager: # Fire global event. Assuming we have an eventmanager. self.eventma...
[ "def", "fire", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "eventmanager", ":", "# Fire global event. Assuming we have an eventmanager.\r", "self", ".", "eventmanager", ".", "got_event", "(", "self", ".", "name", ",", ...
Fires an event, executing all it's handlers with given args and kwargs. You can also use Event() directly instead of Event.fire()
[ "Fires", "an", "event", "executing", "all", "it", "s", "handlers", "with", "given", "args", "and", "kwargs", ".", "You", "can", "also", "use", "Event", "()", "directly", "instead", "of", "Event", ".", "fire", "()" ]
39c722335e908ff28a3e4814e62db012ced211f2
https://github.com/dkkline/EventManager/blob/39c722335e908ff28a3e4814e62db012ced211f2/EventManager/EventManager.py#L40-L52
train
Fires an event executing all the handlers with given args and kwargs.
dkkline/EventManager
EventManager/EventManager.py
EventManager.apply
def apply(self, events): """ EventManager.apply(events) -> Takes an object with methods, and applies them to EventManager. Example: class TestEvents(object): @staticmethod def test_method(): pass e = T...
python
def apply(self, events): """ EventManager.apply(events) -> Takes an object with methods, and applies them to EventManager. Example: class TestEvents(object): @staticmethod def test_method(): pass e = T...
[ "def", "apply", "(", "self", ",", "events", ")", ":", "for", "method", "in", "dir", "(", "events", ")", ":", "# Skip attributes\r", "if", "not", "callable", "(", "getattr", "(", "events", ",", "method", ")", ")", ":", "continue", "# Skip \"trash\" function...
EventManager.apply(events) -> Takes an object with methods, and applies them to EventManager. Example: class TestEvents(object): @staticmethod def test_method(): pass e = TestEvents() em = EventManager() ...
[ "EventManager", ".", "apply", "(", "events", ")", "-", ">", "Takes", "an", "object", "with", "methods", "and", "applies", "them", "to", "EventManager", ".", "Example", ":", "class", "TestEvents", "(", "object", ")", ":" ]
39c722335e908ff28a3e4814e62db012ced211f2
https://github.com/dkkline/EventManager/blob/39c722335e908ff28a3e4814e62db012ced211f2/EventManager/EventManager.py#L89-L115
train
Applies methods to events and creates Event objects.
mardix/Juice
juice/utils.py
is_valid_email
def is_valid_email(email): """ Check if email is valid """ pattern = re.compile(r'[\w\.-]+@[\w\.-]+[.]\w+') return bool(pattern.match(email))
python
def is_valid_email(email): """ Check if email is valid """ pattern = re.compile(r'[\w\.-]+@[\w\.-]+[.]\w+') return bool(pattern.match(email))
[ "def", "is_valid_email", "(", "email", ")", ":", "pattern", "=", "re", ".", "compile", "(", "r'[\\w\\.-]+@[\\w\\.-]+[.]\\w+'", ")", "return", "bool", "(", "pattern", ".", "match", "(", "email", ")", ")" ]
Check if email is valid
[ "Check", "if", "email", "is", "valid" ]
7afa8d4238868235dfcdae82272bd77958dd416a
https://github.com/mardix/Juice/blob/7afa8d4238868235dfcdae82272bd77958dd416a/juice/utils.py#L30-L35
train
Check if email is valid
mardix/Juice
juice/utils.py
is_valid_password
def is_valid_password(password): """ Check if a password is valid """ pattern = re.compile(r"^.{4,75}$") return bool(pattern.match(password))
python
def is_valid_password(password): """ Check if a password is valid """ pattern = re.compile(r"^.{4,75}$") return bool(pattern.match(password))
[ "def", "is_valid_password", "(", "password", ")", ":", "pattern", "=", "re", ".", "compile", "(", "r\"^.{4,75}$\"", ")", "return", "bool", "(", "pattern", ".", "match", "(", "password", ")", ")" ]
Check if a password is valid
[ "Check", "if", "a", "password", "is", "valid" ]
7afa8d4238868235dfcdae82272bd77958dd416a
https://github.com/mardix/Juice/blob/7afa8d4238868235dfcdae82272bd77958dd416a/juice/utils.py#L38-L43
train
Check if a password is valid
mardix/Juice
juice/utils.py
md5_string
def md5_string(s): """ Shortcut to create md5 hash :param s: :return: """ m = hashlib.md5() m.update(s) return str(m.hexdigest())
python
def md5_string(s): """ Shortcut to create md5 hash :param s: :return: """ m = hashlib.md5() m.update(s) return str(m.hexdigest())
[ "def", "md5_string", "(", "s", ")", ":", "m", "=", "hashlib", ".", "md5", "(", ")", "m", ".", "update", "(", "s", ")", "return", "str", "(", "m", ".", "hexdigest", "(", ")", ")" ]
Shortcut to create md5 hash :param s: :return:
[ "Shortcut", "to", "create", "md5", "hash", ":", "param", "s", ":", ":", "return", ":" ]
7afa8d4238868235dfcdae82272bd77958dd416a
https://github.com/mardix/Juice/blob/7afa8d4238868235dfcdae82272bd77958dd416a/juice/utils.py#L67-L75
train
Shortcut to create md5 hash of a sequence of strings
mardix/Juice
juice/utils.py
get_domain_name
def get_domain_name(url): """ Get the domain name :param url: :return: """ if not url.startswith("http"): url = "http://" + url if not is_valid_url(url): raise ValueError("Invalid URL '%s'" % url) parse = urlparse(url) return parse.netloc
python
def get_domain_name(url): """ Get the domain name :param url: :return: """ if not url.startswith("http"): url = "http://" + url if not is_valid_url(url): raise ValueError("Invalid URL '%s'" % url) parse = urlparse(url) return parse.netloc
[ "def", "get_domain_name", "(", "url", ")", ":", "if", "not", "url", ".", "startswith", "(", "\"http\"", ")", ":", "url", "=", "\"http://\"", "+", "url", "if", "not", "is_valid_url", "(", "url", ")", ":", "raise", "ValueError", "(", "\"Invalid URL '%s'\"", ...
Get the domain name :param url: :return:
[ "Get", "the", "domain", "name", ":", "param", "url", ":", ":", "return", ":" ]
7afa8d4238868235dfcdae82272bd77958dd416a
https://github.com/mardix/Juice/blob/7afa8d4238868235dfcdae82272bd77958dd416a/juice/utils.py#L107-L118
train
Get the domain name of the url
mardix/Juice
juice/utils.py
time_ago
def time_ago(dt): """ Return the current time ago """ now = datetime.datetime.now() return humanize.naturaltime(now - dt)
python
def time_ago(dt): """ Return the current time ago """ now = datetime.datetime.now() return humanize.naturaltime(now - dt)
[ "def", "time_ago", "(", "dt", ")", ":", "now", "=", "datetime", ".", "datetime", ".", "now", "(", ")", "return", "humanize", ".", "naturaltime", "(", "now", "-", "dt", ")" ]
Return the current time ago
[ "Return", "the", "current", "time", "ago" ]
7afa8d4238868235dfcdae82272bd77958dd416a
https://github.com/mardix/Juice/blob/7afa8d4238868235dfcdae82272bd77958dd416a/juice/utils.py#L228-L233
train
Return the current time ago
mardix/Juice
juice/utils.py
DotDict.get
def get(self, keys, default=None): """ To get a value by dot notation :param keys: dot notaion string :param default: :return: """ try: d = self for k in keys.split("."): if not k in d: d[k] = {} ...
python
def get(self, keys, default=None): """ To get a value by dot notation :param keys: dot notaion string :param default: :return: """ try: d = self for k in keys.split("."): if not k in d: d[k] = {} ...
[ "def", "get", "(", "self", ",", "keys", ",", "default", "=", "None", ")", ":", "try", ":", "d", "=", "self", "for", "k", "in", "keys", ".", "split", "(", "\".\"", ")", ":", "if", "not", "k", "in", "d", ":", "d", "[", "k", "]", "=", "{", "...
To get a value by dot notation :param keys: dot notaion string :param default: :return:
[ "To", "get", "a", "value", "by", "dot", "notation", ":", "param", "keys", ":", "dot", "notaion", "string", ":", "param", "default", ":", ":", "return", ":" ]
7afa8d4238868235dfcdae82272bd77958dd416a
https://github.com/mardix/Juice/blob/7afa8d4238868235dfcdae82272bd77958dd416a/juice/utils.py#L286-L303
train
Get a value by dot notation notaion string
rraadd88/rohan
rohan/dandage/db/uniprot.py
get_sequence
def get_sequence(queries,fap=None,fmt='fasta', organism_taxid=9606, test=False): """ http://www.ebi.ac.uk/Tools/dbfetch/dbfetch?db=uniprotkb&id=P14060+P26439&format=fasta&style=raw&Retrieve=Retrieve https://www.uniprot.org/uniprot/?format=fasta&organism=9606&query=O75116+O75116+...
python
def get_sequence(queries,fap=None,fmt='fasta', organism_taxid=9606, test=False): """ http://www.ebi.ac.uk/Tools/dbfetch/dbfetch?db=uniprotkb&id=P14060+P26439&format=fasta&style=raw&Retrieve=Retrieve https://www.uniprot.org/uniprot/?format=fasta&organism=9606&query=O75116+O75116+...
[ "def", "get_sequence", "(", "queries", ",", "fap", "=", "None", ",", "fmt", "=", "'fasta'", ",", "organism_taxid", "=", "9606", ",", "test", "=", "False", ")", ":", "url", "=", "'http://www.ebi.ac.uk/Tools/dbfetch/dbfetch'", "params", "=", "{", "'id'", ":", ...
http://www.ebi.ac.uk/Tools/dbfetch/dbfetch?db=uniprotkb&id=P14060+P26439&format=fasta&style=raw&Retrieve=Retrieve https://www.uniprot.org/uniprot/?format=fasta&organism=9606&query=O75116+O75116+P35548+O14944+O14944
[ "http", ":", "//", "www", ".", "ebi", ".", "ac", ".", "uk", "/", "Tools", "/", "dbfetch", "/", "dbfetch?db", "=", "uniprotkb&id", "=", "P14060", "+", "P26439&format", "=", "fasta&style", "=", "raw&Retrieve", "=", "Retrieve", "https", ":", "//", "www", ...
b0643a3582a2fffc0165ace69fb80880d92bfb10
https://github.com/rraadd88/rohan/blob/b0643a3582a2fffc0165ace69fb80880d92bfb10/rohan/dandage/db/uniprot.py#L5-L32
train
Get sequence from UniProt.
rraadd88/rohan
rohan/dandage/db/uniprot.py
map_ids
def map_ids(queries,frm='ACC',to='ENSEMBL_PRO_ID', organism_taxid=9606,test=False): """ https://www.uniprot.org/help/api_idmapping """ url = 'https://www.uniprot.org/uploadlists/' params = { 'from':frm, 'to':to, 'format':'tab', 'organism':organism_taxid, 'query':'...
python
def map_ids(queries,frm='ACC',to='ENSEMBL_PRO_ID', organism_taxid=9606,test=False): """ https://www.uniprot.org/help/api_idmapping """ url = 'https://www.uniprot.org/uploadlists/' params = { 'from':frm, 'to':to, 'format':'tab', 'organism':organism_taxid, 'query':'...
[ "def", "map_ids", "(", "queries", ",", "frm", "=", "'ACC'", ",", "to", "=", "'ENSEMBL_PRO_ID'", ",", "organism_taxid", "=", "9606", ",", "test", "=", "False", ")", ":", "url", "=", "'https://www.uniprot.org/uploadlists/'", "params", "=", "{", "'from'", ":", ...
https://www.uniprot.org/help/api_idmapping
[ "https", ":", "//", "www", ".", "uniprot", ".", "org", "/", "help", "/", "api_idmapping" ]
b0643a3582a2fffc0165ace69fb80880d92bfb10
https://github.com/rraadd88/rohan/blob/b0643a3582a2fffc0165ace69fb80880d92bfb10/rohan/dandage/db/uniprot.py#L46-L67
train
Map IDs to UniProt IDs.
tjcsl/cslbot
cslbot/commands/insult.py
cmd
def cmd(send, msg, args): """Insults a user. Syntax: {command} [nick] """ if not msg: user = choice(get_users(args)) else: user = msg send(gen_insult(user))
python
def cmd(send, msg, args): """Insults a user. Syntax: {command} [nick] """ if not msg: user = choice(get_users(args)) else: user = msg send(gen_insult(user))
[ "def", "cmd", "(", "send", ",", "msg", ",", "args", ")", ":", "if", "not", "msg", ":", "user", "=", "choice", "(", "get_users", "(", "args", ")", ")", "else", ":", "user", "=", "msg", "send", "(", "gen_insult", "(", "user", ")", ")" ]
Insults a user. Syntax: {command} [nick]
[ "Insults", "a", "user", "." ]
aebe07be47141f61d7c180706bddfb707f19b2b5
https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/insult.py#L26-L37
train
Insults a user.
klahnakoski/mo-json
mo_json/stream.py
parse
def parse(json, query_path, expected_vars=NO_VARS): """ INTENDED TO TREAT JSON AS A STREAM; USING MINIMAL MEMORY WHILE IT ITERATES THROUGH THE STRUCTURE. ASSUMING THE JSON IS LARGE, AND HAS A HIGH LEVEL ARRAY STRUCTURE, IT WILL yield EACH OBJECT IN THAT ARRAY. NESTED ARRAYS ARE HANDLED BY REPEATIN...
python
def parse(json, query_path, expected_vars=NO_VARS): """ INTENDED TO TREAT JSON AS A STREAM; USING MINIMAL MEMORY WHILE IT ITERATES THROUGH THE STRUCTURE. ASSUMING THE JSON IS LARGE, AND HAS A HIGH LEVEL ARRAY STRUCTURE, IT WILL yield EACH OBJECT IN THAT ARRAY. NESTED ARRAYS ARE HANDLED BY REPEATIN...
[ "def", "parse", "(", "json", ",", "query_path", ",", "expected_vars", "=", "NO_VARS", ")", ":", "if", "hasattr", "(", "json", ",", "\"read\"", ")", ":", "# ASSUME IT IS A STREAM", "temp", "=", "json", "def", "get_more", "(", ")", ":", "return", "temp", "...
INTENDED TO TREAT JSON AS A STREAM; USING MINIMAL MEMORY WHILE IT ITERATES THROUGH THE STRUCTURE. ASSUMING THE JSON IS LARGE, AND HAS A HIGH LEVEL ARRAY STRUCTURE, IT WILL yield EACH OBJECT IN THAT ARRAY. NESTED ARRAYS ARE HANDLED BY REPEATING THE PARENT PROPERTIES FOR EACH MEMBER OF THE NESTED ARRAY....
[ "INTENDED", "TO", "TREAT", "JSON", "AS", "A", "STREAM", ";", "USING", "MINIMAL", "MEMORY", "WHILE", "IT", "ITERATES", "THROUGH", "THE", "STRUCTURE", ".", "ASSUMING", "THE", "JSON", "IS", "LARGE", "AND", "HAS", "A", "HIGH", "LEVEL", "ARRAY", "STRUCTURE", "I...
0d44d6a7e37f0ea50e583c30c2cbc42488d5de7f
https://github.com/klahnakoski/mo-json/blob/0d44d6a7e37f0ea50e583c30c2cbc42488d5de7f/mo_json/stream.py#L31-L323
train
Parses a JSON string into a list of objects.
klahnakoski/mo-json
mo_json/stream.py
needed
def needed(name, required): """ RETURN SUBSET IF name IN REQUIRED """ return [ relative_field(r, name) if r and startswith_field(r, name) else None for r in required ]
python
def needed(name, required): """ RETURN SUBSET IF name IN REQUIRED """ return [ relative_field(r, name) if r and startswith_field(r, name) else None for r in required ]
[ "def", "needed", "(", "name", ",", "required", ")", ":", "return", "[", "relative_field", "(", "r", ",", "name", ")", "if", "r", "and", "startswith_field", "(", "r", ",", "name", ")", "else", "None", "for", "r", "in", "required", "]" ]
RETURN SUBSET IF name IN REQUIRED
[ "RETURN", "SUBSET", "IF", "name", "IN", "REQUIRED" ]
0d44d6a7e37f0ea50e583c30c2cbc42488d5de7f
https://github.com/klahnakoski/mo-json/blob/0d44d6a7e37f0ea50e583c30c2cbc42488d5de7f/mo_json/stream.py#L326-L333
train
Return a list of the names of the required ones.
klahnakoski/mo-json
mo_json/stream.py
List_usingStream.mark
def mark(self, index): """ KEEP THIS index IN MEMORY UNTIL release() """ if index < self.start: Log.error("Can not go in reverse on stream") if self._mark != -1: Log.error("Not expected") self._mark = index
python
def mark(self, index): """ KEEP THIS index IN MEMORY UNTIL release() """ if index < self.start: Log.error("Can not go in reverse on stream") if self._mark != -1: Log.error("Not expected") self._mark = index
[ "def", "mark", "(", "self", ",", "index", ")", ":", "if", "index", "<", "self", ".", "start", ":", "Log", ".", "error", "(", "\"Can not go in reverse on stream\"", ")", "if", "self", ".", "_mark", "!=", "-", "1", ":", "Log", ".", "error", "(", "\"Not...
KEEP THIS index IN MEMORY UNTIL release()
[ "KEEP", "THIS", "index", "IN", "MEMORY", "UNTIL", "release", "()" ]
0d44d6a7e37f0ea50e583c30c2cbc42488d5de7f
https://github.com/klahnakoski/mo-json/blob/0d44d6a7e37f0ea50e583c30c2cbc42488d5de7f/mo_json/stream.py#L393-L401
train
Mark the current entry in the memory.
toumorokoshi/swagger-schema
swagger_schema/parameter.py
_match_data_to_parameter
def _match_data_to_parameter(cls, data): """ find the appropriate parameter for a parameter field """ in_value = data["in"] for cls in [QueryParameter, HeaderParameter, FormDataParameter, PathParameter, BodyParameter]: if in_value == cls.IN: return cls return None
python
def _match_data_to_parameter(cls, data): """ find the appropriate parameter for a parameter field """ in_value = data["in"] for cls in [QueryParameter, HeaderParameter, FormDataParameter, PathParameter, BodyParameter]: if in_value == cls.IN: return cls return None
[ "def", "_match_data_to_parameter", "(", "cls", ",", "data", ")", ":", "in_value", "=", "data", "[", "\"in\"", "]", "for", "cls", "in", "[", "QueryParameter", ",", "HeaderParameter", ",", "FormDataParameter", ",", "PathParameter", ",", "BodyParameter", "]", ":"...
find the appropriate parameter for a parameter field
[ "find", "the", "appropriate", "parameter", "for", "a", "parameter", "field" ]
24aa13d1f4ac59dfd81af2f5d8d4d1e66a139c97
https://github.com/toumorokoshi/swagger-schema/blob/24aa13d1f4ac59dfd81af2f5d8d4d1e66a139c97/swagger_schema/parameter.py#L49-L56
train
find the appropriate parameter for a given data field
nucypher/constantSorrow
constant_sorrow/__init__.py
constant_or_bytes
def constant_or_bytes(possible_constant): from .constants import _Constant from .constants import _constants_registry_by_hash """ Utility function for getting a constant (that has already been registered) from a serialized constant (ie, bytes of its hash) """ if _Constant in possible_constant.__...
python
def constant_or_bytes(possible_constant): from .constants import _Constant from .constants import _constants_registry_by_hash """ Utility function for getting a constant (that has already been registered) from a serialized constant (ie, bytes of its hash) """ if _Constant in possible_constant.__...
[ "def", "constant_or_bytes", "(", "possible_constant", ")", ":", "from", ".", "constants", "import", "_Constant", "from", ".", "constants", "import", "_constants_registry_by_hash", "if", "_Constant", "in", "possible_constant", ".", "__class__", ".", "__bases__", ":", ...
Utility function for getting a constant (that has already been registered) from a serialized constant (ie, bytes of its hash)
[ "Utility", "function", "for", "getting", "a", "constant", "(", "that", "has", "already", "been", "registered", ")", "from", "a", "serialized", "constant", "(", "ie", "bytes", "of", "its", "hash", ")" ]
546f83d7e8e8f551b57c16bc754a1ea33d73f92e
https://github.com/nucypher/constantSorrow/blob/546f83d7e8e8f551b57c16bc754a1ea33d73f92e/constant_sorrow/__init__.py#L11-L26
train
Utility function for getting a constant from a serialized _Constant object or a bytes object.
tjcsl/cslbot
cslbot/commands/msg.py
cmd
def cmd(send, msg, args): """Sends a message to a channel Syntax: {command} <channel> <message> """ parser = arguments.ArgParser(args['config']) parser.add_argument('channel', action=arguments.ChanParser) parser.add_argument('message', nargs='+') try: cmdargs = parser.parse_args(msg)...
python
def cmd(send, msg, args): """Sends a message to a channel Syntax: {command} <channel> <message> """ parser = arguments.ArgParser(args['config']) parser.add_argument('channel', action=arguments.ChanParser) parser.add_argument('message', nargs='+') try: cmdargs = parser.parse_args(msg)...
[ "def", "cmd", "(", "send", ",", "msg", ",", "args", ")", ":", "parser", "=", "arguments", ".", "ArgParser", "(", "args", "[", "'config'", "]", ")", "parser", ".", "add_argument", "(", "'channel'", ",", "action", "=", "arguments", ".", "ChanParser", ")"...
Sends a message to a channel Syntax: {command} <channel> <message>
[ "Sends", "a", "message", "to", "a", "channel", "Syntax", ":", "{", "command", "}", "<channel", ">", "<message", ">" ]
aebe07be47141f61d7c180706bddfb707f19b2b5
https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/msg.py#L23-L37
train
Sends a message to a channel
tjcsl/cslbot
cslbot/commands/eix.py
cmd
def cmd(send, msg, args): """Runs eix with the given arguments. Syntax: {command} <package> """ if not msg: result = subprocess.run(['eix', '-c'], env={'EIX_LIMIT': '0', 'HOME': os.environ['HOME']}, stdout=subprocess.PIPE, universal_newlines=True) if result.returncode: send...
python
def cmd(send, msg, args): """Runs eix with the given arguments. Syntax: {command} <package> """ if not msg: result = subprocess.run(['eix', '-c'], env={'EIX_LIMIT': '0', 'HOME': os.environ['HOME']}, stdout=subprocess.PIPE, universal_newlines=True) if result.returncode: send...
[ "def", "cmd", "(", "send", ",", "msg", ",", "args", ")", ":", "if", "not", "msg", ":", "result", "=", "subprocess", ".", "run", "(", "[", "'eix'", ",", "'-c'", "]", ",", "env", "=", "{", "'EIX_LIMIT'", ":", "'0'", ",", "'HOME'", ":", "os", ".",...
Runs eix with the given arguments. Syntax: {command} <package>
[ "Runs", "eix", "with", "the", "given", "arguments", "." ]
aebe07be47141f61d7c180706bddfb707f19b2b5
https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/eix.py#L26-L44
train
Runs eix with the given arguments.
ktdreyer/txkoji
txkoji/task_states.py
to_str
def to_str(number): """ Convert a task state ID number to a string. :param int number: task state ID, eg. 1 :returns: state name like eg. "OPEN", or "(unknown)" if we don't know the name of this task state ID number. """ states = globals() for name, value in states.items(): ...
python
def to_str(number): """ Convert a task state ID number to a string. :param int number: task state ID, eg. 1 :returns: state name like eg. "OPEN", or "(unknown)" if we don't know the name of this task state ID number. """ states = globals() for name, value in states.items(): ...
[ "def", "to_str", "(", "number", ")", ":", "states", "=", "globals", "(", ")", "for", "name", ",", "value", "in", "states", ".", "items", "(", ")", ":", "if", "number", "==", "value", "and", "name", ".", "isalpha", "(", ")", "and", "name", ".", "i...
Convert a task state ID number to a string. :param int number: task state ID, eg. 1 :returns: state name like eg. "OPEN", or "(unknown)" if we don't know the name of this task state ID number.
[ "Convert", "a", "task", "state", "ID", "number", "to", "a", "string", "." ]
a7de380f29f745bf11730b27217208f6d4da7733
https://github.com/ktdreyer/txkoji/blob/a7de380f29f745bf11730b27217208f6d4da7733/txkoji/task_states.py#L14-L26
train
Convert a task state ID number to a string.
shapiromatron/bmds
bmds/batch.py
SessionBatch.to_json
def to_json(self, filename, indent=2): """ Return a JSON string of all model inputs and outputs. Parameters ---------- filename : str or file Either the file name (string) or an open file (file-like object) where the data will be saved. indent : i...
python
def to_json(self, filename, indent=2): """ Return a JSON string of all model inputs and outputs. Parameters ---------- filename : str or file Either the file name (string) or an open file (file-like object) where the data will be saved. indent : i...
[ "def", "to_json", "(", "self", ",", "filename", ",", "indent", "=", "2", ")", ":", "d", "=", "self", ".", "to_dicts", "(", ")", "if", "hasattr", "(", "filename", ",", "\"write\"", ")", ":", "json", ".", "dump", "(", "d", ",", "filename", ",", "in...
Return a JSON string of all model inputs and outputs. Parameters ---------- filename : str or file Either the file name (string) or an open file (file-like object) where the data will be saved. indent : int, optional Indentation level for JSON output....
[ "Return", "a", "JSON", "string", "of", "all", "model", "inputs", "and", "outputs", "." ]
395c6ce84ad82876fd9fa4a89a3497fb61616de0
https://github.com/shapiromatron/bmds/blob/395c6ce84ad82876fd9fa4a89a3497fb61616de0/bmds/batch.py#L59-L84
train
Returns a JSON string of all model inputs and outputs.
shapiromatron/bmds
bmds/batch.py
SessionBatch.to_df
def to_df(self, recommended_only=False, include_io=True): """ Return a pandas DataFrame for each model and dataset. Parameters ---------- recommended_only : bool, optional If True, only recommended models for each session are included. If no model is reco...
python
def to_df(self, recommended_only=False, include_io=True): """ Return a pandas DataFrame for each model and dataset. Parameters ---------- recommended_only : bool, optional If True, only recommended models for each session are included. If no model is reco...
[ "def", "to_df", "(", "self", ",", "recommended_only", "=", "False", ",", "include_io", "=", "True", ")", ":", "od", "=", "BMDS", ".", "_df_ordered_dict", "(", "include_io", ")", "[", "session", ".", "_add_to_to_ordered_dict", "(", "od", ",", "i", ",", "r...
Return a pandas DataFrame for each model and dataset. Parameters ---------- recommended_only : bool, optional If True, only recommended models for each session are included. If no model is recommended, then a row with it's ID will be included, but all fields ...
[ "Return", "a", "pandas", "DataFrame", "for", "each", "model", "and", "dataset", "." ]
395c6ce84ad82876fd9fa4a89a3497fb61616de0
https://github.com/shapiromatron/bmds/blob/395c6ce84ad82876fd9fa4a89a3497fb61616de0/bmds/batch.py#L86-L111
train
Returns a pandas DataFrame containing the models and outputs for each session.
shapiromatron/bmds
bmds/batch.py
SessionBatch.to_csv
def to_csv(self, filename, delimiter=",", recommended_only=False, include_io=True): """ Return a CSV for each model and dataset. Parameters ---------- filename : str or file Either the file name (string) or an open file (file-like object) where the data w...
python
def to_csv(self, filename, delimiter=",", recommended_only=False, include_io=True): """ Return a CSV for each model and dataset. Parameters ---------- filename : str or file Either the file name (string) or an open file (file-like object) where the data w...
[ "def", "to_csv", "(", "self", ",", "filename", ",", "delimiter", "=", "\",\"", ",", "recommended_only", "=", "False", ",", "include_io", "=", "True", ")", ":", "df", "=", "self", ".", "to_df", "(", "recommended_only", ",", "include_io", ")", "df", ".", ...
Return a CSV for each model and dataset. Parameters ---------- filename : str or file Either the file name (string) or an open file (file-like object) where the data will be saved. delimiter : str, optional Delimiter used in CSV file between fields. ...
[ "Return", "a", "CSV", "for", "each", "model", "and", "dataset", "." ]
395c6ce84ad82876fd9fa4a89a3497fb61616de0
https://github.com/shapiromatron/bmds/blob/395c6ce84ad82876fd9fa4a89a3497fb61616de0/bmds/batch.py#L113-L138
train
Returns a CSV file for each model and dataset.