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
cfusting/fastgp
fastgp/parametrized/simple_parametrized_terminals.py
SimpleParametrizedPrimitiveTree.from_string
def from_string(cls, string, pset): """Try to convert a string expression into a PrimitiveTree given a PrimitiveSet *pset*. The primitive set needs to contain every primitive present in the expression. :param string: String representation of a Python expression. :param pset: Pri...
python
def from_string(cls, string, pset): """Try to convert a string expression into a PrimitiveTree given a PrimitiveSet *pset*. The primitive set needs to contain every primitive present in the expression. :param string: String representation of a Python expression. :param pset: Pri...
[ "def", "from_string", "(", "cls", ",", "string", ",", "pset", ")", ":", "tokens", "=", "re", ".", "split", "(", "\"[ \\t\\n\\r\\f\\v(),]\"", ",", "string", ")", "expr", "=", "[", "]", "def", "get_parts", "(", "token_string", ")", ":", "parts", "=", "to...
Try to convert a string expression into a PrimitiveTree given a PrimitiveSet *pset*. The primitive set needs to contain every primitive present in the expression. :param string: String representation of a Python expression. :param pset: Primitive set from which primitives are selected. ...
[ "Try", "to", "convert", "a", "string", "expression", "into", "a", "PrimitiveTree", "given", "a", "PrimitiveSet", "*", "pset", "*", ".", "The", "primitive", "set", "needs", "to", "contain", "every", "primitive", "present", "in", "the", "expression", "." ]
6cf3c5d14abedaea064feef6ca434ee806a11756
https://github.com/cfusting/fastgp/blob/6cf3c5d14abedaea064feef6ca434ee806a11756/fastgp/parametrized/simple_parametrized_terminals.py#L40-L82
train
Try to convert a string expression into a PrimitiveTree given a PrimitiveSet.
cfusting/fastgp
fastgp/parametrized/simple_parametrized_terminals.py
RangeOperationTerminal.initialize_parameters
def initialize_parameters(self, variable_type_indices, names, operation=None, begin_range_name=None, end_range_name=None, *args): """ :param variable_type_indices: A sequence of variable type indices where each entry defines the index of a variable type in the desig...
python
def initialize_parameters(self, variable_type_indices, names, operation=None, begin_range_name=None, end_range_name=None, *args): """ :param variable_type_indices: A sequence of variable type indices where each entry defines the index of a variable type in the desig...
[ "def", "initialize_parameters", "(", "self", ",", "variable_type_indices", ",", "names", ",", "operation", "=", "None", ",", "begin_range_name", "=", "None", ",", "end_range_name", "=", "None", ",", "*", "args", ")", ":", "self", ".", "names", "=", "names", ...
:param variable_type_indices: A sequence of variable type indices where each entry defines the index of a variable type in the design matrix. For example a design matrix with two variable types will have indices [j,n] where variable type A spans 0 to j and variable type B spans j + 1 to n. :para...
[ ":", "param", "variable_type_indices", ":", "A", "sequence", "of", "variable", "type", "indices", "where", "each", "entry", "defines", "the", "index", "of", "a", "variable", "type", "in", "the", "design", "matrix", ".", "For", "example", "a", "design", "matr...
6cf3c5d14abedaea064feef6ca434ee806a11756
https://github.com/cfusting/fastgp/blob/6cf3c5d14abedaea064feef6ca434ee806a11756/fastgp/parametrized/simple_parametrized_terminals.py#L128-L170
train
Initializes the parameters of the object based on the provided parameters.
delicb/mvvm
mvvm.py
_Messenger.instance
def instance(cls, interval=5): ''' Returns existing instance of messenger. If one does not exist it will be created and returned. :param int interval: Number of miliseconds that represents interval when messages will be processed. Note that this param...
python
def instance(cls, interval=5): ''' Returns existing instance of messenger. If one does not exist it will be created and returned. :param int interval: Number of miliseconds that represents interval when messages will be processed. Note that this param...
[ "def", "instance", "(", "cls", ",", "interval", "=", "5", ")", ":", "if", "not", "cls", ".", "_instance", ":", "cls", ".", "_instance", "=", "_Messenger", "(", "interval", ")", "return", "cls", ".", "_instance" ]
Returns existing instance of messenger. If one does not exist it will be created and returned. :param int interval: Number of miliseconds that represents interval when messages will be processed. Note that this parameter will be used only the first time when ...
[ "Returns", "existing", "instance", "of", "messenger", ".", "If", "one", "does", "not", "exist", "it", "will", "be", "created", "and", "returned", "." ]
29bf0ab2cc0835b58bed75b2606a9b380c38a272
https://github.com/delicb/mvvm/blob/29bf0ab2cc0835b58bed75b2606a9b380c38a272/mvvm.py#L87-L101
train
Returns existing instance of _Messenger.
delicb/mvvm
mvvm.py
_Messenger.send
def send(self, message, *args, **kwargs): ''' Sends provided message to all listeners. Message is only added to queue and will be processed on next tick. :param Message message: Message to send. ''' self._messages.put((message, args, kwargs), False)
python
def send(self, message, *args, **kwargs): ''' Sends provided message to all listeners. Message is only added to queue and will be processed on next tick. :param Message message: Message to send. ''' self._messages.put((message, args, kwargs), False)
[ "def", "send", "(", "self", ",", "message", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_messages", ".", "put", "(", "(", "message", ",", "args", ",", "kwargs", ")", ",", "False", ")" ]
Sends provided message to all listeners. Message is only added to queue and will be processed on next tick. :param Message message: Message to send.
[ "Sends", "provided", "message", "to", "all", "listeners", ".", "Message", "is", "only", "added", "to", "queue", "and", "will", "be", "processed", "on", "next", "tick", "." ]
29bf0ab2cc0835b58bed75b2606a9b380c38a272
https://github.com/delicb/mvvm/blob/29bf0ab2cc0835b58bed75b2606a9b380c38a272/mvvm.py#L117-L125
train
Sends provided message to all listeners.
delicb/mvvm
mvvm.py
_Messenger.subscribe
def subscribe(self, message, handler): ''' Adds hander for specified message. :param str message: Name of message to subscribe to. :param callable handler: Handler for this message type. Handler must receive single parameter and that parameter will b...
python
def subscribe(self, message, handler): ''' Adds hander for specified message. :param str message: Name of message to subscribe to. :param callable handler: Handler for this message type. Handler must receive single parameter and that parameter will b...
[ "def", "subscribe", "(", "self", ",", "message", ",", "handler", ")", ":", "with", "self", ".", "_lock", ":", "ref", "=", "WeakCallable", "(", "handler", ",", "self", ".", "_on_collect", ")", "self", ".", "_subscribers", "[", "message", "]", ".", "appe...
Adds hander for specified message. :param str message: Name of message to subscribe to. :param callable handler: Handler for this message type. Handler must receive single parameter and that parameter will be instance of sent message.
[ "Adds", "hander", "for", "specified", "message", "." ]
29bf0ab2cc0835b58bed75b2606a9b380c38a272
https://github.com/delicb/mvvm/blob/29bf0ab2cc0835b58bed75b2606a9b380c38a272/mvvm.py#L127-L140
train
Adds a handler to be called when a message is received.
delicb/mvvm
mvvm.py
_Messenger.unsubscribe
def unsubscribe(self, message, handler): ''' Removes handler from message listeners. :param str message: Name of message to unsubscribe handler from. :param callable handler: Callable that should be removed as handler for `message`. ''' with self...
python
def unsubscribe(self, message, handler): ''' Removes handler from message listeners. :param str message: Name of message to unsubscribe handler from. :param callable handler: Callable that should be removed as handler for `message`. ''' with self...
[ "def", "unsubscribe", "(", "self", ",", "message", ",", "handler", ")", ":", "with", "self", ".", "_lock", ":", "self", ".", "_subscribers", "[", "message", "]", ".", "remove", "(", "WeakCallable", "(", "handler", ")", ")" ]
Removes handler from message listeners. :param str message: Name of message to unsubscribe handler from. :param callable handler: Callable that should be removed as handler for `message`.
[ "Removes", "handler", "from", "message", "listeners", "." ]
29bf0ab2cc0835b58bed75b2606a9b380c38a272
https://github.com/delicb/mvvm/blob/29bf0ab2cc0835b58bed75b2606a9b380c38a272/mvvm.py#L143-L154
train
Unsubscribe handler from a message.
delicb/mvvm
mvvm.py
_Messenger._execute
def _execute(self, sender, event_args): ''' Event handler for timer that processes all queued messages. ''' with self._lock: while not self._messages.empty(): msg, args, kwargs = self._messages.get(False) for subscriber in self._subscribers[msg...
python
def _execute(self, sender, event_args): ''' Event handler for timer that processes all queued messages. ''' with self._lock: while not self._messages.empty(): msg, args, kwargs = self._messages.get(False) for subscriber in self._subscribers[msg...
[ "def", "_execute", "(", "self", ",", "sender", ",", "event_args", ")", ":", "with", "self", ".", "_lock", ":", "while", "not", "self", ".", "_messages", ".", "empty", "(", ")", ":", "msg", ",", "args", ",", "kwargs", "=", "self", ".", "_messages", ...
Event handler for timer that processes all queued messages.
[ "Event", "handler", "for", "timer", "that", "processes", "all", "queued", "messages", "." ]
29bf0ab2cc0835b58bed75b2606a9b380c38a272
https://github.com/delicb/mvvm/blob/29bf0ab2cc0835b58bed75b2606a9b380c38a272/mvvm.py#L156-L168
train
Execute all queued messages.
delicb/mvvm
mvvm.py
Signal.emit
def emit(self, *args, **kwargs): ''' Emits this signal. As result, all handlers will be invoked. ''' self._messanger.send(self, *args, **kwargs)
python
def emit(self, *args, **kwargs): ''' Emits this signal. As result, all handlers will be invoked. ''' self._messanger.send(self, *args, **kwargs)
[ "def", "emit", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_messanger", ".", "send", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
Emits this signal. As result, all handlers will be invoked.
[ "Emits", "this", "signal", ".", "As", "result", "all", "handlers", "will", "be", "invoked", "." ]
29bf0ab2cc0835b58bed75b2606a9b380c38a272
https://github.com/delicb/mvvm/blob/29bf0ab2cc0835b58bed75b2606a9b380c38a272/mvvm.py#L204-L208
train
Emits this signal.
delicb/mvvm
mvvm.py
ViewModel.RaisePropertyChanged
def RaisePropertyChanged(self, property_name): ''' Raises event that property value has changed for provided property name. :param str property_name: Name of property whose value has changed. ''' args = PropertyChangedEventArgs(property_name) for handler in s...
python
def RaisePropertyChanged(self, property_name): ''' Raises event that property value has changed for provided property name. :param str property_name: Name of property whose value has changed. ''' args = PropertyChangedEventArgs(property_name) for handler in s...
[ "def", "RaisePropertyChanged", "(", "self", ",", "property_name", ")", ":", "args", "=", "PropertyChangedEventArgs", "(", "property_name", ")", "for", "handler", "in", "self", ".", "property_chaged_handlers", ":", "handler", "(", "self", ",", "args", ")" ]
Raises event that property value has changed for provided property name. :param str property_name: Name of property whose value has changed.
[ "Raises", "event", "that", "property", "value", "has", "changed", "for", "provided", "property", "name", "." ]
29bf0ab2cc0835b58bed75b2606a9b380c38a272
https://github.com/delicb/mvvm/blob/29bf0ab2cc0835b58bed75b2606a9b380c38a272/mvvm.py#L350-L359
train
Raises event that property value has changed for provided property name.
totalgood/pugnlp
src/pugnlp/futil.py
expand_path
def expand_path(path, follow_links=False): """ Expand shell variables ("$VAR"), user directory symbols (~), and return absolute path >>> path0 = '~/whatever.txt' >>> path = expand_path(path0) >>> path.endswith(path0[2:]) True >>> len(path) > len(path0) True >>> '~' in path False ...
python
def expand_path(path, follow_links=False): """ Expand shell variables ("$VAR"), user directory symbols (~), and return absolute path >>> path0 = '~/whatever.txt' >>> path = expand_path(path0) >>> path.endswith(path0[2:]) True >>> len(path) > len(path0) True >>> '~' in path False ...
[ "def", "expand_path", "(", "path", ",", "follow_links", "=", "False", ")", ":", "path", "=", "os", ".", "path", ".", "expandvars", "(", "os", ".", "path", ".", "expanduser", "(", "path", ")", ")", "if", "follow_links", ":", "return", "os", ".", "path...
Expand shell variables ("$VAR"), user directory symbols (~), and return absolute path >>> path0 = '~/whatever.txt' >>> path = expand_path(path0) >>> path.endswith(path0[2:]) True >>> len(path) > len(path0) True >>> '~' in path False >>> path.startswith(os.path.sep) True
[ "Expand", "shell", "variables", "(", "$VAR", ")", "user", "directory", "symbols", "(", "~", ")", "and", "return", "absolute", "path" ]
c43445b14afddfdeadc5f3076675c9e8fc1ee67c
https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/futil.py#L25-L42
train
Expand shell variables user directory symbols and return absolute path
totalgood/pugnlp
src/pugnlp/futil.py
walk_level
def walk_level(path, level=1): """Like os.walk, but takes `level` kwarg that indicates how deep the recursion will go. Notes: TODO: refactor `level`->`depth` References: http://stackoverflow.com/a/234329/623735 Args: path (str): Root path to begin file tree traversal (walk) ...
python
def walk_level(path, level=1): """Like os.walk, but takes `level` kwarg that indicates how deep the recursion will go. Notes: TODO: refactor `level`->`depth` References: http://stackoverflow.com/a/234329/623735 Args: path (str): Root path to begin file tree traversal (walk) ...
[ "def", "walk_level", "(", "path", ",", "level", "=", "1", ")", ":", "if", "level", "is", "None", ":", "level", "=", "float", "(", "'inf'", ")", "path", "=", "expand_path", "(", "path", ")", "if", "os", ".", "path", ".", "isdir", "(", "path", ")",...
Like os.walk, but takes `level` kwarg that indicates how deep the recursion will go. Notes: TODO: refactor `level`->`depth` References: http://stackoverflow.com/a/234329/623735 Args: path (str): Root path to begin file tree traversal (walk) level (int, optional): Dept...
[ "Like", "os", ".", "walk", "but", "takes", "level", "kwarg", "that", "indicates", "how", "deep", "the", "recursion", "will", "go", "." ]
c43445b14afddfdeadc5f3076675c9e8fc1ee67c
https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/futil.py#L45-L79
train
Like os. walk but takes level kwarg that indicates how deep the recursion will go at the root level.
totalgood/pugnlp
src/pugnlp/futil.py
get_type
def get_type(full_path): """Get the type (socket, file, dir, symlink, ...) for the provided path""" status = {'type': []} if os.path.ismount(full_path): status['type'] += ['mount-point'] elif os.path.islink(full_path): status['type'] += ['symlink'] if os.path.isfile(full_path): ...
python
def get_type(full_path): """Get the type (socket, file, dir, symlink, ...) for the provided path""" status = {'type': []} if os.path.ismount(full_path): status['type'] += ['mount-point'] elif os.path.islink(full_path): status['type'] += ['symlink'] if os.path.isfile(full_path): ...
[ "def", "get_type", "(", "full_path", ")", ":", "status", "=", "{", "'type'", ":", "[", "]", "}", "if", "os", ".", "path", ".", "ismount", "(", "full_path", ")", ":", "status", "[", "'type'", "]", "+=", "[", "'mount-point'", "]", "elif", "os", ".", ...
Get the type (socket, file, dir, symlink, ...) for the provided path
[ "Get", "the", "type", "(", "socket", "file", "dir", "symlink", "...", ")", "for", "the", "provided", "path" ]
c43445b14afddfdeadc5f3076675c9e8fc1ee67c
https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/futil.py#L82-L106
train
Get the type of the file or dir for the provided path
totalgood/pugnlp
src/pugnlp/futil.py
get_stat
def get_stat(full_path): """Use python builtin equivalents to unix `stat` command and return dict containing stat data about a file""" status = {} status['size'] = os.path.getsize(full_path) status['accessed'] = datetime.datetime.fromtimestamp(os.path.getatime(full_path)) status['modified'] = dateti...
python
def get_stat(full_path): """Use python builtin equivalents to unix `stat` command and return dict containing stat data about a file""" status = {} status['size'] = os.path.getsize(full_path) status['accessed'] = datetime.datetime.fromtimestamp(os.path.getatime(full_path)) status['modified'] = dateti...
[ "def", "get_stat", "(", "full_path", ")", ":", "status", "=", "{", "}", "status", "[", "'size'", "]", "=", "os", ".", "path", ".", "getsize", "(", "full_path", ")", "status", "[", "'accessed'", "]", "=", "datetime", ".", "datetime", ".", "fromtimestamp...
Use python builtin equivalents to unix `stat` command and return dict containing stat data about a file
[ "Use", "python", "builtin", "equivalents", "to", "unix", "stat", "command", "and", "return", "dict", "containing", "stat", "data", "about", "a", "file" ]
c43445b14afddfdeadc5f3076675c9e8fc1ee67c
https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/futil.py#L109-L119
train
Use python builtin equivalents to unix stat command and return dict containing stat data about a file
totalgood/pugnlp
src/pugnlp/futil.py
path_status
def path_status(path, filename='', status=None, deep=False, verbosity=0): """ Retrieve the access, modify, and create timetags for a path along with its size Arguments: path (str): full path to the file or directory to be statused status (dict): optional existing status to be updated/overwritte...
python
def path_status(path, filename='', status=None, deep=False, verbosity=0): """ Retrieve the access, modify, and create timetags for a path along with its size Arguments: path (str): full path to the file or directory to be statused status (dict): optional existing status to be updated/overwritte...
[ "def", "path_status", "(", "path", ",", "filename", "=", "''", ",", "status", "=", "None", ",", "deep", "=", "False", ",", "verbosity", "=", "0", ")", ":", "status", "=", "{", "}", "if", "status", "is", "None", "else", "status", "path", "=", "expan...
Retrieve the access, modify, and create timetags for a path along with its size Arguments: path (str): full path to the file or directory to be statused status (dict): optional existing status to be updated/overwritten with new status values try_open (bool): whether to try to open the file ...
[ "Retrieve", "the", "access", "modify", "and", "create", "timetags", "for", "a", "path", "along", "with", "its", "size" ]
c43445b14afddfdeadc5f3076675c9e8fc1ee67c
https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/futil.py#L122-L162
train
Retrieve the access modify and create timetags for a path along with its size
totalgood/pugnlp
src/pugnlp/futil.py
generate_files
def generate_files(path='', ext='', level=None, dirs=False, files=True, verbosity=0): """ Recursively generate files (and thier stats) in the indicated directory Filter by the indicated file name extension (ext) Args: path (str): Root/base path to search. ext (str or list of str): File n...
python
def generate_files(path='', ext='', level=None, dirs=False, files=True, verbosity=0): """ Recursively generate files (and thier stats) in the indicated directory Filter by the indicated file name extension (ext) Args: path (str): Root/base path to search. ext (str or list of str): File n...
[ "def", "generate_files", "(", "path", "=", "''", ",", "ext", "=", "''", ",", "level", "=", "None", ",", "dirs", "=", "False", ",", "files", "=", "True", ",", "verbosity", "=", "0", ")", ":", "path", "=", "expand_path", "(", "path", "or", "'.'", "...
Recursively generate files (and thier stats) in the indicated directory Filter by the indicated file name extension (ext) Args: path (str): Root/base path to search. ext (str or list of str): File name extension(s). Only file paths that ".endswith()" this string will be returned ...
[ "Recursively", "generate", "files", "(", "and", "thier", "stats", ")", "in", "the", "indicated", "directory" ]
c43445b14afddfdeadc5f3076675c9e8fc1ee67c
https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/futil.py#L225-L313
train
Generate files in the specified directory tree.
totalgood/pugnlp
src/pugnlp/futil.py
touch
def touch(filepath, times=None, mkdir=False): """ Update the modify (modify) and change (ctime) timestamps of a file, create if necessary >>> from pugnlp.constants import DATA_PATH >>> filepath = os.path.join(DATA_PATH, 'tmpfilefortouch.txt') >>> touch(filepath).endswith('tmpfilefortouch.txt') True...
python
def touch(filepath, times=None, mkdir=False): """ Update the modify (modify) and change (ctime) timestamps of a file, create if necessary >>> from pugnlp.constants import DATA_PATH >>> filepath = os.path.join(DATA_PATH, 'tmpfilefortouch.txt') >>> touch(filepath).endswith('tmpfilefortouch.txt') True...
[ "def", "touch", "(", "filepath", ",", "times", "=", "None", ",", "mkdir", "=", "False", ")", ":", "filepath", "=", "expand_path", "(", "filepath", ")", "if", "mkdir", ":", "mkdir_p", "(", "os", ".", "path", ".", "dirname", "(", "filepath", ")", ")", ...
Update the modify (modify) and change (ctime) timestamps of a file, create if necessary >>> from pugnlp.constants import DATA_PATH >>> filepath = os.path.join(DATA_PATH, 'tmpfilefortouch.txt') >>> touch(filepath).endswith('tmpfilefortouch.txt') True >>> os.path.isfile(filepath) True >>> os....
[ "Update", "the", "modify", "(", "modify", ")", "and", "change", "(", "ctime", ")", "timestamps", "of", "a", "file", "create", "if", "necessary" ]
c43445b14afddfdeadc5f3076675c9e8fc1ee67c
https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/futil.py#L347-L364
train
Update the modify and change timestamps of a file
totalgood/pugnlp
src/pugnlp/futil.py
touch_p
def touch_p(filepath, times=None, mkdir=True): """ mkdir_p(filepath) then touch(filepath) >>> from pugnlp.constants import DATA_PATH >>> filepath = os.path.join(DATA_PATH, 'tmpdirfortouch', 'tmpfilefortouch.txt') >>> touch_p(filepath).endswith(os.path.join('tmpdirfortouch', 'tmpfilefortouch.txt')) ...
python
def touch_p(filepath, times=None, mkdir=True): """ mkdir_p(filepath) then touch(filepath) >>> from pugnlp.constants import DATA_PATH >>> filepath = os.path.join(DATA_PATH, 'tmpdirfortouch', 'tmpfilefortouch.txt') >>> touch_p(filepath).endswith(os.path.join('tmpdirfortouch', 'tmpfilefortouch.txt')) ...
[ "def", "touch_p", "(", "filepath", ",", "times", "=", "None", ",", "mkdir", "=", "True", ")", ":", "return", "touch", "(", "filepath", "=", "filepath", ",", "times", "=", "times", ",", "mkdir", "=", "mkdir", ")" ]
mkdir_p(filepath) then touch(filepath) >>> from pugnlp.constants import DATA_PATH >>> filepath = os.path.join(DATA_PATH, 'tmpdirfortouch', 'tmpfilefortouch.txt') >>> touch_p(filepath).endswith(os.path.join('tmpdirfortouch', 'tmpfilefortouch.txt')) True >>> os.path.isfile(filepath) True >>> ...
[ "mkdir_p", "(", "filepath", ")", "then", "touch", "(", "filepath", ")" ]
c43445b14afddfdeadc5f3076675c9e8fc1ee67c
https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/futil.py#L367-L379
train
touch a file
totalgood/pugnlp
src/pugnlp/futil.py
sudo_yield_file_lines
def sudo_yield_file_lines(file_path='/etc/NetworkManager/system-connections/*'): r"""Cat a file iterating/yielding one line at a time, shell will execute: `sudo cat $file_path` so if your shell doesn't have sudo or cat, no joy Input: file_path(str): glob stars are fine >> for line ...
python
def sudo_yield_file_lines(file_path='/etc/NetworkManager/system-connections/*'): r"""Cat a file iterating/yielding one line at a time, shell will execute: `sudo cat $file_path` so if your shell doesn't have sudo or cat, no joy Input: file_path(str): glob stars are fine >> for line ...
[ "def", "sudo_yield_file_lines", "(", "file_path", "=", "'/etc/NetworkManager/system-connections/*'", ")", ":", "# substitute your Windoze/DOS/PowerlessShell command here:", "sudo_cat_cmd", "=", "'sudo cat {}'", ".", "format", "(", "file_path", ")", "process", "=", "subprocess",...
r"""Cat a file iterating/yielding one line at a time, shell will execute: `sudo cat $file_path` so if your shell doesn't have sudo or cat, no joy Input: file_path(str): glob stars are fine >> for line in sudo_yield_file_lines('/etc/NetworkManager/system-connections/*')
[ "r", "Cat", "a", "file", "iterating", "/", "yielding", "one", "line", "at", "a", "time" ]
c43445b14afddfdeadc5f3076675c9e8fc1ee67c
https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/futil.py#L382-L399
train
Yields lines from a file in a node s network - connection tree
totalgood/pugnlp
src/pugnlp/futil.py
read_json
def read_json(file_or_path): """Parse json contents of string or file object or file path and return python nested dict/lists""" try: with (open(file_or_path, 'r') if isinstance(file_or_path, (str, bytes)) else file_or_path) as f: obj = json.load(f) except IOError: obj = json.loa...
python
def read_json(file_or_path): """Parse json contents of string or file object or file path and return python nested dict/lists""" try: with (open(file_or_path, 'r') if isinstance(file_or_path, (str, bytes)) else file_or_path) as f: obj = json.load(f) except IOError: obj = json.loa...
[ "def", "read_json", "(", "file_or_path", ")", ":", "try", ":", "with", "(", "open", "(", "file_or_path", ",", "'r'", ")", "if", "isinstance", "(", "file_or_path", ",", "(", "str", ",", "bytes", ")", ")", "else", "file_or_path", ")", "as", "f", ":", "...
Parse json contents of string or file object or file path and return python nested dict/lists
[ "Parse", "json", "contents", "of", "string", "or", "file", "object", "or", "file", "path", "and", "return", "python", "nested", "dict", "/", "lists" ]
c43445b14afddfdeadc5f3076675c9e8fc1ee67c
https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/futil.py#L443-L450
train
Parse json contents of string or file object or file path and return python nested dict / lists
DarkEnergySurvey/ugali
ugali/preprocess/maglims.py
inFootprint
def inFootprint(footprint,ra,dec): """ Check if set of ra,dec combinations are in footprint. Careful, input files must be in celestial coordinates. filename : Either healpix map or mangle polygon file ra,dec : Celestial coordinates Returns: inside : boolean array of coordinates in ...
python
def inFootprint(footprint,ra,dec): """ Check if set of ra,dec combinations are in footprint. Careful, input files must be in celestial coordinates. filename : Either healpix map or mangle polygon file ra,dec : Celestial coordinates Returns: inside : boolean array of coordinates in ...
[ "def", "inFootprint", "(", "footprint", ",", "ra", ",", "dec", ")", ":", "if", "footprint", "is", "None", ":", "return", "np", ".", "ones", "(", "len", "(", "ra", ")", ",", "dtype", "=", "bool", ")", "try", ":", "if", "isinstance", "(", "footprint"...
Check if set of ra,dec combinations are in footprint. Careful, input files must be in celestial coordinates. filename : Either healpix map or mangle polygon file ra,dec : Celestial coordinates Returns: inside : boolean array of coordinates in footprint
[ "Check", "if", "set", "of", "ra", "dec", "combinations", "are", "in", "footprint", ".", "Careful", "input", "files", "must", "be", "in", "celestial", "coordinates", ".", "filename", ":", "Either", "healpix", "map", "or", "mangle", "polygon", "file", "ra", ...
21e890b4117fc810afb6fb058e8055d564f03382
https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/preprocess/maglims.py#L185-L211
train
Check if set of ra dec combinations are in footprint.
DarkEnergySurvey/ugali
ugali/preprocess/maglims.py
split
def split(config,dirname='split',force=False): """ Take a pre-existing maglim map and divide it into chunks consistent with the catalog pixels. """ config = Config(config) filenames = config.getFilenames() #healpix = filenames['pix'].compressed() # Check that things are ok basedir,basename...
python
def split(config,dirname='split',force=False): """ Take a pre-existing maglim map and divide it into chunks consistent with the catalog pixels. """ config = Config(config) filenames = config.getFilenames() #healpix = filenames['pix'].compressed() # Check that things are ok basedir,basename...
[ "def", "split", "(", "config", ",", "dirname", "=", "'split'", ",", "force", "=", "False", ")", ":", "config", "=", "Config", "(", "config", ")", "filenames", "=", "config", ".", "getFilenames", "(", ")", "#healpix = filenames['pix'].compressed()", "# Check th...
Take a pre-existing maglim map and divide it into chunks consistent with the catalog pixels.
[ "Take", "a", "pre", "-", "existing", "maglim", "map", "and", "divide", "it", "into", "chunks", "consistent", "with", "the", "catalog", "pixels", "." ]
21e890b4117fc810afb6fb058e8055d564f03382
https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/preprocess/maglims.py#L266-L332
train
Split a pre - existing maglim map into chunks consistent with the catalog pixels.
DarkEnergySurvey/ugali
ugali/preprocess/maglims.py
Maglims.run
def run(self,field=None,simple=False,force=False): """ Loop through pixels containing catalog objects and calculate the magnitude limit. This gets a bit convoluted due to all the different pixel resolutions... """ if field is None: fields = [1,2] else: ...
python
def run(self,field=None,simple=False,force=False): """ Loop through pixels containing catalog objects and calculate the magnitude limit. This gets a bit convoluted due to all the different pixel resolutions... """ if field is None: fields = [1,2] else: ...
[ "def", "run", "(", "self", ",", "field", "=", "None", ",", "simple", "=", "False", ",", "force", "=", "False", ")", ":", "if", "field", "is", "None", ":", "fields", "=", "[", "1", ",", "2", "]", "else", ":", "fields", "=", "[", "field", "]", ...
Loop through pixels containing catalog objects and calculate the magnitude limit. This gets a bit convoluted due to all the different pixel resolutions...
[ "Loop", "through", "pixels", "containing", "catalog", "objects", "and", "calculate", "the", "magnitude", "limit", ".", "This", "gets", "a", "bit", "convoluted", "due", "to", "all", "the", "different", "pixel", "resolutions", "..." ]
21e890b4117fc810afb6fb058e8055d564f03382
https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/preprocess/maglims.py#L52-L75
train
This method runs the actual calculation of the image and stores the result in a file.
consbio/ncdjango
ncdjango/interfaces/arcgis/views.py
ArcGISMapServerMixin.get_variable_set
def get_variable_set(self, variable_set, data): """Filters the given variable set based on request parameters""" if data.get('dynamic_layers'): variable_set = [] # TODO elif data.get('layers'): op, layer_ids = data['layers'].split(':', 1) op = op.lower() ...
python
def get_variable_set(self, variable_set, data): """Filters the given variable set based on request parameters""" if data.get('dynamic_layers'): variable_set = [] # TODO elif data.get('layers'): op, layer_ids = data['layers'].split(':', 1) op = op.lower() ...
[ "def", "get_variable_set", "(", "self", ",", "variable_set", ",", "data", ")", ":", "if", "data", ".", "get", "(", "'dynamic_layers'", ")", ":", "variable_set", "=", "[", "]", "# TODO", "elif", "data", ".", "get", "(", "'layers'", ")", ":", "op", ",", ...
Filters the given variable set based on request parameters
[ "Filters", "the", "given", "variable", "set", "based", "on", "request", "parameters" ]
f807bfd1e4083ab29fbc3c4d4418be108383a710
https://github.com/consbio/ncdjango/blob/f807bfd1e4083ab29fbc3c4d4418be108383a710/ncdjango/interfaces/arcgis/views.py#L207-L224
train
Filters the given variable set based on the request parameters.
consbio/ncdjango
ncdjango/interfaces/arcgis/views.py
ArcGISMapServerMixin.apply_time_to_configurations
def apply_time_to_configurations(self, configurations, data): """Applies the correct time index to configurations""" time_value = None if data.get('time'): time_value = data['time'] # Only single time values are supported. For extents, just grab the first value ...
python
def apply_time_to_configurations(self, configurations, data): """Applies the correct time index to configurations""" time_value = None if data.get('time'): time_value = data['time'] # Only single time values are supported. For extents, just grab the first value ...
[ "def", "apply_time_to_configurations", "(", "self", ",", "configurations", ",", "data", ")", ":", "time_value", "=", "None", "if", "data", ".", "get", "(", "'time'", ")", ":", "time_value", "=", "data", "[", "'time'", "]", "# Only single time values are supporte...
Applies the correct time index to configurations
[ "Applies", "the", "correct", "time", "index", "to", "configurations" ]
f807bfd1e4083ab29fbc3c4d4418be108383a710
https://github.com/consbio/ncdjango/blob/f807bfd1e4083ab29fbc3c4d4418be108383a710/ncdjango/interfaces/arcgis/views.py#L226-L241
train
Applies the correct time index to configurations
consbio/ncdjango
ncdjango/interfaces/arcgis/views.py
GetImageView._get_form_defaults
def _get_form_defaults(self): """Returns default values for the get image form""" return { 'response_format': 'html', 'bbox': self.service.full_extent, 'size': '400,400', 'dpi': 200, 'image_projection': pyproj.Proj(str(self.service.projection)...
python
def _get_form_defaults(self): """Returns default values for the get image form""" return { 'response_format': 'html', 'bbox': self.service.full_extent, 'size': '400,400', 'dpi': 200, 'image_projection': pyproj.Proj(str(self.service.projection)...
[ "def", "_get_form_defaults", "(", "self", ")", ":", "return", "{", "'response_format'", ":", "'html'", ",", "'bbox'", ":", "self", ".", "service", ".", "full_extent", ",", "'size'", ":", "'400,400'", ",", "'dpi'", ":", "200", ",", "'image_projection'", ":", ...
Returns default values for the get image form
[ "Returns", "default", "values", "for", "the", "get", "image", "form" ]
f807bfd1e4083ab29fbc3c4d4418be108383a710
https://github.com/consbio/ncdjango/blob/f807bfd1e4083ab29fbc3c4d4418be108383a710/ncdjango/interfaces/arcgis/views.py#L247-L259
train
Returns default values for the get image form
consbio/ncdjango
ncdjango/interfaces/arcgis/views.py
GetImageView.format_image
def format_image(self, image, image_format, **kwargs): """Returns an image in the request format""" image_format = image_format.lower() accept = self.request.META['HTTP_ACCEPT'].split(',') if FORCE_WEBP and 'image/webp' in accept: image_format = 'webp' elif image_fo...
python
def format_image(self, image, image_format, **kwargs): """Returns an image in the request format""" image_format = image_format.lower() accept = self.request.META['HTTP_ACCEPT'].split(',') if FORCE_WEBP and 'image/webp' in accept: image_format = 'webp' elif image_fo...
[ "def", "format_image", "(", "self", ",", "image", ",", "image_format", ",", "*", "*", "kwargs", ")", ":", "image_format", "=", "image_format", ".", "lower", "(", ")", "accept", "=", "self", ".", "request", ".", "META", "[", "'HTTP_ACCEPT'", "]", ".", "...
Returns an image in the request format
[ "Returns", "an", "image", "in", "the", "request", "format" ]
f807bfd1e4083ab29fbc3c4d4418be108383a710
https://github.com/consbio/ncdjango/blob/f807bfd1e4083ab29fbc3c4d4418be108383a710/ncdjango/interfaces/arcgis/views.py#L264-L282
train
Returns an image in the request format
consbio/ncdjango
ncdjango/interfaces/arcgis/views.py
GetImageView.get_render_configurations
def get_render_configurations(self, request, **kwargs): """Render image interface""" data = self.process_form_data(self._get_form_defaults(), kwargs) variable_set = self.get_variable_set(self.service.variable_set.order_by('index'), data) base_config = ImageConfiguration( ex...
python
def get_render_configurations(self, request, **kwargs): """Render image interface""" data = self.process_form_data(self._get_form_defaults(), kwargs) variable_set = self.get_variable_set(self.service.variable_set.order_by('index'), data) base_config = ImageConfiguration( ex...
[ "def", "get_render_configurations", "(", "self", ",", "request", ",", "*", "*", "kwargs", ")", ":", "data", "=", "self", ".", "process_form_data", "(", "self", ".", "_get_form_defaults", "(", ")", ",", "kwargs", ")", "variable_set", "=", "self", ".", "get_...
Render image interface
[ "Render", "image", "interface" ]
f807bfd1e4083ab29fbc3c4d4418be108383a710
https://github.com/consbio/ncdjango/blob/f807bfd1e4083ab29fbc3c4d4418be108383a710/ncdjango/interfaces/arcgis/views.py#L284-L297
train
Render image interface
consbio/ncdjango
ncdjango/interfaces/arcgis/views.py
IdentifyView._get_form_defaults
def _get_form_defaults(self): """Returns default values for the identify form""" return { 'response_format': 'html', 'geometry_type': 'esriGeometryPoint', 'projection': pyproj.Proj(str(self.service.projection)), 'return_geometry': True, 'maxim...
python
def _get_form_defaults(self): """Returns default values for the identify form""" return { 'response_format': 'html', 'geometry_type': 'esriGeometryPoint', 'projection': pyproj.Proj(str(self.service.projection)), 'return_geometry': True, 'maxim...
[ "def", "_get_form_defaults", "(", "self", ")", ":", "return", "{", "'response_format'", ":", "'html'", ",", "'geometry_type'", ":", "'esriGeometryPoint'", ",", "'projection'", ":", "pyproj", ".", "Proj", "(", "str", "(", "self", ".", "service", ".", "projectio...
Returns default values for the identify form
[ "Returns", "default", "values", "for", "the", "identify", "form" ]
f807bfd1e4083ab29fbc3c4d4418be108383a710
https://github.com/consbio/ncdjango/blob/f807bfd1e4083ab29fbc3c4d4418be108383a710/ncdjango/interfaces/arcgis/views.py#L303-L315
train
Returns default values for the identify form
juju/theblues
theblues/terms.py
Terms.get_terms
def get_terms(self, name, revision=None): """ Retrieve a specific term and condition. @param name of the terms. @param revision of the terms, if none provided it will return the latest. @return The list of terms. @raise ServerError """ url = '{}ter...
python
def get_terms(self, name, revision=None): """ Retrieve a specific term and condition. @param name of the terms. @param revision of the terms, if none provided it will return the latest. @return The list of terms. @raise ServerError """ url = '{}ter...
[ "def", "get_terms", "(", "self", ",", "name", ",", "revision", "=", "None", ")", ":", "url", "=", "'{}terms/{}'", ".", "format", "(", "self", ".", "url", ",", "name", ")", "if", "revision", ":", "url", "=", "'{}?revision={}'", ".", "format", "(", "ur...
Retrieve a specific term and condition. @param name of the terms. @param revision of the terms, if none provided it will return the latest. @return The list of terms. @raise ServerError
[ "Retrieve", "a", "specific", "term", "and", "condition", "." ]
f4431f29e43d04fc32f38f4f86cea45cd4e6ae98
https://github.com/juju/theblues/blob/f4431f29e43d04fc32f38f4f86cea45cd4e6ae98/theblues/terms.py#L38-L67
train
Retrieve a specific term and condition.
consbio/ncdjango
ncdjango/views.py
NetCdfDatasetMixin.open_dataset
def open_dataset(self, service): """Opens and returns the NetCDF dataset associated with a service, or returns a previously-opened dataset""" if not self.dataset: path = os.path.join(SERVICE_DATA_ROOT, service.data_path) self.dataset = netCDF4.Dataset(path, 'r') return s...
python
def open_dataset(self, service): """Opens and returns the NetCDF dataset associated with a service, or returns a previously-opened dataset""" if not self.dataset: path = os.path.join(SERVICE_DATA_ROOT, service.data_path) self.dataset = netCDF4.Dataset(path, 'r') return s...
[ "def", "open_dataset", "(", "self", ",", "service", ")", ":", "if", "not", "self", ".", "dataset", ":", "path", "=", "os", ".", "path", ".", "join", "(", "SERVICE_DATA_ROOT", ",", "service", ".", "data_path", ")", "self", ".", "dataset", "=", "netCDF4"...
Opens and returns the NetCDF dataset associated with a service, or returns a previously-opened dataset
[ "Opens", "and", "returns", "the", "NetCDF", "dataset", "associated", "with", "a", "service", "or", "returns", "a", "previously", "-", "opened", "dataset" ]
f807bfd1e4083ab29fbc3c4d4418be108383a710
https://github.com/consbio/ncdjango/blob/f807bfd1e4083ab29fbc3c4d4418be108383a710/ncdjango/views.py#L80-L86
train
Opens and returns the NetCDF dataset associated with a service or returns a previously - opened dataset
consbio/ncdjango
ncdjango/views.py
NetCdfDatasetMixin.get_grid_spatial_dimensions
def get_grid_spatial_dimensions(self, variable): """Returns (width, height) for the given variable""" data = self.open_dataset(self.service).variables[variable.variable] dimensions = list(data.dimensions) return data.shape[dimensions.index(variable.x_dimension)], data.shape[dimensions.i...
python
def get_grid_spatial_dimensions(self, variable): """Returns (width, height) for the given variable""" data = self.open_dataset(self.service).variables[variable.variable] dimensions = list(data.dimensions) return data.shape[dimensions.index(variable.x_dimension)], data.shape[dimensions.i...
[ "def", "get_grid_spatial_dimensions", "(", "self", ",", "variable", ")", ":", "data", "=", "self", ".", "open_dataset", "(", "self", ".", "service", ")", ".", "variables", "[", "variable", ".", "variable", "]", "dimensions", "=", "list", "(", "data", ".", ...
Returns (width, height) for the given variable
[ "Returns", "(", "width", "height", ")", "for", "the", "given", "variable" ]
f807bfd1e4083ab29fbc3c4d4418be108383a710
https://github.com/consbio/ncdjango/blob/f807bfd1e4083ab29fbc3c4d4418be108383a710/ncdjango/views.py#L128-L133
train
Returns the width and height for the given variable
consbio/ncdjango
ncdjango/views.py
GetImageViewBase._normalize_bbox
def _normalize_bbox(self, bbox, size): """Returns this bbox normalized to match the ratio of the given size.""" bbox_ratio = float(bbox.width) / float(bbox.height) size_ratio = float(size[0]) / float(size[1]) if round(size_ratio, 4) == round(bbox_ratio, 4): return bbox ...
python
def _normalize_bbox(self, bbox, size): """Returns this bbox normalized to match the ratio of the given size.""" bbox_ratio = float(bbox.width) / float(bbox.height) size_ratio = float(size[0]) / float(size[1]) if round(size_ratio, 4) == round(bbox_ratio, 4): return bbox ...
[ "def", "_normalize_bbox", "(", "self", ",", "bbox", ",", "size", ")", ":", "bbox_ratio", "=", "float", "(", "bbox", ".", "width", ")", "/", "float", "(", "bbox", ".", "height", ")", "size_ratio", "=", "float", "(", "size", "[", "0", "]", ")", "/", ...
Returns this bbox normalized to match the ratio of the given size.
[ "Returns", "this", "bbox", "normalized", "to", "match", "the", "ratio", "of", "the", "given", "size", "." ]
f807bfd1e4083ab29fbc3c4d4418be108383a710
https://github.com/consbio/ncdjango/blob/f807bfd1e4083ab29fbc3c4d4418be108383a710/ncdjango/views.py#L148-L162
train
Returns this bbox normalized to match the ratio of the given size.
consbio/ncdjango
ncdjango/views.py
GetImageViewBase.format_image
def format_image(self, image, image_format, **kwargs): """Returns an image in the request format""" if image_format in ('png', 'jpg', 'jpeg', 'gif', 'bmp', 'webp'): if image_format != 'webp' and FORCE_WEBP: # Always return WebP when supported by the browser a...
python
def format_image(self, image, image_format, **kwargs): """Returns an image in the request format""" if image_format in ('png', 'jpg', 'jpeg', 'gif', 'bmp', 'webp'): if image_format != 'webp' and FORCE_WEBP: # Always return WebP when supported by the browser a...
[ "def", "format_image", "(", "self", ",", "image", ",", "image_format", ",", "*", "*", "kwargs", ")", ":", "if", "image_format", "in", "(", "'png'", ",", "'jpg'", ",", "'jpeg'", ",", "'gif'", ",", "'bmp'", ",", "'webp'", ")", ":", "if", "image_format", ...
Returns an image in the request format
[ "Returns", "an", "image", "in", "the", "request", "format" ]
f807bfd1e4083ab29fbc3c4d4418be108383a710
https://github.com/consbio/ncdjango/blob/f807bfd1e4083ab29fbc3c4d4418be108383a710/ncdjango/views.py#L174-L196
train
Returns an image in the request format
consbio/ncdjango
ncdjango/views.py
GetImageViewBase.create_response
def create_response(self, request, image, content_type): """Returns a response object for the given image. Can be overridden to return different responses.""" return HttpResponse(content=image, content_type=content_type)
python
def create_response(self, request, image, content_type): """Returns a response object for the given image. Can be overridden to return different responses.""" return HttpResponse(content=image, content_type=content_type)
[ "def", "create_response", "(", "self", ",", "request", ",", "image", ",", "content_type", ")", ":", "return", "HttpResponse", "(", "content", "=", "image", ",", "content_type", "=", "content_type", ")" ]
Returns a response object for the given image. Can be overridden to return different responses.
[ "Returns", "a", "response", "object", "for", "the", "given", "image", ".", "Can", "be", "overridden", "to", "return", "different", "responses", "." ]
f807bfd1e4083ab29fbc3c4d4418be108383a710
https://github.com/consbio/ncdjango/blob/f807bfd1e4083ab29fbc3c4d4418be108383a710/ncdjango/views.py#L198-L201
train
Returns a response object for the given image.
consbio/ncdjango
ncdjango/views.py
IdentifyViewBase.create_response
def create_response(self, request, content, content_type): """Returns a response object for the request. Can be overridden to return different responses.""" return HttpResponse(content=content, content_type=content_type)
python
def create_response(self, request, content, content_type): """Returns a response object for the request. Can be overridden to return different responses.""" return HttpResponse(content=content, content_type=content_type)
[ "def", "create_response", "(", "self", ",", "request", ",", "content", ",", "content_type", ")", ":", "return", "HttpResponse", "(", "content", "=", "content", ",", "content_type", "=", "content_type", ")" ]
Returns a response object for the request. Can be overridden to return different responses.
[ "Returns", "a", "response", "object", "for", "the", "request", ".", "Can", "be", "overridden", "to", "return", "different", "responses", "." ]
f807bfd1e4083ab29fbc3c4d4418be108383a710
https://github.com/consbio/ncdjango/blob/f807bfd1e4083ab29fbc3c4d4418be108383a710/ncdjango/views.py#L324-L327
train
Returns a response object for the request. Can be overridden to return different responses.
consbio/ncdjango
ncdjango/views.py
TemporaryFileUploadViewBase.process_temporary_file
def process_temporary_file(self, tmp_file): """Truncates the filename if necessary, saves the model, and returns a response""" #Truncate filename if necessary if len(tmp_file.filename) > 100: base_filename = tmp_file.filename[:tmp_file.filename.rfind(".")] tmp_file.filen...
python
def process_temporary_file(self, tmp_file): """Truncates the filename if necessary, saves the model, and returns a response""" #Truncate filename if necessary if len(tmp_file.filename) > 100: base_filename = tmp_file.filename[:tmp_file.filename.rfind(".")] tmp_file.filen...
[ "def", "process_temporary_file", "(", "self", ",", "tmp_file", ")", ":", "#Truncate filename if necessary", "if", "len", "(", "tmp_file", ".", "filename", ")", ">", "100", ":", "base_filename", "=", "tmp_file", ".", "filename", "[", ":", "tmp_file", ".", "file...
Truncates the filename if necessary, saves the model, and returns a response
[ "Truncates", "the", "filename", "if", "necessary", "saves", "the", "model", "and", "returns", "a", "response" ]
f807bfd1e4083ab29fbc3c4d4418be108383a710
https://github.com/consbio/ncdjango/blob/f807bfd1e4083ab29fbc3c4d4418be108383a710/ncdjango/views.py#L438-L455
train
Truncates the filename if necessary saves the model and returns a response
DarkEnergySurvey/ugali
ugali/analysis/search.py
CandidateSearch.createLabels2D
def createLabels2D(self): """ 2D labeling at zmax """ logger.debug(" Creating 2D labels...") self.zmax = np.argmax(self.values,axis=1) self.vmax = self.values[np.arange(len(self.pixels),dtype=int),self.zmax] kwargs=dict(pixels=self.pixels,values=self.vmax,nside=self.nside, ...
python
def createLabels2D(self): """ 2D labeling at zmax """ logger.debug(" Creating 2D labels...") self.zmax = np.argmax(self.values,axis=1) self.vmax = self.values[np.arange(len(self.pixels),dtype=int),self.zmax] kwargs=dict(pixels=self.pixels,values=self.vmax,nside=self.nside, ...
[ "def", "createLabels2D", "(", "self", ")", ":", "logger", ".", "debug", "(", "\" Creating 2D labels...\"", ")", "self", ".", "zmax", "=", "np", ".", "argmax", "(", "self", ".", "values", ",", "axis", "=", "1", ")", "self", ".", "vmax", "=", "self", ...
2D labeling at zmax
[ "2D", "labeling", "at", "zmax" ]
21e890b4117fc810afb6fb058e8055d564f03382
https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/analysis/search.py#L73-L84
train
Create 2D labels at zmax
DarkEnergySurvey/ugali
ugali/analysis/search.py
CandidateSearch.labelHealpix
def labelHealpix(pixels, values, nside, threshold=0, xsize=1000): """ Label contiguous regions of a (sparse) HEALPix map. Works by mapping HEALPix array to a Mollweide projection and applying scipy.ndimage.label Assumes non-nested HEALPix map. Parameters: ...
python
def labelHealpix(pixels, values, nside, threshold=0, xsize=1000): """ Label contiguous regions of a (sparse) HEALPix map. Works by mapping HEALPix array to a Mollweide projection and applying scipy.ndimage.label Assumes non-nested HEALPix map. Parameters: ...
[ "def", "labelHealpix", "(", "pixels", ",", "values", ",", "nside", ",", "threshold", "=", "0", ",", "xsize", "=", "1000", ")", ":", "proj", "=", "healpy", ".", "projector", ".", "MollweideProj", "(", "xsize", "=", "xsize", ")", "vec", "=", "healpy", ...
Label contiguous regions of a (sparse) HEALPix map. Works by mapping HEALPix array to a Mollweide projection and applying scipy.ndimage.label Assumes non-nested HEALPix map. Parameters: pixels : Pixel values associated to (sparse) HEALPix array values : (Spa...
[ "Label", "contiguous", "regions", "of", "a", "(", "sparse", ")", "HEALPix", "map", ".", "Works", "by", "mapping", "HEALPix", "array", "to", "a", "Mollweide", "projection", "and", "applying", "scipy", ".", "ndimage", ".", "label", "Assumes", "non", "-", "ne...
21e890b4117fc810afb6fb058e8055d564f03382
https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/analysis/search.py#L146-L198
train
Label contiguous regions of a HEALPix array.
DarkEnergySurvey/ugali
ugali/analysis/search.py
CandidateSearch.findObjects
def findObjects(pixels, values, nside, zvalues, rev, good): """ Characterize labelled candidates in a multi-dimensional HEALPix map. Parameters: values : (Sparse) HEALPix array of data values nside : HEALPix dimensionality pixels : Pixel values associated ...
python
def findObjects(pixels, values, nside, zvalues, rev, good): """ Characterize labelled candidates in a multi-dimensional HEALPix map. Parameters: values : (Sparse) HEALPix array of data values nside : HEALPix dimensionality pixels : Pixel values associated ...
[ "def", "findObjects", "(", "pixels", ",", "values", ",", "nside", ",", "zvalues", ",", "rev", ",", "good", ")", ":", "ngood", "=", "len", "(", "good", ")", "objs", "=", "numpy", ".", "recarray", "(", "(", "ngood", ",", ")", ",", "dtype", "=", "["...
Characterize labelled candidates in a multi-dimensional HEALPix map. Parameters: values : (Sparse) HEALPix array of data values nside : HEALPix dimensionality pixels : Pixel values associated to (sparse) HEALPix array zvalues : Values of the z-dimension (usually...
[ "Characterize", "labelled", "candidates", "in", "a", "multi", "-", "dimensional", "HEALPix", "map", ".", "Parameters", ":", "values", ":", "(", "Sparse", ")", "HEALPix", "array", "of", "data", "values", "nside", ":", "HEALPix", "dimensionality", "pixels", ":",...
21e890b4117fc810afb6fb058e8055d564f03382
https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/analysis/search.py#L201-L286
train
Find the objects in a multi - dimensional HEALPix map.
DarkEnergySurvey/ugali
ugali/simulation/population.py
satellitePopulation
def satellitePopulation(mask, nside_pix, n, range_distance=[5., 500.], range_stellar_mass=[1.e1, 1.e6], range_r_physical=[1.e-3, 2.], plot=False): """ Create a population of n randomly placed satellites within a surv...
python
def satellitePopulation(mask, nside_pix, n, range_distance=[5., 500.], range_stellar_mass=[1.e1, 1.e6], range_r_physical=[1.e-3, 2.], plot=False): """ Create a population of n randomly placed satellites within a surv...
[ "def", "satellitePopulation", "(", "mask", ",", "nside_pix", ",", "n", ",", "range_distance", "=", "[", "5.", ",", "500.", "]", ",", "range_stellar_mass", "=", "[", "1.e1", ",", "1.e6", "]", ",", "range_r_physical", "=", "[", "1.e-3", ",", "2.", "]", "...
Create a population of n randomly placed satellites within a survey mask. Satellites are distributed uniformly in log(distance) (kpc), uniformly in log(stellar_mass) (M_sol), and uniformly in physical half-light radius log(r_physical) (kpc). The ranges can be set by the user. Returns the simulated area (de...
[ "Create", "a", "population", "of", "n", "randomly", "placed", "satellites", "within", "a", "survey", "mask", ".", "Satellites", "are", "distributed", "uniformly", "in", "log", "(", "distance", ")", "(", "kpc", ")", "uniformly", "in", "log", "(", "stellar_mas...
21e890b4117fc810afb6fb058e8055d564f03382
https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/simulation/population.py#L18-L88
train
Generate a population of n random satellites within a survey mask.
DarkEnergySurvey/ugali
ugali/simulation/population.py
satellitePopulationOrig
def satellitePopulationOrig(config, n, range_distance_modulus=[16.5, 24.], range_stellar_mass=[1.e2, 1.e5], range_r_physical=[5.e-3, 1.], mode='mask', plot=False): """ Crea...
python
def satellitePopulationOrig(config, n, range_distance_modulus=[16.5, 24.], range_stellar_mass=[1.e2, 1.e5], range_r_physical=[5.e-3, 1.], mode='mask', plot=False): """ Crea...
[ "def", "satellitePopulationOrig", "(", "config", ",", "n", ",", "range_distance_modulus", "=", "[", "16.5", ",", "24.", "]", ",", "range_stellar_mass", "=", "[", "1.e2", ",", "1.e5", "]", ",", "range_r_physical", "=", "[", "5.e-3", ",", "1.", "]", ",", "...
Create a population of n randomly placed satellites within a survey mask or catalog specified in the config file. Satellites are distributed uniformly in distance modulus, uniformly in log(stellar_mass) (M_sol), and uniformly in log(r_physical) (kpc). The ranges can be set by the user. Returns the simulate...
[ "Create", "a", "population", "of", "n", "randomly", "placed", "satellites", "within", "a", "survey", "mask", "or", "catalog", "specified", "in", "the", "config", "file", ".", "Satellites", "are", "distributed", "uniformly", "in", "distance", "modulus", "uniforml...
21e890b4117fc810afb6fb058e8055d564f03382
https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/simulation/population.py#L92-L162
train
Create a new satellite population with n random positions within a survey mask or catalog.
alphagov/performanceplatform-collector
performanceplatform/collector/main.py
_get_query_params
def _get_query_params(query): """ >>> _get_query_params({'query': {'a': 1, 'c': 3, 'b': 5}}) 'a=1 b=5 c=3' """ query_params = OrderedDict(sorted(query['query'].items())) return ' '.join(['{}={}'.format(k, v) for k, v in query_params.items()])
python
def _get_query_params(query): """ >>> _get_query_params({'query': {'a': 1, 'c': 3, 'b': 5}}) 'a=1 b=5 c=3' """ query_params = OrderedDict(sorted(query['query'].items())) return ' '.join(['{}={}'.format(k, v) for k, v in query_params.items()])
[ "def", "_get_query_params", "(", "query", ")", ":", "query_params", "=", "OrderedDict", "(", "sorted", "(", "query", "[", "'query'", "]", ".", "items", "(", ")", ")", ")", "return", "' '", ".", "join", "(", "[", "'{}={}'", ".", "format", "(", "k", ",...
>>> _get_query_params({'query': {'a': 1, 'c': 3, 'b': 5}}) 'a=1 b=5 c=3'
[ ">>>", "_get_query_params", "(", "{", "query", ":", "{", "a", ":", "1", "c", ":", "3", "b", ":", "5", "}}", ")", "a", "=", "1", "b", "=", "5", "c", "=", "3" ]
de68ab4aa500c31e436e050fa1268fa928c522a5
https://github.com/alphagov/performanceplatform-collector/blob/de68ab4aa500c31e436e050fa1268fa928c522a5/performanceplatform/collector/main.py#L25-L31
train
Get the query params from a query dict.
alphagov/performanceplatform-collector
performanceplatform/collector/main.py
make_extra_json_fields
def make_extra_json_fields(args): """ From the parsed command-line arguments, generate a dictionary of additional fields to be inserted into JSON logs (logstash_formatter module) """ extra_json_fields = { 'data_group': _get_data_group(args.query), 'data_type': _get_data_type(args.que...
python
def make_extra_json_fields(args): """ From the parsed command-line arguments, generate a dictionary of additional fields to be inserted into JSON logs (logstash_formatter module) """ extra_json_fields = { 'data_group': _get_data_group(args.query), 'data_type': _get_data_type(args.que...
[ "def", "make_extra_json_fields", "(", "args", ")", ":", "extra_json_fields", "=", "{", "'data_group'", ":", "_get_data_group", "(", "args", ".", "query", ")", ",", "'data_type'", ":", "_get_data_type", "(", "args", ".", "query", ")", ",", "'data_group_data_type'...
From the parsed command-line arguments, generate a dictionary of additional fields to be inserted into JSON logs (logstash_formatter module)
[ "From", "the", "parsed", "command", "-", "line", "arguments", "generate", "a", "dictionary", "of", "additional", "fields", "to", "be", "inserted", "into", "JSON", "logs", "(", "logstash_formatter", "module", ")" ]
de68ab4aa500c31e436e050fa1268fa928c522a5
https://github.com/alphagov/performanceplatform-collector/blob/de68ab4aa500c31e436e050fa1268fa928c522a5/performanceplatform/collector/main.py#L38-L51
train
Generate a dictionary of additional json fields to be inserted into JSON logs
alphagov/performanceplatform-collector
performanceplatform/collector/gcloud/sales_parser.py
process_csv
def process_csv(f): """ Take a file-like object and yield OrderedDicts to be inserted into raw spending database. """ reader = unicodecsv.DictReader(f, encoding=_ENCODING) for row in reader: month, year = parse_month_year(row['Return Month']) yield OrderedDict([ ('cu...
python
def process_csv(f): """ Take a file-like object and yield OrderedDicts to be inserted into raw spending database. """ reader = unicodecsv.DictReader(f, encoding=_ENCODING) for row in reader: month, year = parse_month_year(row['Return Month']) yield OrderedDict([ ('cu...
[ "def", "process_csv", "(", "f", ")", ":", "reader", "=", "unicodecsv", ".", "DictReader", "(", "f", ",", "encoding", "=", "_ENCODING", ")", "for", "row", "in", "reader", ":", "month", ",", "year", "=", "parse_month_year", "(", "row", "[", "'Return Month'...
Take a file-like object and yield OrderedDicts to be inserted into raw spending database.
[ "Take", "a", "file", "-", "like", "object", "and", "yield", "OrderedDicts", "to", "be", "inserted", "into", "raw", "spending", "database", "." ]
de68ab4aa500c31e436e050fa1268fa928c522a5
https://github.com/alphagov/performanceplatform-collector/blob/de68ab4aa500c31e436e050fa1268fa928c522a5/performanceplatform/collector/gcloud/sales_parser.py#L71-L90
train
Takes a file - like object and yields OrderedDicts to be inserted into raw spending database.
alphagov/performanceplatform-collector
performanceplatform/collector/gcloud/sales_parser.py
parse_month_year
def parse_month_year(date_string): """ >>> parse_month_year('01/10/2012') (10, 2012) """ match = re.match('\d{2}/(?P<month>\d{2})/(?P<year>\d{4})$', date_string.lower()) if not match: raise ValueError("Not format 'dd/mm/yyyy': '{}'".format(date_string)) month = i...
python
def parse_month_year(date_string): """ >>> parse_month_year('01/10/2012') (10, 2012) """ match = re.match('\d{2}/(?P<month>\d{2})/(?P<year>\d{4})$', date_string.lower()) if not match: raise ValueError("Not format 'dd/mm/yyyy': '{}'".format(date_string)) month = i...
[ "def", "parse_month_year", "(", "date_string", ")", ":", "match", "=", "re", ".", "match", "(", "'\\d{2}/(?P<month>\\d{2})/(?P<year>\\d{4})$'", ",", "date_string", ".", "lower", "(", ")", ")", "if", "not", "match", ":", "raise", "ValueError", "(", "\"Not format ...
>>> parse_month_year('01/10/2012') (10, 2012)
[ ">>>", "parse_month_year", "(", "01", "/", "10", "/", "2012", ")", "(", "10", "2012", ")" ]
de68ab4aa500c31e436e050fa1268fa928c522a5
https://github.com/alphagov/performanceplatform-collector/blob/de68ab4aa500c31e436e050fa1268fa928c522a5/performanceplatform/collector/gcloud/sales_parser.py#L93-L104
train
Parse a date string into a month and year tuple.
alphagov/performanceplatform-collector
performanceplatform/collector/gcloud/sales_parser.py
parse_price
def parse_price(price_string): """ >>> parse_price('£16,000.00') 16000.0 >>> parse_price('-£16,000.00') -16000.0 """ return float(re.sub('[£,]', '', price_string)) match = re.match('(?P<amount>-?£[\d,]+(\.\d{2})?)', price_string) if not match: raise ValueError("Charge not in...
python
def parse_price(price_string): """ >>> parse_price('£16,000.00') 16000.0 >>> parse_price('-£16,000.00') -16000.0 """ return float(re.sub('[£,]', '', price_string)) match = re.match('(?P<amount>-?£[\d,]+(\.\d{2})?)', price_string) if not match: raise ValueError("Charge not in...
[ "def", "parse_price", "(", "price_string", ")", ":", "return", "float", "(", "re", ".", "sub", "(", "'[£,]',", " ", "',", " ", "rice_string)", ")", "", "match", "=", "re", ".", "match", "(", "'(?P<amount>-?£[\\d,]+(\\.\\d{2})?)',", " ", "rice_string)", "", ...
>>> parse_price('£16,000.00') 16000.0 >>> parse_price('-£16,000.00') -16000.0
[ ">>>", "parse_price", "(", "£16", "000", ".", "00", ")", "16000", ".", "0", ">>>", "parse_price", "(", "-", "£16", "000", ".", "00", ")", "-", "16000", ".", "0" ]
de68ab4aa500c31e436e050fa1268fa928c522a5
https://github.com/alphagov/performanceplatform-collector/blob/de68ab4aa500c31e436e050fa1268fa928c522a5/performanceplatform/collector/gcloud/sales_parser.py#L107-L120
train
Parse a price string into a sequence of numbers.
DarkEnergySurvey/ugali
ugali/utils/logger.py
file_found
def file_found(filename,force): """Check if a file exists""" if os.path.exists(filename) and not force: logger.info("Found %s; skipping..."%filename) return True else: return False
python
def file_found(filename,force): """Check if a file exists""" if os.path.exists(filename) and not force: logger.info("Found %s; skipping..."%filename) return True else: return False
[ "def", "file_found", "(", "filename", ",", "force", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "filename", ")", "and", "not", "force", ":", "logger", ".", "info", "(", "\"Found %s; skipping...\"", "%", "filename", ")", "return", "True", "else...
Check if a file exists
[ "Check", "if", "a", "file", "exists" ]
21e890b4117fc810afb6fb058e8055d564f03382
https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/utils/logger.py#L39-L45
train
Check if a file exists and if not skip it
cfusting/fastgp
fastgp/algorithms/truncation_with_elite.py
generate_next_population
def generate_next_population(individuals, toolbox): """ Perform truncated selection with elitism. :param individuals: :param toolbox: :return: """ individuals = [toolbox.clone(ind) for ind in individuals] individuals.sort(key=lambda x: x.error) offspring = [] pop_size = len(indi...
python
def generate_next_population(individuals, toolbox): """ Perform truncated selection with elitism. :param individuals: :param toolbox: :return: """ individuals = [toolbox.clone(ind) for ind in individuals] individuals.sort(key=lambda x: x.error) offspring = [] pop_size = len(indi...
[ "def", "generate_next_population", "(", "individuals", ",", "toolbox", ")", ":", "individuals", "=", "[", "toolbox", ".", "clone", "(", "ind", ")", "for", "ind", "in", "individuals", "]", "individuals", ".", "sort", "(", "key", "=", "lambda", "x", ":", "...
Perform truncated selection with elitism. :param individuals: :param toolbox: :return:
[ "Perform", "truncated", "selection", "with", "elitism", ".", ":", "param", "individuals", ":", ":", "param", "toolbox", ":", ":", "return", ":" ]
6cf3c5d14abedaea064feef6ca434ee806a11756
https://github.com/cfusting/fastgp/blob/6cf3c5d14abedaea064feef6ca434ee806a11756/fastgp/algorithms/truncation_with_elite.py#L8-L27
train
Perform truncated selection with elitism.
cfusting/fastgp
fastgp/algorithms/truncation_with_elite.py
optimize
def optimize(population, toolbox, ngen, archive=None, stats=None, verbose=False, history=None): """ Optimize a population of individuals. :param population: :param toolbox: :param mut_prob: :param ngen: :param archive: :param stats: :param verbose: :param history: :return: ...
python
def optimize(population, toolbox, ngen, archive=None, stats=None, verbose=False, history=None): """ Optimize a population of individuals. :param population: :param toolbox: :param mut_prob: :param ngen: :param archive: :param stats: :param verbose: :param history: :return: ...
[ "def", "optimize", "(", "population", ",", "toolbox", ",", "ngen", ",", "archive", "=", "None", ",", "stats", "=", "None", ",", "verbose", "=", "False", ",", "history", "=", "None", ")", ":", "start", "=", "time", ".", "time", "(", ")", "if", "hist...
Optimize a population of individuals. :param population: :param toolbox: :param mut_prob: :param ngen: :param archive: :param stats: :param verbose: :param history: :return:
[ "Optimize", "a", "population", "of", "individuals", ".", ":", "param", "population", ":", ":", "param", "toolbox", ":", ":", "param", "mut_prob", ":", ":", "param", "ngen", ":", ":", "param", "archive", ":", ":", "param", "stats", ":", ":", "param", "v...
6cf3c5d14abedaea064feef6ca434ee806a11756
https://github.com/cfusting/fastgp/blob/6cf3c5d14abedaea064feef6ca434ee806a11756/fastgp/algorithms/truncation_with_elite.py#L47-L72
train
Optimize a population of individuals.
alphagov/performanceplatform-collector
performanceplatform/collector/ga/core.py
try_number
def try_number(value): """ Attempt to cast the string `value` to an int, and failing that, a float, failing that, raise a ValueError. """ for cast_function in [int, float]: try: return cast_function(value) except ValueError: pass raise ValueError("Unable...
python
def try_number(value): """ Attempt to cast the string `value` to an int, and failing that, a float, failing that, raise a ValueError. """ for cast_function in [int, float]: try: return cast_function(value) except ValueError: pass raise ValueError("Unable...
[ "def", "try_number", "(", "value", ")", ":", "for", "cast_function", "in", "[", "int", ",", "float", "]", ":", "try", ":", "return", "cast_function", "(", "value", ")", "except", "ValueError", ":", "pass", "raise", "ValueError", "(", "\"Unable to use value a...
Attempt to cast the string `value` to an int, and failing that, a float, failing that, raise a ValueError.
[ "Attempt", "to", "cast", "the", "string", "value", "to", "an", "int", "and", "failing", "that", "a", "float", "failing", "that", "raise", "a", "ValueError", "." ]
de68ab4aa500c31e436e050fa1268fa928c522a5
https://github.com/alphagov/performanceplatform-collector/blob/de68ab4aa500c31e436e050fa1268fa928c522a5/performanceplatform/collector/ga/core.py#L37-L50
train
Try to cast the string value to an int or float.
alphagov/performanceplatform-collector
performanceplatform/collector/ga/core.py
convert_durations
def convert_durations(metric): """ Convert session duration metrics from seconds to milliseconds. """ if metric[0] == 'avgSessionDuration' and metric[1]: new_metric = (metric[0], metric[1] * 1000) else: new_metric = metric return new_metric
python
def convert_durations(metric): """ Convert session duration metrics from seconds to milliseconds. """ if metric[0] == 'avgSessionDuration' and metric[1]: new_metric = (metric[0], metric[1] * 1000) else: new_metric = metric return new_metric
[ "def", "convert_durations", "(", "metric", ")", ":", "if", "metric", "[", "0", "]", "==", "'avgSessionDuration'", "and", "metric", "[", "1", "]", ":", "new_metric", "=", "(", "metric", "[", "0", "]", ",", "metric", "[", "1", "]", "*", "1000", ")", ...
Convert session duration metrics from seconds to milliseconds.
[ "Convert", "session", "duration", "metrics", "from", "seconds", "to", "milliseconds", "." ]
de68ab4aa500c31e436e050fa1268fa928c522a5
https://github.com/alphagov/performanceplatform-collector/blob/de68ab4aa500c31e436e050fa1268fa928c522a5/performanceplatform/collector/ga/core.py#L53-L61
train
Convert session duration metrics from seconds to milliseconds.
akx/lepo
lepo/parameter_utils.py
read_parameters
def read_parameters(request, view_kwargs=None, capture_errors=False): # noqa: C901 """ :param request: HttpRequest with attached api_info :type request: HttpRequest :type view_kwargs: dict[str, object] :type capture_errors: bool :rtype: dict[str, object] """ if view_kwargs is None: ...
python
def read_parameters(request, view_kwargs=None, capture_errors=False): # noqa: C901 """ :param request: HttpRequest with attached api_info :type request: HttpRequest :type view_kwargs: dict[str, object] :type capture_errors: bool :rtype: dict[str, object] """ if view_kwargs is None: ...
[ "def", "read_parameters", "(", "request", ",", "view_kwargs", "=", "None", ",", "capture_errors", "=", "False", ")", ":", "# noqa: C901", "if", "view_kwargs", "is", "None", ":", "view_kwargs", "=", "{", "}", "params", "=", "{", "}", "errors", "=", "{", "...
:param request: HttpRequest with attached api_info :type request: HttpRequest :type view_kwargs: dict[str, object] :type capture_errors: bool :rtype: dict[str, object]
[ ":", "param", "request", ":", "HttpRequest", "with", "attached", "api_info", ":", "type", "request", ":", "HttpRequest", ":", "type", "view_kwargs", ":", "dict", "[", "str", "object", "]", ":", "type", "capture_errors", ":", "bool", ":", "rtype", ":", "dic...
34cfb24a40f18ea40f672c1ea9a0734ee1816b7d
https://github.com/akx/lepo/blob/34cfb24a40f18ea40f672c1ea9a0734ee1816b7d/lepo/parameter_utils.py#L31-L61
train
Reads the parameters from the request.
alphagov/performanceplatform-collector
performanceplatform/collector/piwik/core.py
Parser.to_datetime
def to_datetime(date_key): ''' Extract the first date from 'key' matching YYYY-MM-DD or YYYY-MM, and convert to datetime. ''' match = re.search(r'\d{4}-\d{2}(-\d{2})?', date_key) formatter = '%Y-%m' if len(match.group()) == 10: formatter += '-%d' ...
python
def to_datetime(date_key): ''' Extract the first date from 'key' matching YYYY-MM-DD or YYYY-MM, and convert to datetime. ''' match = re.search(r'\d{4}-\d{2}(-\d{2})?', date_key) formatter = '%Y-%m' if len(match.group()) == 10: formatter += '-%d' ...
[ "def", "to_datetime", "(", "date_key", ")", ":", "match", "=", "re", ".", "search", "(", "r'\\d{4}-\\d{2}(-\\d{2})?'", ",", "date_key", ")", "formatter", "=", "'%Y-%m'", "if", "len", "(", "match", ".", "group", "(", ")", ")", "==", "10", ":", "formatter"...
Extract the first date from 'key' matching YYYY-MM-DD or YYYY-MM, and convert to datetime.
[ "Extract", "the", "first", "date", "from", "key", "matching", "YYYY", "-", "MM", "-", "DD", "or", "YYYY", "-", "MM", "and", "convert", "to", "datetime", "." ]
de68ab4aa500c31e436e050fa1268fa928c522a5
https://github.com/alphagov/performanceplatform-collector/blob/de68ab4aa500c31e436e050fa1268fa928c522a5/performanceplatform/collector/piwik/core.py#L77-L87
train
Extract the first date from key matching YYYY - MM - DD or YYYY - MM and convert to datetime.
stevearc/dynamo3
dynamo3/types.py
float_to_decimal
def float_to_decimal(f): """ Convert a float to a 38-precision Decimal """ n, d = f.as_integer_ratio() numerator, denominator = Decimal(n), Decimal(d) return DECIMAL_CONTEXT.divide(numerator, denominator)
python
def float_to_decimal(f): """ Convert a float to a 38-precision Decimal """ n, d = f.as_integer_ratio() numerator, denominator = Decimal(n), Decimal(d) return DECIMAL_CONTEXT.divide(numerator, denominator)
[ "def", "float_to_decimal", "(", "f", ")", ":", "n", ",", "d", "=", "f", ".", "as_integer_ratio", "(", ")", "numerator", ",", "denominator", "=", "Decimal", "(", "n", ")", ",", "Decimal", "(", "d", ")", "return", "DECIMAL_CONTEXT", ".", "divide", "(", ...
Convert a float to a 38-precision Decimal
[ "Convert", "a", "float", "to", "a", "38", "-", "precision", "Decimal" ]
f897c40ece28586272dbcab8f0d99a14a1831dda
https://github.com/stevearc/dynamo3/blob/f897c40ece28586272dbcab8f0d99a14a1831dda/dynamo3/types.py#L13-L17
train
Convert a float to a 38 - precision Decimal
stevearc/dynamo3
dynamo3/types.py
is_dynamo_value
def is_dynamo_value(value): """ Returns True if the value is a Dynamo-formatted value """ if not isinstance(value, dict) or len(value) != 1: return False subkey = six.next(six.iterkeys(value)) return subkey in TYPES_REV
python
def is_dynamo_value(value): """ Returns True if the value is a Dynamo-formatted value """ if not isinstance(value, dict) or len(value) != 1: return False subkey = six.next(six.iterkeys(value)) return subkey in TYPES_REV
[ "def", "is_dynamo_value", "(", "value", ")", ":", "if", "not", "isinstance", "(", "value", ",", "dict", ")", "or", "len", "(", "value", ")", "!=", "1", ":", "return", "False", "subkey", "=", "six", ".", "next", "(", "six", ".", "iterkeys", "(", "va...
Returns True if the value is a Dynamo-formatted value
[ "Returns", "True", "if", "the", "value", "is", "a", "Dynamo", "-", "formatted", "value" ]
f897c40ece28586272dbcab8f0d99a14a1831dda
https://github.com/stevearc/dynamo3/blob/f897c40ece28586272dbcab8f0d99a14a1831dda/dynamo3/types.py#L35-L40
train
Returns True if the value is a Dynamo - formatted value.
stevearc/dynamo3
dynamo3/types.py
encode_set
def encode_set(dynamizer, value): """ Encode a set for the DynamoDB format """ inner_value = next(iter(value)) inner_type = dynamizer.raw_encode(inner_value)[0] return inner_type + 'S', [dynamizer.raw_encode(v)[1] for v in value]
python
def encode_set(dynamizer, value): """ Encode a set for the DynamoDB format """ inner_value = next(iter(value)) inner_type = dynamizer.raw_encode(inner_value)[0] return inner_type + 'S', [dynamizer.raw_encode(v)[1] for v in value]
[ "def", "encode_set", "(", "dynamizer", ",", "value", ")", ":", "inner_value", "=", "next", "(", "iter", "(", "value", ")", ")", "inner_type", "=", "dynamizer", ".", "raw_encode", "(", "inner_value", ")", "[", "0", "]", "return", "inner_type", "+", "'S'",...
Encode a set for the DynamoDB format
[ "Encode", "a", "set", "for", "the", "DynamoDB", "format" ]
f897c40ece28586272dbcab8f0d99a14a1831dda
https://github.com/stevearc/dynamo3/blob/f897c40ece28586272dbcab8f0d99a14a1831dda/dynamo3/types.py#L77-L81
train
Encode a set for the DynamoDB format
stevearc/dynamo3
dynamo3/types.py
encode_list
def encode_list(dynamizer, value): """ Encode a list for the DynamoDB format """ encoded_list = [] dict(map(dynamizer.raw_encode, value)) for v in value: encoded_type, encoded_value = dynamizer.raw_encode(v) encoded_list.append({ encoded_type: encoded_value, }) re...
python
def encode_list(dynamizer, value): """ Encode a list for the DynamoDB format """ encoded_list = [] dict(map(dynamizer.raw_encode, value)) for v in value: encoded_type, encoded_value = dynamizer.raw_encode(v) encoded_list.append({ encoded_type: encoded_value, }) re...
[ "def", "encode_list", "(", "dynamizer", ",", "value", ")", ":", "encoded_list", "=", "[", "]", "dict", "(", "map", "(", "dynamizer", ".", "raw_encode", ",", "value", ")", ")", "for", "v", "in", "value", ":", "encoded_type", ",", "encoded_value", "=", "...
Encode a list for the DynamoDB format
[ "Encode", "a", "list", "for", "the", "DynamoDB", "format" ]
f897c40ece28586272dbcab8f0d99a14a1831dda
https://github.com/stevearc/dynamo3/blob/f897c40ece28586272dbcab8f0d99a14a1831dda/dynamo3/types.py#L84-L93
train
Encode a list for the DynamoDB format
stevearc/dynamo3
dynamo3/types.py
encode_dict
def encode_dict(dynamizer, value): """ Encode a dict for the DynamoDB format """ encoded_dict = {} for k, v in six.iteritems(value): encoded_type, encoded_value = dynamizer.raw_encode(v) encoded_dict[k] = { encoded_type: encoded_value, } return 'M', encoded_dict
python
def encode_dict(dynamizer, value): """ Encode a dict for the DynamoDB format """ encoded_dict = {} for k, v in six.iteritems(value): encoded_type, encoded_value = dynamizer.raw_encode(v) encoded_dict[k] = { encoded_type: encoded_value, } return 'M', encoded_dict
[ "def", "encode_dict", "(", "dynamizer", ",", "value", ")", ":", "encoded_dict", "=", "{", "}", "for", "k", ",", "v", "in", "six", ".", "iteritems", "(", "value", ")", ":", "encoded_type", ",", "encoded_value", "=", "dynamizer", ".", "raw_encode", "(", ...
Encode a dict for the DynamoDB format
[ "Encode", "a", "dict", "for", "the", "DynamoDB", "format" ]
f897c40ece28586272dbcab8f0d99a14a1831dda
https://github.com/stevearc/dynamo3/blob/f897c40ece28586272dbcab8f0d99a14a1831dda/dynamo3/types.py#L96-L104
train
Encode a dict for the DynamoDB format
stevearc/dynamo3
dynamo3/types.py
Dynamizer.raw_encode
def raw_encode(self, value): """ Run the encoder on a value """ if type(value) in self.encoders: encoder = self.encoders[type(value)] return encoder(self, value) raise ValueError("No encoder for value '%s' of type '%s'" % (value, type(value)))
python
def raw_encode(self, value): """ Run the encoder on a value """ if type(value) in self.encoders: encoder = self.encoders[type(value)] return encoder(self, value) raise ValueError("No encoder for value '%s' of type '%s'" % (value, type(value)))
[ "def", "raw_encode", "(", "self", ",", "value", ")", ":", "if", "type", "(", "value", ")", "in", "self", ".", "encoders", ":", "encoder", "=", "self", ".", "encoders", "[", "type", "(", "value", ")", "]", "return", "encoder", "(", "self", ",", "val...
Run the encoder on a value
[ "Run", "the", "encoder", "on", "a", "value" ]
f897c40ece28586272dbcab8f0d99a14a1831dda
https://github.com/stevearc/dynamo3/blob/f897c40ece28586272dbcab8f0d99a14a1831dda/dynamo3/types.py#L150-L156
train
Run the encoder on a value
stevearc/dynamo3
dynamo3/types.py
Dynamizer.encode_keys
def encode_keys(self, keys): """ Run the encoder on a dict of values """ return dict(((k, self.encode(v)) for k, v in six.iteritems(keys) if not is_null(v)))
python
def encode_keys(self, keys): """ Run the encoder on a dict of values """ return dict(((k, self.encode(v)) for k, v in six.iteritems(keys) if not is_null(v)))
[ "def", "encode_keys", "(", "self", ",", "keys", ")", ":", "return", "dict", "(", "(", "(", "k", ",", "self", ".", "encode", "(", "v", ")", ")", "for", "k", ",", "v", "in", "six", ".", "iteritems", "(", "keys", ")", "if", "not", "is_null", "(", ...
Run the encoder on a dict of values
[ "Run", "the", "encoder", "on", "a", "dict", "of", "values" ]
f897c40ece28586272dbcab8f0d99a14a1831dda
https://github.com/stevearc/dynamo3/blob/f897c40ece28586272dbcab8f0d99a14a1831dda/dynamo3/types.py#L158-L161
train
Run the encoder on a dict of keys
stevearc/dynamo3
dynamo3/types.py
Dynamizer.maybe_encode_keys
def maybe_encode_keys(self, keys): """ Same as encode_keys but a no-op if already in Dynamo format """ ret = {} for k, v in six.iteritems(keys): if is_dynamo_value(v): return keys elif not is_null(v): ret[k] = self.encode(v) return ...
python
def maybe_encode_keys(self, keys): """ Same as encode_keys but a no-op if already in Dynamo format """ ret = {} for k, v in six.iteritems(keys): if is_dynamo_value(v): return keys elif not is_null(v): ret[k] = self.encode(v) return ...
[ "def", "maybe_encode_keys", "(", "self", ",", "keys", ")", ":", "ret", "=", "{", "}", "for", "k", ",", "v", "in", "six", ".", "iteritems", "(", "keys", ")", ":", "if", "is_dynamo_value", "(", "v", ")", ":", "return", "keys", "elif", "not", "is_null...
Same as encode_keys but a no-op if already in Dynamo format
[ "Same", "as", "encode_keys", "but", "a", "no", "-", "op", "if", "already", "in", "Dynamo", "format" ]
f897c40ece28586272dbcab8f0d99a14a1831dda
https://github.com/stevearc/dynamo3/blob/f897c40ece28586272dbcab8f0d99a14a1831dda/dynamo3/types.py#L163-L171
train
Encode keys if they are already in Dynamo format.
stevearc/dynamo3
dynamo3/types.py
Dynamizer.decode_keys
def decode_keys(self, keys): """ Run the decoder on a dict of values """ return dict(((k, self.decode(v)) for k, v in six.iteritems(keys)))
python
def decode_keys(self, keys): """ Run the decoder on a dict of values """ return dict(((k, self.decode(v)) for k, v in six.iteritems(keys)))
[ "def", "decode_keys", "(", "self", ",", "keys", ")", ":", "return", "dict", "(", "(", "(", "k", ",", "self", ".", "decode", "(", "v", ")", ")", "for", "k", ",", "v", "in", "six", ".", "iteritems", "(", "keys", ")", ")", ")" ]
Run the decoder on a dict of values
[ "Run", "the", "decoder", "on", "a", "dict", "of", "values" ]
f897c40ece28586272dbcab8f0d99a14a1831dda
https://github.com/stevearc/dynamo3/blob/f897c40ece28586272dbcab8f0d99a14a1831dda/dynamo3/types.py#L177-L179
train
Run the decoder on a dict of keys
stevearc/dynamo3
dynamo3/types.py
Dynamizer.decode
def decode(self, dynamo_value): """ Decode a dynamo value into a python value """ type, value = next(six.iteritems(dynamo_value)) if type == STRING: return value elif type == BINARY: return Binary(value) elif type == NUMBER: return Decimal(valu...
python
def decode(self, dynamo_value): """ Decode a dynamo value into a python value """ type, value = next(six.iteritems(dynamo_value)) if type == STRING: return value elif type == BINARY: return Binary(value) elif type == NUMBER: return Decimal(valu...
[ "def", "decode", "(", "self", ",", "dynamo_value", ")", ":", "type", ",", "value", "=", "next", "(", "six", ".", "iteritems", "(", "dynamo_value", ")", ")", "if", "type", "==", "STRING", ":", "return", "value", "elif", "type", "==", "BINARY", ":", "r...
Decode a dynamo value into a python value
[ "Decode", "a", "dynamo", "value", "into", "a", "python", "value" ]
f897c40ece28586272dbcab8f0d99a14a1831dda
https://github.com/stevearc/dynamo3/blob/f897c40ece28586272dbcab8f0d99a14a1831dda/dynamo3/types.py#L181-L208
train
Decode a dynamo value into a python value
accraze/python-markov-novel
src/markov_novel/paragraph.py
Paragraph.get_paragraph
def get_paragraph(self): """ Write a paragraph of 5 sentences. """ self.text = '' for x in range(randint(5, 12)): sentence = self._write_sentence() self.text = self.text + sentence return self.text
python
def get_paragraph(self): """ Write a paragraph of 5 sentences. """ self.text = '' for x in range(randint(5, 12)): sentence = self._write_sentence() self.text = self.text + sentence return self.text
[ "def", "get_paragraph", "(", "self", ")", ":", "self", ".", "text", "=", "''", "for", "x", "in", "range", "(", "randint", "(", "5", ",", "12", ")", ")", ":", "sentence", "=", "self", ".", "_write_sentence", "(", ")", "self", ".", "text", "=", "se...
Write a paragraph of 5 sentences.
[ "Write", "a", "paragraph", "of", "5", "sentences", "." ]
ff451639e93a3ac11fb0268b92bc0cffc00bfdbe
https://github.com/accraze/python-markov-novel/blob/ff451639e93a3ac11fb0268b92bc0cffc00bfdbe/src/markov_novel/paragraph.py#L18-L27
train
Write a paragraph of 5 sentences.
alphagov/performanceplatform-collector
performanceplatform/collector/crontab.py
parse_job_line
def parse_job_line(line): """ >>> parse_job_line( \ "* * * *,myquery,mycredentials,mytoken,performanceplatform\\n") ('* * * *', 'myquery', 'mycredentials', 'mytoken', 'performanceplatform') >>> parse_job_line(" ") is None True >>> parse_job_line("# comment") is None Tr...
python
def parse_job_line(line): """ >>> parse_job_line( \ "* * * *,myquery,mycredentials,mytoken,performanceplatform\\n") ('* * * *', 'myquery', 'mycredentials', 'mytoken', 'performanceplatform') >>> parse_job_line(" ") is None True >>> parse_job_line("# comment") is None Tr...
[ "def", "parse_job_line", "(", "line", ")", ":", "parsed", "=", "None", "if", "not", "ignore_line_re", ".", "match", "(", "line", ")", ":", "parsed", "=", "tuple", "(", "line", ".", "strip", "(", ")", ".", "split", "(", "','", ")", ")", "return", "p...
>>> parse_job_line( \ "* * * *,myquery,mycredentials,mytoken,performanceplatform\\n") ('* * * *', 'myquery', 'mycredentials', 'mytoken', 'performanceplatform') >>> parse_job_line(" ") is None True >>> parse_job_line("# comment") is None True
[ ">>>", "parse_job_line", "(", "\\", "*", "*", "*", "*", "myquery", "mycredentials", "mytoken", "performanceplatform", "\\\\", "n", ")", "(", "*", "*", "*", "*", "myquery", "mycredentials", "mytoken", "performanceplatform", ")", ">>>", "parse_job_line", "(", ")...
de68ab4aa500c31e436e050fa1268fa928c522a5
https://github.com/alphagov/performanceplatform-collector/blob/de68ab4aa500c31e436e050fa1268fa928c522a5/performanceplatform/collector/crontab.py#L39-L54
train
Parses a single line of a job into a tuple.
alphagov/performanceplatform-collector
performanceplatform/collector/crontab.py
skip_job
def skip_job(counter): """ Should we skip the job based on its number If the machine has a number at the end of its hostname (n), and we have m machines in the pool - on machine 1, run job 1, 1 + m, 1+2m etc on machine 2, run job 2, 2 + m , 2 + 2m etc Else run all the jobs """ try: ...
python
def skip_job(counter): """ Should we skip the job based on its number If the machine has a number at the end of its hostname (n), and we have m machines in the pool - on machine 1, run job 1, 1 + m, 1+2m etc on machine 2, run job 2, 2 + m , 2 + 2m etc Else run all the jobs """ try: ...
[ "def", "skip_job", "(", "counter", ")", ":", "try", ":", "host_number", "=", "int", "(", "socket", ".", "gethostname", "(", ")", ".", "split", "(", "'-'", ")", "[", "-", "1", "]", ")", "except", "ValueError", ":", "return", "False", "if", "(", "cou...
Should we skip the job based on its number If the machine has a number at the end of its hostname (n), and we have m machines in the pool - on machine 1, run job 1, 1 + m, 1+2m etc on machine 2, run job 2, 2 + m , 2 + 2m etc Else run all the jobs
[ "Should", "we", "skip", "the", "job", "based", "on", "its", "number" ]
de68ab4aa500c31e436e050fa1268fa928c522a5
https://github.com/alphagov/performanceplatform-collector/blob/de68ab4aa500c31e436e050fa1268fa928c522a5/performanceplatform/collector/crontab.py#L57-L75
train
Should we skip the job based on its number
alphagov/performanceplatform-collector
performanceplatform/collector/crontab.py
generate_crontab
def generate_crontab(current_crontab, path_to_jobs, path_to_app, unique_id): """Returns a crontab with jobs from job path It replaces jobs previously generated by this function It preserves jobs not generated by this function """ set_disable_envar = '' if os.environ.get('DISABLE_COLLECTORS') ==...
python
def generate_crontab(current_crontab, path_to_jobs, path_to_app, unique_id): """Returns a crontab with jobs from job path It replaces jobs previously generated by this function It preserves jobs not generated by this function """ set_disable_envar = '' if os.environ.get('DISABLE_COLLECTORS') ==...
[ "def", "generate_crontab", "(", "current_crontab", ",", "path_to_jobs", ",", "path_to_app", ",", "unique_id", ")", ":", "set_disable_envar", "=", "''", "if", "os", ".", "environ", ".", "get", "(", "'DISABLE_COLLECTORS'", ")", "==", "'true'", ":", "set_disable_en...
Returns a crontab with jobs from job path It replaces jobs previously generated by this function It preserves jobs not generated by this function
[ "Returns", "a", "crontab", "with", "jobs", "from", "job", "path" ]
de68ab4aa500c31e436e050fa1268fa928c522a5
https://github.com/alphagov/performanceplatform-collector/blob/de68ab4aa500c31e436e050fa1268fa928c522a5/performanceplatform/collector/crontab.py#L78-L135
train
Generates a crontab from a file path
consbio/ncdjango
ncdjango/interfaces/arcgis/forms.py
ArcGisFormBase.map_parameters
def map_parameters(cls, params): """Maps parameters to form field names""" d = {} for k, v in six.iteritems(params): d[cls.FIELD_MAP.get(k.lower(), k)] = v return d
python
def map_parameters(cls, params): """Maps parameters to form field names""" d = {} for k, v in six.iteritems(params): d[cls.FIELD_MAP.get(k.lower(), k)] = v return d
[ "def", "map_parameters", "(", "cls", ",", "params", ")", ":", "d", "=", "{", "}", "for", "k", ",", "v", "in", "six", ".", "iteritems", "(", "params", ")", ":", "d", "[", "cls", ".", "FIELD_MAP", ".", "get", "(", "k", ".", "lower", "(", ")", "...
Maps parameters to form field names
[ "Maps", "parameters", "to", "form", "field", "names" ]
f807bfd1e4083ab29fbc3c4d4418be108383a710
https://github.com/consbio/ncdjango/blob/f807bfd1e4083ab29fbc3c4d4418be108383a710/ncdjango/interfaces/arcgis/forms.py#L21-L27
train
Maps parameters to form field names
consbio/ncdjango
ncdjango/geoimage.py
world_to_image
def world_to_image(bbox, size): """Function generator to create functions for converting from world coordinates to image coordinates""" px_per_unit = (float(size[0])/bbox.width, float(size[1])/bbox.height) return lambda x,y: ((x-bbox.xmin) * px_per_unit[0], size[1] - (y-bbox.ymin)*px_per_unit[1])
python
def world_to_image(bbox, size): """Function generator to create functions for converting from world coordinates to image coordinates""" px_per_unit = (float(size[0])/bbox.width, float(size[1])/bbox.height) return lambda x,y: ((x-bbox.xmin) * px_per_unit[0], size[1] - (y-bbox.ymin)*px_per_unit[1])
[ "def", "world_to_image", "(", "bbox", ",", "size", ")", ":", "px_per_unit", "=", "(", "float", "(", "size", "[", "0", "]", ")", "/", "bbox", ".", "width", ",", "float", "(", "size", "[", "1", "]", ")", "/", "bbox", ".", "height", ")", "return", ...
Function generator to create functions for converting from world coordinates to image coordinates
[ "Function", "generator", "to", "create", "functions", "for", "converting", "from", "world", "coordinates", "to", "image", "coordinates" ]
f807bfd1e4083ab29fbc3c4d4418be108383a710
https://github.com/consbio/ncdjango/blob/f807bfd1e4083ab29fbc3c4d4418be108383a710/ncdjango/geoimage.py#L173-L177
train
Function generator to create functions for converting from world coordinates to image coordinates
consbio/ncdjango
ncdjango/geoimage.py
GeoImage.warp
def warp(self, target_bbox, target_size=None): """Returns a copy of this image warped to a target size and bounding box""" # Determine target size based on pixels per unit of the source image and the target bounding box reprojected # to the source projection. if not target_size: ...
python
def warp(self, target_bbox, target_size=None): """Returns a copy of this image warped to a target size and bounding box""" # Determine target size based on pixels per unit of the source image and the target bounding box reprojected # to the source projection. if not target_size: ...
[ "def", "warp", "(", "self", ",", "target_bbox", ",", "target_size", "=", "None", ")", ":", "# Determine target size based on pixels per unit of the source image and the target bounding box reprojected", "# to the source projection.", "if", "not", "target_size", ":", "px_per_unit"...
Returns a copy of this image warped to a target size and bounding box
[ "Returns", "a", "copy", "of", "this", "image", "warped", "to", "a", "target", "size", "and", "bounding", "box" ]
f807bfd1e4083ab29fbc3c4d4418be108383a710
https://github.com/consbio/ncdjango/blob/f807bfd1e4083ab29fbc3c4d4418be108383a710/ncdjango/geoimage.py#L121-L170
train
Returns a copy of this image warped to a target size and bounding box.
alphagov/performanceplatform-collector
performanceplatform/collector/ga/plugins/department.py
try_get_department
def try_get_department(department_or_code): """ Try to take the first department code, or fall back to string as passed """ try: value = take_first_department_code(department_or_code) except AssertionError: value = department_or_code if value in DEPARTMENT_MAPPING: value...
python
def try_get_department(department_or_code): """ Try to take the first department code, or fall back to string as passed """ try: value = take_first_department_code(department_or_code) except AssertionError: value = department_or_code if value in DEPARTMENT_MAPPING: value...
[ "def", "try_get_department", "(", "department_or_code", ")", ":", "try", ":", "value", "=", "take_first_department_code", "(", "department_or_code", ")", "except", "AssertionError", ":", "value", "=", "department_or_code", "if", "value", "in", "DEPARTMENT_MAPPING", ":...
Try to take the first department code, or fall back to string as passed
[ "Try", "to", "take", "the", "first", "department", "code", "or", "fall", "back", "to", "string", "as", "passed" ]
de68ab4aa500c31e436e050fa1268fa928c522a5
https://github.com/alphagov/performanceplatform-collector/blob/de68ab4aa500c31e436e050fa1268fa928c522a5/performanceplatform/collector/ga/plugins/department.py#L62-L74
train
Try to take the first department code or fall back to string as passed
juju/theblues
theblues/identity_manager.py
IdentityManager.get_user
def get_user(self, username, macaroons): """Fetch user data. Raise a ServerError if an error occurs in the request process. @param username the user's name. @param macaroons the encoded macaroons string. """ url = '{}u/{}'.format(self.url, username) return make_...
python
def get_user(self, username, macaroons): """Fetch user data. Raise a ServerError if an error occurs in the request process. @param username the user's name. @param macaroons the encoded macaroons string. """ url = '{}u/{}'.format(self.url, username) return make_...
[ "def", "get_user", "(", "self", ",", "username", ",", "macaroons", ")", ":", "url", "=", "'{}u/{}'", ".", "format", "(", "self", ".", "url", ",", "username", ")", "return", "make_request", "(", "url", ",", "timeout", "=", "self", ".", "timeout", ",", ...
Fetch user data. Raise a ServerError if an error occurs in the request process. @param username the user's name. @param macaroons the encoded macaroons string.
[ "Fetch", "user", "data", "." ]
f4431f29e43d04fc32f38f4f86cea45cd4e6ae98
https://github.com/juju/theblues/blob/f4431f29e43d04fc32f38f4f86cea45cd4e6ae98/theblues/identity_manager.py#L33-L42
train
Fetch user data.
juju/theblues
theblues/identity_manager.py
IdentityManager.debug
def debug(self): """Retrieve the debug information from the identity manager.""" url = '{}debug/status'.format(self.url) try: return make_request(url, timeout=self.timeout) except ServerError as err: return {"error": str(err)}
python
def debug(self): """Retrieve the debug information from the identity manager.""" url = '{}debug/status'.format(self.url) try: return make_request(url, timeout=self.timeout) except ServerError as err: return {"error": str(err)}
[ "def", "debug", "(", "self", ")", ":", "url", "=", "'{}debug/status'", ".", "format", "(", "self", ".", "url", ")", "try", ":", "return", "make_request", "(", "url", ",", "timeout", "=", "self", ".", "timeout", ")", "except", "ServerError", "as", "err"...
Retrieve the debug information from the identity manager.
[ "Retrieve", "the", "debug", "information", "from", "the", "identity", "manager", "." ]
f4431f29e43d04fc32f38f4f86cea45cd4e6ae98
https://github.com/juju/theblues/blob/f4431f29e43d04fc32f38f4f86cea45cd4e6ae98/theblues/identity_manager.py#L44-L50
train
Retrieve the debug information from the identity manager.
juju/theblues
theblues/identity_manager.py
IdentityManager.login
def login(self, username, json_document): """Send user identity information to the identity manager. Raise a ServerError if an error occurs in the request process. @param username The logged in user. @param json_document The JSON payload for login. """ url = '{}u/{}'.fo...
python
def login(self, username, json_document): """Send user identity information to the identity manager. Raise a ServerError if an error occurs in the request process. @param username The logged in user. @param json_document The JSON payload for login. """ url = '{}u/{}'.fo...
[ "def", "login", "(", "self", ",", "username", ",", "json_document", ")", ":", "url", "=", "'{}u/{}'", ".", "format", "(", "self", ".", "url", ",", "username", ")", "make_request", "(", "url", ",", "method", "=", "'PUT'", ",", "body", "=", "json_documen...
Send user identity information to the identity manager. Raise a ServerError if an error occurs in the request process. @param username The logged in user. @param json_document The JSON payload for login.
[ "Send", "user", "identity", "information", "to", "the", "identity", "manager", "." ]
f4431f29e43d04fc32f38f4f86cea45cd4e6ae98
https://github.com/juju/theblues/blob/f4431f29e43d04fc32f38f4f86cea45cd4e6ae98/theblues/identity_manager.py#L52-L62
train
Send user identity information to the identity manager.
juju/theblues
theblues/identity_manager.py
IdentityManager.discharge
def discharge(self, username, macaroon): """Discharge the macarooon for the identity. Raise a ServerError if an error occurs in the request process. @param username The logged in user. @param macaroon The macaroon returned from the charm store. @return The resulting base64 enco...
python
def discharge(self, username, macaroon): """Discharge the macarooon for the identity. Raise a ServerError if an error occurs in the request process. @param username The logged in user. @param macaroon The macaroon returned from the charm store. @return The resulting base64 enco...
[ "def", "discharge", "(", "self", ",", "username", ",", "macaroon", ")", ":", "caveats", "=", "macaroon", ".", "third_party_caveats", "(", ")", "if", "len", "(", "caveats", ")", "!=", "1", ":", "raise", "InvalidMacaroon", "(", "'Invalid number of third party ca...
Discharge the macarooon for the identity. Raise a ServerError if an error occurs in the request process. @param username The logged in user. @param macaroon The macaroon returned from the charm store. @return The resulting base64 encoded macaroon. @raises ServerError when makin...
[ "Discharge", "the", "macarooon", "for", "the", "identity", "." ]
f4431f29e43d04fc32f38f4f86cea45cd4e6ae98
https://github.com/juju/theblues/blob/f4431f29e43d04fc32f38f4f86cea45cd4e6ae98/theblues/identity_manager.py#L64-L92
train
Discharge the macarooon for the identity.
juju/theblues
theblues/identity_manager.py
IdentityManager.discharge_token
def discharge_token(self, username): """Discharge token for a user. Raise a ServerError if an error occurs in the request process. @param username The logged in user. @return The resulting base64 encoded discharged token. """ url = '{}discharge-token-for-user?username={...
python
def discharge_token(self, username): """Discharge token for a user. Raise a ServerError if an error occurs in the request process. @param username The logged in user. @return The resulting base64 encoded discharged token. """ url = '{}discharge-token-for-user?username={...
[ "def", "discharge_token", "(", "self", ",", "username", ")", ":", "url", "=", "'{}discharge-token-for-user?username={}'", ".", "format", "(", "self", ".", "url", ",", "quote", "(", "username", ")", ")", "logging", ".", "debug", "(", "'Sending identity info to {}...
Discharge token for a user. Raise a ServerError if an error occurs in the request process. @param username The logged in user. @return The resulting base64 encoded discharged token.
[ "Discharge", "token", "for", "a", "user", "." ]
f4431f29e43d04fc32f38f4f86cea45cd4e6ae98
https://github.com/juju/theblues/blob/f4431f29e43d04fc32f38f4f86cea45cd4e6ae98/theblues/identity_manager.py#L94-L113
train
Discharge a user s identity token.
juju/theblues
theblues/identity_manager.py
IdentityManager.set_extra_info
def set_extra_info(self, username, extra_info): """Set extra info for the given user. Raise a ServerError if an error occurs in the request process. @param username The username for the user to update. @param info The extra info as a JSON encoded string, or as a Python dict...
python
def set_extra_info(self, username, extra_info): """Set extra info for the given user. Raise a ServerError if an error occurs in the request process. @param username The username for the user to update. @param info The extra info as a JSON encoded string, or as a Python dict...
[ "def", "set_extra_info", "(", "self", ",", "username", ",", "extra_info", ")", ":", "url", "=", "self", ".", "_get_extra_info_url", "(", "username", ")", "make_request", "(", "url", ",", "method", "=", "'PUT'", ",", "body", "=", "extra_info", ",", "timeout...
Set extra info for the given user. Raise a ServerError if an error occurs in the request process. @param username The username for the user to update. @param info The extra info as a JSON encoded string, or as a Python dictionary like object.
[ "Set", "extra", "info", "for", "the", "given", "user", "." ]
f4431f29e43d04fc32f38f4f86cea45cd4e6ae98
https://github.com/juju/theblues/blob/f4431f29e43d04fc32f38f4f86cea45cd4e6ae98/theblues/identity_manager.py#L122-L132
train
Set extra info for the given user.
juju/theblues
theblues/identity_manager.py
IdentityManager.get_extra_info
def get_extra_info(self, username): """Get extra info for the given user. Raise a ServerError if an error occurs in the request process. @param username The username for the user who's info is being accessed. """ url = self._get_extra_info_url(username) return make_requ...
python
def get_extra_info(self, username): """Get extra info for the given user. Raise a ServerError if an error occurs in the request process. @param username The username for the user who's info is being accessed. """ url = self._get_extra_info_url(username) return make_requ...
[ "def", "get_extra_info", "(", "self", ",", "username", ")", ":", "url", "=", "self", ".", "_get_extra_info_url", "(", "username", ")", "return", "make_request", "(", "url", ",", "timeout", "=", "self", ".", "timeout", ")" ]
Get extra info for the given user. Raise a ServerError if an error occurs in the request process. @param username The username for the user who's info is being accessed.
[ "Get", "extra", "info", "for", "the", "given", "user", "." ]
f4431f29e43d04fc32f38f4f86cea45cd4e6ae98
https://github.com/juju/theblues/blob/f4431f29e43d04fc32f38f4f86cea45cd4e6ae98/theblues/identity_manager.py#L134-L142
train
Get extra info for the given user.
DarkEnergySurvey/ugali
ugali/isochrone/padova.py
Girardi2002._parse
def _parse(self,filename): """ Reads an isochrone in the old Padova format (Girardi 2002, Marigo 2008) and determines the age (log10 yrs and Gyr), metallicity (Z and [Fe/H]), and creates arrays with the initial stellar mass and corresponding magnitudes for each step along...
python
def _parse(self,filename): """ Reads an isochrone in the old Padova format (Girardi 2002, Marigo 2008) and determines the age (log10 yrs and Gyr), metallicity (Z and [Fe/H]), and creates arrays with the initial stellar mass and corresponding magnitudes for each step along...
[ "def", "_parse", "(", "self", ",", "filename", ")", ":", "try", ":", "columns", "=", "self", ".", "columns", "[", "self", ".", "survey", ".", "lower", "(", ")", "]", "except", "KeyError", "as", "e", ":", "logger", ".", "warning", "(", "'did not recog...
Reads an isochrone in the old Padova format (Girardi 2002, Marigo 2008) and determines the age (log10 yrs and Gyr), metallicity (Z and [Fe/H]), and creates arrays with the initial stellar mass and corresponding magnitudes for each step along the isochrone. http://stev.oapd.inaf.i...
[ "Reads", "an", "isochrone", "in", "the", "old", "Padova", "format", "(", "Girardi", "2002", "Marigo", "2008", ")", "and", "determines", "the", "age", "(", "log10", "yrs", "and", "Gyr", ")", "metallicity", "(", "Z", "and", "[", "Fe", "/", "H", "]", ")...
21e890b4117fc810afb6fb058e8055d564f03382
https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/isochrone/padova.py#L48-L84
train
Reads an ISOchrone from a file and parses the data into a dictionary of properties.
consbio/ncdjango
ncdjango/geoprocessing/params.py
ParameterCollection.is_complete
def is_complete(self): """Do all required parameters have values?""" return all(p.name in self.values for p in self.parameters if p.required)
python
def is_complete(self): """Do all required parameters have values?""" return all(p.name in self.values for p in self.parameters if p.required)
[ "def", "is_complete", "(", "self", ")", ":", "return", "all", "(", "p", ".", "name", "in", "self", ".", "values", "for", "p", "in", "self", ".", "parameters", "if", "p", ".", "required", ")" ]
Do all required parameters have values?
[ "Do", "all", "required", "parameters", "have", "values?" ]
f807bfd1e4083ab29fbc3c4d4418be108383a710
https://github.com/consbio/ncdjango/blob/f807bfd1e4083ab29fbc3c4d4418be108383a710/ncdjango/geoprocessing/params.py#L95-L98
train
Do all required parameters have values?
consbio/ncdjango
ncdjango/geoprocessing/params.py
MultiParameter.clean
def clean(self, value): """Cleans and returns the given value, or raises a ParameterNotValidError exception""" for parameter_obj in self.types: try: return parameter_obj.clean(value) except ParameterNotValidError: continue raise Parameter...
python
def clean(self, value): """Cleans and returns the given value, or raises a ParameterNotValidError exception""" for parameter_obj in self.types: try: return parameter_obj.clean(value) except ParameterNotValidError: continue raise Parameter...
[ "def", "clean", "(", "self", ",", "value", ")", ":", "for", "parameter_obj", "in", "self", ".", "types", ":", "try", ":", "return", "parameter_obj", ".", "clean", "(", "value", ")", "except", "ParameterNotValidError", ":", "continue", "raise", "ParameterNotV...
Cleans and returns the given value, or raises a ParameterNotValidError exception
[ "Cleans", "and", "returns", "the", "given", "value", "or", "raises", "a", "ParameterNotValidError", "exception" ]
f807bfd1e4083ab29fbc3c4d4418be108383a710
https://github.com/consbio/ncdjango/blob/f807bfd1e4083ab29fbc3c4d4418be108383a710/ncdjango/geoprocessing/params.py#L129-L138
train
Cleans and returns the given value
consbio/ncdjango
ncdjango/geoprocessing/params.py
MultiParameter.serialize_args
def serialize_args(self): """Returns (args, kwargs) to be used when deserializing this parameter.""" args, kwargs = super(MultiParameter, self).serialize_args() args.insert(0, [[t.id, t.serialize_args()] for t in self.types]) return args, kwargs
python
def serialize_args(self): """Returns (args, kwargs) to be used when deserializing this parameter.""" args, kwargs = super(MultiParameter, self).serialize_args() args.insert(0, [[t.id, t.serialize_args()] for t in self.types]) return args, kwargs
[ "def", "serialize_args", "(", "self", ")", ":", "args", ",", "kwargs", "=", "super", "(", "MultiParameter", ",", "self", ")", ".", "serialize_args", "(", ")", "args", ".", "insert", "(", "0", ",", "[", "[", "t", ".", "id", ",", "t", ".", "serialize...
Returns (args, kwargs) to be used when deserializing this parameter.
[ "Returns", "(", "args", "kwargs", ")", "to", "be", "used", "when", "deserializing", "this", "parameter", "." ]
f807bfd1e4083ab29fbc3c4d4418be108383a710
https://github.com/consbio/ncdjango/blob/f807bfd1e4083ab29fbc3c4d4418be108383a710/ncdjango/geoprocessing/params.py#L140-L146
train
Returns ( args kwargs ) to be used when deserializing this parameter.
consbio/ncdjango
ncdjango/geoprocessing/params.py
ListParameter.clean
def clean(self, value): """Cleans and returns the given value, or raises a ParameterNotValidError exception""" if not isinstance(value, (list, tuple, set, GeneratorType)): value = [value] gen = (self.param_type.clean(x) for x in value) if isinstance(value, GeneratorType): ...
python
def clean(self, value): """Cleans and returns the given value, or raises a ParameterNotValidError exception""" if not isinstance(value, (list, tuple, set, GeneratorType)): value = [value] gen = (self.param_type.clean(x) for x in value) if isinstance(value, GeneratorType): ...
[ "def", "clean", "(", "self", ",", "value", ")", ":", "if", "not", "isinstance", "(", "value", ",", "(", "list", ",", "tuple", ",", "set", ",", "GeneratorType", ")", ")", ":", "value", "=", "[", "value", "]", "gen", "=", "(", "self", ".", "param_t...
Cleans and returns the given value, or raises a ParameterNotValidError exception
[ "Cleans", "and", "returns", "the", "given", "value", "or", "raises", "a", "ParameterNotValidError", "exception" ]
f807bfd1e4083ab29fbc3c4d4418be108383a710
https://github.com/consbio/ncdjango/blob/f807bfd1e4083ab29fbc3c4d4418be108383a710/ncdjango/geoprocessing/params.py#L181-L192
train
Cleans and returns the given value or raises a ParameterNotValidError exception
consbio/ncdjango
ncdjango/geoprocessing/params.py
ListParameter.serialize_args
def serialize_args(self): """Returns (args, kwargs) to be used when deserializing this parameter.""" args, kwargs = super(ListParameter, self).serialize_args() args.insert(0, [self.param_type.id, self.param_type.serialize_args()])
python
def serialize_args(self): """Returns (args, kwargs) to be used when deserializing this parameter.""" args, kwargs = super(ListParameter, self).serialize_args() args.insert(0, [self.param_type.id, self.param_type.serialize_args()])
[ "def", "serialize_args", "(", "self", ")", ":", "args", ",", "kwargs", "=", "super", "(", "ListParameter", ",", "self", ")", ".", "serialize_args", "(", ")", "args", ".", "insert", "(", "0", ",", "[", "self", ".", "param_type", ".", "id", ",", "self"...
Returns (args, kwargs) to be used when deserializing this parameter.
[ "Returns", "(", "args", "kwargs", ")", "to", "be", "used", "when", "deserializing", "this", "parameter", "." ]
f807bfd1e4083ab29fbc3c4d4418be108383a710
https://github.com/consbio/ncdjango/blob/f807bfd1e4083ab29fbc3c4d4418be108383a710/ncdjango/geoprocessing/params.py#L194-L198
train
Returns ( args kwargs ) to be used when deserializing this parameter.
consbio/ncdjango
ncdjango/geoprocessing/params.py
StringParameter.clean
def clean(self, value): """Cleans and returns the given value, or raises a ParameterNotValidError exception""" if isinstance(value, six.string_types): return value elif isinstance(value, numbers.Number): return str(value) raise ParameterNotValidError
python
def clean(self, value): """Cleans and returns the given value, or raises a ParameterNotValidError exception""" if isinstance(value, six.string_types): return value elif isinstance(value, numbers.Number): return str(value) raise ParameterNotValidError
[ "def", "clean", "(", "self", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "six", ".", "string_types", ")", ":", "return", "value", "elif", "isinstance", "(", "value", ",", "numbers", ".", "Number", ")", ":", "return", "str", "(", "v...
Cleans and returns the given value, or raises a ParameterNotValidError exception
[ "Cleans", "and", "returns", "the", "given", "value", "or", "raises", "a", "ParameterNotValidError", "exception" ]
f807bfd1e4083ab29fbc3c4d4418be108383a710
https://github.com/consbio/ncdjango/blob/f807bfd1e4083ab29fbc3c4d4418be108383a710/ncdjango/geoprocessing/params.py#L217-L225
train
Cleans and returns the given value
consbio/ncdjango
ncdjango/geoprocessing/params.py
NumberParameter.clean
def clean(self, value): """Cleans and returns the given value, or raises a ParameterNotValidError exception""" if isinstance(value, numbers.Number): return value elif isinstance(value, six.string_types): try: value = float(value) return in...
python
def clean(self, value): """Cleans and returns the given value, or raises a ParameterNotValidError exception""" if isinstance(value, numbers.Number): return value elif isinstance(value, six.string_types): try: value = float(value) return in...
[ "def", "clean", "(", "self", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "numbers", ".", "Number", ")", ":", "return", "value", "elif", "isinstance", "(", "value", ",", "six", ".", "string_types", ")", ":", "try", ":", "value", "="...
Cleans and returns the given value, or raises a ParameterNotValidError exception
[ "Cleans", "and", "returns", "the", "given", "value", "or", "raises", "a", "ParameterNotValidError", "exception" ]
f807bfd1e4083ab29fbc3c4d4418be108383a710
https://github.com/consbio/ncdjango/blob/f807bfd1e4083ab29fbc3c4d4418be108383a710/ncdjango/geoprocessing/params.py#L233-L245
train
Cleans and returns the given value or raises a ParameterNotValidError exception
consbio/ncdjango
ncdjango/geoprocessing/params.py
BooleanParameter.clean
def clean(self, value): """Cleans and returns the given value, or raises a ParameterNotValidError exception""" if isinstance(value, six.string_types) and value.lower() == 'false': return False return bool(value)
python
def clean(self, value): """Cleans and returns the given value, or raises a ParameterNotValidError exception""" if isinstance(value, six.string_types) and value.lower() == 'false': return False return bool(value)
[ "def", "clean", "(", "self", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "six", ".", "string_types", ")", "and", "value", ".", "lower", "(", ")", "==", "'false'", ":", "return", "False", "return", "bool", "(", "value", ")" ]
Cleans and returns the given value, or raises a ParameterNotValidError exception
[ "Cleans", "and", "returns", "the", "given", "value", "or", "raises", "a", "ParameterNotValidError", "exception" ]
f807bfd1e4083ab29fbc3c4d4418be108383a710
https://github.com/consbio/ncdjango/blob/f807bfd1e4083ab29fbc3c4d4418be108383a710/ncdjango/geoprocessing/params.py#L275-L281
train
Cleans and returns the given value raises a ParameterNotValidError exception
consbio/ncdjango
ncdjango/geoprocessing/params.py
NdArrayParameter.clean
def clean(self, value): """Cleans and returns the given value, or raises a ParameterNotValidError exception""" if isinstance(value, numpy.ndarray): return value elif isinstance(value, (list, tuple)): return numpy.array(value) raise ParameterNotValidError
python
def clean(self, value): """Cleans and returns the given value, or raises a ParameterNotValidError exception""" if isinstance(value, numpy.ndarray): return value elif isinstance(value, (list, tuple)): return numpy.array(value) raise ParameterNotValidError
[ "def", "clean", "(", "self", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "numpy", ".", "ndarray", ")", ":", "return", "value", "elif", "isinstance", "(", "value", ",", "(", "list", ",", "tuple", ")", ")", ":", "return", "numpy", ...
Cleans and returns the given value, or raises a ParameterNotValidError exception
[ "Cleans", "and", "returns", "the", "given", "value", "or", "raises", "a", "ParameterNotValidError", "exception" ]
f807bfd1e4083ab29fbc3c4d4418be108383a710
https://github.com/consbio/ncdjango/blob/f807bfd1e4083ab29fbc3c4d4418be108383a710/ncdjango/geoprocessing/params.py#L303-L311
train
Cleans and returns the given value
consbio/ncdjango
ncdjango/geoprocessing/params.py
FeatureCollectionParameter.clean
def clean(self, value): """Cleans and returns the given value, or raises a ParameterNotValidError exception""" if isinstance(value, (list, tuple)): return [super(FeatureCollectionParameter, self).clean(x) for x in value] raise ParameterNotValidError
python
def clean(self, value): """Cleans and returns the given value, or raises a ParameterNotValidError exception""" if isinstance(value, (list, tuple)): return [super(FeatureCollectionParameter, self).clean(x) for x in value] raise ParameterNotValidError
[ "def", "clean", "(", "self", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "(", "list", ",", "tuple", ")", ")", ":", "return", "[", "super", "(", "FeatureCollectionParameter", ",", "self", ")", ".", "clean", "(", "x", ")", "for", "...
Cleans and returns the given value, or raises a ParameterNotValidError exception
[ "Cleans", "and", "returns", "the", "given", "value", "or", "raises", "a", "ParameterNotValidError", "exception" ]
f807bfd1e4083ab29fbc3c4d4418be108383a710
https://github.com/consbio/ncdjango/blob/f807bfd1e4083ab29fbc3c4d4418be108383a710/ncdjango/geoprocessing/params.py#L349-L355
train
Cleans and returns the given value or raises a ParameterNotValidError exception
consbio/ncdjango
ncdjango/geoprocessing/params.py
RegisteredDatasetParameter.clean
def clean(self, value): """Cleans and returns the given value, or raises a ParameterNotValidError exception""" if not isinstance(value, six.string_types): raise ParameterNotValidError try: source, value = value.split('://', 1) except ValueError: rais...
python
def clean(self, value): """Cleans and returns the given value, or raises a ParameterNotValidError exception""" if not isinstance(value, six.string_types): raise ParameterNotValidError try: source, value = value.split('://', 1) except ValueError: rais...
[ "def", "clean", "(", "self", ",", "value", ")", ":", "if", "not", "isinstance", "(", "value", ",", "six", ".", "string_types", ")", ":", "raise", "ParameterNotValidError", "try", ":", "source", ",", "value", "=", "value", ".", "split", "(", "'://'", ",...
Cleans and returns the given value, or raises a ParameterNotValidError exception
[ "Cleans", "and", "returns", "the", "given", "value", "or", "raises", "a", "ParameterNotValidError", "exception" ]
f807bfd1e4083ab29fbc3c4d4418be108383a710
https://github.com/consbio/ncdjango/blob/f807bfd1e4083ab29fbc3c4d4418be108383a710/ncdjango/geoprocessing/params.py#L394-L443
train
Cleans and returns the given value or raises a ParameterNotValidError exception
stevearc/dynamo3
dynamo3/batch.py
_encode_write
def _encode_write(dynamizer, data, action, key): """ Encode an item write command """ # Strip null values out of data data = dict(((k, dynamizer.encode(v)) for k, v in six.iteritems(data) if not is_null(v))) return { action: { key: data, } }
python
def _encode_write(dynamizer, data, action, key): """ Encode an item write command """ # Strip null values out of data data = dict(((k, dynamizer.encode(v)) for k, v in six.iteritems(data) if not is_null(v))) return { action: { key: data, } }
[ "def", "_encode_write", "(", "dynamizer", ",", "data", ",", "action", ",", "key", ")", ":", "# Strip null values out of data", "data", "=", "dict", "(", "(", "(", "k", ",", "dynamizer", ".", "encode", "(", "v", ")", ")", "for", "k", ",", "v", "in", "...
Encode an item write command
[ "Encode", "an", "item", "write", "command" ]
f897c40ece28586272dbcab8f0d99a14a1831dda
https://github.com/stevearc/dynamo3/blob/f897c40ece28586272dbcab8f0d99a14a1831dda/dynamo3/batch.py#L148-L157
train
Encode an item write command
stevearc/dynamo3
dynamo3/batch.py
encode_query_kwargs
def encode_query_kwargs(dynamizer, kwargs): """ Encode query constraints in Dynamo format """ ret = {} for k, v in six.iteritems(kwargs): if '__' not in k: raise TypeError("Invalid query argument '%s'" % k) name, condition_key = k.split('__') # Convert ==None to IS_NULL ...
python
def encode_query_kwargs(dynamizer, kwargs): """ Encode query constraints in Dynamo format """ ret = {} for k, v in six.iteritems(kwargs): if '__' not in k: raise TypeError("Invalid query argument '%s'" % k) name, condition_key = k.split('__') # Convert ==None to IS_NULL ...
[ "def", "encode_query_kwargs", "(", "dynamizer", ",", "kwargs", ")", ":", "ret", "=", "{", "}", "for", "k", ",", "v", "in", "six", ".", "iteritems", "(", "kwargs", ")", ":", "if", "'__'", "not", "in", "k", ":", "raise", "TypeError", "(", "\"Invalid qu...
Encode query constraints in Dynamo format
[ "Encode", "query", "constraints", "in", "Dynamo", "format" ]
f897c40ece28586272dbcab8f0d99a14a1831dda
https://github.com/stevearc/dynamo3/blob/f897c40ece28586272dbcab8f0d99a14a1831dda/dynamo3/batch.py#L165-L188
train
Encode query constraints in Dynamo format
stevearc/dynamo3
dynamo3/batch.py
ItemUpdate.attrs
def attrs(self, dynamizer): """ Get the attributes for the update """ ret = { self.key: { 'Action': self.action, } } if not is_null(self.value): ret[self.key]['Value'] = dynamizer.encode(self.value) return ret
python
def attrs(self, dynamizer): """ Get the attributes for the update """ ret = { self.key: { 'Action': self.action, } } if not is_null(self.value): ret[self.key]['Value'] = dynamizer.encode(self.value) return ret
[ "def", "attrs", "(", "self", ",", "dynamizer", ")", ":", "ret", "=", "{", "self", ".", "key", ":", "{", "'Action'", ":", "self", ".", "action", ",", "}", "}", "if", "not", "is_null", "(", "self", ".", "value", ")", ":", "ret", "[", "self", ".",...
Get the attributes for the update
[ "Get", "the", "attributes", "for", "the", "update" ]
f897c40ece28586272dbcab8f0d99a14a1831dda
https://github.com/stevearc/dynamo3/blob/f897c40ece28586272dbcab8f0d99a14a1831dda/dynamo3/batch.py#L109-L118
train
Get the attributes for the update
stevearc/dynamo3
dynamo3/batch.py
ItemUpdate.expected
def expected(self, dynamizer): """ Get the expected values for the update """ if self._expect_kwargs: return encode_query_kwargs(dynamizer, self._expect_kwargs) if self._expected is not NO_ARG: ret = {} if is_null(self._expected): ret['Exists']...
python
def expected(self, dynamizer): """ Get the expected values for the update """ if self._expect_kwargs: return encode_query_kwargs(dynamizer, self._expect_kwargs) if self._expected is not NO_ARG: ret = {} if is_null(self._expected): ret['Exists']...
[ "def", "expected", "(", "self", ",", "dynamizer", ")", ":", "if", "self", ".", "_expect_kwargs", ":", "return", "encode_query_kwargs", "(", "dynamizer", ",", "self", ".", "_expect_kwargs", ")", "if", "self", ".", "_expected", "is", "not", "NO_ARG", ":", "r...
Get the expected values for the update
[ "Get", "the", "expected", "values", "for", "the", "update" ]
f897c40ece28586272dbcab8f0d99a14a1831dda
https://github.com/stevearc/dynamo3/blob/f897c40ece28586272dbcab8f0d99a14a1831dda/dynamo3/batch.py#L120-L132
train
Get the expected values for the update
stevearc/dynamo3
dynamo3/batch.py
BatchWriter.put
def put(self, data): """ Write an item (will overwrite existing data) Parameters ---------- data : dict Item data """ self._to_put.append(data) if self.should_flush(): self.flush()
python
def put(self, data): """ Write an item (will overwrite existing data) Parameters ---------- data : dict Item data """ self._to_put.append(data) if self.should_flush(): self.flush()
[ "def", "put", "(", "self", ",", "data", ")", ":", "self", ".", "_to_put", ".", "append", "(", "data", ")", "if", "self", ".", "should_flush", "(", ")", ":", "self", ".", "flush", "(", ")" ]
Write an item (will overwrite existing data) Parameters ---------- data : dict Item data
[ "Write", "an", "item", "(", "will", "overwrite", "existing", "data", ")" ]
f897c40ece28586272dbcab8f0d99a14a1831dda
https://github.com/stevearc/dynamo3/blob/f897c40ece28586272dbcab8f0d99a14a1831dda/dynamo3/batch.py#L227-L240
train
Writes an item to the cache.
stevearc/dynamo3
dynamo3/batch.py
BatchWriter.delete
def delete(self, kwargs): """ Delete an item Parameters ---------- kwargs : dict The primary key of the item to delete """ self._to_delete.append(kwargs) if self.should_flush(): self.flush()
python
def delete(self, kwargs): """ Delete an item Parameters ---------- kwargs : dict The primary key of the item to delete """ self._to_delete.append(kwargs) if self.should_flush(): self.flush()
[ "def", "delete", "(", "self", ",", "kwargs", ")", ":", "self", ".", "_to_delete", ".", "append", "(", "kwargs", ")", "if", "self", ".", "should_flush", "(", ")", ":", "self", ".", "flush", "(", ")" ]
Delete an item Parameters ---------- kwargs : dict The primary key of the item to delete
[ "Delete", "an", "item" ]
f897c40ece28586272dbcab8f0d99a14a1831dda
https://github.com/stevearc/dynamo3/blob/f897c40ece28586272dbcab8f0d99a14a1831dda/dynamo3/batch.py#L242-L255
train
Delete an item from the cache.
stevearc/dynamo3
dynamo3/batch.py
BatchWriter.flush
def flush(self): """ Flush pending items to Dynamo """ items = [] for data in self._to_put: items.append(encode_put(self.connection.dynamizer, data)) for data in self._to_delete: items.append(encode_delete(self.connection.dynamizer, data)) self._write(it...
python
def flush(self): """ Flush pending items to Dynamo """ items = [] for data in self._to_put: items.append(encode_put(self.connection.dynamizer, data)) for data in self._to_delete: items.append(encode_delete(self.connection.dynamizer, data)) self._write(it...
[ "def", "flush", "(", "self", ")", ":", "items", "=", "[", "]", "for", "data", "in", "self", ".", "_to_put", ":", "items", ".", "append", "(", "encode_put", "(", "self", ".", "connection", ".", "dynamizer", ",", "data", ")", ")", "for", "data", "in"...
Flush pending items to Dynamo
[ "Flush", "pending", "items", "to", "Dynamo" ]
f897c40ece28586272dbcab8f0d99a14a1831dda
https://github.com/stevearc/dynamo3/blob/f897c40ece28586272dbcab8f0d99a14a1831dda/dynamo3/batch.py#L261-L272
train
Flush pending items to Dynamo
stevearc/dynamo3
dynamo3/batch.py
BatchWriter._write
def _write(self, items): """ Perform a batch write and handle the response """ response = self._batch_write_item(items) if 'consumed_capacity' in response: # Comes back as a list from BatchWriteItem self.consumed_capacity = \ sum(response['consumed_capacit...
python
def _write(self, items): """ Perform a batch write and handle the response """ response = self._batch_write_item(items) if 'consumed_capacity' in response: # Comes back as a list from BatchWriteItem self.consumed_capacity = \ sum(response['consumed_capacit...
[ "def", "_write", "(", "self", ",", "items", ")", ":", "response", "=", "self", ".", "_batch_write_item", "(", "items", ")", "if", "'consumed_capacity'", "in", "response", ":", "# Comes back as a list from BatchWriteItem", "self", ".", "consumed_capacity", "=", "su...
Perform a batch write and handle the response
[ "Perform", "a", "batch", "write", "and", "handle", "the", "response" ]
f897c40ece28586272dbcab8f0d99a14a1831dda
https://github.com/stevearc/dynamo3/blob/f897c40ece28586272dbcab8f0d99a14a1831dda/dynamo3/batch.py#L274-L299
train
Perform a batch write and handle the response
stevearc/dynamo3
dynamo3/batch.py
BatchWriter.resend_unprocessed
def resend_unprocessed(self): """ Resend all unprocessed items """ LOG.info("Re-sending %d unprocessed items.", len(self._unprocessed)) while self._unprocessed: to_resend = self._unprocessed[:MAX_WRITE_BATCH] self._unprocessed = self._unprocessed[MAX_WRITE_BATCH:] ...
python
def resend_unprocessed(self): """ Resend all unprocessed items """ LOG.info("Re-sending %d unprocessed items.", len(self._unprocessed)) while self._unprocessed: to_resend = self._unprocessed[:MAX_WRITE_BATCH] self._unprocessed = self._unprocessed[MAX_WRITE_BATCH:] ...
[ "def", "resend_unprocessed", "(", "self", ")", ":", "LOG", ".", "info", "(", "\"Re-sending %d unprocessed items.\"", ",", "len", "(", "self", ".", "_unprocessed", ")", ")", "while", "self", ".", "_unprocessed", ":", "to_resend", "=", "self", ".", "_unprocessed...
Resend all unprocessed items
[ "Resend", "all", "unprocessed", "items" ]
f897c40ece28586272dbcab8f0d99a14a1831dda
https://github.com/stevearc/dynamo3/blob/f897c40ece28586272dbcab8f0d99a14a1831dda/dynamo3/batch.py#L301-L310
train
Resend all unprocessed items.
stevearc/dynamo3
dynamo3/batch.py
BatchWriter._batch_write_item
def _batch_write_item(self, items): """ Make a BatchWriteItem call to Dynamo """ kwargs = { 'RequestItems': { self.tablename: items, }, 'ReturnConsumedCapacity': self.return_capacity, 'ReturnItemCollectionMetrics': self.return_item_collecti...
python
def _batch_write_item(self, items): """ Make a BatchWriteItem call to Dynamo """ kwargs = { 'RequestItems': { self.tablename: items, }, 'ReturnConsumedCapacity': self.return_capacity, 'ReturnItemCollectionMetrics': self.return_item_collecti...
[ "def", "_batch_write_item", "(", "self", ",", "items", ")", ":", "kwargs", "=", "{", "'RequestItems'", ":", "{", "self", ".", "tablename", ":", "items", ",", "}", ",", "'ReturnConsumedCapacity'", ":", "self", ".", "return_capacity", ",", "'ReturnItemCollection...
Make a BatchWriteItem call to Dynamo
[ "Make", "a", "BatchWriteItem", "call", "to", "Dynamo" ]
f897c40ece28586272dbcab8f0d99a14a1831dda
https://github.com/stevearc/dynamo3/blob/f897c40ece28586272dbcab8f0d99a14a1831dda/dynamo3/batch.py#L312-L321
train
Make a BatchWriteItem call to Dynamo