partition
stringclasses
3 values
func_name
stringlengths
1
134
docstring
stringlengths
1
46.9k
path
stringlengths
4
223
original_string
stringlengths
75
104k
code
stringlengths
75
104k
docstring_tokens
listlengths
1
1.97k
repo
stringlengths
7
55
language
stringclasses
1 value
url
stringlengths
87
315
code_tokens
listlengths
19
28.4k
sha
stringlengths
40
40
valid
dict_to_env
Convert a python dict to a dict containing valid environment variable values. :param d: Dict to convert to an env dict :param pathsep: Path separator used to join lists(default os.pathsep)
cpenv/utils.py
def dict_to_env(d, pathsep=os.pathsep): ''' Convert a python dict to a dict containing valid environment variable values. :param d: Dict to convert to an env dict :param pathsep: Path separator used to join lists(default os.pathsep) ''' out_env = {} for k, v in d.iteritems(): if isinstance(v, list): out_env[k] = pathsep.join(v) elif isinstance(v, string_types): out_env[k] = v else: raise TypeError('{} not a valid env var type'.format(type(v))) return out_env
def dict_to_env(d, pathsep=os.pathsep): ''' Convert a python dict to a dict containing valid environment variable values. :param d: Dict to convert to an env dict :param pathsep: Path separator used to join lists(default os.pathsep) ''' out_env = {} for k, v in d.iteritems(): if isinstance(v, list): out_env[k] = pathsep.join(v) elif isinstance(v, string_types): out_env[k] = v else: raise TypeError('{} not a valid env var type'.format(type(v))) return out_env
[ "Convert", "a", "python", "dict", "to", "a", "dict", "containing", "valid", "environment", "variable", "values", "." ]
cpenv/cpenv
python
https://github.com/cpenv/cpenv/blob/afbb569ae04002743db041d3629a5be8c290bd89/cpenv/utils.py#L282-L301
[ "def", "dict_to_env", "(", "d", ",", "pathsep", "=", "os", ".", "pathsep", ")", ":", "out_env", "=", "{", "}", "for", "k", ",", "v", "in", "d", ".", "iteritems", "(", ")", ":", "if", "isinstance", "(", "v", ",", "list", ")", ":", "out_env", "[", "k", "]", "=", "pathsep", ".", "join", "(", "v", ")", "elif", "isinstance", "(", "v", ",", "string_types", ")", ":", "out_env", "[", "k", "]", "=", "v", "else", ":", "raise", "TypeError", "(", "'{} not a valid env var type'", ".", "format", "(", "type", "(", "v", ")", ")", ")", "return", "out_env" ]
afbb569ae04002743db041d3629a5be8c290bd89
valid
expand_envvars
Expand all environment variables in an environment dict :param env: Environment dict
cpenv/utils.py
def expand_envvars(env): ''' Expand all environment variables in an environment dict :param env: Environment dict ''' out_env = {} for k, v in env.iteritems(): out_env[k] = Template(v).safe_substitute(env) # Expand twice to make sure we expand everything we possibly can for k, v in out_env.items(): out_env[k] = Template(v).safe_substitute(out_env) return out_env
def expand_envvars(env): ''' Expand all environment variables in an environment dict :param env: Environment dict ''' out_env = {} for k, v in env.iteritems(): out_env[k] = Template(v).safe_substitute(env) # Expand twice to make sure we expand everything we possibly can for k, v in out_env.items(): out_env[k] = Template(v).safe_substitute(out_env) return out_env
[ "Expand", "all", "environment", "variables", "in", "an", "environment", "dict" ]
cpenv/cpenv
python
https://github.com/cpenv/cpenv/blob/afbb569ae04002743db041d3629a5be8c290bd89/cpenv/utils.py#L304-L320
[ "def", "expand_envvars", "(", "env", ")", ":", "out_env", "=", "{", "}", "for", "k", ",", "v", "in", "env", ".", "iteritems", "(", ")", ":", "out_env", "[", "k", "]", "=", "Template", "(", "v", ")", ".", "safe_substitute", "(", "env", ")", "# Expand twice to make sure we expand everything we possibly can", "for", "k", ",", "v", "in", "out_env", ".", "items", "(", ")", ":", "out_env", "[", "k", "]", "=", "Template", "(", "v", ")", ".", "safe_substitute", "(", "out_env", ")", "return", "out_env" ]
afbb569ae04002743db041d3629a5be8c290bd89
valid
get_store_env_tmp
Returns an unused random filepath.
cpenv/utils.py
def get_store_env_tmp(): '''Returns an unused random filepath.''' tempdir = tempfile.gettempdir() temp_name = 'envstore{0:0>3d}' temp_path = unipath(tempdir, temp_name.format(random.getrandbits(9))) if not os.path.exists(temp_path): return temp_path else: return get_store_env_tmp()
def get_store_env_tmp(): '''Returns an unused random filepath.''' tempdir = tempfile.gettempdir() temp_name = 'envstore{0:0>3d}' temp_path = unipath(tempdir, temp_name.format(random.getrandbits(9))) if not os.path.exists(temp_path): return temp_path else: return get_store_env_tmp()
[ "Returns", "an", "unused", "random", "filepath", "." ]
cpenv/cpenv
python
https://github.com/cpenv/cpenv/blob/afbb569ae04002743db041d3629a5be8c290bd89/cpenv/utils.py#L323-L332
[ "def", "get_store_env_tmp", "(", ")", ":", "tempdir", "=", "tempfile", ".", "gettempdir", "(", ")", "temp_name", "=", "'envstore{0:0>3d}'", "temp_path", "=", "unipath", "(", "tempdir", ",", "temp_name", ".", "format", "(", "random", ".", "getrandbits", "(", "9", ")", ")", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "temp_path", ")", ":", "return", "temp_path", "else", ":", "return", "get_store_env_tmp", "(", ")" ]
afbb569ae04002743db041d3629a5be8c290bd89
valid
store_env
Encode current environment as yaml and store in path or a temporary file. Return the path to the stored environment.
cpenv/utils.py
def store_env(path=None): '''Encode current environment as yaml and store in path or a temporary file. Return the path to the stored environment. ''' path = path or get_store_env_tmp() env_dict = yaml.safe_dump(os.environ.data, default_flow_style=False) with open(path, 'w') as f: f.write(env_dict) return path
def store_env(path=None): '''Encode current environment as yaml and store in path or a temporary file. Return the path to the stored environment. ''' path = path or get_store_env_tmp() env_dict = yaml.safe_dump(os.environ.data, default_flow_style=False) with open(path, 'w') as f: f.write(env_dict) return path
[ "Encode", "current", "environment", "as", "yaml", "and", "store", "in", "path", "or", "a", "temporary", "file", ".", "Return", "the", "path", "to", "the", "stored", "environment", "." ]
cpenv/cpenv
python
https://github.com/cpenv/cpenv/blob/afbb569ae04002743db041d3629a5be8c290bd89/cpenv/utils.py#L335-L347
[ "def", "store_env", "(", "path", "=", "None", ")", ":", "path", "=", "path", "or", "get_store_env_tmp", "(", ")", "env_dict", "=", "yaml", ".", "safe_dump", "(", "os", ".", "environ", ".", "data", ",", "default_flow_style", "=", "False", ")", "with", "open", "(", "path", ",", "'w'", ")", "as", "f", ":", "f", ".", "write", "(", "env_dict", ")", "return", "path" ]
afbb569ae04002743db041d3629a5be8c290bd89
valid
restore_env
Set environment variables in the current python process from a dict containing envvars and values.
cpenv/utils.py
def restore_env(env_dict): '''Set environment variables in the current python process from a dict containing envvars and values.''' if hasattr(sys, 'real_prefix'): sys.prefix = sys.real_prefix del(sys.real_prefix) replace_osenviron(expand_envvars(dict_to_env(env_dict)))
def restore_env(env_dict): '''Set environment variables in the current python process from a dict containing envvars and values.''' if hasattr(sys, 'real_prefix'): sys.prefix = sys.real_prefix del(sys.real_prefix) replace_osenviron(expand_envvars(dict_to_env(env_dict)))
[ "Set", "environment", "variables", "in", "the", "current", "python", "process", "from", "a", "dict", "containing", "envvars", "and", "values", "." ]
cpenv/cpenv
python
https://github.com/cpenv/cpenv/blob/afbb569ae04002743db041d3629a5be8c290bd89/cpenv/utils.py#L350-L358
[ "def", "restore_env", "(", "env_dict", ")", ":", "if", "hasattr", "(", "sys", ",", "'real_prefix'", ")", ":", "sys", ".", "prefix", "=", "sys", ".", "real_prefix", "del", "(", "sys", ".", "real_prefix", ")", "replace_osenviron", "(", "expand_envvars", "(", "dict_to_env", "(", "env_dict", ")", ")", ")" ]
afbb569ae04002743db041d3629a5be8c290bd89
valid
restore_env_from_file
Restore the current environment from an environment stored in a yaml yaml file. :param env_file: Path to environment yaml file.
cpenv/utils.py
def restore_env_from_file(env_file): '''Restore the current environment from an environment stored in a yaml yaml file. :param env_file: Path to environment yaml file. ''' with open(env_file, 'r') as f: env_dict = yaml.load(f.read()) restore_env(env_dict)
def restore_env_from_file(env_file): '''Restore the current environment from an environment stored in a yaml yaml file. :param env_file: Path to environment yaml file. ''' with open(env_file, 'r') as f: env_dict = yaml.load(f.read()) restore_env(env_dict)
[ "Restore", "the", "current", "environment", "from", "an", "environment", "stored", "in", "a", "yaml", "yaml", "file", "." ]
cpenv/cpenv
python
https://github.com/cpenv/cpenv/blob/afbb569ae04002743db041d3629a5be8c290bd89/cpenv/utils.py#L361-L371
[ "def", "restore_env_from_file", "(", "env_file", ")", ":", "with", "open", "(", "env_file", ",", "'r'", ")", "as", "f", ":", "env_dict", "=", "yaml", ".", "load", "(", "f", ".", "read", "(", ")", ")", "restore_env", "(", "env_dict", ")" ]
afbb569ae04002743db041d3629a5be8c290bd89
valid
set_env
Set environment variables in the current python process from a dict containing envvars and values.
cpenv/utils.py
def set_env(*env_dicts): '''Set environment variables in the current python process from a dict containing envvars and values.''' old_env_dict = env_to_dict(os.environ.data) new_env_dict = join_dicts(old_env_dict, *env_dicts) new_env = dict_to_env(new_env_dict) replace_osenviron(expand_envvars(new_env))
def set_env(*env_dicts): '''Set environment variables in the current python process from a dict containing envvars and values.''' old_env_dict = env_to_dict(os.environ.data) new_env_dict = join_dicts(old_env_dict, *env_dicts) new_env = dict_to_env(new_env_dict) replace_osenviron(expand_envvars(new_env))
[ "Set", "environment", "variables", "in", "the", "current", "python", "process", "from", "a", "dict", "containing", "envvars", "and", "values", "." ]
cpenv/cpenv
python
https://github.com/cpenv/cpenv/blob/afbb569ae04002743db041d3629a5be8c290bd89/cpenv/utils.py#L374-L381
[ "def", "set_env", "(", "*", "env_dicts", ")", ":", "old_env_dict", "=", "env_to_dict", "(", "os", ".", "environ", ".", "data", ")", "new_env_dict", "=", "join_dicts", "(", "old_env_dict", ",", "*", "env_dicts", ")", "new_env", "=", "dict_to_env", "(", "new_env_dict", ")", "replace_osenviron", "(", "expand_envvars", "(", "new_env", ")", ")" ]
afbb569ae04002743db041d3629a5be8c290bd89
valid
set_env_from_file
Restore the current environment from an environment stored in a yaml yaml file. :param env_file: Path to environment yaml file.
cpenv/utils.py
def set_env_from_file(env_file): '''Restore the current environment from an environment stored in a yaml yaml file. :param env_file: Path to environment yaml file. ''' with open(env_file, 'r') as f: env_dict = yaml.load(f.read()) if 'environment' in env_dict: env_dict = env_dict['environment'] set_env(env_dict)
def set_env_from_file(env_file): '''Restore the current environment from an environment stored in a yaml yaml file. :param env_file: Path to environment yaml file. ''' with open(env_file, 'r') as f: env_dict = yaml.load(f.read()) if 'environment' in env_dict: env_dict = env_dict['environment'] set_env(env_dict)
[ "Restore", "the", "current", "environment", "from", "an", "environment", "stored", "in", "a", "yaml", "yaml", "file", "." ]
cpenv/cpenv
python
https://github.com/cpenv/cpenv/blob/afbb569ae04002743db041d3629a5be8c290bd89/cpenv/utils.py#L384-L397
[ "def", "set_env_from_file", "(", "env_file", ")", ":", "with", "open", "(", "env_file", ",", "'r'", ")", "as", "f", ":", "env_dict", "=", "yaml", ".", "load", "(", "f", ".", "read", "(", ")", ")", "if", "'environment'", "in", "env_dict", ":", "env_dict", "=", "env_dict", "[", "'environment'", "]", "set_env", "(", "env_dict", ")" ]
afbb569ae04002743db041d3629a5be8c290bd89
valid
BaseHandler.upstream_url
Returns the URL to the upstream data source for the given URI based on configuration
httpcache.py
def upstream_url(self, uri): "Returns the URL to the upstream data source for the given URI based on configuration" return self.application.options.upstream + self.request.uri
def upstream_url(self, uri): "Returns the URL to the upstream data source for the given URI based on configuration" return self.application.options.upstream + self.request.uri
[ "Returns", "the", "URL", "to", "the", "upstream", "data", "source", "for", "the", "given", "URI", "based", "on", "configuration" ]
langloisjp/pysvccache
python
https://github.com/langloisjp/pysvccache/blob/c4b95f1982f3a99e1f63341d15173099361e549b/httpcache.py#L62-L64
[ "def", "upstream_url", "(", "self", ",", "uri", ")", ":", "return", "self", ".", "application", ".", "options", ".", "upstream", "+", "self", ".", "request", ".", "uri" ]
c4b95f1982f3a99e1f63341d15173099361e549b
valid
BaseHandler.cache_get
Returns (headers, body) from the cache or raise KeyError
httpcache.py
def cache_get(self): "Returns (headers, body) from the cache or raise KeyError" key = self.cache_key() (headers, body, expires_ts) = self.application._cache[key] if expires_ts < time.now(): # asset has expired, delete it del self.application._cache[key] raise KeyError(key) return (headers, body)
def cache_get(self): "Returns (headers, body) from the cache or raise KeyError" key = self.cache_key() (headers, body, expires_ts) = self.application._cache[key] if expires_ts < time.now(): # asset has expired, delete it del self.application._cache[key] raise KeyError(key) return (headers, body)
[ "Returns", "(", "headers", "body", ")", "from", "the", "cache", "or", "raise", "KeyError" ]
langloisjp/pysvccache
python
https://github.com/langloisjp/pysvccache/blob/c4b95f1982f3a99e1f63341d15173099361e549b/httpcache.py#L70-L79
[ "def", "cache_get", "(", "self", ")", ":", "key", "=", "self", ".", "cache_key", "(", ")", "(", "headers", ",", "body", ",", "expires_ts", ")", "=", "self", ".", "application", ".", "_cache", "[", "key", "]", "if", "expires_ts", "<", "time", ".", "now", "(", ")", ":", "# asset has expired, delete it", "del", "self", ".", "application", ".", "_cache", "[", "key", "]", "raise", "KeyError", "(", "key", ")", "return", "(", "headers", ",", "body", ")" ]
c4b95f1982f3a99e1f63341d15173099361e549b
valid
ProxyHandler.make_upstream_request
Return request object for calling the upstream
httpcache.py
def make_upstream_request(self): "Return request object for calling the upstream" url = self.upstream_url(self.request.uri) return tornado.httpclient.HTTPRequest(url, method=self.request.method, headers=self.request.headers, body=self.request.body if self.request.body else None)
def make_upstream_request(self): "Return request object for calling the upstream" url = self.upstream_url(self.request.uri) return tornado.httpclient.HTTPRequest(url, method=self.request.method, headers=self.request.headers, body=self.request.body if self.request.body else None)
[ "Return", "request", "object", "for", "calling", "the", "upstream" ]
langloisjp/pysvccache
python
https://github.com/langloisjp/pysvccache/blob/c4b95f1982f3a99e1f63341d15173099361e549b/httpcache.py#L123-L129
[ "def", "make_upstream_request", "(", "self", ")", ":", "url", "=", "self", ".", "upstream_url", "(", "self", ".", "request", ".", "uri", ")", "return", "tornado", ".", "httpclient", ".", "HTTPRequest", "(", "url", ",", "method", "=", "self", ".", "request", ".", "method", ",", "headers", "=", "self", ".", "request", ".", "headers", ",", "body", "=", "self", ".", "request", ".", "body", "if", "self", ".", "request", ".", "body", "else", "None", ")" ]
c4b95f1982f3a99e1f63341d15173099361e549b
valid
ProxyHandler.ttl
Returns time to live in seconds. 0 means no caching. Criteria: - response code 200 - read-only method (GET, HEAD, OPTIONS) Plus http headers: - cache-control: option1, option2, ... where options are: private | public no-cache no-store max-age: seconds s-maxage: seconds must-revalidate proxy-revalidate - expires: Thu, 01 Dec 1983 20:00:00 GMT - pragma: no-cache (=cache-control: no-cache) See http://www.mobify.com/blog/beginners-guide-to-http-cache-headers/ TODO: tests
httpcache.py
def ttl(self, response): """Returns time to live in seconds. 0 means no caching. Criteria: - response code 200 - read-only method (GET, HEAD, OPTIONS) Plus http headers: - cache-control: option1, option2, ... where options are: private | public no-cache no-store max-age: seconds s-maxage: seconds must-revalidate proxy-revalidate - expires: Thu, 01 Dec 1983 20:00:00 GMT - pragma: no-cache (=cache-control: no-cache) See http://www.mobify.com/blog/beginners-guide-to-http-cache-headers/ TODO: tests """ if response.code != 200: return 0 if not self.request.method in ['GET', 'HEAD', 'OPTIONS']: return 0 try: pragma = self.request.headers['pragma'] if pragma == 'no-cache': return 0 except KeyError: pass try: cache_control = self.request.headers['cache-control'] # no caching options for option in ['private', 'no-cache', 'no-store', 'must-revalidate', 'proxy-revalidate']: if cache_control.find(option): return 0 # further parsing to get a ttl options = parse_cache_control(cache_control) try: return int(options['s-maxage']) except KeyError: pass try: return int(options['max-age']) except KeyError: pass if 's-maxage' in options: max_age = options['s-maxage'] if max_age < ttl: ttl = max_age if 'max-age' in options: max_age = options['max-age'] if max_age < ttl: ttl = max_age return ttl except KeyError: pass try: expires = self.request.headers['expires'] return time.mktime(time.strptime(expires, '%a, %d %b %Y %H:%M:%S')) - time.time() except KeyError: pass
def ttl(self, response): """Returns time to live in seconds. 0 means no caching. Criteria: - response code 200 - read-only method (GET, HEAD, OPTIONS) Plus http headers: - cache-control: option1, option2, ... where options are: private | public no-cache no-store max-age: seconds s-maxage: seconds must-revalidate proxy-revalidate - expires: Thu, 01 Dec 1983 20:00:00 GMT - pragma: no-cache (=cache-control: no-cache) See http://www.mobify.com/blog/beginners-guide-to-http-cache-headers/ TODO: tests """ if response.code != 200: return 0 if not self.request.method in ['GET', 'HEAD', 'OPTIONS']: return 0 try: pragma = self.request.headers['pragma'] if pragma == 'no-cache': return 0 except KeyError: pass try: cache_control = self.request.headers['cache-control'] # no caching options for option in ['private', 'no-cache', 'no-store', 'must-revalidate', 'proxy-revalidate']: if cache_control.find(option): return 0 # further parsing to get a ttl options = parse_cache_control(cache_control) try: return int(options['s-maxage']) except KeyError: pass try: return int(options['max-age']) except KeyError: pass if 's-maxage' in options: max_age = options['s-maxage'] if max_age < ttl: ttl = max_age if 'max-age' in options: max_age = options['max-age'] if max_age < ttl: ttl = max_age return ttl except KeyError: pass try: expires = self.request.headers['expires'] return time.mktime(time.strptime(expires, '%a, %d %b %Y %H:%M:%S')) - time.time() except KeyError: pass
[ "Returns", "time", "to", "live", "in", "seconds", ".", "0", "means", "no", "caching", "." ]
langloisjp/pysvccache
python
https://github.com/langloisjp/pysvccache/blob/c4b95f1982f3a99e1f63341d15173099361e549b/httpcache.py#L131-L197
[ "def", "ttl", "(", "self", ",", "response", ")", ":", "if", "response", ".", "code", "!=", "200", ":", "return", "0", "if", "not", "self", ".", "request", ".", "method", "in", "[", "'GET'", ",", "'HEAD'", ",", "'OPTIONS'", "]", ":", "return", "0", "try", ":", "pragma", "=", "self", ".", "request", ".", "headers", "[", "'pragma'", "]", "if", "pragma", "==", "'no-cache'", ":", "return", "0", "except", "KeyError", ":", "pass", "try", ":", "cache_control", "=", "self", ".", "request", ".", "headers", "[", "'cache-control'", "]", "# no caching options", "for", "option", "in", "[", "'private'", ",", "'no-cache'", ",", "'no-store'", ",", "'must-revalidate'", ",", "'proxy-revalidate'", "]", ":", "if", "cache_control", ".", "find", "(", "option", ")", ":", "return", "0", "# further parsing to get a ttl", "options", "=", "parse_cache_control", "(", "cache_control", ")", "try", ":", "return", "int", "(", "options", "[", "'s-maxage'", "]", ")", "except", "KeyError", ":", "pass", "try", ":", "return", "int", "(", "options", "[", "'max-age'", "]", ")", "except", "KeyError", ":", "pass", "if", "'s-maxage'", "in", "options", ":", "max_age", "=", "options", "[", "'s-maxage'", "]", "if", "max_age", "<", "ttl", ":", "ttl", "=", "max_age", "if", "'max-age'", "in", "options", ":", "max_age", "=", "options", "[", "'max-age'", "]", "if", "max_age", "<", "ttl", ":", "ttl", "=", "max_age", "return", "ttl", "except", "KeyError", ":", "pass", "try", ":", "expires", "=", "self", ".", "request", ".", "headers", "[", "'expires'", "]", "return", "time", ".", "mktime", "(", "time", ".", "strptime", "(", "expires", ",", "'%a, %d %b %Y %H:%M:%S'", ")", ")", "-", "time", ".", "time", "(", ")", "except", "KeyError", ":", "pass" ]
c4b95f1982f3a99e1f63341d15173099361e549b
valid
hist2d
Creates a 2-D histogram of data *x*, *y* with *bins*, *labels* = :code:`[title, xlabel, ylabel]`, aspect ration *aspect*. Attempts to use axis *ax* first, then the current axis of *fig*, then the last axis, to use an already-created window. Plotting (*plot*) is on by default, setting false doesn't attempt to create a figure. *interpolation* sets the interpolation type of :meth:`matplotlib.axis.imshow`. Returns a handle and extent as :code:`h, extent`
scisalt/matplotlib/hist2d.py
def hist2d(x, y, bins=10, labels=None, aspect="auto", plot=True, fig=None, ax=None, interpolation='none', cbar=True, **kwargs): """ Creates a 2-D histogram of data *x*, *y* with *bins*, *labels* = :code:`[title, xlabel, ylabel]`, aspect ration *aspect*. Attempts to use axis *ax* first, then the current axis of *fig*, then the last axis, to use an already-created window. Plotting (*plot*) is on by default, setting false doesn't attempt to create a figure. *interpolation* sets the interpolation type of :meth:`matplotlib.axis.imshow`. Returns a handle and extent as :code:`h, extent` """ h_range = kwargs.pop('range', None) h_normed = kwargs.pop('normed', None) h_weights = kwargs.pop('weights', None) h, xe, ye = _np.histogram2d(x, y, bins=bins, range=h_range, normed=h_normed, weights=h_weights) extent = [xe[0], xe[-1], ye[0], ye[-1]] # fig = plt.figure() if plot: if ax is None: if fig is None: fig = _figure('hist2d') ax = fig.gca() ax.clear() img = ax.imshow(h.transpose(), extent=extent, interpolation=interpolation, aspect=aspect, **kwargs) if cbar: _colorbar(ax=ax, im=img) if labels is not None: _addlabel(labels[0], labels[1], labels[2]) # _showfig(fig, aspect) return h, extent
def hist2d(x, y, bins=10, labels=None, aspect="auto", plot=True, fig=None, ax=None, interpolation='none', cbar=True, **kwargs): """ Creates a 2-D histogram of data *x*, *y* with *bins*, *labels* = :code:`[title, xlabel, ylabel]`, aspect ration *aspect*. Attempts to use axis *ax* first, then the current axis of *fig*, then the last axis, to use an already-created window. Plotting (*plot*) is on by default, setting false doesn't attempt to create a figure. *interpolation* sets the interpolation type of :meth:`matplotlib.axis.imshow`. Returns a handle and extent as :code:`h, extent` """ h_range = kwargs.pop('range', None) h_normed = kwargs.pop('normed', None) h_weights = kwargs.pop('weights', None) h, xe, ye = _np.histogram2d(x, y, bins=bins, range=h_range, normed=h_normed, weights=h_weights) extent = [xe[0], xe[-1], ye[0], ye[-1]] # fig = plt.figure() if plot: if ax is None: if fig is None: fig = _figure('hist2d') ax = fig.gca() ax.clear() img = ax.imshow(h.transpose(), extent=extent, interpolation=interpolation, aspect=aspect, **kwargs) if cbar: _colorbar(ax=ax, im=img) if labels is not None: _addlabel(labels[0], labels[1], labels[2]) # _showfig(fig, aspect) return h, extent
[ "Creates", "a", "2", "-", "D", "histogram", "of", "data", "*", "x", "*", "*", "y", "*", "with", "*", "bins", "*", "*", "labels", "*", "=", ":", "code", ":", "[", "title", "xlabel", "ylabel", "]", "aspect", "ration", "*", "aspect", "*", ".", "Attempts", "to", "use", "axis", "*", "ax", "*", "first", "then", "the", "current", "axis", "of", "*", "fig", "*", "then", "the", "last", "axis", "to", "use", "an", "already", "-", "created", "window", ".", "Plotting", "(", "*", "plot", "*", ")", "is", "on", "by", "default", "setting", "false", "doesn", "t", "attempt", "to", "create", "a", "figure", "." ]
joelfrederico/SciSalt
python
https://github.com/joelfrederico/SciSalt/blob/7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f/scisalt/matplotlib/hist2d.py#L12-L44
[ "def", "hist2d", "(", "x", ",", "y", ",", "bins", "=", "10", ",", "labels", "=", "None", ",", "aspect", "=", "\"auto\"", ",", "plot", "=", "True", ",", "fig", "=", "None", ",", "ax", "=", "None", ",", "interpolation", "=", "'none'", ",", "cbar", "=", "True", ",", "*", "*", "kwargs", ")", ":", "h_range", "=", "kwargs", ".", "pop", "(", "'range'", ",", "None", ")", "h_normed", "=", "kwargs", ".", "pop", "(", "'normed'", ",", "None", ")", "h_weights", "=", "kwargs", ".", "pop", "(", "'weights'", ",", "None", ")", "h", ",", "xe", ",", "ye", "=", "_np", ".", "histogram2d", "(", "x", ",", "y", ",", "bins", "=", "bins", ",", "range", "=", "h_range", ",", "normed", "=", "h_normed", ",", "weights", "=", "h_weights", ")", "extent", "=", "[", "xe", "[", "0", "]", ",", "xe", "[", "-", "1", "]", ",", "ye", "[", "0", "]", ",", "ye", "[", "-", "1", "]", "]", "# fig = plt.figure()", "if", "plot", ":", "if", "ax", "is", "None", ":", "if", "fig", "is", "None", ":", "fig", "=", "_figure", "(", "'hist2d'", ")", "ax", "=", "fig", ".", "gca", "(", ")", "ax", ".", "clear", "(", ")", "img", "=", "ax", ".", "imshow", "(", "h", ".", "transpose", "(", ")", ",", "extent", "=", "extent", ",", "interpolation", "=", "interpolation", ",", "aspect", "=", "aspect", ",", "*", "*", "kwargs", ")", "if", "cbar", ":", "_colorbar", "(", "ax", "=", "ax", ",", "im", "=", "img", ")", "if", "labels", "is", "not", "None", ":", "_addlabel", "(", "labels", "[", "0", "]", ",", "labels", "[", "1", "]", ",", "labels", "[", "2", "]", ")", "# _showfig(fig, aspect)", "return", "h", ",", "extent" ]
7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f
valid
Plasma.w_p
Plasma frequency :math:`\\omega_p` for given plasma density
scisalt/PWFA/plasma.py
def w_p(self): """ Plasma frequency :math:`\\omega_p` for given plasma density """ return _np.sqrt(self.n_p * _np.power(_spc.e, 2) / (_spc.m_e * _spc.epsilon_0))
def w_p(self): """ Plasma frequency :math:`\\omega_p` for given plasma density """ return _np.sqrt(self.n_p * _np.power(_spc.e, 2) / (_spc.m_e * _spc.epsilon_0))
[ "Plasma", "frequency", ":", "math", ":", "\\\\", "omega_p", "for", "given", "plasma", "density" ]
joelfrederico/SciSalt
python
https://github.com/joelfrederico/SciSalt/blob/7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f/scisalt/PWFA/plasma.py#L82-L86
[ "def", "w_p", "(", "self", ")", ":", "return", "_np", ".", "sqrt", "(", "self", ".", "n_p", "*", "_np", ".", "power", "(", "_spc", ".", "e", ",", "2", ")", "/", "(", "_spc", ".", "m_e", "*", "_spc", ".", "epsilon_0", ")", ")" ]
7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f
valid
Plasma.k_ion
Geometric focusing force due to ion column for given plasma density as a function of *E*
scisalt/PWFA/plasma.py
def k_ion(self, E): """ Geometric focusing force due to ion column for given plasma density as a function of *E* """ return self.n_p * _np.power(_spc.e, 2) / (2*_sltr.GeV2joule(E) * _spc.epsilon_0)
def k_ion(self, E): """ Geometric focusing force due to ion column for given plasma density as a function of *E* """ return self.n_p * _np.power(_spc.e, 2) / (2*_sltr.GeV2joule(E) * _spc.epsilon_0)
[ "Geometric", "focusing", "force", "due", "to", "ion", "column", "for", "given", "plasma", "density", "as", "a", "function", "of", "*", "E", "*" ]
joelfrederico/SciSalt
python
https://github.com/joelfrederico/SciSalt/blob/7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f/scisalt/PWFA/plasma.py#L88-L92
[ "def", "k_ion", "(", "self", ",", "E", ")", ":", "return", "self", ".", "n_p", "*", "_np", ".", "power", "(", "_spc", ".", "e", ",", "2", ")", "/", "(", "2", "*", "_sltr", ".", "GeV2joule", "(", "E", ")", "*", "_spc", ".", "epsilon_0", ")" ]
7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f
valid
manifest
Guarantee the existence of a basic MANIFEST.in. manifest doc: http://docs.python.org/distutils/sourcedist.html#manifest `options.paved.dist.manifest.include`: set of files (or globs) to include with the `include` directive. `options.paved.dist.manifest.recursive_include`: set of files (or globs) to include with the `recursive-include` directive. `options.paved.dist.manifest.prune`: set of files (or globs) to exclude with the `prune` directive. `options.paved.dist.manifest.include_sphinx_docroot`: True -> sphinx docroot is added as `graft` `options.paved.dist.manifest.include_sphinx_docroot`: True -> sphinx builddir is added as `prune`
paved/dist.py
def manifest(): """Guarantee the existence of a basic MANIFEST.in. manifest doc: http://docs.python.org/distutils/sourcedist.html#manifest `options.paved.dist.manifest.include`: set of files (or globs) to include with the `include` directive. `options.paved.dist.manifest.recursive_include`: set of files (or globs) to include with the `recursive-include` directive. `options.paved.dist.manifest.prune`: set of files (or globs) to exclude with the `prune` directive. `options.paved.dist.manifest.include_sphinx_docroot`: True -> sphinx docroot is added as `graft` `options.paved.dist.manifest.include_sphinx_docroot`: True -> sphinx builddir is added as `prune` """ prune = options.paved.dist.manifest.prune graft = set() if options.paved.dist.manifest.include_sphinx_docroot: docroot = options.get('docroot', 'docs') graft.update([docroot]) if options.paved.dist.manifest.exclude_sphinx_builddir: builddir = docroot + '/' + options.get("builddir", ".build") prune.update([builddir]) with open(options.paved.cwd / 'MANIFEST.in', 'w') as fo: for item in graft: fo.write('graft %s\n' % item) for item in options.paved.dist.manifest.include: fo.write('include %s\n' % item) for item in options.paved.dist.manifest.recursive_include: fo.write('recursive-include %s\n' % item) for item in prune: fo.write('prune %s\n' % item)
def manifest(): """Guarantee the existence of a basic MANIFEST.in. manifest doc: http://docs.python.org/distutils/sourcedist.html#manifest `options.paved.dist.manifest.include`: set of files (or globs) to include with the `include` directive. `options.paved.dist.manifest.recursive_include`: set of files (or globs) to include with the `recursive-include` directive. `options.paved.dist.manifest.prune`: set of files (or globs) to exclude with the `prune` directive. `options.paved.dist.manifest.include_sphinx_docroot`: True -> sphinx docroot is added as `graft` `options.paved.dist.manifest.include_sphinx_docroot`: True -> sphinx builddir is added as `prune` """ prune = options.paved.dist.manifest.prune graft = set() if options.paved.dist.manifest.include_sphinx_docroot: docroot = options.get('docroot', 'docs') graft.update([docroot]) if options.paved.dist.manifest.exclude_sphinx_builddir: builddir = docroot + '/' + options.get("builddir", ".build") prune.update([builddir]) with open(options.paved.cwd / 'MANIFEST.in', 'w') as fo: for item in graft: fo.write('graft %s\n' % item) for item in options.paved.dist.manifest.include: fo.write('include %s\n' % item) for item in options.paved.dist.manifest.recursive_include: fo.write('recursive-include %s\n' % item) for item in prune: fo.write('prune %s\n' % item)
[ "Guarantee", "the", "existence", "of", "a", "basic", "MANIFEST", ".", "in", "." ]
eykd/paved
python
https://github.com/eykd/paved/blob/f04f8a4248c571f3d5ce882b325884a3e5d80203/paved/dist.py#L42-L77
[ "def", "manifest", "(", ")", ":", "prune", "=", "options", ".", "paved", ".", "dist", ".", "manifest", ".", "prune", "graft", "=", "set", "(", ")", "if", "options", ".", "paved", ".", "dist", ".", "manifest", ".", "include_sphinx_docroot", ":", "docroot", "=", "options", ".", "get", "(", "'docroot'", ",", "'docs'", ")", "graft", ".", "update", "(", "[", "docroot", "]", ")", "if", "options", ".", "paved", ".", "dist", ".", "manifest", ".", "exclude_sphinx_builddir", ":", "builddir", "=", "docroot", "+", "'/'", "+", "options", ".", "get", "(", "\"builddir\"", ",", "\".build\"", ")", "prune", ".", "update", "(", "[", "builddir", "]", ")", "with", "open", "(", "options", ".", "paved", ".", "cwd", "/", "'MANIFEST.in'", ",", "'w'", ")", "as", "fo", ":", "for", "item", "in", "graft", ":", "fo", ".", "write", "(", "'graft %s\\n'", "%", "item", ")", "for", "item", "in", "options", ".", "paved", ".", "dist", ".", "manifest", ".", "include", ":", "fo", ".", "write", "(", "'include %s\\n'", "%", "item", ")", "for", "item", "in", "options", ".", "paved", ".", "dist", ".", "manifest", ".", "recursive_include", ":", "fo", ".", "write", "(", "'recursive-include %s\\n'", "%", "item", ")", "for", "item", "in", "prune", ":", "fo", ".", "write", "(", "'prune %s\\n'", "%", "item", ")" ]
f04f8a4248c571f3d5ce882b325884a3e5d80203
valid
accessor
This template tag is used to do complex nested attribute accessing of an object. The first parameter is the object being accessed, subsequent paramters are one of: * a variable in the template context * a literal in the template context * either of the above surrounded in square brackets For each variable or literal parameter given a `getattr` is called on the object, chaining to the next parameter. For any sqaure bracket enclosed items the access is done through a dictionary lookup. Example:: {% accessor car where 'front_seat' [position] ['fabric'] %} The above would result in the following chain of commands: .. code-block:: python ref = getattr(car, where) ref = getattr(ref, 'front_seat') ref = ref[position] return ref['fabric'] This tag also supports "as" syntax, putting the results into a template variable:: {% accessor car 'interior' as foo %}
awl/templatetags/awltags.py
def accessor(parser, token): """This template tag is used to do complex nested attribute accessing of an object. The first parameter is the object being accessed, subsequent paramters are one of: * a variable in the template context * a literal in the template context * either of the above surrounded in square brackets For each variable or literal parameter given a `getattr` is called on the object, chaining to the next parameter. For any sqaure bracket enclosed items the access is done through a dictionary lookup. Example:: {% accessor car where 'front_seat' [position] ['fabric'] %} The above would result in the following chain of commands: .. code-block:: python ref = getattr(car, where) ref = getattr(ref, 'front_seat') ref = ref[position] return ref['fabric'] This tag also supports "as" syntax, putting the results into a template variable:: {% accessor car 'interior' as foo %} """ contents = token.split_contents() tag = contents[0] if len(contents) < 3: raise template.TemplateSyntaxError(('%s requires at least two ' 'arguments: object and one or more getattr parms') % tag) as_var = None if len(contents) >= 4: # check for "as" syntax if contents[-2] == 'as': as_var = contents[-1] contents = contents[:-2] return AccessorNode(contents[1], contents[2:], as_var)
def accessor(parser, token): """This template tag is used to do complex nested attribute accessing of an object. The first parameter is the object being accessed, subsequent paramters are one of: * a variable in the template context * a literal in the template context * either of the above surrounded in square brackets For each variable or literal parameter given a `getattr` is called on the object, chaining to the next parameter. For any sqaure bracket enclosed items the access is done through a dictionary lookup. Example:: {% accessor car where 'front_seat' [position] ['fabric'] %} The above would result in the following chain of commands: .. code-block:: python ref = getattr(car, where) ref = getattr(ref, 'front_seat') ref = ref[position] return ref['fabric'] This tag also supports "as" syntax, putting the results into a template variable:: {% accessor car 'interior' as foo %} """ contents = token.split_contents() tag = contents[0] if len(contents) < 3: raise template.TemplateSyntaxError(('%s requires at least two ' 'arguments: object and one or more getattr parms') % tag) as_var = None if len(contents) >= 4: # check for "as" syntax if contents[-2] == 'as': as_var = contents[-1] contents = contents[:-2] return AccessorNode(contents[1], contents[2:], as_var)
[ "This", "template", "tag", "is", "used", "to", "do", "complex", "nested", "attribute", "accessing", "of", "an", "object", ".", "The", "first", "parameter", "is", "the", "object", "being", "accessed", "subsequent", "paramters", "are", "one", "of", ":" ]
cltrudeau/django-awl
python
https://github.com/cltrudeau/django-awl/blob/70d469ef9a161c1170b53aa017cf02d7c15eb90c/awl/templatetags/awltags.py#L40-L84
[ "def", "accessor", "(", "parser", ",", "token", ")", ":", "contents", "=", "token", ".", "split_contents", "(", ")", "tag", "=", "contents", "[", "0", "]", "if", "len", "(", "contents", ")", "<", "3", ":", "raise", "template", ".", "TemplateSyntaxError", "(", "(", "'%s requires at least two '", "'arguments: object and one or more getattr parms'", ")", "%", "tag", ")", "as_var", "=", "None", "if", "len", "(", "contents", ")", ">=", "4", ":", "# check for \"as\" syntax", "if", "contents", "[", "-", "2", "]", "==", "'as'", ":", "as_var", "=", "contents", "[", "-", "1", "]", "contents", "=", "contents", "[", ":", "-", "2", "]", "return", "AccessorNode", "(", "contents", "[", "1", "]", ",", "contents", "[", "2", ":", "]", ",", "as_var", ")" ]
70d469ef9a161c1170b53aa017cf02d7c15eb90c
valid
get_field_value_from_context
Helper to get field value from string path. String '<context>' is used to go up on context stack. It just can be used at the beginning of path: <context>.<context>.field_name_1 On the other hand, '<root>' is used to start lookup from first item on context.
dirty_validators/complex.py
def get_field_value_from_context(field_name, context_list): """ Helper to get field value from string path. String '<context>' is used to go up on context stack. It just can be used at the beginning of path: <context>.<context>.field_name_1 On the other hand, '<root>' is used to start lookup from first item on context. """ field_path = field_name.split('.') if field_path[0] == '<root>': context_index = 0 field_path.pop(0) else: context_index = -1 while field_path[0] == '<context>': context_index -= 1 field_path.pop(0) try: field_value = context_list[context_index] while len(field_path): field = field_path.pop(0) if isinstance(field_value, (list, tuple, ListModel)): if field.isdigit(): field = int(field) field_value = field_value[field] elif isinstance(field_value, dict): try: field_value = field_value[field] except KeyError: if field.isdigit(): field = int(field) field_value = field_value[field] else: field_value = None else: field_value = getattr(field_value, field) return field_value except (IndexError, AttributeError, KeyError, TypeError): return None
def get_field_value_from_context(field_name, context_list): """ Helper to get field value from string path. String '<context>' is used to go up on context stack. It just can be used at the beginning of path: <context>.<context>.field_name_1 On the other hand, '<root>' is used to start lookup from first item on context. """ field_path = field_name.split('.') if field_path[0] == '<root>': context_index = 0 field_path.pop(0) else: context_index = -1 while field_path[0] == '<context>': context_index -= 1 field_path.pop(0) try: field_value = context_list[context_index] while len(field_path): field = field_path.pop(0) if isinstance(field_value, (list, tuple, ListModel)): if field.isdigit(): field = int(field) field_value = field_value[field] elif isinstance(field_value, dict): try: field_value = field_value[field] except KeyError: if field.isdigit(): field = int(field) field_value = field_value[field] else: field_value = None else: field_value = getattr(field_value, field) return field_value except (IndexError, AttributeError, KeyError, TypeError): return None
[ "Helper", "to", "get", "field", "value", "from", "string", "path", ".", "String", "<context", ">", "is", "used", "to", "go", "up", "on", "context", "stack", ".", "It", "just", "can", "be", "used", "at", "the", "beginning", "of", "path", ":", "<context", ">", ".", "<context", ">", ".", "field_name_1", "On", "the", "other", "hand", "<root", ">", "is", "used", "to", "start", "lookup", "from", "first", "item", "on", "context", "." ]
alfred82santa/dirty-validators
python
https://github.com/alfred82santa/dirty-validators/blob/95af84fb8e6452c8a6d88af496cbdb31bca7a608/dirty_validators/complex.py#L214-L256
[ "def", "get_field_value_from_context", "(", "field_name", ",", "context_list", ")", ":", "field_path", "=", "field_name", ".", "split", "(", "'.'", ")", "if", "field_path", "[", "0", "]", "==", "'<root>'", ":", "context_index", "=", "0", "field_path", ".", "pop", "(", "0", ")", "else", ":", "context_index", "=", "-", "1", "while", "field_path", "[", "0", "]", "==", "'<context>'", ":", "context_index", "-=", "1", "field_path", ".", "pop", "(", "0", ")", "try", ":", "field_value", "=", "context_list", "[", "context_index", "]", "while", "len", "(", "field_path", ")", ":", "field", "=", "field_path", ".", "pop", "(", "0", ")", "if", "isinstance", "(", "field_value", ",", "(", "list", ",", "tuple", ",", "ListModel", ")", ")", ":", "if", "field", ".", "isdigit", "(", ")", ":", "field", "=", "int", "(", "field", ")", "field_value", "=", "field_value", "[", "field", "]", "elif", "isinstance", "(", "field_value", ",", "dict", ")", ":", "try", ":", "field_value", "=", "field_value", "[", "field", "]", "except", "KeyError", ":", "if", "field", ".", "isdigit", "(", ")", ":", "field", "=", "int", "(", "field", ")", "field_value", "=", "field_value", "[", "field", "]", "else", ":", "field_value", "=", "None", "else", ":", "field_value", "=", "getattr", "(", "field_value", ",", "field", ")", "return", "field_value", "except", "(", "IndexError", ",", "AttributeError", ",", "KeyError", ",", "TypeError", ")", ":", "return", "None" ]
95af84fb8e6452c8a6d88af496cbdb31bca7a608
valid
create_threadpool_executed_func
Returns a function wrapper that defers function calls execute inside gevent's threadpool but keeps any exception or backtrace in the caller's context. :param original_func: function to wrap :returns: wrapper function
src/infi/gevent_utils/deferred.py
def create_threadpool_executed_func(original_func): """ Returns a function wrapper that defers function calls execute inside gevent's threadpool but keeps any exception or backtrace in the caller's context. :param original_func: function to wrap :returns: wrapper function """ def wrapped_func(*args, **kwargs): try: result = original_func(*args, **kwargs) return True, result except: return False, sys.exc_info() def new_func(*args, **kwargs): status, result = gevent.get_hub().threadpool.apply(wrapped_func, args, kwargs) if status: return result else: six.reraise(*result) new_func.__name__ = original_func.__name__ new_func.__doc__ = "(gevent-friendly)" + (" " + original_func.__doc__ if original_func.__doc__ is not None else "") return new_func
def create_threadpool_executed_func(original_func): """ Returns a function wrapper that defers function calls execute inside gevent's threadpool but keeps any exception or backtrace in the caller's context. :param original_func: function to wrap :returns: wrapper function """ def wrapped_func(*args, **kwargs): try: result = original_func(*args, **kwargs) return True, result except: return False, sys.exc_info() def new_func(*args, **kwargs): status, result = gevent.get_hub().threadpool.apply(wrapped_func, args, kwargs) if status: return result else: six.reraise(*result) new_func.__name__ = original_func.__name__ new_func.__doc__ = "(gevent-friendly)" + (" " + original_func.__doc__ if original_func.__doc__ is not None else "") return new_func
[ "Returns", "a", "function", "wrapper", "that", "defers", "function", "calls", "execute", "inside", "gevent", "s", "threadpool", "but", "keeps", "any", "exception", "or", "backtrace", "in", "the", "caller", "s", "context", ".", ":", "param", "original_func", ":", "function", "to", "wrap", ":", "returns", ":", "wrapper", "function" ]
Infinidat/infi.gevent_utils
python
https://github.com/Infinidat/infi.gevent_utils/blob/7eb3c1601b8f2c9aaa3a83154ee7dfce8e5e5a5a/src/infi/gevent_utils/deferred.py#L6-L28
[ "def", "create_threadpool_executed_func", "(", "original_func", ")", ":", "def", "wrapped_func", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "result", "=", "original_func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "True", ",", "result", "except", ":", "return", "False", ",", "sys", ".", "exc_info", "(", ")", "def", "new_func", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "status", ",", "result", "=", "gevent", ".", "get_hub", "(", ")", ".", "threadpool", ".", "apply", "(", "wrapped_func", ",", "args", ",", "kwargs", ")", "if", "status", ":", "return", "result", "else", ":", "six", ".", "reraise", "(", "*", "result", ")", "new_func", ".", "__name__", "=", "original_func", ".", "__name__", "new_func", ".", "__doc__", "=", "\"(gevent-friendly)\"", "+", "(", "\" \"", "+", "original_func", ".", "__doc__", "if", "original_func", ".", "__doc__", "is", "not", "None", "else", "\"\"", ")", "return", "new_func" ]
7eb3c1601b8f2c9aaa3a83154ee7dfce8e5e5a5a
valid
format_pathname
Format a pathname :param str pathname: Pathname to format :param int max_length: Maximum length of result pathname (> 3) :return: Formatted pathname :rtype: str :raises ValueError: If *max_length* is not larger than 3 This function formats a pathname so it is not longer than *max_length* characters. The resulting pathname is returned. It does so by replacing characters at the start of the *pathname* with three dots, if necessary. The idea is that the end of the *pathname* is the most important part to be able to identify the file.
starling/flask/template_filter.py
def format_pathname( pathname, max_length): """ Format a pathname :param str pathname: Pathname to format :param int max_length: Maximum length of result pathname (> 3) :return: Formatted pathname :rtype: str :raises ValueError: If *max_length* is not larger than 3 This function formats a pathname so it is not longer than *max_length* characters. The resulting pathname is returned. It does so by replacing characters at the start of the *pathname* with three dots, if necessary. The idea is that the end of the *pathname* is the most important part to be able to identify the file. """ if max_length <= 3: raise ValueError("max length must be larger than 3") if len(pathname) > max_length: pathname = "...{}".format(pathname[-(max_length-3):]) return pathname
def format_pathname( pathname, max_length): """ Format a pathname :param str pathname: Pathname to format :param int max_length: Maximum length of result pathname (> 3) :return: Formatted pathname :rtype: str :raises ValueError: If *max_length* is not larger than 3 This function formats a pathname so it is not longer than *max_length* characters. The resulting pathname is returned. It does so by replacing characters at the start of the *pathname* with three dots, if necessary. The idea is that the end of the *pathname* is the most important part to be able to identify the file. """ if max_length <= 3: raise ValueError("max length must be larger than 3") if len(pathname) > max_length: pathname = "...{}".format(pathname[-(max_length-3):]) return pathname
[ "Format", "a", "pathname" ]
geoneric/starling
python
https://github.com/geoneric/starling/blob/a8e1324c4d6e8b063a0d353bcd03bb8e57edd888/starling/flask/template_filter.py#L9-L33
[ "def", "format_pathname", "(", "pathname", ",", "max_length", ")", ":", "if", "max_length", "<=", "3", ":", "raise", "ValueError", "(", "\"max length must be larger than 3\"", ")", "if", "len", "(", "pathname", ")", ">", "max_length", ":", "pathname", "=", "\"...{}\"", ".", "format", "(", "pathname", "[", "-", "(", "max_length", "-", "3", ")", ":", "]", ")", "return", "pathname" ]
a8e1324c4d6e8b063a0d353bcd03bb8e57edd888
valid
format_time_point
:param str time_point_string: String representation of a time point to format :return: Formatted time point :rtype: str :raises ValueError: If *time_point_string* is not formatted by dateutil.parser.parse See :py:meth:`datetime.datetime.isoformat` function for supported formats.
starling/flask/template_filter.py
def format_time_point( time_point_string): """ :param str time_point_string: String representation of a time point to format :return: Formatted time point :rtype: str :raises ValueError: If *time_point_string* is not formatted by dateutil.parser.parse See :py:meth:`datetime.datetime.isoformat` function for supported formats. """ time_point = dateutil.parser.parse(time_point_string) if not is_aware(time_point): time_point = make_aware(time_point) time_point = local_time_point(time_point) return time_point.strftime("%Y-%m-%dT%H:%M:%S")
def format_time_point( time_point_string): """ :param str time_point_string: String representation of a time point to format :return: Formatted time point :rtype: str :raises ValueError: If *time_point_string* is not formatted by dateutil.parser.parse See :py:meth:`datetime.datetime.isoformat` function for supported formats. """ time_point = dateutil.parser.parse(time_point_string) if not is_aware(time_point): time_point = make_aware(time_point) time_point = local_time_point(time_point) return time_point.strftime("%Y-%m-%dT%H:%M:%S")
[ ":", "param", "str", "time_point_string", ":", "String", "representation", "of", "a", "time", "point", "to", "format", ":", "return", ":", "Formatted", "time", "point", ":", "rtype", ":", "str", ":", "raises", "ValueError", ":", "If", "*", "time_point_string", "*", "is", "not", "formatted", "by", "dateutil", ".", "parser", ".", "parse" ]
geoneric/starling
python
https://github.com/geoneric/starling/blob/a8e1324c4d6e8b063a0d353bcd03bb8e57edd888/starling/flask/template_filter.py#L36-L56
[ "def", "format_time_point", "(", "time_point_string", ")", ":", "time_point", "=", "dateutil", ".", "parser", ".", "parse", "(", "time_point_string", ")", "if", "not", "is_aware", "(", "time_point", ")", ":", "time_point", "=", "make_aware", "(", "time_point", ")", "time_point", "=", "local_time_point", "(", "time_point", ")", "return", "time_point", ".", "strftime", "(", "\"%Y-%m-%dT%H:%M:%S\"", ")" ]
a8e1324c4d6e8b063a0d353bcd03bb8e57edd888
valid
format_uuid
Format a UUID string :param str uuid: UUID to format :param int max_length: Maximum length of result string (> 3) :return: Formatted UUID :rtype: str :raises ValueError: If *max_length* is not larger than 3 This function formats a UUID so it is not longer than *max_length* characters. The resulting string is returned. It does so by replacing characters at the end of the *uuid* with three dots, if necessary. The idea is that the start of the *uuid* is the most important part to be able to identify the related entity. The default *max_length* is 10, which will result in a string containing the first 7 characters of the *uuid* passed in. Most of the time, such a string is still unique within a collection of UUIDs.
starling/flask/template_filter.py
def format_uuid( uuid, max_length=10): """ Format a UUID string :param str uuid: UUID to format :param int max_length: Maximum length of result string (> 3) :return: Formatted UUID :rtype: str :raises ValueError: If *max_length* is not larger than 3 This function formats a UUID so it is not longer than *max_length* characters. The resulting string is returned. It does so by replacing characters at the end of the *uuid* with three dots, if necessary. The idea is that the start of the *uuid* is the most important part to be able to identify the related entity. The default *max_length* is 10, which will result in a string containing the first 7 characters of the *uuid* passed in. Most of the time, such a string is still unique within a collection of UUIDs. """ if max_length <= 3: raise ValueError("max length must be larger than 3") if len(uuid) > max_length: uuid = "{}...".format(uuid[0:max_length-3]) return uuid
def format_uuid( uuid, max_length=10): """ Format a UUID string :param str uuid: UUID to format :param int max_length: Maximum length of result string (> 3) :return: Formatted UUID :rtype: str :raises ValueError: If *max_length* is not larger than 3 This function formats a UUID so it is not longer than *max_length* characters. The resulting string is returned. It does so by replacing characters at the end of the *uuid* with three dots, if necessary. The idea is that the start of the *uuid* is the most important part to be able to identify the related entity. The default *max_length* is 10, which will result in a string containing the first 7 characters of the *uuid* passed in. Most of the time, such a string is still unique within a collection of UUIDs. """ if max_length <= 3: raise ValueError("max length must be larger than 3") if len(uuid) > max_length: uuid = "{}...".format(uuid[0:max_length-3]) return uuid
[ "Format", "a", "UUID", "string" ]
geoneric/starling
python
https://github.com/geoneric/starling/blob/a8e1324c4d6e8b063a0d353bcd03bb8e57edd888/starling/flask/template_filter.py#L59-L87
[ "def", "format_uuid", "(", "uuid", ",", "max_length", "=", "10", ")", ":", "if", "max_length", "<=", "3", ":", "raise", "ValueError", "(", "\"max length must be larger than 3\"", ")", "if", "len", "(", "uuid", ")", ">", "max_length", ":", "uuid", "=", "\"{}...\"", ".", "format", "(", "uuid", "[", "0", ":", "max_length", "-", "3", "]", ")", "return", "uuid" ]
a8e1324c4d6e8b063a0d353bcd03bb8e57edd888
valid
chisquare
Finds the reduced chi square difference of *observe* and *expect* with a given *error* and *ddof* degrees of freedom. *verbose* flag determines if the reduced chi square is printed to the terminal.
scisalt/scipy/chisquare.py
def chisquare(observe, expect, error, ddof, verbose=True): """ Finds the reduced chi square difference of *observe* and *expect* with a given *error* and *ddof* degrees of freedom. *verbose* flag determines if the reduced chi square is printed to the terminal. """ chisq = 0 error = error.flatten() observe = observe.flatten() expect = expect.flatten() for i, el in enumerate(observe): chisq = chisq + _np.power((el - expect[i]) / error[i], 2) red_chisq = chisq / (len(observe) - ddof) if verbose: # print 'Chi-Squared is {}.'.format(chisq) print('Reduced Chi-Squared is {}.'.format(red_chisq)) return red_chisq
def chisquare(observe, expect, error, ddof, verbose=True): """ Finds the reduced chi square difference of *observe* and *expect* with a given *error* and *ddof* degrees of freedom. *verbose* flag determines if the reduced chi square is printed to the terminal. """ chisq = 0 error = error.flatten() observe = observe.flatten() expect = expect.flatten() for i, el in enumerate(observe): chisq = chisq + _np.power((el - expect[i]) / error[i], 2) red_chisq = chisq / (len(observe) - ddof) if verbose: # print 'Chi-Squared is {}.'.format(chisq) print('Reduced Chi-Squared is {}.'.format(red_chisq)) return red_chisq
[ "Finds", "the", "reduced", "chi", "square", "difference", "of", "*", "observe", "*", "and", "*", "expect", "*", "with", "a", "given", "*", "error", "*", "and", "*", "ddof", "*", "degrees", "of", "freedom", "." ]
joelfrederico/SciSalt
python
https://github.com/joelfrederico/SciSalt/blob/7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f/scisalt/scipy/chisquare.py#L7-L25
[ "def", "chisquare", "(", "observe", ",", "expect", ",", "error", ",", "ddof", ",", "verbose", "=", "True", ")", ":", "chisq", "=", "0", "error", "=", "error", ".", "flatten", "(", ")", "observe", "=", "observe", ".", "flatten", "(", ")", "expect", "=", "expect", ".", "flatten", "(", ")", "for", "i", ",", "el", "in", "enumerate", "(", "observe", ")", ":", "chisq", "=", "chisq", "+", "_np", ".", "power", "(", "(", "el", "-", "expect", "[", "i", "]", ")", "/", "error", "[", "i", "]", ",", "2", ")", "red_chisq", "=", "chisq", "/", "(", "len", "(", "observe", ")", "-", "ddof", ")", "if", "verbose", ":", "# print 'Chi-Squared is {}.'.format(chisq)", "print", "(", "'Reduced Chi-Squared is {}.'", ".", "format", "(", "red_chisq", ")", ")", "return", "red_chisq" ]
7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f
valid
frexp10
Finds the mantissa and exponent of a number :math:`x` such that :math:`x = m 10^e`. Parameters ---------- x : float Number :math:`x` such that :math:`x = m 10^e`. Returns ------- mantissa : float Number :math:`m` such that :math:`x = m 10^e`. exponent : float Number :math:`e` such that :math:`x = m 10^e`.
scisalt/numpy/frexp10.py
def frexp10(x): """ Finds the mantissa and exponent of a number :math:`x` such that :math:`x = m 10^e`. Parameters ---------- x : float Number :math:`x` such that :math:`x = m 10^e`. Returns ------- mantissa : float Number :math:`m` such that :math:`x = m 10^e`. exponent : float Number :math:`e` such that :math:`x = m 10^e`. """ expon = _np.int(_np.floor(_np.log10(_np.abs(x)))) mant = x/_np.power(10, expon) return (mant, expon)
def frexp10(x): """ Finds the mantissa and exponent of a number :math:`x` such that :math:`x = m 10^e`. Parameters ---------- x : float Number :math:`x` such that :math:`x = m 10^e`. Returns ------- mantissa : float Number :math:`m` such that :math:`x = m 10^e`. exponent : float Number :math:`e` such that :math:`x = m 10^e`. """ expon = _np.int(_np.floor(_np.log10(_np.abs(x)))) mant = x/_np.power(10, expon) return (mant, expon)
[ "Finds", "the", "mantissa", "and", "exponent", "of", "a", "number", ":", "math", ":", "x", "such", "that", ":", "math", ":", "x", "=", "m", "10^e", "." ]
joelfrederico/SciSalt
python
https://github.com/joelfrederico/SciSalt/blob/7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f/scisalt/numpy/frexp10.py#L7-L27
[ "def", "frexp10", "(", "x", ")", ":", "expon", "=", "_np", ".", "int", "(", "_np", ".", "floor", "(", "_np", ".", "log10", "(", "_np", ".", "abs", "(", "x", ")", ")", ")", ")", "mant", "=", "x", "/", "_np", ".", "power", "(", "10", ",", "expon", ")", "return", "(", "mant", ",", "expon", ")" ]
7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f
valid
get_upcoming_events_count
Returns count of upcoming events for a given number of days, either featured or all Usage: {% get_upcoming_events_count DAYS as events_count %} with days being the number of days you want, or 5 by default
build/lib/happenings/templatetags/event_tags.py
def get_upcoming_events_count(days=14, featured=False): """ Returns count of upcoming events for a given number of days, either featured or all Usage: {% get_upcoming_events_count DAYS as events_count %} with days being the number of days you want, or 5 by default """ from happenings.models import Event start_period = today - datetime.timedelta(days=2) end_period = today + datetime.timedelta(days=days) if featured: return Event.objects.filter( featured=True, start_date__gte=start_period, start_date__lte=end_period ).count() return Event.objects.filter(start_date__gte=start_period, start_date__lte=end_period).count()
def get_upcoming_events_count(days=14, featured=False): """ Returns count of upcoming events for a given number of days, either featured or all Usage: {% get_upcoming_events_count DAYS as events_count %} with days being the number of days you want, or 5 by default """ from happenings.models import Event start_period = today - datetime.timedelta(days=2) end_period = today + datetime.timedelta(days=days) if featured: return Event.objects.filter( featured=True, start_date__gte=start_period, start_date__lte=end_period ).count() return Event.objects.filter(start_date__gte=start_period, start_date__lte=end_period).count()
[ "Returns", "count", "of", "upcoming", "events", "for", "a", "given", "number", "of", "days", "either", "featured", "or", "all", "Usage", ":", "{", "%", "get_upcoming_events_count", "DAYS", "as", "events_count", "%", "}", "with", "days", "being", "the", "number", "of", "days", "you", "want", "or", "5", "by", "default" ]
tBaxter/tango-happenings
python
https://github.com/tBaxter/tango-happenings/blob/cb3c49ea39e0a6cef9c6ffb534c2fbf401139ba2/build/lib/happenings/templatetags/event_tags.py#L11-L27
[ "def", "get_upcoming_events_count", "(", "days", "=", "14", ",", "featured", "=", "False", ")", ":", "from", "happenings", ".", "models", "import", "Event", "start_period", "=", "today", "-", "datetime", ".", "timedelta", "(", "days", "=", "2", ")", "end_period", "=", "today", "+", "datetime", ".", "timedelta", "(", "days", "=", "days", ")", "if", "featured", ":", "return", "Event", ".", "objects", ".", "filter", "(", "featured", "=", "True", ",", "start_date__gte", "=", "start_period", ",", "start_date__lte", "=", "end_period", ")", ".", "count", "(", ")", "return", "Event", ".", "objects", ".", "filter", "(", "start_date__gte", "=", "start_period", ",", "start_date__lte", "=", "end_period", ")", ".", "count", "(", ")" ]
cb3c49ea39e0a6cef9c6ffb534c2fbf401139ba2
valid
get_upcoming_events
Get upcoming events. Allows slicing to a given number, picking the number of days to hold them after they've started and whether they should be featured or not. Usage: {% get_upcoming_events 5 14 featured as events %} Would return no more than 5 Featured events, holding them for 14 days past their start date.
build/lib/happenings/templatetags/event_tags.py
def get_upcoming_events(num, days, featured=False): """ Get upcoming events. Allows slicing to a given number, picking the number of days to hold them after they've started and whether they should be featured or not. Usage: {% get_upcoming_events 5 14 featured as events %} Would return no more than 5 Featured events, holding them for 14 days past their start date. """ from happenings.models import Event start_date = today - datetime.timedelta(days=days) events = Event.objects.filter(start_date__gt=start_date).order_by('start_date') if featured: events = events.filter(featured=True) events = events[:num] return events
def get_upcoming_events(num, days, featured=False): """ Get upcoming events. Allows slicing to a given number, picking the number of days to hold them after they've started and whether they should be featured or not. Usage: {% get_upcoming_events 5 14 featured as events %} Would return no more than 5 Featured events, holding them for 14 days past their start date. """ from happenings.models import Event start_date = today - datetime.timedelta(days=days) events = Event.objects.filter(start_date__gt=start_date).order_by('start_date') if featured: events = events.filter(featured=True) events = events[:num] return events
[ "Get", "upcoming", "events", ".", "Allows", "slicing", "to", "a", "given", "number", "picking", "the", "number", "of", "days", "to", "hold", "them", "after", "they", "ve", "started", "and", "whether", "they", "should", "be", "featured", "or", "not", ".", "Usage", ":", "{", "%", "get_upcoming_events", "5", "14", "featured", "as", "events", "%", "}", "Would", "return", "no", "more", "than", "5", "Featured", "events", "holding", "them", "for", "14", "days", "past", "their", "start", "date", "." ]
tBaxter/tango-happenings
python
https://github.com/tBaxter/tango-happenings/blob/cb3c49ea39e0a6cef9c6ffb534c2fbf401139ba2/build/lib/happenings/templatetags/event_tags.py#L31-L49
[ "def", "get_upcoming_events", "(", "num", ",", "days", ",", "featured", "=", "False", ")", ":", "from", "happenings", ".", "models", "import", "Event", "start_date", "=", "today", "-", "datetime", ".", "timedelta", "(", "days", "=", "days", ")", "events", "=", "Event", ".", "objects", ".", "filter", "(", "start_date__gt", "=", "start_date", ")", ".", "order_by", "(", "'start_date'", ")", "if", "featured", ":", "events", "=", "events", ".", "filter", "(", "featured", "=", "True", ")", "events", "=", "events", "[", ":", "num", "]", "return", "events" ]
cb3c49ea39e0a6cef9c6ffb534c2fbf401139ba2
valid
get_events_by_date_range
Get upcoming events for a given number of days (days out) Allows specifying number of days to hold events after they've started The max number to show (defaults to 5) and whether they should be featured or not. Usage: {% get_events_by_date_range 14 3 3 'featured' as events %} Would return no more than 3 featured events, that fall within the next 14 days or have ended within the past 3.
build/lib/happenings/templatetags/event_tags.py
def get_events_by_date_range(days_out, days_hold, max_num=5, featured=False): """ Get upcoming events for a given number of days (days out) Allows specifying number of days to hold events after they've started The max number to show (defaults to 5) and whether they should be featured or not. Usage: {% get_events_by_date_range 14 3 3 'featured' as events %} Would return no more than 3 featured events, that fall within the next 14 days or have ended within the past 3. """ from happenings.models import Event range_start = today - datetime.timedelta(days=days_hold) range_end = today + datetime.timedelta(days=days_out) events = Event.objects.filter( start_date__gte=range_start, start_date__lte=range_end ).order_by('start_date') if featured: events = events.filter(featured=True) events = events[:max_num] return events
def get_events_by_date_range(days_out, days_hold, max_num=5, featured=False): """ Get upcoming events for a given number of days (days out) Allows specifying number of days to hold events after they've started The max number to show (defaults to 5) and whether they should be featured or not. Usage: {% get_events_by_date_range 14 3 3 'featured' as events %} Would return no more than 3 featured events, that fall within the next 14 days or have ended within the past 3. """ from happenings.models import Event range_start = today - datetime.timedelta(days=days_hold) range_end = today + datetime.timedelta(days=days_out) events = Event.objects.filter( start_date__gte=range_start, start_date__lte=range_end ).order_by('start_date') if featured: events = events.filter(featured=True) events = events[:max_num] return events
[ "Get", "upcoming", "events", "for", "a", "given", "number", "of", "days", "(", "days", "out", ")", "Allows", "specifying", "number", "of", "days", "to", "hold", "events", "after", "they", "ve", "started", "The", "max", "number", "to", "show", "(", "defaults", "to", "5", ")", "and", "whether", "they", "should", "be", "featured", "or", "not", ".", "Usage", ":", "{", "%", "get_events_by_date_range", "14", "3", "3", "featured", "as", "events", "%", "}", "Would", "return", "no", "more", "than", "3", "featured", "events", "that", "fall", "within", "the", "next", "14", "days", "or", "have", "ended", "within", "the", "past", "3", "." ]
tBaxter/tango-happenings
python
https://github.com/tBaxter/tango-happenings/blob/cb3c49ea39e0a6cef9c6ffb534c2fbf401139ba2/build/lib/happenings/templatetags/event_tags.py#L53-L75
[ "def", "get_events_by_date_range", "(", "days_out", ",", "days_hold", ",", "max_num", "=", "5", ",", "featured", "=", "False", ")", ":", "from", "happenings", ".", "models", "import", "Event", "range_start", "=", "today", "-", "datetime", ".", "timedelta", "(", "days", "=", "days_hold", ")", "range_end", "=", "today", "+", "datetime", ".", "timedelta", "(", "days", "=", "days_out", ")", "events", "=", "Event", ".", "objects", ".", "filter", "(", "start_date__gte", "=", "range_start", ",", "start_date__lte", "=", "range_end", ")", ".", "order_by", "(", "'start_date'", ")", "if", "featured", ":", "events", "=", "events", ".", "filter", "(", "featured", "=", "True", ")", "events", "=", "events", "[", ":", "max_num", "]", "return", "events" ]
cb3c49ea39e0a6cef9c6ffb534c2fbf401139ba2
valid
paginate_update
attempts to get next and previous on updates
build/lib/happenings/templatetags/event_tags.py
def paginate_update(update): """ attempts to get next and previous on updates """ from happenings.models import Update time = update.pub_time event = update.event try: next = Update.objects.filter( event=event, pub_time__gt=time ).order_by('pub_time').only('title')[0] except: next = None try: previous = Update.objects.filter( event=event, pub_time__lt=time ).order_by('-pub_time').only('title')[0] except: previous = None return {'next': next, 'previous': previous, 'event': event}
def paginate_update(update): """ attempts to get next and previous on updates """ from happenings.models import Update time = update.pub_time event = update.event try: next = Update.objects.filter( event=event, pub_time__gt=time ).order_by('pub_time').only('title')[0] except: next = None try: previous = Update.objects.filter( event=event, pub_time__lt=time ).order_by('-pub_time').only('title')[0] except: previous = None return {'next': next, 'previous': previous, 'event': event}
[ "attempts", "to", "get", "next", "and", "previous", "on", "updates" ]
tBaxter/tango-happenings
python
https://github.com/tBaxter/tango-happenings/blob/cb3c49ea39e0a6cef9c6ffb534c2fbf401139ba2/build/lib/happenings/templatetags/event_tags.py#L99-L120
[ "def", "paginate_update", "(", "update", ")", ":", "from", "happenings", ".", "models", "import", "Update", "time", "=", "update", ".", "pub_time", "event", "=", "update", ".", "event", "try", ":", "next", "=", "Update", ".", "objects", ".", "filter", "(", "event", "=", "event", ",", "pub_time__gt", "=", "time", ")", ".", "order_by", "(", "'pub_time'", ")", ".", "only", "(", "'title'", ")", "[", "0", "]", "except", ":", "next", "=", "None", "try", ":", "previous", "=", "Update", ".", "objects", ".", "filter", "(", "event", "=", "event", ",", "pub_time__lt", "=", "time", ")", ".", "order_by", "(", "'-pub_time'", ")", ".", "only", "(", "'title'", ")", "[", "0", "]", "except", ":", "previous", "=", "None", "return", "{", "'next'", ":", "next", ",", "'previous'", ":", "previous", ",", "'event'", ":", "event", "}" ]
cb3c49ea39e0a6cef9c6ffb534c2fbf401139ba2
valid
notify_client
Notify the client of the result of handling a request The payload contains two elements: - client_id - result The *client_id* is the id of the client to notify. It is assumed that the notifier service is able to identify the client by this id and that it can pass the *result* to it. The *result* always contains a *status_code* element. In case the message passed in is not None, it will also contain a *message* element. In case the notifier service does not exist or returns an error, an error message will be logged to *stderr*.
starling/pika/decorator.py
def notify_client( notifier_uri, client_id, status_code, message=None): """ Notify the client of the result of handling a request The payload contains two elements: - client_id - result The *client_id* is the id of the client to notify. It is assumed that the notifier service is able to identify the client by this id and that it can pass the *result* to it. The *result* always contains a *status_code* element. In case the message passed in is not None, it will also contain a *message* element. In case the notifier service does not exist or returns an error, an error message will be logged to *stderr*. """ payload = { "client_id": client_id, "result": { "response": { "status_code": status_code } } } if message is not None: payload["result"]["response"]["message"] = message response = requests.post(notifier_uri, json=payload) if response.status_code != 201: sys.stderr.write("failed to notify client: {}\n".format(payload)) sys.stderr.flush()
def notify_client( notifier_uri, client_id, status_code, message=None): """ Notify the client of the result of handling a request The payload contains two elements: - client_id - result The *client_id* is the id of the client to notify. It is assumed that the notifier service is able to identify the client by this id and that it can pass the *result* to it. The *result* always contains a *status_code* element. In case the message passed in is not None, it will also contain a *message* element. In case the notifier service does not exist or returns an error, an error message will be logged to *stderr*. """ payload = { "client_id": client_id, "result": { "response": { "status_code": status_code } } } if message is not None: payload["result"]["response"]["message"] = message response = requests.post(notifier_uri, json=payload) if response.status_code != 201: sys.stderr.write("failed to notify client: {}\n".format(payload)) sys.stderr.flush()
[ "Notify", "the", "client", "of", "the", "result", "of", "handling", "a", "request" ]
geoneric/starling
python
https://github.com/geoneric/starling/blob/a8e1324c4d6e8b063a0d353bcd03bb8e57edd888/starling/pika/decorator.py#L7-L47
[ "def", "notify_client", "(", "notifier_uri", ",", "client_id", ",", "status_code", ",", "message", "=", "None", ")", ":", "payload", "=", "{", "\"client_id\"", ":", "client_id", ",", "\"result\"", ":", "{", "\"response\"", ":", "{", "\"status_code\"", ":", "status_code", "}", "}", "}", "if", "message", "is", "not", "None", ":", "payload", "[", "\"result\"", "]", "[", "\"response\"", "]", "[", "\"message\"", "]", "=", "message", "response", "=", "requests", ".", "post", "(", "notifier_uri", ",", "json", "=", "payload", ")", "if", "response", ".", "status_code", "!=", "201", ":", "sys", ".", "stderr", ".", "write", "(", "\"failed to notify client: {}\\n\"", ".", "format", "(", "payload", ")", ")", "sys", ".", "stderr", ".", "flush", "(", ")" ]
a8e1324c4d6e8b063a0d353bcd03bb8e57edd888
valid
consume_message
Decorator for methods handling requests from RabbitMQ The goal of this decorator is to perform the tasks common to all methods handling requests: - Log the raw message to *stdout* - Decode the message into a Python dictionary - Log errors to *stderr* - Signal the broker that we're done handling the request The method passed in will be called with the message body as a dictionary. It is assumed here that the message body is a JSON string encoded in UTF8.
starling/pika/decorator.py
def consume_message( method): """ Decorator for methods handling requests from RabbitMQ The goal of this decorator is to perform the tasks common to all methods handling requests: - Log the raw message to *stdout* - Decode the message into a Python dictionary - Log errors to *stderr* - Signal the broker that we're done handling the request The method passed in will be called with the message body as a dictionary. It is assumed here that the message body is a JSON string encoded in UTF8. """ def wrapper( self, channel, method_frame, header_frame, body): # Log the message sys.stdout.write("received message: {}\n".format(body)) sys.stdout.flush() try: # Grab the data and call the method body = body.decode("utf-8") data = json.loads(body) method(self, data) except Exception as exception: # Log the error message sys.stderr.write("{}\n".format(traceback.format_exc())) sys.stderr.flush() # Signal the broker we are done channel.basic_ack(delivery_tag=method_frame.delivery_tag) return wrapper
def consume_message( method): """ Decorator for methods handling requests from RabbitMQ The goal of this decorator is to perform the tasks common to all methods handling requests: - Log the raw message to *stdout* - Decode the message into a Python dictionary - Log errors to *stderr* - Signal the broker that we're done handling the request The method passed in will be called with the message body as a dictionary. It is assumed here that the message body is a JSON string encoded in UTF8. """ def wrapper( self, channel, method_frame, header_frame, body): # Log the message sys.stdout.write("received message: {}\n".format(body)) sys.stdout.flush() try: # Grab the data and call the method body = body.decode("utf-8") data = json.loads(body) method(self, data) except Exception as exception: # Log the error message sys.stderr.write("{}\n".format(traceback.format_exc())) sys.stderr.flush() # Signal the broker we are done channel.basic_ack(delivery_tag=method_frame.delivery_tag) return wrapper
[ "Decorator", "for", "methods", "handling", "requests", "from", "RabbitMQ" ]
geoneric/starling
python
https://github.com/geoneric/starling/blob/a8e1324c4d6e8b063a0d353bcd03bb8e57edd888/starling/pika/decorator.py#L50-L96
[ "def", "consume_message", "(", "method", ")", ":", "def", "wrapper", "(", "self", ",", "channel", ",", "method_frame", ",", "header_frame", ",", "body", ")", ":", "# Log the message", "sys", ".", "stdout", ".", "write", "(", "\"received message: {}\\n\"", ".", "format", "(", "body", ")", ")", "sys", ".", "stdout", ".", "flush", "(", ")", "try", ":", "# Grab the data and call the method", "body", "=", "body", ".", "decode", "(", "\"utf-8\"", ")", "data", "=", "json", ".", "loads", "(", "body", ")", "method", "(", "self", ",", "data", ")", "except", "Exception", "as", "exception", ":", "# Log the error message", "sys", ".", "stderr", ".", "write", "(", "\"{}\\n\"", ".", "format", "(", "traceback", ".", "format_exc", "(", ")", ")", ")", "sys", ".", "stderr", ".", "flush", "(", ")", "# Signal the broker we are done", "channel", ".", "basic_ack", "(", "delivery_tag", "=", "method_frame", ".", "delivery_tag", ")", "return", "wrapper" ]
a8e1324c4d6e8b063a0d353bcd03bb8e57edd888
valid
consume_message_with_notify
Decorator for methods handling requests from RabbitMQ This decorator builds on the :py:func:`consume_message` decorator. It extents it by logic for notifying a client of the result of handling the request. The *notifier_uri_getter* argument must be a callable which accepts *self* and returns the uri of the notifier service.
starling/pika/decorator.py
def consume_message_with_notify( notifier_uri_getter): """ Decorator for methods handling requests from RabbitMQ This decorator builds on the :py:func:`consume_message` decorator. It extents it by logic for notifying a client of the result of handling the request. The *notifier_uri_getter* argument must be a callable which accepts *self* and returns the uri of the notifier service. """ def consume_message_with_notify_decorator( method): @consume_message def wrapper( self, data): notifier_uri = notifier_uri_getter(self) client_id = data["client_id"] # Forward the call to the method and notify the client of the # result try: method(self, data) notify_client(notifier_uri, client_id, 200) except Exception as exception: notify_client(notifier_uri, client_id, 400, str(exception)) raise return wrapper return consume_message_with_notify_decorator
def consume_message_with_notify( notifier_uri_getter): """ Decorator for methods handling requests from RabbitMQ This decorator builds on the :py:func:`consume_message` decorator. It extents it by logic for notifying a client of the result of handling the request. The *notifier_uri_getter* argument must be a callable which accepts *self* and returns the uri of the notifier service. """ def consume_message_with_notify_decorator( method): @consume_message def wrapper( self, data): notifier_uri = notifier_uri_getter(self) client_id = data["client_id"] # Forward the call to the method and notify the client of the # result try: method(self, data) notify_client(notifier_uri, client_id, 200) except Exception as exception: notify_client(notifier_uri, client_id, 400, str(exception)) raise return wrapper return consume_message_with_notify_decorator
[ "Decorator", "for", "methods", "handling", "requests", "from", "RabbitMQ" ]
geoneric/starling
python
https://github.com/geoneric/starling/blob/a8e1324c4d6e8b063a0d353bcd03bb8e57edd888/starling/pika/decorator.py#L99-L134
[ "def", "consume_message_with_notify", "(", "notifier_uri_getter", ")", ":", "def", "consume_message_with_notify_decorator", "(", "method", ")", ":", "@", "consume_message", "def", "wrapper", "(", "self", ",", "data", ")", ":", "notifier_uri", "=", "notifier_uri_getter", "(", "self", ")", "client_id", "=", "data", "[", "\"client_id\"", "]", "# Forward the call to the method and notify the client of the", "# result", "try", ":", "method", "(", "self", ",", "data", ")", "notify_client", "(", "notifier_uri", ",", "client_id", ",", "200", ")", "except", "Exception", "as", "exception", ":", "notify_client", "(", "notifier_uri", ",", "client_id", ",", "400", ",", "str", "(", "exception", ")", ")", "raise", "return", "wrapper", "return", "consume_message_with_notify_decorator" ]
a8e1324c4d6e8b063a0d353bcd03bb8e57edd888
valid
LRUCache.get
>>> c = LRUCache() >>> c.get('toto') Traceback (most recent call last): ... KeyError: 'toto' >>> c.stats()['misses'] 1 >>> c.put('toto', 'tata') >>> c.get('toto') 'tata' >>> c.stats()['hits'] 1
lrucache.py
def get(self, key): """ >>> c = LRUCache() >>> c.get('toto') Traceback (most recent call last): ... KeyError: 'toto' >>> c.stats()['misses'] 1 >>> c.put('toto', 'tata') >>> c.get('toto') 'tata' >>> c.stats()['hits'] 1 """ try: value = self._cache[key] self._order.push(key) self._hits += 1 return value except KeyError, e: self._misses += 1 raise
def get(self, key): """ >>> c = LRUCache() >>> c.get('toto') Traceback (most recent call last): ... KeyError: 'toto' >>> c.stats()['misses'] 1 >>> c.put('toto', 'tata') >>> c.get('toto') 'tata' >>> c.stats()['hits'] 1 """ try: value = self._cache[key] self._order.push(key) self._hits += 1 return value except KeyError, e: self._misses += 1 raise
[ ">>>", "c", "=", "LRUCache", "()", ">>>", "c", ".", "get", "(", "toto", ")", "Traceback", "(", "most", "recent", "call", "last", ")", ":", "...", "KeyError", ":", "toto", ">>>", "c", ".", "stats", "()", "[", "misses", "]", "1", ">>>", "c", ".", "put", "(", "toto", "tata", ")", ">>>", "c", ".", "get", "(", "toto", ")", "tata", ">>>", "c", ".", "stats", "()", "[", "hits", "]", "1" ]
langloisjp/pysvccache
python
https://github.com/langloisjp/pysvccache/blob/c4b95f1982f3a99e1f63341d15173099361e549b/lrucache.py#L35-L57
[ "def", "get", "(", "self", ",", "key", ")", ":", "try", ":", "value", "=", "self", ".", "_cache", "[", "key", "]", "self", ".", "_order", ".", "push", "(", "key", ")", "self", ".", "_hits", "+=", "1", "return", "value", "except", "KeyError", ",", "e", ":", "self", ".", "_misses", "+=", "1", "raise" ]
c4b95f1982f3a99e1f63341d15173099361e549b
valid
LRUCache.put
>>> c = LRUCache() >>> c.put(1, 'one') >>> c.get(1) 'one' >>> c.size() 1 >>> c.put(2, 'two') >>> c.put(3, 'three') >>> c.put(4, 'four') >>> c.put(5, 'five') >>> c.get(5) 'five' >>> c.size() 5
lrucache.py
def put(self, key, value): """ >>> c = LRUCache() >>> c.put(1, 'one') >>> c.get(1) 'one' >>> c.size() 1 >>> c.put(2, 'two') >>> c.put(3, 'three') >>> c.put(4, 'four') >>> c.put(5, 'five') >>> c.get(5) 'five' >>> c.size() 5 """ self._cache[key] = value self._order.push(key) self._size += 1
def put(self, key, value): """ >>> c = LRUCache() >>> c.put(1, 'one') >>> c.get(1) 'one' >>> c.size() 1 >>> c.put(2, 'two') >>> c.put(3, 'three') >>> c.put(4, 'four') >>> c.put(5, 'five') >>> c.get(5) 'five' >>> c.size() 5 """ self._cache[key] = value self._order.push(key) self._size += 1
[ ">>>", "c", "=", "LRUCache", "()", ">>>", "c", ".", "put", "(", "1", "one", ")", ">>>", "c", ".", "get", "(", "1", ")", "one", ">>>", "c", ".", "size", "()", "1", ">>>", "c", ".", "put", "(", "2", "two", ")", ">>>", "c", ".", "put", "(", "3", "three", ")", ">>>", "c", ".", "put", "(", "4", "four", ")", ">>>", "c", ".", "put", "(", "5", "five", ")", ">>>", "c", ".", "get", "(", "5", ")", "five", ">>>", "c", ".", "size", "()", "5" ]
langloisjp/pysvccache
python
https://github.com/langloisjp/pysvccache/blob/c4b95f1982f3a99e1f63341d15173099361e549b/lrucache.py#L59-L78
[ "def", "put", "(", "self", ",", "key", ",", "value", ")", ":", "self", ".", "_cache", "[", "key", "]", "=", "value", "self", ".", "_order", ".", "push", "(", "key", ")", "self", ".", "_size", "+=", "1" ]
c4b95f1982f3a99e1f63341d15173099361e549b
valid
LRUCache.delete
>>> c = LRUCache() >>> c.put(1, 'one') >>> c.get(1) 'one' >>> c.delete(1) >>> c.get(1) Traceback (most recent call last): ... KeyError: 1 >>> c.delete(1) Traceback (most recent call last): ... KeyError: 1
lrucache.py
def delete(self, key): """ >>> c = LRUCache() >>> c.put(1, 'one') >>> c.get(1) 'one' >>> c.delete(1) >>> c.get(1) Traceback (most recent call last): ... KeyError: 1 >>> c.delete(1) Traceback (most recent call last): ... KeyError: 1 """ del self._cache[key] self._order.delete(key) self._size -= 1
def delete(self, key): """ >>> c = LRUCache() >>> c.put(1, 'one') >>> c.get(1) 'one' >>> c.delete(1) >>> c.get(1) Traceback (most recent call last): ... KeyError: 1 >>> c.delete(1) Traceback (most recent call last): ... KeyError: 1 """ del self._cache[key] self._order.delete(key) self._size -= 1
[ ">>>", "c", "=", "LRUCache", "()", ">>>", "c", ".", "put", "(", "1", "one", ")", ">>>", "c", ".", "get", "(", "1", ")", "one", ">>>", "c", ".", "delete", "(", "1", ")", ">>>", "c", ".", "get", "(", "1", ")", "Traceback", "(", "most", "recent", "call", "last", ")", ":", "...", "KeyError", ":", "1", ">>>", "c", ".", "delete", "(", "1", ")", "Traceback", "(", "most", "recent", "call", "last", ")", ":", "...", "KeyError", ":", "1" ]
langloisjp/pysvccache
python
https://github.com/langloisjp/pysvccache/blob/c4b95f1982f3a99e1f63341d15173099361e549b/lrucache.py#L80-L98
[ "def", "delete", "(", "self", ",", "key", ")", ":", "del", "self", ".", "_cache", "[", "key", "]", "self", ".", "_order", ".", "delete", "(", "key", ")", "self", ".", "_size", "-=", "1" ]
c4b95f1982f3a99e1f63341d15173099361e549b
valid
MemSizeLRUCache.put
>>> c = MemSizeLRUCache(maxmem=24*4) >>> c.put(1, 1) >>> c.mem() # 24-bytes per integer 24 >>> c.put(2, 2) >>> c.put(3, 3) >>> c.put(4, 4) >>> c.get(1) 1 >>> c.mem() 96 >>> c.size() 4 >>> c.put(5, 5) >>> c.size() 4 >>> c.get(2) Traceback (most recent call last): ... KeyError: 2
lrucache.py
def put(self, key, value): """ >>> c = MemSizeLRUCache(maxmem=24*4) >>> c.put(1, 1) >>> c.mem() # 24-bytes per integer 24 >>> c.put(2, 2) >>> c.put(3, 3) >>> c.put(4, 4) >>> c.get(1) 1 >>> c.mem() 96 >>> c.size() 4 >>> c.put(5, 5) >>> c.size() 4 >>> c.get(2) Traceback (most recent call last): ... KeyError: 2 """ mem = sys.getsizeof(value) if self._mem + mem > self._maxmem: self.delete(self.last()) LRUCache.put(self, key, (value, mem)) self._mem += mem
def put(self, key, value): """ >>> c = MemSizeLRUCache(maxmem=24*4) >>> c.put(1, 1) >>> c.mem() # 24-bytes per integer 24 >>> c.put(2, 2) >>> c.put(3, 3) >>> c.put(4, 4) >>> c.get(1) 1 >>> c.mem() 96 >>> c.size() 4 >>> c.put(5, 5) >>> c.size() 4 >>> c.get(2) Traceback (most recent call last): ... KeyError: 2 """ mem = sys.getsizeof(value) if self._mem + mem > self._maxmem: self.delete(self.last()) LRUCache.put(self, key, (value, mem)) self._mem += mem
[ ">>>", "c", "=", "MemSizeLRUCache", "(", "maxmem", "=", "24", "*", "4", ")", ">>>", "c", ".", "put", "(", "1", "1", ")", ">>>", "c", ".", "mem", "()", "#", "24", "-", "bytes", "per", "integer", "24", ">>>", "c", ".", "put", "(", "2", "2", ")", ">>>", "c", ".", "put", "(", "3", "3", ")", ">>>", "c", ".", "put", "(", "4", "4", ")", ">>>", "c", ".", "get", "(", "1", ")", "1", ">>>", "c", ".", "mem", "()", "96", ">>>", "c", ".", "size", "()", "4", ">>>", "c", ".", "put", "(", "5", "5", ")", ">>>", "c", ".", "size", "()", "4", ">>>", "c", ".", "get", "(", "2", ")", "Traceback", "(", "most", "recent", "call", "last", ")", ":", "...", "KeyError", ":", "2" ]
langloisjp/pysvccache
python
https://github.com/langloisjp/pysvccache/blob/c4b95f1982f3a99e1f63341d15173099361e549b/lrucache.py#L162-L189
[ "def", "put", "(", "self", ",", "key", ",", "value", ")", ":", "mem", "=", "sys", ".", "getsizeof", "(", "value", ")", "if", "self", ".", "_mem", "+", "mem", ">", "self", ".", "_maxmem", ":", "self", ".", "delete", "(", "self", ".", "last", "(", ")", ")", "LRUCache", ".", "put", "(", "self", ",", "key", ",", "(", "value", ",", "mem", ")", ")", "self", ".", "_mem", "+=", "mem" ]
c4b95f1982f3a99e1f63341d15173099361e549b
valid
MemSizeLRUCache.delete
>>> c = MemSizeLRUCache() >>> c.put(1, 1) >>> c.mem() 24 >>> c.delete(1) >>> c.mem() 0
lrucache.py
def delete(self, key): """ >>> c = MemSizeLRUCache() >>> c.put(1, 1) >>> c.mem() 24 >>> c.delete(1) >>> c.mem() 0 """ (_value, mem) = LRUCache.get(self, key) self._mem -= mem LRUCache.delete(self, key)
def delete(self, key): """ >>> c = MemSizeLRUCache() >>> c.put(1, 1) >>> c.mem() 24 >>> c.delete(1) >>> c.mem() 0 """ (_value, mem) = LRUCache.get(self, key) self._mem -= mem LRUCache.delete(self, key)
[ ">>>", "c", "=", "MemSizeLRUCache", "()", ">>>", "c", ".", "put", "(", "1", "1", ")", ">>>", "c", ".", "mem", "()", "24", ">>>", "c", ".", "delete", "(", "1", ")", ">>>", "c", ".", "mem", "()", "0" ]
langloisjp/pysvccache
python
https://github.com/langloisjp/pysvccache/blob/c4b95f1982f3a99e1f63341d15173099361e549b/lrucache.py#L195-L207
[ "def", "delete", "(", "self", ",", "key", ")", ":", "(", "_value", ",", "mem", ")", "=", "LRUCache", ".", "get", "(", "self", ",", "key", ")", "self", ".", "_mem", "-=", "mem", "LRUCache", ".", "delete", "(", "self", ",", "key", ")" ]
c4b95f1982f3a99e1f63341d15173099361e549b
valid
FixedSizeLRUCache.put
>>> c = FixedSizeLRUCache(maxsize=5) >>> c.put(1, 'one') >>> c.get(1) 'one' >>> c.size() 1 >>> c.put(2, 'two') >>> c.put(3, 'three') >>> c.put(4, 'four') >>> c.put(5, 'five') >>> c.get(5) 'five' >>> c.size() 5 >>> c.put(6, 'six') >>> c.size() 5 >>> c.get(1) Traceback (most recent call last): ... KeyError: 1 >>> c.get(2) 'two' >>> c.put(7, 'seven') >>> c.get(2) 'two' >>> c.get(3) Traceback (most recent call last): ... KeyError: 3
lrucache.py
def put(self, key, value): """ >>> c = FixedSizeLRUCache(maxsize=5) >>> c.put(1, 'one') >>> c.get(1) 'one' >>> c.size() 1 >>> c.put(2, 'two') >>> c.put(3, 'three') >>> c.put(4, 'four') >>> c.put(5, 'five') >>> c.get(5) 'five' >>> c.size() 5 >>> c.put(6, 'six') >>> c.size() 5 >>> c.get(1) Traceback (most recent call last): ... KeyError: 1 >>> c.get(2) 'two' >>> c.put(7, 'seven') >>> c.get(2) 'two' >>> c.get(3) Traceback (most recent call last): ... KeyError: 3 """ # check if we're maxed out first if self.size() == self._maxsize: # need to kick something out... self.delete(self.last()) LRUCache.put(self, key, value)
def put(self, key, value): """ >>> c = FixedSizeLRUCache(maxsize=5) >>> c.put(1, 'one') >>> c.get(1) 'one' >>> c.size() 1 >>> c.put(2, 'two') >>> c.put(3, 'three') >>> c.put(4, 'four') >>> c.put(5, 'five') >>> c.get(5) 'five' >>> c.size() 5 >>> c.put(6, 'six') >>> c.size() 5 >>> c.get(1) Traceback (most recent call last): ... KeyError: 1 >>> c.get(2) 'two' >>> c.put(7, 'seven') >>> c.get(2) 'two' >>> c.get(3) Traceback (most recent call last): ... KeyError: 3 """ # check if we're maxed out first if self.size() == self._maxsize: # need to kick something out... self.delete(self.last()) LRUCache.put(self, key, value)
[ ">>>", "c", "=", "FixedSizeLRUCache", "(", "maxsize", "=", "5", ")", ">>>", "c", ".", "put", "(", "1", "one", ")", ">>>", "c", ".", "get", "(", "1", ")", "one", ">>>", "c", ".", "size", "()", "1", ">>>", "c", ".", "put", "(", "2", "two", ")", ">>>", "c", ".", "put", "(", "3", "three", ")", ">>>", "c", ".", "put", "(", "4", "four", ")", ">>>", "c", ".", "put", "(", "5", "five", ")", ">>>", "c", ".", "get", "(", "5", ")", "five", ">>>", "c", ".", "size", "()", "5", ">>>", "c", ".", "put", "(", "6", "six", ")", ">>>", "c", ".", "size", "()", "5", ">>>", "c", ".", "get", "(", "1", ")", "Traceback", "(", "most", "recent", "call", "last", ")", ":", "...", "KeyError", ":", "1", ">>>", "c", ".", "get", "(", "2", ")", "two", ">>>", "c", ".", "put", "(", "7", "seven", ")", ">>>", "c", ".", "get", "(", "2", ")", "two", ">>>", "c", ".", "get", "(", "3", ")", "Traceback", "(", "most", "recent", "call", "last", ")", ":", "...", "KeyError", ":", "3" ]
langloisjp/pysvccache
python
https://github.com/langloisjp/pysvccache/blob/c4b95f1982f3a99e1f63341d15173099361e549b/lrucache.py#L216-L253
[ "def", "put", "(", "self", ",", "key", ",", "value", ")", ":", "# check if we're maxed out first", "if", "self", ".", "size", "(", ")", "==", "self", ".", "_maxsize", ":", "# need to kick something out...", "self", ".", "delete", "(", "self", ".", "last", "(", ")", ")", "LRUCache", ".", "put", "(", "self", ",", "key", ",", "value", ")" ]
c4b95f1982f3a99e1f63341d15173099361e549b
valid
Plugin.setting
Retrieves the setting value whose name is indicated by name_hyphen. Values starting with $ are assumed to reference environment variables, and the value stored in environment variables is retrieved. It's an error if thes corresponding environment variable it not set.
cashew/plugin.py
def setting(self, name_hyphen): """ Retrieves the setting value whose name is indicated by name_hyphen. Values starting with $ are assumed to reference environment variables, and the value stored in environment variables is retrieved. It's an error if thes corresponding environment variable it not set. """ if name_hyphen in self._instance_settings: value = self._instance_settings[name_hyphen][1] else: msg = "No setting named '%s'" % name_hyphen raise UserFeedback(msg) if hasattr(value, 'startswith') and value.startswith("$"): env_var = value.lstrip("$") if env_var in os.environ: return os.getenv(env_var) else: msg = "'%s' is not defined in your environment" % env_var raise UserFeedback(msg) elif hasattr(value, 'startswith') and value.startswith("\$"): return value.replace("\$", "$") else: return value
def setting(self, name_hyphen): """ Retrieves the setting value whose name is indicated by name_hyphen. Values starting with $ are assumed to reference environment variables, and the value stored in environment variables is retrieved. It's an error if thes corresponding environment variable it not set. """ if name_hyphen in self._instance_settings: value = self._instance_settings[name_hyphen][1] else: msg = "No setting named '%s'" % name_hyphen raise UserFeedback(msg) if hasattr(value, 'startswith') and value.startswith("$"): env_var = value.lstrip("$") if env_var in os.environ: return os.getenv(env_var) else: msg = "'%s' is not defined in your environment" % env_var raise UserFeedback(msg) elif hasattr(value, 'startswith') and value.startswith("\$"): return value.replace("\$", "$") else: return value
[ "Retrieves", "the", "setting", "value", "whose", "name", "is", "indicated", "by", "name_hyphen", "." ]
dexy/cashew
python
https://github.com/dexy/cashew/blob/39890a6e1e4e4e514e98cdb18368e29cc6710e52/cashew/plugin.py#L79-L105
[ "def", "setting", "(", "self", ",", "name_hyphen", ")", ":", "if", "name_hyphen", "in", "self", ".", "_instance_settings", ":", "value", "=", "self", ".", "_instance_settings", "[", "name_hyphen", "]", "[", "1", "]", "else", ":", "msg", "=", "\"No setting named '%s'\"", "%", "name_hyphen", "raise", "UserFeedback", "(", "msg", ")", "if", "hasattr", "(", "value", ",", "'startswith'", ")", "and", "value", ".", "startswith", "(", "\"$\"", ")", ":", "env_var", "=", "value", ".", "lstrip", "(", "\"$\"", ")", "if", "env_var", "in", "os", ".", "environ", ":", "return", "os", ".", "getenv", "(", "env_var", ")", "else", ":", "msg", "=", "\"'%s' is not defined in your environment\"", "%", "env_var", "raise", "UserFeedback", "(", "msg", ")", "elif", "hasattr", "(", "value", ",", "'startswith'", ")", "and", "value", ".", "startswith", "(", "\"\\$\"", ")", ":", "return", "value", ".", "replace", "(", "\"\\$\"", ",", "\"$\"", ")", "else", ":", "return", "value" ]
39890a6e1e4e4e514e98cdb18368e29cc6710e52
valid
Plugin.setting_values
Returns dict of all setting values (removes the helpstrings).
cashew/plugin.py
def setting_values(self, skip=None): """ Returns dict of all setting values (removes the helpstrings). """ if not skip: skip = [] return dict( (k, v[1]) for k, v in six.iteritems(self._instance_settings) if not k in skip)
def setting_values(self, skip=None): """ Returns dict of all setting values (removes the helpstrings). """ if not skip: skip = [] return dict( (k, v[1]) for k, v in six.iteritems(self._instance_settings) if not k in skip)
[ "Returns", "dict", "of", "all", "setting", "values", "(", "removes", "the", "helpstrings", ")", "." ]
dexy/cashew
python
https://github.com/dexy/cashew/blob/39890a6e1e4e4e514e98cdb18368e29cc6710e52/cashew/plugin.py#L107-L117
[ "def", "setting_values", "(", "self", ",", "skip", "=", "None", ")", ":", "if", "not", "skip", ":", "skip", "=", "[", "]", "return", "dict", "(", "(", "k", ",", "v", "[", "1", "]", ")", "for", "k", ",", "v", "in", "six", ".", "iteritems", "(", "self", ".", "_instance_settings", ")", "if", "not", "k", "in", "skip", ")" ]
39890a6e1e4e4e514e98cdb18368e29cc6710e52
valid
Plugin._update_settings
This method does the work of updating settings. Can be passed with enforce_helpstring = False which you may want if allowing end users to add arbitrary metadata via the settings system. Preferable to use update_settings (without leading _) in code to do the right thing and always have docstrings.
cashew/plugin.py
def _update_settings(self, new_settings, enforce_helpstring=True): """ This method does the work of updating settings. Can be passed with enforce_helpstring = False which you may want if allowing end users to add arbitrary metadata via the settings system. Preferable to use update_settings (without leading _) in code to do the right thing and always have docstrings. """ for raw_setting_name, value in six.iteritems(new_settings): setting_name = raw_setting_name.replace("_", "-") setting_already_exists = setting_name in self._instance_settings value_is_list_len_2 = isinstance(value, list) and len(value) == 2 treat_as_tuple = not setting_already_exists and value_is_list_len_2 if isinstance(value, tuple) or treat_as_tuple: self._instance_settings[setting_name] = value else: if setting_name not in self._instance_settings: if enforce_helpstring: msg = "You must specify param '%s' as a tuple of (helpstring, value)" raise InternalCashewException(msg % setting_name) else: # Create entry with blank helpstring. self._instance_settings[setting_name] = ('', value,) else: # Save inherited helpstring, replace default value. orig = self._instance_settings[setting_name] self._instance_settings[setting_name] = (orig[0], value,)
def _update_settings(self, new_settings, enforce_helpstring=True): """ This method does the work of updating settings. Can be passed with enforce_helpstring = False which you may want if allowing end users to add arbitrary metadata via the settings system. Preferable to use update_settings (without leading _) in code to do the right thing and always have docstrings. """ for raw_setting_name, value in six.iteritems(new_settings): setting_name = raw_setting_name.replace("_", "-") setting_already_exists = setting_name in self._instance_settings value_is_list_len_2 = isinstance(value, list) and len(value) == 2 treat_as_tuple = not setting_already_exists and value_is_list_len_2 if isinstance(value, tuple) or treat_as_tuple: self._instance_settings[setting_name] = value else: if setting_name not in self._instance_settings: if enforce_helpstring: msg = "You must specify param '%s' as a tuple of (helpstring, value)" raise InternalCashewException(msg % setting_name) else: # Create entry with blank helpstring. self._instance_settings[setting_name] = ('', value,) else: # Save inherited helpstring, replace default value. orig = self._instance_settings[setting_name] self._instance_settings[setting_name] = (orig[0], value,)
[ "This", "method", "does", "the", "work", "of", "updating", "settings", ".", "Can", "be", "passed", "with", "enforce_helpstring", "=", "False", "which", "you", "may", "want", "if", "allowing", "end", "users", "to", "add", "arbitrary", "metadata", "via", "the", "settings", "system", "." ]
dexy/cashew
python
https://github.com/dexy/cashew/blob/39890a6e1e4e4e514e98cdb18368e29cc6710e52/cashew/plugin.py#L128-L160
[ "def", "_update_settings", "(", "self", ",", "new_settings", ",", "enforce_helpstring", "=", "True", ")", ":", "for", "raw_setting_name", ",", "value", "in", "six", ".", "iteritems", "(", "new_settings", ")", ":", "setting_name", "=", "raw_setting_name", ".", "replace", "(", "\"_\"", ",", "\"-\"", ")", "setting_already_exists", "=", "setting_name", "in", "self", ".", "_instance_settings", "value_is_list_len_2", "=", "isinstance", "(", "value", ",", "list", ")", "and", "len", "(", "value", ")", "==", "2", "treat_as_tuple", "=", "not", "setting_already_exists", "and", "value_is_list_len_2", "if", "isinstance", "(", "value", ",", "tuple", ")", "or", "treat_as_tuple", ":", "self", ".", "_instance_settings", "[", "setting_name", "]", "=", "value", "else", ":", "if", "setting_name", "not", "in", "self", ".", "_instance_settings", ":", "if", "enforce_helpstring", ":", "msg", "=", "\"You must specify param '%s' as a tuple of (helpstring, value)\"", "raise", "InternalCashewException", "(", "msg", "%", "setting_name", ")", "else", ":", "# Create entry with blank helpstring.", "self", ".", "_instance_settings", "[", "setting_name", "]", "=", "(", "''", ",", "value", ",", ")", "else", ":", "# Save inherited helpstring, replace default value.", "orig", "=", "self", ".", "_instance_settings", "[", "setting_name", "]", "self", ".", "_instance_settings", "[", "setting_name", "]", "=", "(", "orig", "[", "0", "]", ",", "value", ",", ")" ]
39890a6e1e4e4e514e98cdb18368e29cc6710e52
valid
Plugin.settings_and_attributes
Return a combined dictionary of setting values and attribute values.
cashew/plugin.py
def settings_and_attributes(self): """Return a combined dictionary of setting values and attribute values.""" attrs = self.setting_values() attrs.update(self.__dict__) skip = ["_instance_settings", "aliases"] for a in skip: del attrs[a] return attrs
def settings_and_attributes(self): """Return a combined dictionary of setting values and attribute values.""" attrs = self.setting_values() attrs.update(self.__dict__) skip = ["_instance_settings", "aliases"] for a in skip: del attrs[a] return attrs
[ "Return", "a", "combined", "dictionary", "of", "setting", "values", "and", "attribute", "values", "." ]
dexy/cashew
python
https://github.com/dexy/cashew/blob/39890a6e1e4e4e514e98cdb18368e29cc6710e52/cashew/plugin.py#L162-L169
[ "def", "settings_and_attributes", "(", "self", ")", ":", "attrs", "=", "self", ".", "setting_values", "(", ")", "attrs", ".", "update", "(", "self", ".", "__dict__", ")", "skip", "=", "[", "\"_instance_settings\"", ",", "\"aliases\"", "]", "for", "a", "in", "skip", ":", "del", "attrs", "[", "a", "]", "return", "attrs" ]
39890a6e1e4e4e514e98cdb18368e29cc6710e52
valid
PluginMeta.get_reference_to_class
Detect if we get a class or a name, convert a name to a class.
cashew/plugin.py
def get_reference_to_class(cls, class_or_class_name): """ Detect if we get a class or a name, convert a name to a class. """ if isinstance(class_or_class_name, type): return class_or_class_name elif isinstance(class_or_class_name, string_types): if ":" in class_or_class_name: mod_name, class_name = class_or_class_name.split(":") if not mod_name in sys.modules: __import__(mod_name) mod = sys.modules[mod_name] return mod.__dict__[class_name] else: return cls.load_class_from_locals(class_or_class_name) else: msg = "Unexpected Type '%s'" % type(class_or_class_name) raise InternalCashewException(msg)
def get_reference_to_class(cls, class_or_class_name): """ Detect if we get a class or a name, convert a name to a class. """ if isinstance(class_or_class_name, type): return class_or_class_name elif isinstance(class_or_class_name, string_types): if ":" in class_or_class_name: mod_name, class_name = class_or_class_name.split(":") if not mod_name in sys.modules: __import__(mod_name) mod = sys.modules[mod_name] return mod.__dict__[class_name] else: return cls.load_class_from_locals(class_or_class_name) else: msg = "Unexpected Type '%s'" % type(class_or_class_name) raise InternalCashewException(msg)
[ "Detect", "if", "we", "get", "a", "class", "or", "a", "name", "convert", "a", "name", "to", "a", "class", "." ]
dexy/cashew
python
https://github.com/dexy/cashew/blob/39890a6e1e4e4e514e98cdb18368e29cc6710e52/cashew/plugin.py#L230-L252
[ "def", "get_reference_to_class", "(", "cls", ",", "class_or_class_name", ")", ":", "if", "isinstance", "(", "class_or_class_name", ",", "type", ")", ":", "return", "class_or_class_name", "elif", "isinstance", "(", "class_or_class_name", ",", "string_types", ")", ":", "if", "\":\"", "in", "class_or_class_name", ":", "mod_name", ",", "class_name", "=", "class_or_class_name", ".", "split", "(", "\":\"", ")", "if", "not", "mod_name", "in", "sys", ".", "modules", ":", "__import__", "(", "mod_name", ")", "mod", "=", "sys", ".", "modules", "[", "mod_name", "]", "return", "mod", ".", "__dict__", "[", "class_name", "]", "else", ":", "return", "cls", ".", "load_class_from_locals", "(", "class_or_class_name", ")", "else", ":", "msg", "=", "\"Unexpected Type '%s'\"", "%", "type", "(", "class_or_class_name", ")", "raise", "InternalCashewException", "(", "msg", ")" ]
39890a6e1e4e4e514e98cdb18368e29cc6710e52
valid
PluginMeta.check_docstring
Asserts that the class has a docstring, returning it if successful.
cashew/plugin.py
def check_docstring(cls): """ Asserts that the class has a docstring, returning it if successful. """ docstring = inspect.getdoc(cls) if not docstring: breadcrumbs = " -> ".join(t.__name__ for t in inspect.getmro(cls)[:-1][::-1]) msg = "docstring required for plugin '%s' (%s, defined in %s)" args = (cls.__name__, breadcrumbs, cls.__module__) raise InternalCashewException(msg % args) max_line_length = cls._class_settings.get('max-docstring-length') if max_line_length: for i, line in enumerate(docstring.splitlines()): if len(line) > max_line_length: msg = "docstring line %s of %s is %s chars too long" args = (i, cls.__name__, len(line) - max_line_length) raise Exception(msg % args) return docstring
def check_docstring(cls): """ Asserts that the class has a docstring, returning it if successful. """ docstring = inspect.getdoc(cls) if not docstring: breadcrumbs = " -> ".join(t.__name__ for t in inspect.getmro(cls)[:-1][::-1]) msg = "docstring required for plugin '%s' (%s, defined in %s)" args = (cls.__name__, breadcrumbs, cls.__module__) raise InternalCashewException(msg % args) max_line_length = cls._class_settings.get('max-docstring-length') if max_line_length: for i, line in enumerate(docstring.splitlines()): if len(line) > max_line_length: msg = "docstring line %s of %s is %s chars too long" args = (i, cls.__name__, len(line) - max_line_length) raise Exception(msg % args) return docstring
[ "Asserts", "that", "the", "class", "has", "a", "docstring", "returning", "it", "if", "successful", "." ]
dexy/cashew
python
https://github.com/dexy/cashew/blob/39890a6e1e4e4e514e98cdb18368e29cc6710e52/cashew/plugin.py#L257-L276
[ "def", "check_docstring", "(", "cls", ")", ":", "docstring", "=", "inspect", ".", "getdoc", "(", "cls", ")", "if", "not", "docstring", ":", "breadcrumbs", "=", "\" -> \"", ".", "join", "(", "t", ".", "__name__", "for", "t", "in", "inspect", ".", "getmro", "(", "cls", ")", "[", ":", "-", "1", "]", "[", ":", ":", "-", "1", "]", ")", "msg", "=", "\"docstring required for plugin '%s' (%s, defined in %s)\"", "args", "=", "(", "cls", ".", "__name__", ",", "breadcrumbs", ",", "cls", ".", "__module__", ")", "raise", "InternalCashewException", "(", "msg", "%", "args", ")", "max_line_length", "=", "cls", ".", "_class_settings", ".", "get", "(", "'max-docstring-length'", ")", "if", "max_line_length", ":", "for", "i", ",", "line", "in", "enumerate", "(", "docstring", ".", "splitlines", "(", ")", ")", ":", "if", "len", "(", "line", ")", ">", "max_line_length", ":", "msg", "=", "\"docstring line %s of %s is %s chars too long\"", "args", "=", "(", "i", ",", "cls", ".", "__name__", ",", "len", "(", "line", ")", "-", "max_line_length", ")", "raise", "Exception", "(", "msg", "%", "args", ")", "return", "docstring" ]
39890a6e1e4e4e514e98cdb18368e29cc6710e52
valid
logbookForm.resourcePath
Get absolute path to resource, works for dev and for PyInstaller
scisalt/facettools/logbookForm.py
def resourcePath(self, relative_path): """ Get absolute path to resource, works for dev and for PyInstaller """ from os import path import sys try: # PyInstaller creates a temp folder and stores path in _MEIPASS base_path = sys._MEIPASS except Exception: base_path = path.dirname(path.abspath(__file__)) return path.join(base_path, relative_path)
def resourcePath(self, relative_path): """ Get absolute path to resource, works for dev and for PyInstaller """ from os import path import sys try: # PyInstaller creates a temp folder and stores path in _MEIPASS base_path = sys._MEIPASS except Exception: base_path = path.dirname(path.abspath(__file__)) return path.join(base_path, relative_path)
[ "Get", "absolute", "path", "to", "resource", "works", "for", "dev", "and", "for", "PyInstaller" ]
joelfrederico/SciSalt
python
https://github.com/joelfrederico/SciSalt/blob/7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f/scisalt/facettools/logbookForm.py#L63-L73
[ "def", "resourcePath", "(", "self", ",", "relative_path", ")", ":", "from", "os", "import", "path", "import", "sys", "try", ":", "# PyInstaller creates a temp folder and stores path in _MEIPASS", "base_path", "=", "sys", ".", "_MEIPASS", "except", "Exception", ":", "base_path", "=", "path", ".", "dirname", "(", "path", ".", "abspath", "(", "__file__", ")", ")", "return", "path", ".", "join", "(", "base_path", ",", "relative_path", ")" ]
7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f
valid
logbookForm.addLogbook
Add new block of logbook selection windows. Only 5 allowed.
scisalt/facettools/logbookForm.py
def addLogbook(self, physDef= "LCLS", mccDef="MCC", initialInstance=False): '''Add new block of logbook selection windows. Only 5 allowed.''' if self.logMenuCount < 5: self.logMenus.append(LogSelectMenu(self.logui.multiLogLayout, initialInstance)) self.logMenus[-1].addLogbooks(self.logTypeList[1], self.physics_programs, physDef) self.logMenus[-1].addLogbooks(self.logTypeList[0], self.mcc_programs, mccDef) self.logMenus[-1].show() self.logMenuCount += 1 if initialInstance: # Initial logbook menu can add additional menus, all others can only remove themselves. QObject.connect(self.logMenus[-1].logButton, SIGNAL("clicked()"), self.addLogbook) else: from functools import partial QObject.connect(self.logMenus[-1].logButton, SIGNAL("clicked()"), partial(self.removeLogbook, self.logMenus[-1]))
def addLogbook(self, physDef= "LCLS", mccDef="MCC", initialInstance=False): '''Add new block of logbook selection windows. Only 5 allowed.''' if self.logMenuCount < 5: self.logMenus.append(LogSelectMenu(self.logui.multiLogLayout, initialInstance)) self.logMenus[-1].addLogbooks(self.logTypeList[1], self.physics_programs, physDef) self.logMenus[-1].addLogbooks(self.logTypeList[0], self.mcc_programs, mccDef) self.logMenus[-1].show() self.logMenuCount += 1 if initialInstance: # Initial logbook menu can add additional menus, all others can only remove themselves. QObject.connect(self.logMenus[-1].logButton, SIGNAL("clicked()"), self.addLogbook) else: from functools import partial QObject.connect(self.logMenus[-1].logButton, SIGNAL("clicked()"), partial(self.removeLogbook, self.logMenus[-1]))
[ "Add", "new", "block", "of", "logbook", "selection", "windows", ".", "Only", "5", "allowed", "." ]
joelfrederico/SciSalt
python
https://github.com/joelfrederico/SciSalt/blob/7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f/scisalt/facettools/logbookForm.py#L143-L156
[ "def", "addLogbook", "(", "self", ",", "physDef", "=", "\"LCLS\"", ",", "mccDef", "=", "\"MCC\"", ",", "initialInstance", "=", "False", ")", ":", "if", "self", ".", "logMenuCount", "<", "5", ":", "self", ".", "logMenus", ".", "append", "(", "LogSelectMenu", "(", "self", ".", "logui", ".", "multiLogLayout", ",", "initialInstance", ")", ")", "self", ".", "logMenus", "[", "-", "1", "]", ".", "addLogbooks", "(", "self", ".", "logTypeList", "[", "1", "]", ",", "self", ".", "physics_programs", ",", "physDef", ")", "self", ".", "logMenus", "[", "-", "1", "]", ".", "addLogbooks", "(", "self", ".", "logTypeList", "[", "0", "]", ",", "self", ".", "mcc_programs", ",", "mccDef", ")", "self", ".", "logMenus", "[", "-", "1", "]", ".", "show", "(", ")", "self", ".", "logMenuCount", "+=", "1", "if", "initialInstance", ":", "# Initial logbook menu can add additional menus, all others can only remove themselves.", "QObject", ".", "connect", "(", "self", ".", "logMenus", "[", "-", "1", "]", ".", "logButton", ",", "SIGNAL", "(", "\"clicked()\"", ")", ",", "self", ".", "addLogbook", ")", "else", ":", "from", "functools", "import", "partial", "QObject", ".", "connect", "(", "self", ".", "logMenus", "[", "-", "1", "]", ".", "logButton", ",", "SIGNAL", "(", "\"clicked()\"", ")", ",", "partial", "(", "self", ".", "removeLogbook", ",", "self", ".", "logMenus", "[", "-", "1", "]", ")", ")" ]
7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f
valid
logbookForm.removeLogbook
Remove logbook menu set.
scisalt/facettools/logbookForm.py
def removeLogbook(self, menu=None): '''Remove logbook menu set.''' if self.logMenuCount > 1 and menu is not None: menu.removeMenu() self.logMenus.remove(menu) self.logMenuCount -= 1
def removeLogbook(self, menu=None): '''Remove logbook menu set.''' if self.logMenuCount > 1 and menu is not None: menu.removeMenu() self.logMenus.remove(menu) self.logMenuCount -= 1
[ "Remove", "logbook", "menu", "set", "." ]
joelfrederico/SciSalt
python
https://github.com/joelfrederico/SciSalt/blob/7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f/scisalt/facettools/logbookForm.py#L158-L163
[ "def", "removeLogbook", "(", "self", ",", "menu", "=", "None", ")", ":", "if", "self", ".", "logMenuCount", ">", "1", "and", "menu", "is", "not", "None", ":", "menu", ".", "removeMenu", "(", ")", "self", ".", "logMenus", ".", "remove", "(", "menu", ")", "self", ".", "logMenuCount", "-=", "1" ]
7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f
valid
logbookForm.selectedLogs
Return selected log books by type.
scisalt/facettools/logbookForm.py
def selectedLogs(self): '''Return selected log books by type.''' mcclogs = [] physlogs = [] for i in range(len(self.logMenus)): logType = self.logMenus[i].selectedType() log = self.logMenus[i].selectedProgram() if logType == "MCC": if log not in mcclogs: mcclogs.append(log) elif logType == "Physics": if log not in physlogs: physlogs.append(log) return mcclogs, physlogs
def selectedLogs(self): '''Return selected log books by type.''' mcclogs = [] physlogs = [] for i in range(len(self.logMenus)): logType = self.logMenus[i].selectedType() log = self.logMenus[i].selectedProgram() if logType == "MCC": if log not in mcclogs: mcclogs.append(log) elif logType == "Physics": if log not in physlogs: physlogs.append(log) return mcclogs, physlogs
[ "Return", "selected", "log", "books", "by", "type", "." ]
joelfrederico/SciSalt
python
https://github.com/joelfrederico/SciSalt/blob/7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f/scisalt/facettools/logbookForm.py#L165-L178
[ "def", "selectedLogs", "(", "self", ")", ":", "mcclogs", "=", "[", "]", "physlogs", "=", "[", "]", "for", "i", "in", "range", "(", "len", "(", "self", ".", "logMenus", ")", ")", ":", "logType", "=", "self", ".", "logMenus", "[", "i", "]", ".", "selectedType", "(", ")", "log", "=", "self", ".", "logMenus", "[", "i", "]", ".", "selectedProgram", "(", ")", "if", "logType", "==", "\"MCC\"", ":", "if", "log", "not", "in", "mcclogs", ":", "mcclogs", ".", "append", "(", "log", ")", "elif", "logType", "==", "\"Physics\"", ":", "if", "log", "not", "in", "physlogs", ":", "physlogs", ".", "append", "(", "log", ")", "return", "mcclogs", ",", "physlogs" ]
7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f
valid
logbookForm.acceptedUser
Verify enetered user name is on accepted MCC logbook list.
scisalt/facettools/logbookForm.py
def acceptedUser(self, logType): '''Verify enetered user name is on accepted MCC logbook list.''' from urllib2 import urlopen, URLError, HTTPError import json isApproved = False userName = str(self.logui.userName.text()) if userName == "": return False # Must have a user name to submit entry if logType == "MCC": networkFault = False data = [] log_url = "https://mccelog.slac.stanford.edu/elog/dev/mgibbs/dev_json_user_list.php/?username=" + userName try: data = urlopen(log_url, None, 5).read() data = json.loads(data) except URLError as error: print("URLError: " + str(error.reason)) networkFault = True except HTTPError as error: print("HTTPError: " + str(error.reason)) networkFault = True # If network fails, ask user to verify if networkFault: msgBox = QMessageBox() msgBox.setText("Cannot connect to MCC Log Server!") msgBox.setInformativeText("Use entered User name anyway?") msgBox.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel) msgBox.setDefaultButton(QMessageBox.Ok) if msgBox.exec_() == QMessageBox.Ok: isApproved = True if data != [] and (data is not None): isApproved = True else: isApproved = True return isApproved
def acceptedUser(self, logType): '''Verify enetered user name is on accepted MCC logbook list.''' from urllib2 import urlopen, URLError, HTTPError import json isApproved = False userName = str(self.logui.userName.text()) if userName == "": return False # Must have a user name to submit entry if logType == "MCC": networkFault = False data = [] log_url = "https://mccelog.slac.stanford.edu/elog/dev/mgibbs/dev_json_user_list.php/?username=" + userName try: data = urlopen(log_url, None, 5).read() data = json.loads(data) except URLError as error: print("URLError: " + str(error.reason)) networkFault = True except HTTPError as error: print("HTTPError: " + str(error.reason)) networkFault = True # If network fails, ask user to verify if networkFault: msgBox = QMessageBox() msgBox.setText("Cannot connect to MCC Log Server!") msgBox.setInformativeText("Use entered User name anyway?") msgBox.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel) msgBox.setDefaultButton(QMessageBox.Ok) if msgBox.exec_() == QMessageBox.Ok: isApproved = True if data != [] and (data is not None): isApproved = True else: isApproved = True return isApproved
[ "Verify", "enetered", "user", "name", "is", "on", "accepted", "MCC", "logbook", "list", "." ]
joelfrederico/SciSalt
python
https://github.com/joelfrederico/SciSalt/blob/7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f/scisalt/facettools/logbookForm.py#L180-L219
[ "def", "acceptedUser", "(", "self", ",", "logType", ")", ":", "from", "urllib2", "import", "urlopen", ",", "URLError", ",", "HTTPError", "import", "json", "isApproved", "=", "False", "userName", "=", "str", "(", "self", ".", "logui", ".", "userName", ".", "text", "(", ")", ")", "if", "userName", "==", "\"\"", ":", "return", "False", "# Must have a user name to submit entry", "if", "logType", "==", "\"MCC\"", ":", "networkFault", "=", "False", "data", "=", "[", "]", "log_url", "=", "\"https://mccelog.slac.stanford.edu/elog/dev/mgibbs/dev_json_user_list.php/?username=\"", "+", "userName", "try", ":", "data", "=", "urlopen", "(", "log_url", ",", "None", ",", "5", ")", ".", "read", "(", ")", "data", "=", "json", ".", "loads", "(", "data", ")", "except", "URLError", "as", "error", ":", "print", "(", "\"URLError: \"", "+", "str", "(", "error", ".", "reason", ")", ")", "networkFault", "=", "True", "except", "HTTPError", "as", "error", ":", "print", "(", "\"HTTPError: \"", "+", "str", "(", "error", ".", "reason", ")", ")", "networkFault", "=", "True", "# If network fails, ask user to verify", "if", "networkFault", ":", "msgBox", "=", "QMessageBox", "(", ")", "msgBox", ".", "setText", "(", "\"Cannot connect to MCC Log Server!\"", ")", "msgBox", ".", "setInformativeText", "(", "\"Use entered User name anyway?\"", ")", "msgBox", ".", "setStandardButtons", "(", "QMessageBox", ".", "Ok", "|", "QMessageBox", ".", "Cancel", ")", "msgBox", ".", "setDefaultButton", "(", "QMessageBox", ".", "Ok", ")", "if", "msgBox", ".", "exec_", "(", ")", "==", "QMessageBox", ".", "Ok", ":", "isApproved", "=", "True", "if", "data", "!=", "[", "]", "and", "(", "data", "is", "not", "None", ")", ":", "isApproved", "=", "True", "else", ":", "isApproved", "=", "True", "return", "isApproved" ]
7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f
valid
logbookForm.xmlSetup
Create xml file with fields from logbook form.
scisalt/facettools/logbookForm.py
def xmlSetup(self, logType, logList): """Create xml file with fields from logbook form.""" from xml.etree.ElementTree import Element, SubElement, ElementTree from datetime import datetime curr_time = datetime.now() if logType == "MCC": # Set up xml tags log_entry = Element('log_entry') title = SubElement(log_entry, 'title') program = SubElement(log_entry, 'program') timestamp = SubElement(log_entry, 'timestamp') priority = SubElement(log_entry, 'priority') os_user = SubElement(log_entry, 'os_user') hostname = SubElement(log_entry, 'hostname') text = SubElement(log_entry, 'text') log_user = SubElement(log_entry, 'log_user') # Check for multiple logbooks and parse into seperate tags logbook = [] for i in range(len(logList)): logbook.append(SubElement(log_entry, 'logbook')) logbook[i].text = logList[i].lower() # Take care of dummy, unchanging tags first log_entry.attrib['type'] = "LOGENTRY" program.text = "152" priority.text = "NORMAL" os_user.text = "nobody" hostname.text = "mccelog" text.attrib['type'] = "text/plain" # Handle attachment if image exists if not self.imagePixmap.isNull(): attachment = SubElement(log_entry, 'attachment') attachment.attrib['name'] = "Figure 1" attachment.attrib['type'] = "image/" + self.imageType attachment.text = curr_time.strftime("%Y%m%d_%H%M%S_") + str(curr_time.microsecond) + "." + self.imageType # Set timestamp format timestamp.text = curr_time.strftime("%Y/%m/%d %H:%M:%S") fileName = "/tmp/" + curr_time.strftime("%Y%m%d_%H%M%S_") + str(curr_time.microsecond) + ".xml" else: # If using Physics logbook timeString = curr_time.strftime("%Y-%m-%dT%H:%M:%S") # Set up xml tags log_entry = Element(None) severity = SubElement(log_entry, 'severity') location = SubElement(log_entry, 'location') keywords = SubElement(log_entry, 'keywords') time = SubElement(log_entry, 'time') isodate = SubElement(log_entry, 'isodate') log_user = SubElement(log_entry, 'author') category = SubElement(log_entry, 'category') title = SubElement(log_entry, 'title') metainfo = SubElement(log_entry, 'metainfo') # Handle attachment if image exists if not self.imagePixmap.isNull(): imageFile = SubElement(log_entry, 'link') imageFile.text = timeString + "-00." + self.imageType thumbnail = SubElement(log_entry, 'file') thumbnail.text = timeString + "-00.png" text = SubElement(log_entry, 'text') # Logbook expects Text tag to come last (for some strange reason) # Take care of dummy, unchanging tags first log_entry.attrib['type'] = "LOGENTRY" category.text = "USERLOG" location.text = "not set" severity.text = "NONE" keywords.text = "none" time.text = curr_time.strftime("%H:%M:%S") isodate.text = curr_time.strftime("%Y-%m-%d") metainfo.text = timeString + "-00.xml" fileName = "/tmp/" + metainfo.text # Fill in user inputs log_user.text = str(self.logui.userName.text()) title.text = str(self.logui.titleEntry.text()) if title.text == "": QMessageBox().warning(self, "No Title entered", "Please enter a title for the entry...") return None text.text = str(self.logui.textEntry.toPlainText()) # If text field is truly empty, ElementTree leaves off tag entirely which causes logbook parser to fail if text.text == "": text.text = " " # Create xml file xmlFile = open(fileName, "w") if logType == "MCC": ElementTree(log_entry).write(xmlFile) else: xmlString = self.prettify(log_entry) xmlFile.write(xmlString) xmlFile.write("\n") # Close with newline so cron job parses correctly xmlFile.close() return fileName.rstrip(".xml")
def xmlSetup(self, logType, logList): """Create xml file with fields from logbook form.""" from xml.etree.ElementTree import Element, SubElement, ElementTree from datetime import datetime curr_time = datetime.now() if logType == "MCC": # Set up xml tags log_entry = Element('log_entry') title = SubElement(log_entry, 'title') program = SubElement(log_entry, 'program') timestamp = SubElement(log_entry, 'timestamp') priority = SubElement(log_entry, 'priority') os_user = SubElement(log_entry, 'os_user') hostname = SubElement(log_entry, 'hostname') text = SubElement(log_entry, 'text') log_user = SubElement(log_entry, 'log_user') # Check for multiple logbooks and parse into seperate tags logbook = [] for i in range(len(logList)): logbook.append(SubElement(log_entry, 'logbook')) logbook[i].text = logList[i].lower() # Take care of dummy, unchanging tags first log_entry.attrib['type'] = "LOGENTRY" program.text = "152" priority.text = "NORMAL" os_user.text = "nobody" hostname.text = "mccelog" text.attrib['type'] = "text/plain" # Handle attachment if image exists if not self.imagePixmap.isNull(): attachment = SubElement(log_entry, 'attachment') attachment.attrib['name'] = "Figure 1" attachment.attrib['type'] = "image/" + self.imageType attachment.text = curr_time.strftime("%Y%m%d_%H%M%S_") + str(curr_time.microsecond) + "." + self.imageType # Set timestamp format timestamp.text = curr_time.strftime("%Y/%m/%d %H:%M:%S") fileName = "/tmp/" + curr_time.strftime("%Y%m%d_%H%M%S_") + str(curr_time.microsecond) + ".xml" else: # If using Physics logbook timeString = curr_time.strftime("%Y-%m-%dT%H:%M:%S") # Set up xml tags log_entry = Element(None) severity = SubElement(log_entry, 'severity') location = SubElement(log_entry, 'location') keywords = SubElement(log_entry, 'keywords') time = SubElement(log_entry, 'time') isodate = SubElement(log_entry, 'isodate') log_user = SubElement(log_entry, 'author') category = SubElement(log_entry, 'category') title = SubElement(log_entry, 'title') metainfo = SubElement(log_entry, 'metainfo') # Handle attachment if image exists if not self.imagePixmap.isNull(): imageFile = SubElement(log_entry, 'link') imageFile.text = timeString + "-00." + self.imageType thumbnail = SubElement(log_entry, 'file') thumbnail.text = timeString + "-00.png" text = SubElement(log_entry, 'text') # Logbook expects Text tag to come last (for some strange reason) # Take care of dummy, unchanging tags first log_entry.attrib['type'] = "LOGENTRY" category.text = "USERLOG" location.text = "not set" severity.text = "NONE" keywords.text = "none" time.text = curr_time.strftime("%H:%M:%S") isodate.text = curr_time.strftime("%Y-%m-%d") metainfo.text = timeString + "-00.xml" fileName = "/tmp/" + metainfo.text # Fill in user inputs log_user.text = str(self.logui.userName.text()) title.text = str(self.logui.titleEntry.text()) if title.text == "": QMessageBox().warning(self, "No Title entered", "Please enter a title for the entry...") return None text.text = str(self.logui.textEntry.toPlainText()) # If text field is truly empty, ElementTree leaves off tag entirely which causes logbook parser to fail if text.text == "": text.text = " " # Create xml file xmlFile = open(fileName, "w") if logType == "MCC": ElementTree(log_entry).write(xmlFile) else: xmlString = self.prettify(log_entry) xmlFile.write(xmlString) xmlFile.write("\n") # Close with newline so cron job parses correctly xmlFile.close() return fileName.rstrip(".xml")
[ "Create", "xml", "file", "with", "fields", "from", "logbook", "form", "." ]
joelfrederico/SciSalt
python
https://github.com/joelfrederico/SciSalt/blob/7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f/scisalt/facettools/logbookForm.py#L221-L326
[ "def", "xmlSetup", "(", "self", ",", "logType", ",", "logList", ")", ":", "from", "xml", ".", "etree", ".", "ElementTree", "import", "Element", ",", "SubElement", ",", "ElementTree", "from", "datetime", "import", "datetime", "curr_time", "=", "datetime", ".", "now", "(", ")", "if", "logType", "==", "\"MCC\"", ":", "# Set up xml tags", "log_entry", "=", "Element", "(", "'log_entry'", ")", "title", "=", "SubElement", "(", "log_entry", ",", "'title'", ")", "program", "=", "SubElement", "(", "log_entry", ",", "'program'", ")", "timestamp", "=", "SubElement", "(", "log_entry", ",", "'timestamp'", ")", "priority", "=", "SubElement", "(", "log_entry", ",", "'priority'", ")", "os_user", "=", "SubElement", "(", "log_entry", ",", "'os_user'", ")", "hostname", "=", "SubElement", "(", "log_entry", ",", "'hostname'", ")", "text", "=", "SubElement", "(", "log_entry", ",", "'text'", ")", "log_user", "=", "SubElement", "(", "log_entry", ",", "'log_user'", ")", "# Check for multiple logbooks and parse into seperate tags", "logbook", "=", "[", "]", "for", "i", "in", "range", "(", "len", "(", "logList", ")", ")", ":", "logbook", ".", "append", "(", "SubElement", "(", "log_entry", ",", "'logbook'", ")", ")", "logbook", "[", "i", "]", ".", "text", "=", "logList", "[", "i", "]", ".", "lower", "(", ")", "# Take care of dummy, unchanging tags first", "log_entry", ".", "attrib", "[", "'type'", "]", "=", "\"LOGENTRY\"", "program", ".", "text", "=", "\"152\"", "priority", ".", "text", "=", "\"NORMAL\"", "os_user", ".", "text", "=", "\"nobody\"", "hostname", ".", "text", "=", "\"mccelog\"", "text", ".", "attrib", "[", "'type'", "]", "=", "\"text/plain\"", "# Handle attachment if image exists", "if", "not", "self", ".", "imagePixmap", ".", "isNull", "(", ")", ":", "attachment", "=", "SubElement", "(", "log_entry", ",", "'attachment'", ")", "attachment", ".", "attrib", "[", "'name'", "]", "=", "\"Figure 1\"", "attachment", ".", "attrib", "[", "'type'", "]", "=", "\"image/\"", "+", "self", ".", "imageType", "attachment", ".", "text", "=", "curr_time", ".", "strftime", "(", "\"%Y%m%d_%H%M%S_\"", ")", "+", "str", "(", "curr_time", ".", "microsecond", ")", "+", "\".\"", "+", "self", ".", "imageType", "# Set timestamp format", "timestamp", ".", "text", "=", "curr_time", ".", "strftime", "(", "\"%Y/%m/%d %H:%M:%S\"", ")", "fileName", "=", "\"/tmp/\"", "+", "curr_time", ".", "strftime", "(", "\"%Y%m%d_%H%M%S_\"", ")", "+", "str", "(", "curr_time", ".", "microsecond", ")", "+", "\".xml\"", "else", ":", "# If using Physics logbook", "timeString", "=", "curr_time", ".", "strftime", "(", "\"%Y-%m-%dT%H:%M:%S\"", ")", "# Set up xml tags", "log_entry", "=", "Element", "(", "None", ")", "severity", "=", "SubElement", "(", "log_entry", ",", "'severity'", ")", "location", "=", "SubElement", "(", "log_entry", ",", "'location'", ")", "keywords", "=", "SubElement", "(", "log_entry", ",", "'keywords'", ")", "time", "=", "SubElement", "(", "log_entry", ",", "'time'", ")", "isodate", "=", "SubElement", "(", "log_entry", ",", "'isodate'", ")", "log_user", "=", "SubElement", "(", "log_entry", ",", "'author'", ")", "category", "=", "SubElement", "(", "log_entry", ",", "'category'", ")", "title", "=", "SubElement", "(", "log_entry", ",", "'title'", ")", "metainfo", "=", "SubElement", "(", "log_entry", ",", "'metainfo'", ")", "# Handle attachment if image exists", "if", "not", "self", ".", "imagePixmap", ".", "isNull", "(", ")", ":", "imageFile", "=", "SubElement", "(", "log_entry", ",", "'link'", ")", "imageFile", ".", "text", "=", "timeString", "+", "\"-00.\"", "+", "self", ".", "imageType", "thumbnail", "=", "SubElement", "(", "log_entry", ",", "'file'", ")", "thumbnail", ".", "text", "=", "timeString", "+", "\"-00.png\"", "text", "=", "SubElement", "(", "log_entry", ",", "'text'", ")", "# Logbook expects Text tag to come last (for some strange reason)", "# Take care of dummy, unchanging tags first", "log_entry", ".", "attrib", "[", "'type'", "]", "=", "\"LOGENTRY\"", "category", ".", "text", "=", "\"USERLOG\"", "location", ".", "text", "=", "\"not set\"", "severity", ".", "text", "=", "\"NONE\"", "keywords", ".", "text", "=", "\"none\"", "time", ".", "text", "=", "curr_time", ".", "strftime", "(", "\"%H:%M:%S\"", ")", "isodate", ".", "text", "=", "curr_time", ".", "strftime", "(", "\"%Y-%m-%d\"", ")", "metainfo", ".", "text", "=", "timeString", "+", "\"-00.xml\"", "fileName", "=", "\"/tmp/\"", "+", "metainfo", ".", "text", "# Fill in user inputs", "log_user", ".", "text", "=", "str", "(", "self", ".", "logui", ".", "userName", ".", "text", "(", ")", ")", "title", ".", "text", "=", "str", "(", "self", ".", "logui", ".", "titleEntry", ".", "text", "(", ")", ")", "if", "title", ".", "text", "==", "\"\"", ":", "QMessageBox", "(", ")", ".", "warning", "(", "self", ",", "\"No Title entered\"", ",", "\"Please enter a title for the entry...\"", ")", "return", "None", "text", ".", "text", "=", "str", "(", "self", ".", "logui", ".", "textEntry", ".", "toPlainText", "(", ")", ")", "# If text field is truly empty, ElementTree leaves off tag entirely which causes logbook parser to fail", "if", "text", ".", "text", "==", "\"\"", ":", "text", ".", "text", "=", "\" \"", "# Create xml file", "xmlFile", "=", "open", "(", "fileName", ",", "\"w\"", ")", "if", "logType", "==", "\"MCC\"", ":", "ElementTree", "(", "log_entry", ")", ".", "write", "(", "xmlFile", ")", "else", ":", "xmlString", "=", "self", ".", "prettify", "(", "log_entry", ")", "xmlFile", ".", "write", "(", "xmlString", ")", "xmlFile", ".", "write", "(", "\"\\n\"", ")", "# Close with newline so cron job parses correctly", "xmlFile", ".", "close", "(", ")", "return", "fileName", ".", "rstrip", "(", "\".xml\"", ")" ]
7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f
valid
logbookForm.prettify
Parse xml elements for pretty printing
scisalt/facettools/logbookForm.py
def prettify(self, elem): """Parse xml elements for pretty printing""" from xml.etree import ElementTree from re import sub rawString = ElementTree.tostring(elem, 'utf-8') parsedString = sub(r'(?=<[^/].*>)', '\n', rawString) # Adds newline after each closing tag return parsedString[1:]
def prettify(self, elem): """Parse xml elements for pretty printing""" from xml.etree import ElementTree from re import sub rawString = ElementTree.tostring(elem, 'utf-8') parsedString = sub(r'(?=<[^/].*>)', '\n', rawString) # Adds newline after each closing tag return parsedString[1:]
[ "Parse", "xml", "elements", "for", "pretty", "printing" ]
joelfrederico/SciSalt
python
https://github.com/joelfrederico/SciSalt/blob/7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f/scisalt/facettools/logbookForm.py#L328-L337
[ "def", "prettify", "(", "self", ",", "elem", ")", ":", "from", "xml", ".", "etree", "import", "ElementTree", "from", "re", "import", "sub", "rawString", "=", "ElementTree", ".", "tostring", "(", "elem", ",", "'utf-8'", ")", "parsedString", "=", "sub", "(", "r'(?=<[^/].*>)'", ",", "'\\n'", ",", "rawString", ")", "# Adds newline after each closing tag", "return", "parsedString", "[", "1", ":", "]" ]
7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f
valid
logbookForm.prepareImages
Convert supplied QPixmap object to image file.
scisalt/facettools/logbookForm.py
def prepareImages(self, fileName, logType): """Convert supplied QPixmap object to image file.""" import subprocess if self.imageType == "png": self.imagePixmap.save(fileName + ".png", "PNG", -1) if logType == "Physics": makePostScript = "convert " + fileName + ".png " + fileName + ".ps" process = subprocess.Popen(makePostScript, shell=True) process.wait() thumbnailPixmap = self.imagePixmap.scaled(500, 450, Qt.KeepAspectRatio) thumbnailPixmap.save(fileName + ".png", "PNG", -1) else: renameImage = "cp " + self.image + " " + fileName + ".gif" process = subprocess.Popen(renameImage, shell=True) process.wait() if logType == "Physics": thumbnailPixmap = self.imagePixmap.scaled(500, 450, Qt.KeepAspectRatio) thumbnailPixmap.save(fileName + ".png", "PNG", -1)
def prepareImages(self, fileName, logType): """Convert supplied QPixmap object to image file.""" import subprocess if self.imageType == "png": self.imagePixmap.save(fileName + ".png", "PNG", -1) if logType == "Physics": makePostScript = "convert " + fileName + ".png " + fileName + ".ps" process = subprocess.Popen(makePostScript, shell=True) process.wait() thumbnailPixmap = self.imagePixmap.scaled(500, 450, Qt.KeepAspectRatio) thumbnailPixmap.save(fileName + ".png", "PNG", -1) else: renameImage = "cp " + self.image + " " + fileName + ".gif" process = subprocess.Popen(renameImage, shell=True) process.wait() if logType == "Physics": thumbnailPixmap = self.imagePixmap.scaled(500, 450, Qt.KeepAspectRatio) thumbnailPixmap.save(fileName + ".png", "PNG", -1)
[ "Convert", "supplied", "QPixmap", "object", "to", "image", "file", "." ]
joelfrederico/SciSalt
python
https://github.com/joelfrederico/SciSalt/blob/7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f/scisalt/facettools/logbookForm.py#L339-L357
[ "def", "prepareImages", "(", "self", ",", "fileName", ",", "logType", ")", ":", "import", "subprocess", "if", "self", ".", "imageType", "==", "\"png\"", ":", "self", ".", "imagePixmap", ".", "save", "(", "fileName", "+", "\".png\"", ",", "\"PNG\"", ",", "-", "1", ")", "if", "logType", "==", "\"Physics\"", ":", "makePostScript", "=", "\"convert \"", "+", "fileName", "+", "\".png \"", "+", "fileName", "+", "\".ps\"", "process", "=", "subprocess", ".", "Popen", "(", "makePostScript", ",", "shell", "=", "True", ")", "process", ".", "wait", "(", ")", "thumbnailPixmap", "=", "self", ".", "imagePixmap", ".", "scaled", "(", "500", ",", "450", ",", "Qt", ".", "KeepAspectRatio", ")", "thumbnailPixmap", ".", "save", "(", "fileName", "+", "\".png\"", ",", "\"PNG\"", ",", "-", "1", ")", "else", ":", "renameImage", "=", "\"cp \"", "+", "self", ".", "image", "+", "\" \"", "+", "fileName", "+", "\".gif\"", "process", "=", "subprocess", ".", "Popen", "(", "renameImage", ",", "shell", "=", "True", ")", "process", ".", "wait", "(", ")", "if", "logType", "==", "\"Physics\"", ":", "thumbnailPixmap", "=", "self", ".", "imagePixmap", ".", "scaled", "(", "500", ",", "450", ",", "Qt", ".", "KeepAspectRatio", ")", "thumbnailPixmap", ".", "save", "(", "fileName", "+", "\".png\"", ",", "\"PNG\"", ",", "-", "1", ")" ]
7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f
valid
logbookForm.submitEntry
Process user inputs and subit logbook entry when user clicks Submit button
scisalt/facettools/logbookForm.py
def submitEntry(self): """Process user inputs and subit logbook entry when user clicks Submit button""" # logType = self.logui.logType.currentText() mcclogs, physlogs = self.selectedLogs() success = True if mcclogs != []: if not self.acceptedUser("MCC"): QMessageBox().warning(self, "Invalid User", "Please enter a valid user name!") return fileName = self.xmlSetup("MCC", mcclogs) if fileName is None: return if not self.imagePixmap.isNull(): self.prepareImages(fileName, "MCC") success = self.sendToLogbook(fileName, "MCC") if physlogs != []: for i in range(len(physlogs)): fileName = self.xmlSetup("Physics", physlogs[i]) if fileName is None: return if not self.imagePixmap.isNull(): self.prepareImages(fileName, "Physics") success_phys = self.sendToLogbook(fileName, "Physics", physlogs[i]) success = success and success_phys self.done(success)
def submitEntry(self): """Process user inputs and subit logbook entry when user clicks Submit button""" # logType = self.logui.logType.currentText() mcclogs, physlogs = self.selectedLogs() success = True if mcclogs != []: if not self.acceptedUser("MCC"): QMessageBox().warning(self, "Invalid User", "Please enter a valid user name!") return fileName = self.xmlSetup("MCC", mcclogs) if fileName is None: return if not self.imagePixmap.isNull(): self.prepareImages(fileName, "MCC") success = self.sendToLogbook(fileName, "MCC") if physlogs != []: for i in range(len(physlogs)): fileName = self.xmlSetup("Physics", physlogs[i]) if fileName is None: return if not self.imagePixmap.isNull(): self.prepareImages(fileName, "Physics") success_phys = self.sendToLogbook(fileName, "Physics", physlogs[i]) success = success and success_phys self.done(success)
[ "Process", "user", "inputs", "and", "subit", "logbook", "entry", "when", "user", "clicks", "Submit", "button" ]
joelfrederico/SciSalt
python
https://github.com/joelfrederico/SciSalt/blob/7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f/scisalt/facettools/logbookForm.py#L359-L390
[ "def", "submitEntry", "(", "self", ")", ":", "# logType = self.logui.logType.currentText()", "mcclogs", ",", "physlogs", "=", "self", ".", "selectedLogs", "(", ")", "success", "=", "True", "if", "mcclogs", "!=", "[", "]", ":", "if", "not", "self", ".", "acceptedUser", "(", "\"MCC\"", ")", ":", "QMessageBox", "(", ")", ".", "warning", "(", "self", ",", "\"Invalid User\"", ",", "\"Please enter a valid user name!\"", ")", "return", "fileName", "=", "self", ".", "xmlSetup", "(", "\"MCC\"", ",", "mcclogs", ")", "if", "fileName", "is", "None", ":", "return", "if", "not", "self", ".", "imagePixmap", ".", "isNull", "(", ")", ":", "self", ".", "prepareImages", "(", "fileName", ",", "\"MCC\"", ")", "success", "=", "self", ".", "sendToLogbook", "(", "fileName", ",", "\"MCC\"", ")", "if", "physlogs", "!=", "[", "]", ":", "for", "i", "in", "range", "(", "len", "(", "physlogs", ")", ")", ":", "fileName", "=", "self", ".", "xmlSetup", "(", "\"Physics\"", ",", "physlogs", "[", "i", "]", ")", "if", "fileName", "is", "None", ":", "return", "if", "not", "self", ".", "imagePixmap", ".", "isNull", "(", ")", ":", "self", ".", "prepareImages", "(", "fileName", ",", "\"Physics\"", ")", "success_phys", "=", "self", ".", "sendToLogbook", "(", "fileName", ",", "\"Physics\"", ",", "physlogs", "[", "i", "]", ")", "success", "=", "success", "and", "success_phys", "self", ".", "done", "(", "success", ")" ]
7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f
valid
logbookForm.sendToLogbook
Process log information and push to selected logbooks.
scisalt/facettools/logbookForm.py
def sendToLogbook(self, fileName, logType, location=None): '''Process log information and push to selected logbooks.''' import subprocess success = True if logType == "MCC": fileString = "" if not self.imagePixmap.isNull(): fileString = fileName + "." + self.imageType logcmd = "xml2elog " + fileName + ".xml " + fileString process = subprocess.Popen(logcmd, shell=True) process.wait() if process.returncode != 0: success = False else: from shutil import copy path = "/u1/" + location.lower() + "/physics/logbook/data/" # Prod path # path = "/home/softegr/alverson/log_test/" # Dev path try: if not self.imagePixmap.isNull(): copy(fileName + ".png", path) if self.imageType == "png": copy(fileName + ".ps", path) else: copy(fileName + "." + self.imageType, path) # Copy .xml file last to ensure images will be picked up by cron job # print("Copying file " + fileName + " to path " + path) copy(fileName + ".xml", path) except IOError as error: print(error) success = False return success
def sendToLogbook(self, fileName, logType, location=None): '''Process log information and push to selected logbooks.''' import subprocess success = True if logType == "MCC": fileString = "" if not self.imagePixmap.isNull(): fileString = fileName + "." + self.imageType logcmd = "xml2elog " + fileName + ".xml " + fileString process = subprocess.Popen(logcmd, shell=True) process.wait() if process.returncode != 0: success = False else: from shutil import copy path = "/u1/" + location.lower() + "/physics/logbook/data/" # Prod path # path = "/home/softegr/alverson/log_test/" # Dev path try: if not self.imagePixmap.isNull(): copy(fileName + ".png", path) if self.imageType == "png": copy(fileName + ".ps", path) else: copy(fileName + "." + self.imageType, path) # Copy .xml file last to ensure images will be picked up by cron job # print("Copying file " + fileName + " to path " + path) copy(fileName + ".xml", path) except IOError as error: print(error) success = False return success
[ "Process", "log", "information", "and", "push", "to", "selected", "logbooks", "." ]
joelfrederico/SciSalt
python
https://github.com/joelfrederico/SciSalt/blob/7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f/scisalt/facettools/logbookForm.py#L392-L427
[ "def", "sendToLogbook", "(", "self", ",", "fileName", ",", "logType", ",", "location", "=", "None", ")", ":", "import", "subprocess", "success", "=", "True", "if", "logType", "==", "\"MCC\"", ":", "fileString", "=", "\"\"", "if", "not", "self", ".", "imagePixmap", ".", "isNull", "(", ")", ":", "fileString", "=", "fileName", "+", "\".\"", "+", "self", ".", "imageType", "logcmd", "=", "\"xml2elog \"", "+", "fileName", "+", "\".xml \"", "+", "fileString", "process", "=", "subprocess", ".", "Popen", "(", "logcmd", ",", "shell", "=", "True", ")", "process", ".", "wait", "(", ")", "if", "process", ".", "returncode", "!=", "0", ":", "success", "=", "False", "else", ":", "from", "shutil", "import", "copy", "path", "=", "\"/u1/\"", "+", "location", ".", "lower", "(", ")", "+", "\"/physics/logbook/data/\"", "# Prod path", "# path = \"/home/softegr/alverson/log_test/\" # Dev path", "try", ":", "if", "not", "self", ".", "imagePixmap", ".", "isNull", "(", ")", ":", "copy", "(", "fileName", "+", "\".png\"", ",", "path", ")", "if", "self", ".", "imageType", "==", "\"png\"", ":", "copy", "(", "fileName", "+", "\".ps\"", ",", "path", ")", "else", ":", "copy", "(", "fileName", "+", "\".\"", "+", "self", ".", "imageType", ",", "path", ")", "# Copy .xml file last to ensure images will be picked up by cron job", "# print(\"Copying file \" + fileName + \" to path \" + path)", "copy", "(", "fileName", "+", "\".xml\"", ",", "path", ")", "except", "IOError", "as", "error", ":", "print", "(", "error", ")", "success", "=", "False", "return", "success" ]
7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f
valid
logbookForm.clearForm
Clear all form fields (except author).
scisalt/facettools/logbookForm.py
def clearForm(self): """Clear all form fields (except author).""" self.logui.titleEntry.clear() self.logui.textEntry.clear() # Remove all log selection menus except the first while self.logMenuCount > 1: self.removeLogbook(self.logMenus[-1])
def clearForm(self): """Clear all form fields (except author).""" self.logui.titleEntry.clear() self.logui.textEntry.clear() # Remove all log selection menus except the first while self.logMenuCount > 1: self.removeLogbook(self.logMenus[-1])
[ "Clear", "all", "form", "fields", "(", "except", "author", ")", "." ]
joelfrederico/SciSalt
python
https://github.com/joelfrederico/SciSalt/blob/7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f/scisalt/facettools/logbookForm.py#L429-L437
[ "def", "clearForm", "(", "self", ")", ":", "self", ".", "logui", ".", "titleEntry", ".", "clear", "(", ")", "self", ".", "logui", ".", "textEntry", ".", "clear", "(", ")", "# Remove all log selection menus except the first", "while", "self", ".", "logMenuCount", ">", "1", ":", "self", ".", "removeLogbook", "(", "self", ".", "logMenus", "[", "-", "1", "]", ")" ]
7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f
valid
LogSelectMenu.setupUI
Create graphical objects for menus.
scisalt/facettools/logbookForm.py
def setupUI(self): '''Create graphical objects for menus.''' labelSizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) labelSizePolicy.setHorizontalStretch(0) labelSizePolicy.setVerticalStretch(0) menuSizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed) menuSizePolicy.setHorizontalStretch(0) menuSizePolicy.setVerticalStretch(0) logTypeLayout = QHBoxLayout() logTypeLayout.setSpacing(0) typeLabel = QLabel("Log Type:") typeLabel.setMinimumSize(QSize(65, 0)) typeLabel.setMaximumSize(QSize(65, 16777215)) typeLabel.setSizePolicy(labelSizePolicy) logTypeLayout.addWidget(typeLabel) self.logType = QComboBox(self) self.logType.setMinimumSize(QSize(100, 0)) self.logType.setMaximumSize(QSize(150, 16777215)) menuSizePolicy.setHeightForWidth(self.logType.sizePolicy().hasHeightForWidth()) self.logType.setSizePolicy(menuSizePolicy) logTypeLayout.addWidget(self.logType) logTypeLayout.setStretch(1, 6) programLayout = QHBoxLayout() programLayout.setSpacing(0) programLabel = QLabel("Program:") programLabel.setMinimumSize(QSize(60, 0)) programLabel.setMaximumSize(QSize(60, 16777215)) programLabel.setSizePolicy(labelSizePolicy) programLayout.addWidget(programLabel) self.programName = QComboBox(self) self.programName.setMinimumSize(QSize(100, 0)) self.programName.setMaximumSize(QSize(150, 16777215)) menuSizePolicy.setHeightForWidth(self.programName.sizePolicy().hasHeightForWidth()) self.programName.setSizePolicy(menuSizePolicy) programLayout.addWidget(self.programName) programLayout.setStretch(1, 6) # Initial instance allows adding additional menus, all following menus can only remove themselves. if self.initialInstance: self.logButton = QPushButton("+", self) self.logButton.setToolTip("Add logbook") else: self.logButton = QPushButton("-") self.logButton.setToolTip("Remove logbook") self.logButton.setMinimumSize(QSize(16, 16)) # 24x24 self.logButton.setMaximumSize(QSize(16, 16)) # 24x24 self.logButton.setObjectName("roundButton") # self.logButton.setAutoFillBackground(True) # region = QRegion(QRect(self.logButton.x()+15, self.logButton.y()+14, 20, 20), QRegion.Ellipse) # self.logButton.setMask(region) self.logButton.setStyleSheet("QPushButton {border-radius: 8px;}") self._logSelectLayout = QHBoxLayout() self._logSelectLayout.setSpacing(6) self._logSelectLayout.addLayout(logTypeLayout) self._logSelectLayout.addLayout(programLayout) self._logSelectLayout.addWidget(self.logButton) self._logSelectLayout.setStretch(0, 6) self._logSelectLayout.setStretch(1, 6)
def setupUI(self): '''Create graphical objects for menus.''' labelSizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) labelSizePolicy.setHorizontalStretch(0) labelSizePolicy.setVerticalStretch(0) menuSizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed) menuSizePolicy.setHorizontalStretch(0) menuSizePolicy.setVerticalStretch(0) logTypeLayout = QHBoxLayout() logTypeLayout.setSpacing(0) typeLabel = QLabel("Log Type:") typeLabel.setMinimumSize(QSize(65, 0)) typeLabel.setMaximumSize(QSize(65, 16777215)) typeLabel.setSizePolicy(labelSizePolicy) logTypeLayout.addWidget(typeLabel) self.logType = QComboBox(self) self.logType.setMinimumSize(QSize(100, 0)) self.logType.setMaximumSize(QSize(150, 16777215)) menuSizePolicy.setHeightForWidth(self.logType.sizePolicy().hasHeightForWidth()) self.logType.setSizePolicy(menuSizePolicy) logTypeLayout.addWidget(self.logType) logTypeLayout.setStretch(1, 6) programLayout = QHBoxLayout() programLayout.setSpacing(0) programLabel = QLabel("Program:") programLabel.setMinimumSize(QSize(60, 0)) programLabel.setMaximumSize(QSize(60, 16777215)) programLabel.setSizePolicy(labelSizePolicy) programLayout.addWidget(programLabel) self.programName = QComboBox(self) self.programName.setMinimumSize(QSize(100, 0)) self.programName.setMaximumSize(QSize(150, 16777215)) menuSizePolicy.setHeightForWidth(self.programName.sizePolicy().hasHeightForWidth()) self.programName.setSizePolicy(menuSizePolicy) programLayout.addWidget(self.programName) programLayout.setStretch(1, 6) # Initial instance allows adding additional menus, all following menus can only remove themselves. if self.initialInstance: self.logButton = QPushButton("+", self) self.logButton.setToolTip("Add logbook") else: self.logButton = QPushButton("-") self.logButton.setToolTip("Remove logbook") self.logButton.setMinimumSize(QSize(16, 16)) # 24x24 self.logButton.setMaximumSize(QSize(16, 16)) # 24x24 self.logButton.setObjectName("roundButton") # self.logButton.setAutoFillBackground(True) # region = QRegion(QRect(self.logButton.x()+15, self.logButton.y()+14, 20, 20), QRegion.Ellipse) # self.logButton.setMask(region) self.logButton.setStyleSheet("QPushButton {border-radius: 8px;}") self._logSelectLayout = QHBoxLayout() self._logSelectLayout.setSpacing(6) self._logSelectLayout.addLayout(logTypeLayout) self._logSelectLayout.addLayout(programLayout) self._logSelectLayout.addWidget(self.logButton) self._logSelectLayout.setStretch(0, 6) self._logSelectLayout.setStretch(1, 6)
[ "Create", "graphical", "objects", "for", "menus", "." ]
joelfrederico/SciSalt
python
https://github.com/joelfrederico/SciSalt/blob/7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f/scisalt/facettools/logbookForm.py#L454-L519
[ "def", "setupUI", "(", "self", ")", ":", "labelSizePolicy", "=", "QSizePolicy", "(", "QSizePolicy", ".", "Fixed", ",", "QSizePolicy", ".", "Fixed", ")", "labelSizePolicy", ".", "setHorizontalStretch", "(", "0", ")", "labelSizePolicy", ".", "setVerticalStretch", "(", "0", ")", "menuSizePolicy", "=", "QSizePolicy", "(", "QSizePolicy", ".", "Expanding", ",", "QSizePolicy", ".", "Fixed", ")", "menuSizePolicy", ".", "setHorizontalStretch", "(", "0", ")", "menuSizePolicy", ".", "setVerticalStretch", "(", "0", ")", "logTypeLayout", "=", "QHBoxLayout", "(", ")", "logTypeLayout", ".", "setSpacing", "(", "0", ")", "typeLabel", "=", "QLabel", "(", "\"Log Type:\"", ")", "typeLabel", ".", "setMinimumSize", "(", "QSize", "(", "65", ",", "0", ")", ")", "typeLabel", ".", "setMaximumSize", "(", "QSize", "(", "65", ",", "16777215", ")", ")", "typeLabel", ".", "setSizePolicy", "(", "labelSizePolicy", ")", "logTypeLayout", ".", "addWidget", "(", "typeLabel", ")", "self", ".", "logType", "=", "QComboBox", "(", "self", ")", "self", ".", "logType", ".", "setMinimumSize", "(", "QSize", "(", "100", ",", "0", ")", ")", "self", ".", "logType", ".", "setMaximumSize", "(", "QSize", "(", "150", ",", "16777215", ")", ")", "menuSizePolicy", ".", "setHeightForWidth", "(", "self", ".", "logType", ".", "sizePolicy", "(", ")", ".", "hasHeightForWidth", "(", ")", ")", "self", ".", "logType", ".", "setSizePolicy", "(", "menuSizePolicy", ")", "logTypeLayout", ".", "addWidget", "(", "self", ".", "logType", ")", "logTypeLayout", ".", "setStretch", "(", "1", ",", "6", ")", "programLayout", "=", "QHBoxLayout", "(", ")", "programLayout", ".", "setSpacing", "(", "0", ")", "programLabel", "=", "QLabel", "(", "\"Program:\"", ")", "programLabel", ".", "setMinimumSize", "(", "QSize", "(", "60", ",", "0", ")", ")", "programLabel", ".", "setMaximumSize", "(", "QSize", "(", "60", ",", "16777215", ")", ")", "programLabel", ".", "setSizePolicy", "(", "labelSizePolicy", ")", "programLayout", ".", "addWidget", "(", "programLabel", ")", "self", ".", "programName", "=", "QComboBox", "(", "self", ")", "self", ".", "programName", ".", "setMinimumSize", "(", "QSize", "(", "100", ",", "0", ")", ")", "self", ".", "programName", ".", "setMaximumSize", "(", "QSize", "(", "150", ",", "16777215", ")", ")", "menuSizePolicy", ".", "setHeightForWidth", "(", "self", ".", "programName", ".", "sizePolicy", "(", ")", ".", "hasHeightForWidth", "(", ")", ")", "self", ".", "programName", ".", "setSizePolicy", "(", "menuSizePolicy", ")", "programLayout", ".", "addWidget", "(", "self", ".", "programName", ")", "programLayout", ".", "setStretch", "(", "1", ",", "6", ")", "# Initial instance allows adding additional menus, all following menus can only remove themselves.", "if", "self", ".", "initialInstance", ":", "self", ".", "logButton", "=", "QPushButton", "(", "\"+\"", ",", "self", ")", "self", ".", "logButton", ".", "setToolTip", "(", "\"Add logbook\"", ")", "else", ":", "self", ".", "logButton", "=", "QPushButton", "(", "\"-\"", ")", "self", ".", "logButton", ".", "setToolTip", "(", "\"Remove logbook\"", ")", "self", ".", "logButton", ".", "setMinimumSize", "(", "QSize", "(", "16", ",", "16", ")", ")", "# 24x24", "self", ".", "logButton", ".", "setMaximumSize", "(", "QSize", "(", "16", ",", "16", ")", ")", "# 24x24", "self", ".", "logButton", ".", "setObjectName", "(", "\"roundButton\"", ")", "# self.logButton.setAutoFillBackground(True)", "# region = QRegion(QRect(self.logButton.x()+15, self.logButton.y()+14, 20, 20), QRegion.Ellipse)", "# self.logButton.setMask(region)", "self", ".", "logButton", ".", "setStyleSheet", "(", "\"QPushButton {border-radius: 8px;}\"", ")", "self", ".", "_logSelectLayout", "=", "QHBoxLayout", "(", ")", "self", ".", "_logSelectLayout", ".", "setSpacing", "(", "6", ")", "self", ".", "_logSelectLayout", ".", "addLayout", "(", "logTypeLayout", ")", "self", ".", "_logSelectLayout", ".", "addLayout", "(", "programLayout", ")", "self", ".", "_logSelectLayout", ".", "addWidget", "(", "self", ".", "logButton", ")", "self", ".", "_logSelectLayout", ".", "setStretch", "(", "0", ",", "6", ")", "self", ".", "_logSelectLayout", ".", "setStretch", "(", "1", ",", "6", ")" ]
7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f
valid
LogSelectMenu.show
Display menus and connect even signals.
scisalt/facettools/logbookForm.py
def show(self): '''Display menus and connect even signals.''' self.parent.addLayout(self._logSelectLayout) self.menuCount += 1 self._connectSlots()
def show(self): '''Display menus and connect even signals.''' self.parent.addLayout(self._logSelectLayout) self.menuCount += 1 self._connectSlots()
[ "Display", "menus", "and", "connect", "even", "signals", "." ]
joelfrederico/SciSalt
python
https://github.com/joelfrederico/SciSalt/blob/7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f/scisalt/facettools/logbookForm.py#L526-L530
[ "def", "show", "(", "self", ")", ":", "self", ".", "parent", ".", "addLayout", "(", "self", ".", "_logSelectLayout", ")", "self", ".", "menuCount", "+=", "1", "self", ".", "_connectSlots", "(", ")" ]
7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f
valid
LogSelectMenu.addLogbooks
Add or change list of logbooks.
scisalt/facettools/logbookForm.py
def addLogbooks(self, type=None, logs=[], default=""): '''Add or change list of logbooks.''' if type is not None and len(logs) != 0: if type in self.logList: for logbook in logs: if logbook not in self.logList.get(type)[0]: # print("Adding log " + " to " + type + " log type.") self.logList.get(type)[0].append(logbook) else: # print("Adding log type: " + type) self.logList[type] = [] self.logList[type].append(logs) # If default given, auto-select upon menu creation if len(self.logList[type]) > 1 and default != "": self.logList.get(type)[1] == default else: self.logList.get(type).append(default) self.logType.clear() self.logType.addItems(list(self.logList.keys())) self.changeLogType()
def addLogbooks(self, type=None, logs=[], default=""): '''Add or change list of logbooks.''' if type is not None and len(logs) != 0: if type in self.logList: for logbook in logs: if logbook not in self.logList.get(type)[0]: # print("Adding log " + " to " + type + " log type.") self.logList.get(type)[0].append(logbook) else: # print("Adding log type: " + type) self.logList[type] = [] self.logList[type].append(logs) # If default given, auto-select upon menu creation if len(self.logList[type]) > 1 and default != "": self.logList.get(type)[1] == default else: self.logList.get(type).append(default) self.logType.clear() self.logType.addItems(list(self.logList.keys())) self.changeLogType()
[ "Add", "or", "change", "list", "of", "logbooks", "." ]
joelfrederico/SciSalt
python
https://github.com/joelfrederico/SciSalt/blob/7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f/scisalt/facettools/logbookForm.py#L538-L559
[ "def", "addLogbooks", "(", "self", ",", "type", "=", "None", ",", "logs", "=", "[", "]", ",", "default", "=", "\"\"", ")", ":", "if", "type", "is", "not", "None", "and", "len", "(", "logs", ")", "!=", "0", ":", "if", "type", "in", "self", ".", "logList", ":", "for", "logbook", "in", "logs", ":", "if", "logbook", "not", "in", "self", ".", "logList", ".", "get", "(", "type", ")", "[", "0", "]", ":", "# print(\"Adding log \" + \" to \" + type + \" log type.\")", "self", ".", "logList", ".", "get", "(", "type", ")", "[", "0", "]", ".", "append", "(", "logbook", ")", "else", ":", "# print(\"Adding log type: \" + type)", "self", ".", "logList", "[", "type", "]", "=", "[", "]", "self", ".", "logList", "[", "type", "]", ".", "append", "(", "logs", ")", "# If default given, auto-select upon menu creation", "if", "len", "(", "self", ".", "logList", "[", "type", "]", ")", ">", "1", "and", "default", "!=", "\"\"", ":", "self", ".", "logList", ".", "get", "(", "type", ")", "[", "1", "]", "==", "default", "else", ":", "self", ".", "logList", ".", "get", "(", "type", ")", ".", "append", "(", "default", ")", "self", ".", "logType", ".", "clear", "(", ")", "self", ".", "logType", ".", "addItems", "(", "list", "(", "self", ".", "logList", ".", "keys", "(", ")", ")", ")", "self", ".", "changeLogType", "(", ")" ]
7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f
valid
LogSelectMenu.removeLogbooks
Remove unwanted logbooks from list.
scisalt/facettools/logbookForm.py
def removeLogbooks(self, type=None, logs=[]): '''Remove unwanted logbooks from list.''' if type is not None and type in self.logList: if len(logs) == 0 or logs == "All": del self.logList[type] else: for logbook in logs: if logbook in self.logList[type]: self.logList[type].remove(logbook) self.changeLogType()
def removeLogbooks(self, type=None, logs=[]): '''Remove unwanted logbooks from list.''' if type is not None and type in self.logList: if len(logs) == 0 or logs == "All": del self.logList[type] else: for logbook in logs: if logbook in self.logList[type]: self.logList[type].remove(logbook) self.changeLogType()
[ "Remove", "unwanted", "logbooks", "from", "list", "." ]
joelfrederico/SciSalt
python
https://github.com/joelfrederico/SciSalt/blob/7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f/scisalt/facettools/logbookForm.py#L561-L571
[ "def", "removeLogbooks", "(", "self", ",", "type", "=", "None", ",", "logs", "=", "[", "]", ")", ":", "if", "type", "is", "not", "None", "and", "type", "in", "self", ".", "logList", ":", "if", "len", "(", "logs", ")", "==", "0", "or", "logs", "==", "\"All\"", ":", "del", "self", ".", "logList", "[", "type", "]", "else", ":", "for", "logbook", "in", "logs", ":", "if", "logbook", "in", "self", ".", "logList", "[", "type", "]", ":", "self", ".", "logList", "[", "type", "]", ".", "remove", "(", "logbook", ")", "self", ".", "changeLogType", "(", ")" ]
7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f
valid
LogSelectMenu.changeLogType
Populate log program list to correspond with log type selection.
scisalt/facettools/logbookForm.py
def changeLogType(self): '''Populate log program list to correspond with log type selection.''' logType = self.selectedType() programs = self.logList.get(logType)[0] default = self.logList.get(logType)[1] if logType in self.logList: self.programName.clear() self.programName.addItems(programs) self.programName.setCurrentIndex(programs.index(default))
def changeLogType(self): '''Populate log program list to correspond with log type selection.''' logType = self.selectedType() programs = self.logList.get(logType)[0] default = self.logList.get(logType)[1] if logType in self.logList: self.programName.clear() self.programName.addItems(programs) self.programName.setCurrentIndex(programs.index(default))
[ "Populate", "log", "program", "list", "to", "correspond", "with", "log", "type", "selection", "." ]
joelfrederico/SciSalt
python
https://github.com/joelfrederico/SciSalt/blob/7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f/scisalt/facettools/logbookForm.py#L573-L581
[ "def", "changeLogType", "(", "self", ")", ":", "logType", "=", "self", ".", "selectedType", "(", ")", "programs", "=", "self", ".", "logList", ".", "get", "(", "logType", ")", "[", "0", "]", "default", "=", "self", ".", "logList", ".", "get", "(", "logType", ")", "[", "1", "]", "if", "logType", "in", "self", ".", "logList", ":", "self", ".", "programName", ".", "clear", "(", ")", "self", ".", "programName", ".", "addItems", "(", "programs", ")", "self", ".", "programName", ".", "setCurrentIndex", "(", "programs", ".", "index", "(", "default", ")", ")" ]
7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f
valid
LogSelectMenu.addMenu
Add menus to parent gui.
scisalt/facettools/logbookForm.py
def addMenu(self): '''Add menus to parent gui.''' self.parent.multiLogLayout.addLayout(self.logSelectLayout) self.getPrograms(logType, programName)
def addMenu(self): '''Add menus to parent gui.''' self.parent.multiLogLayout.addLayout(self.logSelectLayout) self.getPrograms(logType, programName)
[ "Add", "menus", "to", "parent", "gui", "." ]
joelfrederico/SciSalt
python
https://github.com/joelfrederico/SciSalt/blob/7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f/scisalt/facettools/logbookForm.py#L583-L586
[ "def", "addMenu", "(", "self", ")", ":", "self", ".", "parent", ".", "multiLogLayout", ".", "addLayout", "(", "self", ".", "logSelectLayout", ")", "self", ".", "getPrograms", "(", "logType", ",", "programName", ")" ]
7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f
valid
LogSelectMenu.removeLayout
Iteratively remove graphical objects from layout.
scisalt/facettools/logbookForm.py
def removeLayout(self, layout): '''Iteratively remove graphical objects from layout.''' for cnt in reversed(range(layout.count())): item = layout.takeAt(cnt) widget = item.widget() if widget is not None: widget.deleteLater() else: '''If sublayout encountered, iterate recursively.''' self.removeLayout(item.layout())
def removeLayout(self, layout): '''Iteratively remove graphical objects from layout.''' for cnt in reversed(range(layout.count())): item = layout.takeAt(cnt) widget = item.widget() if widget is not None: widget.deleteLater() else: '''If sublayout encountered, iterate recursively.''' self.removeLayout(item.layout())
[ "Iteratively", "remove", "graphical", "objects", "from", "layout", "." ]
joelfrederico/SciSalt
python
https://github.com/joelfrederico/SciSalt/blob/7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f/scisalt/facettools/logbookForm.py#L588-L597
[ "def", "removeLayout", "(", "self", ",", "layout", ")", ":", "for", "cnt", "in", "reversed", "(", "range", "(", "layout", ".", "count", "(", ")", ")", ")", ":", "item", "=", "layout", ".", "takeAt", "(", "cnt", ")", "widget", "=", "item", ".", "widget", "(", ")", "if", "widget", "is", "not", "None", ":", "widget", ".", "deleteLater", "(", ")", "else", ":", "'''If sublayout encountered, iterate recursively.'''", "self", ".", "removeLayout", "(", "item", ".", "layout", "(", ")", ")" ]
7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f
valid
addlabel
Adds labels to a plot.
scisalt/matplotlib/addlabel.py
def addlabel(ax=None, toplabel=None, xlabel=None, ylabel=None, zlabel=None, clabel=None, cb=None, windowlabel=None, fig=None, axes=None): """Adds labels to a plot.""" if (axes is None) and (ax is not None): axes = ax if (windowlabel is not None) and (fig is not None): fig.canvas.set_window_title(windowlabel) if fig is None: fig = _plt.gcf() if fig is not None and axes is None: axes = fig.get_axes() if axes == []: logger.error('No axes found!') if axes is not None: if toplabel is not None: axes.set_title(toplabel) if xlabel is not None: axes.set_xlabel(xlabel) if ylabel is not None: axes.set_ylabel(ylabel) if zlabel is not None: axes.set_zlabel(zlabel) if (clabel is not None) or (cb is not None): if (clabel is not None) and (cb is not None): cb.set_label(clabel) else: if clabel is None: logger.error('Missing colorbar label') else: logger.error('Missing colorbar instance')
def addlabel(ax=None, toplabel=None, xlabel=None, ylabel=None, zlabel=None, clabel=None, cb=None, windowlabel=None, fig=None, axes=None): """Adds labels to a plot.""" if (axes is None) and (ax is not None): axes = ax if (windowlabel is not None) and (fig is not None): fig.canvas.set_window_title(windowlabel) if fig is None: fig = _plt.gcf() if fig is not None and axes is None: axes = fig.get_axes() if axes == []: logger.error('No axes found!') if axes is not None: if toplabel is not None: axes.set_title(toplabel) if xlabel is not None: axes.set_xlabel(xlabel) if ylabel is not None: axes.set_ylabel(ylabel) if zlabel is not None: axes.set_zlabel(zlabel) if (clabel is not None) or (cb is not None): if (clabel is not None) and (cb is not None): cb.set_label(clabel) else: if clabel is None: logger.error('Missing colorbar label') else: logger.error('Missing colorbar instance')
[ "Adds", "labels", "to", "a", "plot", "." ]
joelfrederico/SciSalt
python
https://github.com/joelfrederico/SciSalt/blob/7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f/scisalt/matplotlib/addlabel.py#L9-L43
[ "def", "addlabel", "(", "ax", "=", "None", ",", "toplabel", "=", "None", ",", "xlabel", "=", "None", ",", "ylabel", "=", "None", ",", "zlabel", "=", "None", ",", "clabel", "=", "None", ",", "cb", "=", "None", ",", "windowlabel", "=", "None", ",", "fig", "=", "None", ",", "axes", "=", "None", ")", ":", "if", "(", "axes", "is", "None", ")", "and", "(", "ax", "is", "not", "None", ")", ":", "axes", "=", "ax", "if", "(", "windowlabel", "is", "not", "None", ")", "and", "(", "fig", "is", "not", "None", ")", ":", "fig", ".", "canvas", ".", "set_window_title", "(", "windowlabel", ")", "if", "fig", "is", "None", ":", "fig", "=", "_plt", ".", "gcf", "(", ")", "if", "fig", "is", "not", "None", "and", "axes", "is", "None", ":", "axes", "=", "fig", ".", "get_axes", "(", ")", "if", "axes", "==", "[", "]", ":", "logger", ".", "error", "(", "'No axes found!'", ")", "if", "axes", "is", "not", "None", ":", "if", "toplabel", "is", "not", "None", ":", "axes", ".", "set_title", "(", "toplabel", ")", "if", "xlabel", "is", "not", "None", ":", "axes", ".", "set_xlabel", "(", "xlabel", ")", "if", "ylabel", "is", "not", "None", ":", "axes", ".", "set_ylabel", "(", "ylabel", ")", "if", "zlabel", "is", "not", "None", ":", "axes", ".", "set_zlabel", "(", "zlabel", ")", "if", "(", "clabel", "is", "not", "None", ")", "or", "(", "cb", "is", "not", "None", ")", ":", "if", "(", "clabel", "is", "not", "None", ")", "and", "(", "cb", "is", "not", "None", ")", ":", "cb", ".", "set_label", "(", "clabel", ")", "else", ":", "if", "clabel", "is", "None", ":", "logger", ".", "error", "(", "'Missing colorbar label'", ")", "else", ":", "logger", ".", "error", "(", "'Missing colorbar instance'", ")" ]
7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f
valid
linkcode_resolve
Determine the URL corresponding to Python object
docs/conf.py
def linkcode_resolve(domain, info): """ Determine the URL corresponding to Python object """ if domain != 'py': return None modname = info['module'] fullname = info['fullname'] submod = sys.modules.get(modname) if submod is None: return None obj = submod for part in fullname.split('.'): try: obj = getattr(obj, part) except: return None try: fn = inspect.getsourcefile(obj) except: fn = None if not fn: return None try: source, lineno = inspect.getsourcelines(obj) except: lineno = None if lineno: linespec = "#L%d-L%d" % (lineno, lineno + len(source) - 1) else: linespec = "" fn = relpath(fn, start=dirname(scisalt.__file__)) if 'dev' in scisalt.__version__: return "http://github.com/joelfrederico/SciSalt/blob/master/scisalt/%s%s" % ( fn, linespec) else: return "http://github.com/joelfrederico/SciSalt/blob/v%s/scisalt/%s%s" % ( scisalt.__version__, fn, linespec)
def linkcode_resolve(domain, info): """ Determine the URL corresponding to Python object """ if domain != 'py': return None modname = info['module'] fullname = info['fullname'] submod = sys.modules.get(modname) if submod is None: return None obj = submod for part in fullname.split('.'): try: obj = getattr(obj, part) except: return None try: fn = inspect.getsourcefile(obj) except: fn = None if not fn: return None try: source, lineno = inspect.getsourcelines(obj) except: lineno = None if lineno: linespec = "#L%d-L%d" % (lineno, lineno + len(source) - 1) else: linespec = "" fn = relpath(fn, start=dirname(scisalt.__file__)) if 'dev' in scisalt.__version__: return "http://github.com/joelfrederico/SciSalt/blob/master/scisalt/%s%s" % ( fn, linespec) else: return "http://github.com/joelfrederico/SciSalt/blob/v%s/scisalt/%s%s" % ( scisalt.__version__, fn, linespec)
[ "Determine", "the", "URL", "corresponding", "to", "Python", "object" ]
joelfrederico/SciSalt
python
https://github.com/joelfrederico/SciSalt/blob/7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f/docs/conf.py#L358-L403
[ "def", "linkcode_resolve", "(", "domain", ",", "info", ")", ":", "if", "domain", "!=", "'py'", ":", "return", "None", "modname", "=", "info", "[", "'module'", "]", "fullname", "=", "info", "[", "'fullname'", "]", "submod", "=", "sys", ".", "modules", ".", "get", "(", "modname", ")", "if", "submod", "is", "None", ":", "return", "None", "obj", "=", "submod", "for", "part", "in", "fullname", ".", "split", "(", "'.'", ")", ":", "try", ":", "obj", "=", "getattr", "(", "obj", ",", "part", ")", "except", ":", "return", "None", "try", ":", "fn", "=", "inspect", ".", "getsourcefile", "(", "obj", ")", "except", ":", "fn", "=", "None", "if", "not", "fn", ":", "return", "None", "try", ":", "source", ",", "lineno", "=", "inspect", ".", "getsourcelines", "(", "obj", ")", "except", ":", "lineno", "=", "None", "if", "lineno", ":", "linespec", "=", "\"#L%d-L%d\"", "%", "(", "lineno", ",", "lineno", "+", "len", "(", "source", ")", "-", "1", ")", "else", ":", "linespec", "=", "\"\"", "fn", "=", "relpath", "(", "fn", ",", "start", "=", "dirname", "(", "scisalt", ".", "__file__", ")", ")", "if", "'dev'", "in", "scisalt", ".", "__version__", ":", "return", "\"http://github.com/joelfrederico/SciSalt/blob/master/scisalt/%s%s\"", "%", "(", "fn", ",", "linespec", ")", "else", ":", "return", "\"http://github.com/joelfrederico/SciSalt/blob/v%s/scisalt/%s%s\"", "%", "(", "scisalt", ".", "__version__", ",", "fn", ",", "linespec", ")" ]
7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f
valid
call_manage
Utility function to run commands against Django's `django-admin.py`/`manage.py`. `options.paved.django.project`: the path to the django project files (where `settings.py` typically resides). Will fall back to a DJANGO_SETTINGS_MODULE environment variable. `options.paved.django.manage_py`: the path where the django project's `manage.py` resides.
paved/django.py
def call_manage(cmd, capture=False, ignore_error=False): """Utility function to run commands against Django's `django-admin.py`/`manage.py`. `options.paved.django.project`: the path to the django project files (where `settings.py` typically resides). Will fall back to a DJANGO_SETTINGS_MODULE environment variable. `options.paved.django.manage_py`: the path where the django project's `manage.py` resides. """ settings = (options.paved.django.settings or os.environ.get('DJANGO_SETTINGS_MODULE')) if settings is None: raise BuildFailure("No settings path defined. Use: options.paved.django.settings = 'path.to.project.settings'") manage_py = options.paved.django.manage_py if manage_py is None: manage_py = 'django-admin.py' else: manage_py = path(manage_py) manage_py = 'cd {manage_py.parent}; python ./{manage_py.name}'.format(**locals()) return util.shv('{manage_py} {cmd} --settings={settings}'.format(**locals()), capture=capture, ignore_error=ignore_error)
def call_manage(cmd, capture=False, ignore_error=False): """Utility function to run commands against Django's `django-admin.py`/`manage.py`. `options.paved.django.project`: the path to the django project files (where `settings.py` typically resides). Will fall back to a DJANGO_SETTINGS_MODULE environment variable. `options.paved.django.manage_py`: the path where the django project's `manage.py` resides. """ settings = (options.paved.django.settings or os.environ.get('DJANGO_SETTINGS_MODULE')) if settings is None: raise BuildFailure("No settings path defined. Use: options.paved.django.settings = 'path.to.project.settings'") manage_py = options.paved.django.manage_py if manage_py is None: manage_py = 'django-admin.py' else: manage_py = path(manage_py) manage_py = 'cd {manage_py.parent}; python ./{manage_py.name}'.format(**locals()) return util.shv('{manage_py} {cmd} --settings={settings}'.format(**locals()), capture=capture, ignore_error=ignore_error)
[ "Utility", "function", "to", "run", "commands", "against", "Django", "s", "django", "-", "admin", ".", "py", "/", "manage", ".", "py", "." ]
eykd/paved
python
https://github.com/eykd/paved/blob/f04f8a4248c571f3d5ce882b325884a3e5d80203/paved/django.py#L52-L72
[ "def", "call_manage", "(", "cmd", ",", "capture", "=", "False", ",", "ignore_error", "=", "False", ")", ":", "settings", "=", "(", "options", ".", "paved", ".", "django", ".", "settings", "or", "os", ".", "environ", ".", "get", "(", "'DJANGO_SETTINGS_MODULE'", ")", ")", "if", "settings", "is", "None", ":", "raise", "BuildFailure", "(", "\"No settings path defined. Use: options.paved.django.settings = 'path.to.project.settings'\"", ")", "manage_py", "=", "options", ".", "paved", ".", "django", ".", "manage_py", "if", "manage_py", "is", "None", ":", "manage_py", "=", "'django-admin.py'", "else", ":", "manage_py", "=", "path", "(", "manage_py", ")", "manage_py", "=", "'cd {manage_py.parent}; python ./{manage_py.name}'", ".", "format", "(", "*", "*", "locals", "(", ")", ")", "return", "util", ".", "shv", "(", "'{manage_py} {cmd} --settings={settings}'", ".", "format", "(", "*", "*", "locals", "(", ")", ")", ",", "capture", "=", "capture", ",", "ignore_error", "=", "ignore_error", ")" ]
f04f8a4248c571f3d5ce882b325884a3e5d80203
valid
syncdb
Update the database with model schema. Shorthand for `paver manage syncdb`.
paved/django.py
def syncdb(args): """Update the database with model schema. Shorthand for `paver manage syncdb`. """ cmd = args and 'syncdb %s' % ' '.join(options.args) or 'syncdb --noinput' call_manage(cmd) for fixture in options.paved.django.syncdb.fixtures: call_manage("loaddata %s" % fixture)
def syncdb(args): """Update the database with model schema. Shorthand for `paver manage syncdb`. """ cmd = args and 'syncdb %s' % ' '.join(options.args) or 'syncdb --noinput' call_manage(cmd) for fixture in options.paved.django.syncdb.fixtures: call_manage("loaddata %s" % fixture)
[ "Update", "the", "database", "with", "model", "schema", ".", "Shorthand", "for", "paver", "manage", "syncdb", "." ]
eykd/paved
python
https://github.com/eykd/paved/blob/f04f8a4248c571f3d5ce882b325884a3e5d80203/paved/django.py#L88-L94
[ "def", "syncdb", "(", "args", ")", ":", "cmd", "=", "args", "and", "'syncdb %s'", "%", "' '", ".", "join", "(", "options", ".", "args", ")", "or", "'syncdb --noinput'", "call_manage", "(", "cmd", ")", "for", "fixture", "in", "options", ".", "paved", ".", "django", ".", "syncdb", ".", "fixtures", ":", "call_manage", "(", "\"loaddata %s\"", "%", "fixture", ")" ]
f04f8a4248c571f3d5ce882b325884a3e5d80203
valid
start
Run the dev server. Uses `django_extensions <http://pypi.python.org/pypi/django-extensions/0.5>`, if available, to provide `runserver_plus`. Set the command to use with `options.paved.django.runserver` Set the port to use with `options.paved.django.runserver_port`
paved/django.py
def start(info): """Run the dev server. Uses `django_extensions <http://pypi.python.org/pypi/django-extensions/0.5>`, if available, to provide `runserver_plus`. Set the command to use with `options.paved.django.runserver` Set the port to use with `options.paved.django.runserver_port` """ cmd = options.paved.django.runserver if cmd == 'runserver_plus': try: import django_extensions except ImportError: info("Could not import django_extensions. Using default runserver.") cmd = 'runserver' port = options.paved.django.runserver_port if port: cmd = '%s %s' % (cmd, port) call_manage(cmd)
def start(info): """Run the dev server. Uses `django_extensions <http://pypi.python.org/pypi/django-extensions/0.5>`, if available, to provide `runserver_plus`. Set the command to use with `options.paved.django.runserver` Set the port to use with `options.paved.django.runserver_port` """ cmd = options.paved.django.runserver if cmd == 'runserver_plus': try: import django_extensions except ImportError: info("Could not import django_extensions. Using default runserver.") cmd = 'runserver' port = options.paved.django.runserver_port if port: cmd = '%s %s' % (cmd, port) call_manage(cmd)
[ "Run", "the", "dev", "server", "." ]
eykd/paved
python
https://github.com/eykd/paved/blob/f04f8a4248c571f3d5ce882b325884a3e5d80203/paved/django.py#L116-L138
[ "def", "start", "(", "info", ")", ":", "cmd", "=", "options", ".", "paved", ".", "django", ".", "runserver", "if", "cmd", "==", "'runserver_plus'", ":", "try", ":", "import", "django_extensions", "except", "ImportError", ":", "info", "(", "\"Could not import django_extensions. Using default runserver.\"", ")", "cmd", "=", "'runserver'", "port", "=", "options", ".", "paved", ".", "django", ".", "runserver_port", "if", "port", ":", "cmd", "=", "'%s %s'", "%", "(", "cmd", ",", "port", ")", "call_manage", "(", "cmd", ")" ]
f04f8a4248c571f3d5ce882b325884a3e5d80203
valid
schema
Run South's schemamigration command.
paved/django.py
def schema(args): """Run South's schemamigration command. """ try: import south cmd = args and 'schemamigration %s' % ' '.join(options.args) or 'schemamigration' call_manage(cmd) except ImportError: error('Could not import south.')
def schema(args): """Run South's schemamigration command. """ try: import south cmd = args and 'schemamigration %s' % ' '.join(options.args) or 'schemamigration' call_manage(cmd) except ImportError: error('Could not import south.')
[ "Run", "South", "s", "schemamigration", "command", "." ]
eykd/paved
python
https://github.com/eykd/paved/blob/f04f8a4248c571f3d5ce882b325884a3e5d80203/paved/django.py#L143-L151
[ "def", "schema", "(", "args", ")", ":", "try", ":", "import", "south", "cmd", "=", "args", "and", "'schemamigration %s'", "%", "' '", ".", "join", "(", "options", ".", "args", ")", "or", "'schemamigration'", "call_manage", "(", "cmd", ")", "except", "ImportError", ":", "error", "(", "'Could not import south.'", ")" ]
f04f8a4248c571f3d5ce882b325884a3e5d80203
valid
MapperDefinition.validate
This static method validates a BioMapMapper definition. It returns None on success and throws an exception otherwise.
biomap/core/mapper.py
def validate(cls, definition): ''' This static method validates a BioMapMapper definition. It returns None on success and throws an exception otherwise. ''' schema_path = os.path.join(os.path.dirname(__file__), '../../schema/mapper_definition_schema.json') with open(schema_path, 'r') as jsonfp: schema = json.load(jsonfp) # Validation of JSON schema jsonschema.validate(definition, schema) # Validation of JSON properties relations assert definition['main_key'] in definition['supported_keys'], \ '\'main_key\' must be contained in \'supported_keys\'' assert set(definition.get('list_valued_keys', [])) <= set(definition['supported_keys']), \ '\'list_valued_keys\' must be a subset of \'supported_keys\'' assert set(definition.get('disjoint', [])) <= set(definition.get('list_valued_keys', [])), \ '\'disjoint\' must be a subset of \'list_valued_keys\'' assert set(definition.get('key_synonyms', {}).values()) <= set(definition['supported_keys']), \ '\'The values of the \'key_synonyms\' mapping must be in \'supported_keys\''
def validate(cls, definition): ''' This static method validates a BioMapMapper definition. It returns None on success and throws an exception otherwise. ''' schema_path = os.path.join(os.path.dirname(__file__), '../../schema/mapper_definition_schema.json') with open(schema_path, 'r') as jsonfp: schema = json.load(jsonfp) # Validation of JSON schema jsonschema.validate(definition, schema) # Validation of JSON properties relations assert definition['main_key'] in definition['supported_keys'], \ '\'main_key\' must be contained in \'supported_keys\'' assert set(definition.get('list_valued_keys', [])) <= set(definition['supported_keys']), \ '\'list_valued_keys\' must be a subset of \'supported_keys\'' assert set(definition.get('disjoint', [])) <= set(definition.get('list_valued_keys', [])), \ '\'disjoint\' must be a subset of \'list_valued_keys\'' assert set(definition.get('key_synonyms', {}).values()) <= set(definition['supported_keys']), \ '\'The values of the \'key_synonyms\' mapping must be in \'supported_keys\''
[ "This", "static", "method", "validates", "a", "BioMapMapper", "definition", ".", "It", "returns", "None", "on", "success", "and", "throws", "an", "exception", "otherwise", "." ]
BioMapOrg/biomap-core
python
https://github.com/BioMapOrg/biomap-core/blob/63f6468ae224c663da26e2bb0aca3faab84626c3/biomap/core/mapper.py#L29-L48
[ "def", "validate", "(", "cls", ",", "definition", ")", ":", "schema_path", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ",", "'../../schema/mapper_definition_schema.json'", ")", "with", "open", "(", "schema_path", ",", "'r'", ")", "as", "jsonfp", ":", "schema", "=", "json", ".", "load", "(", "jsonfp", ")", "# Validation of JSON schema", "jsonschema", ".", "validate", "(", "definition", ",", "schema", ")", "# Validation of JSON properties relations", "assert", "definition", "[", "'main_key'", "]", "in", "definition", "[", "'supported_keys'", "]", ",", "'\\'main_key\\' must be contained in \\'supported_keys\\''", "assert", "set", "(", "definition", ".", "get", "(", "'list_valued_keys'", ",", "[", "]", ")", ")", "<=", "set", "(", "definition", "[", "'supported_keys'", "]", ")", ",", "'\\'list_valued_keys\\' must be a subset of \\'supported_keys\\''", "assert", "set", "(", "definition", ".", "get", "(", "'disjoint'", ",", "[", "]", ")", ")", "<=", "set", "(", "definition", ".", "get", "(", "'list_valued_keys'", ",", "[", "]", ")", ")", ",", "'\\'disjoint\\' must be a subset of \\'list_valued_keys\\''", "assert", "set", "(", "definition", ".", "get", "(", "'key_synonyms'", ",", "{", "}", ")", ".", "values", "(", ")", ")", "<=", "set", "(", "definition", "[", "'supported_keys'", "]", ")", ",", "'\\'The values of the \\'key_synonyms\\' mapping must be in \\'supported_keys\\''" ]
63f6468ae224c663da26e2bb0aca3faab84626c3
valid
Mapper.map
The main method of this class and the essence of the package. It allows to "map" stuff. Args: ID_s: Nested lists with strings as leafs (plain strings also possible) FROM (str): Origin key for the mapping (default: main key) TO (str): Destination key for the mapping (default: main key) target_as_set (bool): Whether to summarize the output as a set (removes duplicates) no_match_sub: Object representing the status of an ID not being able to be matched (default: None) Returns: Mapping: a mapping object capturing the result of the mapping request
biomap/core/mapper.py
def map(self, ID_s, FROM=None, TO=None, target_as_set=False, no_match_sub=None): ''' The main method of this class and the essence of the package. It allows to "map" stuff. Args: ID_s: Nested lists with strings as leafs (plain strings also possible) FROM (str): Origin key for the mapping (default: main key) TO (str): Destination key for the mapping (default: main key) target_as_set (bool): Whether to summarize the output as a set (removes duplicates) no_match_sub: Object representing the status of an ID not being able to be matched (default: None) Returns: Mapping: a mapping object capturing the result of the mapping request ''' def io_mode(ID_s): ''' Handles the input/output modalities of the mapping. ''' unlist_return = False list_of_lists = False if isinstance(ID_s, str): ID_s = [ID_s] unlist_return = True elif isinstance(ID_s, list): if len(ID_s) > 0 and isinstance(ID_s[0], list): # assuming ID_s is a list of lists of ID strings list_of_lists = True return ID_s, unlist_return, list_of_lists # interpret input if FROM == TO: return ID_s ID_s, unlist_return, list_of_lists = io_mode(ID_s) # map consistent with interpretation of input if list_of_lists: mapped_ids = [self.map(ID, FROM, TO, target_as_set, no_match_sub) for ID in ID_s] else: mapped_ids = self._map(ID_s, FROM, TO, target_as_set, no_match_sub) # return consistent with interpretation of input if unlist_return: return mapped_ids[0] return Mapping(ID_s, mapped_ids)
def map(self, ID_s, FROM=None, TO=None, target_as_set=False, no_match_sub=None): ''' The main method of this class and the essence of the package. It allows to "map" stuff. Args: ID_s: Nested lists with strings as leafs (plain strings also possible) FROM (str): Origin key for the mapping (default: main key) TO (str): Destination key for the mapping (default: main key) target_as_set (bool): Whether to summarize the output as a set (removes duplicates) no_match_sub: Object representing the status of an ID not being able to be matched (default: None) Returns: Mapping: a mapping object capturing the result of the mapping request ''' def io_mode(ID_s): ''' Handles the input/output modalities of the mapping. ''' unlist_return = False list_of_lists = False if isinstance(ID_s, str): ID_s = [ID_s] unlist_return = True elif isinstance(ID_s, list): if len(ID_s) > 0 and isinstance(ID_s[0], list): # assuming ID_s is a list of lists of ID strings list_of_lists = True return ID_s, unlist_return, list_of_lists # interpret input if FROM == TO: return ID_s ID_s, unlist_return, list_of_lists = io_mode(ID_s) # map consistent with interpretation of input if list_of_lists: mapped_ids = [self.map(ID, FROM, TO, target_as_set, no_match_sub) for ID in ID_s] else: mapped_ids = self._map(ID_s, FROM, TO, target_as_set, no_match_sub) # return consistent with interpretation of input if unlist_return: return mapped_ids[0] return Mapping(ID_s, mapped_ids)
[ "The", "main", "method", "of", "this", "class", "and", "the", "essence", "of", "the", "package", ".", "It", "allows", "to", "map", "stuff", "." ]
BioMapOrg/biomap-core
python
https://github.com/BioMapOrg/biomap-core/blob/63f6468ae224c663da26e2bb0aca3faab84626c3/biomap/core/mapper.py#L180-L229
[ "def", "map", "(", "self", ",", "ID_s", ",", "FROM", "=", "None", ",", "TO", "=", "None", ",", "target_as_set", "=", "False", ",", "no_match_sub", "=", "None", ")", ":", "def", "io_mode", "(", "ID_s", ")", ":", "'''\n Handles the input/output modalities of the mapping.\n '''", "unlist_return", "=", "False", "list_of_lists", "=", "False", "if", "isinstance", "(", "ID_s", ",", "str", ")", ":", "ID_s", "=", "[", "ID_s", "]", "unlist_return", "=", "True", "elif", "isinstance", "(", "ID_s", ",", "list", ")", ":", "if", "len", "(", "ID_s", ")", ">", "0", "and", "isinstance", "(", "ID_s", "[", "0", "]", ",", "list", ")", ":", "# assuming ID_s is a list of lists of ID strings", "list_of_lists", "=", "True", "return", "ID_s", ",", "unlist_return", ",", "list_of_lists", "# interpret input", "if", "FROM", "==", "TO", ":", "return", "ID_s", "ID_s", ",", "unlist_return", ",", "list_of_lists", "=", "io_mode", "(", "ID_s", ")", "# map consistent with interpretation of input", "if", "list_of_lists", ":", "mapped_ids", "=", "[", "self", ".", "map", "(", "ID", ",", "FROM", ",", "TO", ",", "target_as_set", ",", "no_match_sub", ")", "for", "ID", "in", "ID_s", "]", "else", ":", "mapped_ids", "=", "self", ".", "_map", "(", "ID_s", ",", "FROM", ",", "TO", ",", "target_as_set", ",", "no_match_sub", ")", "# return consistent with interpretation of input", "if", "unlist_return", ":", "return", "mapped_ids", "[", "0", "]", "return", "Mapping", "(", "ID_s", ",", "mapped_ids", ")" ]
63f6468ae224c663da26e2bb0aca3faab84626c3
valid
Mapper.get_all
Returns all data entries for a particular key. Default is the main key. Args: key (str): key whose values to return (default: main key) Returns: List of all data entries for the key
biomap/core/mapper.py
def get_all(self, key=None): ''' Returns all data entries for a particular key. Default is the main key. Args: key (str): key whose values to return (default: main key) Returns: List of all data entries for the key ''' key = self.definition.main_key if key is None else key key = self.definition.key_synonyms.get(key, key) entries = self._get_all(key) if key in self.definition.scalar_nonunique_keys: return set(entries) return entries
def get_all(self, key=None): ''' Returns all data entries for a particular key. Default is the main key. Args: key (str): key whose values to return (default: main key) Returns: List of all data entries for the key ''' key = self.definition.main_key if key is None else key key = self.definition.key_synonyms.get(key, key) entries = self._get_all(key) if key in self.definition.scalar_nonunique_keys: return set(entries) return entries
[ "Returns", "all", "data", "entries", "for", "a", "particular", "key", ".", "Default", "is", "the", "main", "key", "." ]
BioMapOrg/biomap-core
python
https://github.com/BioMapOrg/biomap-core/blob/63f6468ae224c663da26e2bb0aca3faab84626c3/biomap/core/mapper.py#L286-L303
[ "def", "get_all", "(", "self", ",", "key", "=", "None", ")", ":", "key", "=", "self", ".", "definition", ".", "main_key", "if", "key", "is", "None", "else", "key", "key", "=", "self", ".", "definition", ".", "key_synonyms", ".", "get", "(", "key", ",", "key", ")", "entries", "=", "self", ".", "_get_all", "(", "key", ")", "if", "key", "in", "self", ".", "definition", ".", "scalar_nonunique_keys", ":", "return", "set", "(", "entries", ")", "return", "entries" ]
63f6468ae224c663da26e2bb0aca3faab84626c3
valid
Requests.get_requests
List requests http://dev.wheniwork.com/#listing-requests
uw_wheniwork/requests.py
def get_requests(self, params={}): """ List requests http://dev.wheniwork.com/#listing-requests """ if "status" in params: params['status'] = ','.join(map(str, params['status'])) requests = [] users = {} messages = {} params['page'] = 0 while True: param_list = [(k, params[k]) for k in sorted(params)] url = "/2/requests/?%s" % urlencode(param_list) data = self._get_resource(url) for entry in data["users"]: user = Users.user_from_json(entry) users[user.user_id] = user for entry in data["requests"]: request = self.request_from_json(entry) requests.append(request) for entry in data["messages"]: message = Messages.message_from_json(entry) if message.request_id not in messages: messages[message.request_id] = [] messages[message.request_id].append(message) if not data['more']: break params['page'] += 1 for request in requests: request.user = users.get(request.user_id, None) request.messages = messages.get(request.request_id, []) return requests
def get_requests(self, params={}): """ List requests http://dev.wheniwork.com/#listing-requests """ if "status" in params: params['status'] = ','.join(map(str, params['status'])) requests = [] users = {} messages = {} params['page'] = 0 while True: param_list = [(k, params[k]) for k in sorted(params)] url = "/2/requests/?%s" % urlencode(param_list) data = self._get_resource(url) for entry in data["users"]: user = Users.user_from_json(entry) users[user.user_id] = user for entry in data["requests"]: request = self.request_from_json(entry) requests.append(request) for entry in data["messages"]: message = Messages.message_from_json(entry) if message.request_id not in messages: messages[message.request_id] = [] messages[message.request_id].append(message) if not data['more']: break params['page'] += 1 for request in requests: request.user = users.get(request.user_id, None) request.messages = messages.get(request.request_id, []) return requests
[ "List", "requests" ]
uw-it-cte/uw-restclients-wheniwork
python
https://github.com/uw-it-cte/uw-restclients-wheniwork/blob/0d3ca09d5bbe808fec12e5f943596570d33a1731/uw_wheniwork/requests.py#L11-L50
[ "def", "get_requests", "(", "self", ",", "params", "=", "{", "}", ")", ":", "if", "\"status\"", "in", "params", ":", "params", "[", "'status'", "]", "=", "','", ".", "join", "(", "map", "(", "str", ",", "params", "[", "'status'", "]", ")", ")", "requests", "=", "[", "]", "users", "=", "{", "}", "messages", "=", "{", "}", "params", "[", "'page'", "]", "=", "0", "while", "True", ":", "param_list", "=", "[", "(", "k", ",", "params", "[", "k", "]", ")", "for", "k", "in", "sorted", "(", "params", ")", "]", "url", "=", "\"/2/requests/?%s\"", "%", "urlencode", "(", "param_list", ")", "data", "=", "self", ".", "_get_resource", "(", "url", ")", "for", "entry", "in", "data", "[", "\"users\"", "]", ":", "user", "=", "Users", ".", "user_from_json", "(", "entry", ")", "users", "[", "user", ".", "user_id", "]", "=", "user", "for", "entry", "in", "data", "[", "\"requests\"", "]", ":", "request", "=", "self", ".", "request_from_json", "(", "entry", ")", "requests", ".", "append", "(", "request", ")", "for", "entry", "in", "data", "[", "\"messages\"", "]", ":", "message", "=", "Messages", ".", "message_from_json", "(", "entry", ")", "if", "message", ".", "request_id", "not", "in", "messages", ":", "messages", "[", "message", ".", "request_id", "]", "=", "[", "]", "messages", "[", "message", ".", "request_id", "]", ".", "append", "(", "message", ")", "if", "not", "data", "[", "'more'", "]", ":", "break", "params", "[", "'page'", "]", "+=", "1", "for", "request", "in", "requests", ":", "request", ".", "user", "=", "users", ".", "get", "(", "request", ".", "user_id", ",", "None", ")", "request", ".", "messages", "=", "messages", ".", "get", "(", "request", ".", "request_id", ",", "[", "]", ")", "return", "requests" ]
0d3ca09d5bbe808fec12e5f943596570d33a1731
valid
GameController.guess
Make a guess, comparing the hidden object to a set of provided digits. The digits should be passed as a set of arguments, e.g: * for a normal game: 0, 1, 2, 3 * for a hex game: 0xA, 0xB, 5, 4 * alternate for hex game: 'A', 'b', 5, 4 :param args: An iterable of digits (int or str) :return: A dictionary object detailing the analysis and results of the guess
python_cowbull_game/GameController.py
def guess(self, *args): """ Make a guess, comparing the hidden object to a set of provided digits. The digits should be passed as a set of arguments, e.g: * for a normal game: 0, 1, 2, 3 * for a hex game: 0xA, 0xB, 5, 4 * alternate for hex game: 'A', 'b', 5, 4 :param args: An iterable of digits (int or str) :return: A dictionary object detailing the analysis and results of the guess """ if self.game is None: raise ValueError("The Game is unexpectedly undefined!") response_object = { "bulls": None, "cows": None, "analysis": None, "status": None } if self.game.status == self.GAME_WON: response_object["status"] = \ self._start_again_message("You already won!") elif self.game.status == self.GAME_LOST: response_object["status"] = \ self._start_again_message("You already lost!") elif self.game.guesses_remaining < 1: response_object["status"] = \ self._start_again_message("You've made too many guesses") else: guess_made = DigitWord(*args, wordtype=self.game.mode.digit_type) comparison = self.game.answer.compare(guess_made) self.game.guesses_made += 1 response_object["bulls"] = 0 response_object["cows"] = 0 response_object["analysis"] = [] for comparison_object in comparison: if comparison_object.match: response_object["bulls"] += 1 elif comparison_object.in_word: response_object["cows"] += 1 response_object["analysis"].append(comparison_object.get_object()) if response_object["bulls"] == self.game.mode.digits: self.game.status = self.GAME_WON self.game.guesses_made = self.game.mode.guesses_allowed response_object["status"] = self._start_again_message( "Congratulations, you win!" ) elif self.game.guesses_remaining < 1: self.game.status = self.GAME_LOST response_object["status"] = self._start_again_message( "Sorry, you lost!" ) return response_object
def guess(self, *args): """ Make a guess, comparing the hidden object to a set of provided digits. The digits should be passed as a set of arguments, e.g: * for a normal game: 0, 1, 2, 3 * for a hex game: 0xA, 0xB, 5, 4 * alternate for hex game: 'A', 'b', 5, 4 :param args: An iterable of digits (int or str) :return: A dictionary object detailing the analysis and results of the guess """ if self.game is None: raise ValueError("The Game is unexpectedly undefined!") response_object = { "bulls": None, "cows": None, "analysis": None, "status": None } if self.game.status == self.GAME_WON: response_object["status"] = \ self._start_again_message("You already won!") elif self.game.status == self.GAME_LOST: response_object["status"] = \ self._start_again_message("You already lost!") elif self.game.guesses_remaining < 1: response_object["status"] = \ self._start_again_message("You've made too many guesses") else: guess_made = DigitWord(*args, wordtype=self.game.mode.digit_type) comparison = self.game.answer.compare(guess_made) self.game.guesses_made += 1 response_object["bulls"] = 0 response_object["cows"] = 0 response_object["analysis"] = [] for comparison_object in comparison: if comparison_object.match: response_object["bulls"] += 1 elif comparison_object.in_word: response_object["cows"] += 1 response_object["analysis"].append(comparison_object.get_object()) if response_object["bulls"] == self.game.mode.digits: self.game.status = self.GAME_WON self.game.guesses_made = self.game.mode.guesses_allowed response_object["status"] = self._start_again_message( "Congratulations, you win!" ) elif self.game.guesses_remaining < 1: self.game.status = self.GAME_LOST response_object["status"] = self._start_again_message( "Sorry, you lost!" ) return response_object
[ "Make", "a", "guess", "comparing", "the", "hidden", "object", "to", "a", "set", "of", "provided", "digits", ".", "The", "digits", "should", "be", "passed", "as", "a", "set", "of", "arguments", "e", ".", "g", ":" ]
dsandersAzure/python_cowbull_game
python
https://github.com/dsandersAzure/python_cowbull_game/blob/82a0d8ee127869123d4fad51a8cd1707879e368f/python_cowbull_game/GameController.py#L56-L116
[ "def", "guess", "(", "self", ",", "*", "args", ")", ":", "if", "self", ".", "game", "is", "None", ":", "raise", "ValueError", "(", "\"The Game is unexpectedly undefined!\"", ")", "response_object", "=", "{", "\"bulls\"", ":", "None", ",", "\"cows\"", ":", "None", ",", "\"analysis\"", ":", "None", ",", "\"status\"", ":", "None", "}", "if", "self", ".", "game", ".", "status", "==", "self", ".", "GAME_WON", ":", "response_object", "[", "\"status\"", "]", "=", "self", ".", "_start_again_message", "(", "\"You already won!\"", ")", "elif", "self", ".", "game", ".", "status", "==", "self", ".", "GAME_LOST", ":", "response_object", "[", "\"status\"", "]", "=", "self", ".", "_start_again_message", "(", "\"You already lost!\"", ")", "elif", "self", ".", "game", ".", "guesses_remaining", "<", "1", ":", "response_object", "[", "\"status\"", "]", "=", "self", ".", "_start_again_message", "(", "\"You've made too many guesses\"", ")", "else", ":", "guess_made", "=", "DigitWord", "(", "*", "args", ",", "wordtype", "=", "self", ".", "game", ".", "mode", ".", "digit_type", ")", "comparison", "=", "self", ".", "game", ".", "answer", ".", "compare", "(", "guess_made", ")", "self", ".", "game", ".", "guesses_made", "+=", "1", "response_object", "[", "\"bulls\"", "]", "=", "0", "response_object", "[", "\"cows\"", "]", "=", "0", "response_object", "[", "\"analysis\"", "]", "=", "[", "]", "for", "comparison_object", "in", "comparison", ":", "if", "comparison_object", ".", "match", ":", "response_object", "[", "\"bulls\"", "]", "+=", "1", "elif", "comparison_object", ".", "in_word", ":", "response_object", "[", "\"cows\"", "]", "+=", "1", "response_object", "[", "\"analysis\"", "]", ".", "append", "(", "comparison_object", ".", "get_object", "(", ")", ")", "if", "response_object", "[", "\"bulls\"", "]", "==", "self", ".", "game", ".", "mode", ".", "digits", ":", "self", ".", "game", ".", "status", "=", "self", ".", "GAME_WON", "self", ".", "game", ".", "guesses_made", "=", "self", ".", "game", ".", "mode", ".", "guesses_allowed", "response_object", "[", "\"status\"", "]", "=", "self", ".", "_start_again_message", "(", "\"Congratulations, you win!\"", ")", "elif", "self", ".", "game", ".", "guesses_remaining", "<", "1", ":", "self", ".", "game", ".", "status", "=", "self", ".", "GAME_LOST", "response_object", "[", "\"status\"", "]", "=", "self", ".", "_start_again_message", "(", "\"Sorry, you lost!\"", ")", "return", "response_object" ]
82a0d8ee127869123d4fad51a8cd1707879e368f
valid
GameController.load
Load a game from a serialized JSON representation. The game expects a well defined structure as follows (Note JSON string format): '{ "guesses_made": int, "key": "str:a 4 word", "status": "str: one of playing, won, lost", "mode": { "digits": int, "digit_type": DigitWord.DIGIT | DigitWord.HEXDIGIT, "mode": GameMode(), "priority": int, "help_text": str, "instruction_text": str, "guesses_allowed": int }, "ttl": int, "answer": [int|str0, int|str1, ..., int|strN] }' * "mode" will be cast to a GameMode object * "answer" will be cast to a DigitWord object :param game_json: The source JSON - MUST be a string :param mode: A mode (str or GameMode) for the game being loaded :return: A game object
python_cowbull_game/GameController.py
def load(self, game_json=None, mode=None): """ Load a game from a serialized JSON representation. The game expects a well defined structure as follows (Note JSON string format): '{ "guesses_made": int, "key": "str:a 4 word", "status": "str: one of playing, won, lost", "mode": { "digits": int, "digit_type": DigitWord.DIGIT | DigitWord.HEXDIGIT, "mode": GameMode(), "priority": int, "help_text": str, "instruction_text": str, "guesses_allowed": int }, "ttl": int, "answer": [int|str0, int|str1, ..., int|strN] }' * "mode" will be cast to a GameMode object * "answer" will be cast to a DigitWord object :param game_json: The source JSON - MUST be a string :param mode: A mode (str or GameMode) for the game being loaded :return: A game object """ if game_json is None: # New game_json if mode is not None: if isinstance(mode, str): _game_object = GameObject(mode=self._match_mode(mode=mode)) elif isinstance(mode, GameMode): _game_object = GameObject(mode=mode) else: raise TypeError("Game mode must be a GameMode or string") else: _game_object = GameObject(mode=self._game_modes[0]) _game_object.status = self.GAME_PLAYING else: if not isinstance(game_json, str): raise TypeError("Game must be passed as a serialized JSON string.") game_dict = json.loads(game_json) if not 'mode' in game_dict: raise ValueError("Mode is not provided in JSON; game_json cannot be loaded!") _mode = GameMode(**game_dict["mode"]) _game_object = GameObject(mode=_mode, source_game=game_dict) self.game = copy.deepcopy(_game_object)
def load(self, game_json=None, mode=None): """ Load a game from a serialized JSON representation. The game expects a well defined structure as follows (Note JSON string format): '{ "guesses_made": int, "key": "str:a 4 word", "status": "str: one of playing, won, lost", "mode": { "digits": int, "digit_type": DigitWord.DIGIT | DigitWord.HEXDIGIT, "mode": GameMode(), "priority": int, "help_text": str, "instruction_text": str, "guesses_allowed": int }, "ttl": int, "answer": [int|str0, int|str1, ..., int|strN] }' * "mode" will be cast to a GameMode object * "answer" will be cast to a DigitWord object :param game_json: The source JSON - MUST be a string :param mode: A mode (str or GameMode) for the game being loaded :return: A game object """ if game_json is None: # New game_json if mode is not None: if isinstance(mode, str): _game_object = GameObject(mode=self._match_mode(mode=mode)) elif isinstance(mode, GameMode): _game_object = GameObject(mode=mode) else: raise TypeError("Game mode must be a GameMode or string") else: _game_object = GameObject(mode=self._game_modes[0]) _game_object.status = self.GAME_PLAYING else: if not isinstance(game_json, str): raise TypeError("Game must be passed as a serialized JSON string.") game_dict = json.loads(game_json) if not 'mode' in game_dict: raise ValueError("Mode is not provided in JSON; game_json cannot be loaded!") _mode = GameMode(**game_dict["mode"]) _game_object = GameObject(mode=_mode, source_game=game_dict) self.game = copy.deepcopy(_game_object)
[ "Load", "a", "game", "from", "a", "serialized", "JSON", "representation", ".", "The", "game", "expects", "a", "well", "defined", "structure", "as", "follows", "(", "Note", "JSON", "string", "format", ")", ":" ]
dsandersAzure/python_cowbull_game
python
https://github.com/dsandersAzure/python_cowbull_game/blob/82a0d8ee127869123d4fad51a8cd1707879e368f/python_cowbull_game/GameController.py#L118-L171
[ "def", "load", "(", "self", ",", "game_json", "=", "None", ",", "mode", "=", "None", ")", ":", "if", "game_json", "is", "None", ":", "# New game_json", "if", "mode", "is", "not", "None", ":", "if", "isinstance", "(", "mode", ",", "str", ")", ":", "_game_object", "=", "GameObject", "(", "mode", "=", "self", ".", "_match_mode", "(", "mode", "=", "mode", ")", ")", "elif", "isinstance", "(", "mode", ",", "GameMode", ")", ":", "_game_object", "=", "GameObject", "(", "mode", "=", "mode", ")", "else", ":", "raise", "TypeError", "(", "\"Game mode must be a GameMode or string\"", ")", "else", ":", "_game_object", "=", "GameObject", "(", "mode", "=", "self", ".", "_game_modes", "[", "0", "]", ")", "_game_object", ".", "status", "=", "self", ".", "GAME_PLAYING", "else", ":", "if", "not", "isinstance", "(", "game_json", ",", "str", ")", ":", "raise", "TypeError", "(", "\"Game must be passed as a serialized JSON string.\"", ")", "game_dict", "=", "json", ".", "loads", "(", "game_json", ")", "if", "not", "'mode'", "in", "game_dict", ":", "raise", "ValueError", "(", "\"Mode is not provided in JSON; game_json cannot be loaded!\"", ")", "_mode", "=", "GameMode", "(", "*", "*", "game_dict", "[", "\"mode\"", "]", ")", "_game_object", "=", "GameObject", "(", "mode", "=", "_mode", ",", "source_game", "=", "game_dict", ")", "self", ".", "game", "=", "copy", ".", "deepcopy", "(", "_game_object", ")" ]
82a0d8ee127869123d4fad51a8cd1707879e368f
valid
GameController.load_modes
Loads modes (GameMode objects) to be supported by the game object. Four default modes are provided (normal, easy, hard, and hex) but others could be provided either by calling load_modes directly or passing a list of GameMode objects to the instantiation call. :param input_modes: A list of GameMode objects; nb: even if only one new GameMode object is provided, it MUST be passed as a list - for example, passing GameMode gm1 would require passing [gm1] NOT gm1. :return: A list of GameMode objects (both defaults and any added).
python_cowbull_game/GameController.py
def load_modes(self, input_modes=None): """ Loads modes (GameMode objects) to be supported by the game object. Four default modes are provided (normal, easy, hard, and hex) but others could be provided either by calling load_modes directly or passing a list of GameMode objects to the instantiation call. :param input_modes: A list of GameMode objects; nb: even if only one new GameMode object is provided, it MUST be passed as a list - for example, passing GameMode gm1 would require passing [gm1] NOT gm1. :return: A list of GameMode objects (both defaults and any added). """ # Set default game modes _modes = [ GameMode( mode="normal", priority=2, digits=4, digit_type=DigitWord.DIGIT, guesses_allowed=10 ), GameMode( mode="easy", priority=1, digits=3, digit_type=DigitWord.DIGIT, guesses_allowed=6 ), GameMode( mode="hard", priority=3, digits=6, digit_type=DigitWord.DIGIT, guesses_allowed=6 ), GameMode( mode="hex", priority=4, digits=4, digit_type=DigitWord.HEXDIGIT, guesses_allowed=10 ) ] if input_modes is not None: if not isinstance(input_modes, list): raise TypeError("Expected list of input_modes") for mode in input_modes: if not isinstance(mode, GameMode): raise TypeError("Expected list to contain only GameMode objects") _modes.append(mode) self._game_modes = copy.deepcopy(_modes)
def load_modes(self, input_modes=None): """ Loads modes (GameMode objects) to be supported by the game object. Four default modes are provided (normal, easy, hard, and hex) but others could be provided either by calling load_modes directly or passing a list of GameMode objects to the instantiation call. :param input_modes: A list of GameMode objects; nb: even if only one new GameMode object is provided, it MUST be passed as a list - for example, passing GameMode gm1 would require passing [gm1] NOT gm1. :return: A list of GameMode objects (both defaults and any added). """ # Set default game modes _modes = [ GameMode( mode="normal", priority=2, digits=4, digit_type=DigitWord.DIGIT, guesses_allowed=10 ), GameMode( mode="easy", priority=1, digits=3, digit_type=DigitWord.DIGIT, guesses_allowed=6 ), GameMode( mode="hard", priority=3, digits=6, digit_type=DigitWord.DIGIT, guesses_allowed=6 ), GameMode( mode="hex", priority=4, digits=4, digit_type=DigitWord.HEXDIGIT, guesses_allowed=10 ) ] if input_modes is not None: if not isinstance(input_modes, list): raise TypeError("Expected list of input_modes") for mode in input_modes: if not isinstance(mode, GameMode): raise TypeError("Expected list to contain only GameMode objects") _modes.append(mode) self._game_modes = copy.deepcopy(_modes)
[ "Loads", "modes", "(", "GameMode", "objects", ")", "to", "be", "supported", "by", "the", "game", "object", ".", "Four", "default", "modes", "are", "provided", "(", "normal", "easy", "hard", "and", "hex", ")", "but", "others", "could", "be", "provided", "either", "by", "calling", "load_modes", "directly", "or", "passing", "a", "list", "of", "GameMode", "objects", "to", "the", "instantiation", "call", "." ]
dsandersAzure/python_cowbull_game
python
https://github.com/dsandersAzure/python_cowbull_game/blob/82a0d8ee127869123d4fad51a8cd1707879e368f/python_cowbull_game/GameController.py#L182-L221
[ "def", "load_modes", "(", "self", ",", "input_modes", "=", "None", ")", ":", "# Set default game modes", "_modes", "=", "[", "GameMode", "(", "mode", "=", "\"normal\"", ",", "priority", "=", "2", ",", "digits", "=", "4", ",", "digit_type", "=", "DigitWord", ".", "DIGIT", ",", "guesses_allowed", "=", "10", ")", ",", "GameMode", "(", "mode", "=", "\"easy\"", ",", "priority", "=", "1", ",", "digits", "=", "3", ",", "digit_type", "=", "DigitWord", ".", "DIGIT", ",", "guesses_allowed", "=", "6", ")", ",", "GameMode", "(", "mode", "=", "\"hard\"", ",", "priority", "=", "3", ",", "digits", "=", "6", ",", "digit_type", "=", "DigitWord", ".", "DIGIT", ",", "guesses_allowed", "=", "6", ")", ",", "GameMode", "(", "mode", "=", "\"hex\"", ",", "priority", "=", "4", ",", "digits", "=", "4", ",", "digit_type", "=", "DigitWord", ".", "HEXDIGIT", ",", "guesses_allowed", "=", "10", ")", "]", "if", "input_modes", "is", "not", "None", ":", "if", "not", "isinstance", "(", "input_modes", ",", "list", ")", ":", "raise", "TypeError", "(", "\"Expected list of input_modes\"", ")", "for", "mode", "in", "input_modes", ":", "if", "not", "isinstance", "(", "mode", ",", "GameMode", ")", ":", "raise", "TypeError", "(", "\"Expected list to contain only GameMode objects\"", ")", "_modes", ".", "append", "(", "mode", ")", "self", ".", "_game_modes", "=", "copy", ".", "deepcopy", "(", "_modes", ")" ]
82a0d8ee127869123d4fad51a8cd1707879e368f
valid
GameController._start_again_message
Simple method to form a start again message and give the answer in readable form.
python_cowbull_game/GameController.py
def _start_again_message(self, message=None): """Simple method to form a start again message and give the answer in readable form.""" logging.debug("Start again message delivered: {}".format(message)) the_answer = ', '.join( [str(d) for d in self.game.answer][:-1] ) + ', and ' + [str(d) for d in self.game.answer][-1] return "{0}{1} The correct answer was {2}. Please start a new game.".format( message, "." if message[-1] not in [".", ",", ";", ":", "!"] else "", the_answer )
def _start_again_message(self, message=None): """Simple method to form a start again message and give the answer in readable form.""" logging.debug("Start again message delivered: {}".format(message)) the_answer = ', '.join( [str(d) for d in self.game.answer][:-1] ) + ', and ' + [str(d) for d in self.game.answer][-1] return "{0}{1} The correct answer was {2}. Please start a new game.".format( message, "." if message[-1] not in [".", ",", ";", ":", "!"] else "", the_answer )
[ "Simple", "method", "to", "form", "a", "start", "again", "message", "and", "give", "the", "answer", "in", "readable", "form", "." ]
dsandersAzure/python_cowbull_game
python
https://github.com/dsandersAzure/python_cowbull_game/blob/82a0d8ee127869123d4fad51a8cd1707879e368f/python_cowbull_game/GameController.py#L237-L248
[ "def", "_start_again_message", "(", "self", ",", "message", "=", "None", ")", ":", "logging", ".", "debug", "(", "\"Start again message delivered: {}\"", ".", "format", "(", "message", ")", ")", "the_answer", "=", "', '", ".", "join", "(", "[", "str", "(", "d", ")", "for", "d", "in", "self", ".", "game", ".", "answer", "]", "[", ":", "-", "1", "]", ")", "+", "', and '", "+", "[", "str", "(", "d", ")", "for", "d", "in", "self", ".", "game", ".", "answer", "]", "[", "-", "1", "]", "return", "\"{0}{1} The correct answer was {2}. Please start a new game.\"", ".", "format", "(", "message", ",", "\".\"", "if", "message", "[", "-", "1", "]", "not", "in", "[", "\".\"", ",", "\",\"", ",", "\";\"", ",", "\":\"", ",", "\"!\"", "]", "else", "\"\"", ",", "the_answer", ")" ]
82a0d8ee127869123d4fad51a8cd1707879e368f
valid
FieldCutter.line
Returns list of strings split by input delimeter Argument: line - Input line to cut
cuts/fields.py
def line(self, line): """Returns list of strings split by input delimeter Argument: line - Input line to cut """ # Remove empty strings in case of multiple instances of delimiter return [x for x in re.split(self.delimiter, line.rstrip()) if x != '']
def line(self, line): """Returns list of strings split by input delimeter Argument: line - Input line to cut """ # Remove empty strings in case of multiple instances of delimiter return [x for x in re.split(self.delimiter, line.rstrip()) if x != '']
[ "Returns", "list", "of", "strings", "split", "by", "input", "delimeter" ]
jpweiser/cuts
python
https://github.com/jpweiser/cuts/blob/5baf7f2e145045942ee8dcaccbc47f8f821fcb56/cuts/fields.py#L25-L32
[ "def", "line", "(", "self", ",", "line", ")", ":", "# Remove empty strings in case of multiple instances of delimiter", "return", "[", "x", "for", "x", "in", "re", ".", "split", "(", "self", ".", "delimiter", ",", "line", ".", "rstrip", "(", ")", ")", "if", "x", "!=", "''", "]" ]
5baf7f2e145045942ee8dcaccbc47f8f821fcb56
valid
Messages.get_message
Get Existing Message http://dev.wheniwork.com/#get-existing-message
uw_wheniwork/messages.py
def get_message(self, message_id): """ Get Existing Message http://dev.wheniwork.com/#get-existing-message """ url = "/2/messages/%s" % message_id return self.message_from_json(self._get_resource(url)["message"])
def get_message(self, message_id): """ Get Existing Message http://dev.wheniwork.com/#get-existing-message """ url = "/2/messages/%s" % message_id return self.message_from_json(self._get_resource(url)["message"])
[ "Get", "Existing", "Message" ]
uw-it-cte/uw-restclients-wheniwork
python
https://github.com/uw-it-cte/uw-restclients-wheniwork/blob/0d3ca09d5bbe808fec12e5f943596570d33a1731/uw_wheniwork/messages.py#L9-L17
[ "def", "get_message", "(", "self", ",", "message_id", ")", ":", "url", "=", "\"/2/messages/%s\"", "%", "message_id", "return", "self", ".", "message_from_json", "(", "self", ".", "_get_resource", "(", "url", ")", "[", "\"message\"", "]", ")" ]
0d3ca09d5bbe808fec12e5f943596570d33a1731
valid
Messages.get_messages
List messages http://dev.wheniwork.com/#listing-messages
uw_wheniwork/messages.py
def get_messages(self, params={}): """ List messages http://dev.wheniwork.com/#listing-messages """ param_list = [(k, params[k]) for k in sorted(params)] url = "/2/messages/?%s" % urlencode(param_list) data = self._get_resource(url) messages = [] for entry in data["messages"]: messages.append(self.message_from_json(entry)) return messages
def get_messages(self, params={}): """ List messages http://dev.wheniwork.com/#listing-messages """ param_list = [(k, params[k]) for k in sorted(params)] url = "/2/messages/?%s" % urlencode(param_list) data = self._get_resource(url) messages = [] for entry in data["messages"]: messages.append(self.message_from_json(entry)) return messages
[ "List", "messages" ]
uw-it-cte/uw-restclients-wheniwork
python
https://github.com/uw-it-cte/uw-restclients-wheniwork/blob/0d3ca09d5bbe808fec12e5f943596570d33a1731/uw_wheniwork/messages.py#L19-L33
[ "def", "get_messages", "(", "self", ",", "params", "=", "{", "}", ")", ":", "param_list", "=", "[", "(", "k", ",", "params", "[", "k", "]", ")", "for", "k", "in", "sorted", "(", "params", ")", "]", "url", "=", "\"/2/messages/?%s\"", "%", "urlencode", "(", "param_list", ")", "data", "=", "self", ".", "_get_resource", "(", "url", ")", "messages", "=", "[", "]", "for", "entry", "in", "data", "[", "\"messages\"", "]", ":", "messages", ".", "append", "(", "self", ".", "message_from_json", "(", "entry", ")", ")", "return", "messages" ]
0d3ca09d5bbe808fec12e5f943596570d33a1731
valid
Messages.create_message
Creates a message http://dev.wheniwork.com/#create/update-message
uw_wheniwork/messages.py
def create_message(self, params={}): """ Creates a message http://dev.wheniwork.com/#create/update-message """ url = "/2/messages/" body = params data = self._post_resource(url, body) return self.message_from_json(data["message"])
def create_message(self, params={}): """ Creates a message http://dev.wheniwork.com/#create/update-message """ url = "/2/messages/" body = params data = self._post_resource(url, body) return self.message_from_json(data["message"])
[ "Creates", "a", "message" ]
uw-it-cte/uw-restclients-wheniwork
python
https://github.com/uw-it-cte/uw-restclients-wheniwork/blob/0d3ca09d5bbe808fec12e5f943596570d33a1731/uw_wheniwork/messages.py#L35-L45
[ "def", "create_message", "(", "self", ",", "params", "=", "{", "}", ")", ":", "url", "=", "\"/2/messages/\"", "body", "=", "params", "data", "=", "self", ".", "_post_resource", "(", "url", ",", "body", ")", "return", "self", ".", "message_from_json", "(", "data", "[", "\"message\"", "]", ")" ]
0d3ca09d5bbe808fec12e5f943596570d33a1731
valid
Messages.update_message
Modify an existing message. http://dev.wheniwork.com/#create/update-message
uw_wheniwork/messages.py
def update_message(self, message): """ Modify an existing message. http://dev.wheniwork.com/#create/update-message """ url = "/2/messages/%s" % message.message_id data = self._put_resource(url, message.json_data()) return self.message_from_json(data)
def update_message(self, message): """ Modify an existing message. http://dev.wheniwork.com/#create/update-message """ url = "/2/messages/%s" % message.message_id data = self._put_resource(url, message.json_data()) return self.message_from_json(data)
[ "Modify", "an", "existing", "message", "." ]
uw-it-cte/uw-restclients-wheniwork
python
https://github.com/uw-it-cte/uw-restclients-wheniwork/blob/0d3ca09d5bbe808fec12e5f943596570d33a1731/uw_wheniwork/messages.py#L47-L56
[ "def", "update_message", "(", "self", ",", "message", ")", ":", "url", "=", "\"/2/messages/%s\"", "%", "message", ".", "message_id", "data", "=", "self", ".", "_put_resource", "(", "url", ",", "message", ".", "json_data", "(", ")", ")", "return", "self", ".", "message_from_json", "(", "data", ")" ]
0d3ca09d5bbe808fec12e5f943596570d33a1731
valid
Messages.delete_messages
Delete existing messages. http://dev.wheniwork.com/#delete-existing-message
uw_wheniwork/messages.py
def delete_messages(self, messages): """ Delete existing messages. http://dev.wheniwork.com/#delete-existing-message """ url = "/2/messages/?%s" % urlencode([('ids', ",".join(messages))]) data = self._delete_resource(url) return data
def delete_messages(self, messages): """ Delete existing messages. http://dev.wheniwork.com/#delete-existing-message """ url = "/2/messages/?%s" % urlencode([('ids', ",".join(messages))]) data = self._delete_resource(url) return data
[ "Delete", "existing", "messages", "." ]
uw-it-cte/uw-restclients-wheniwork
python
https://github.com/uw-it-cte/uw-restclients-wheniwork/blob/0d3ca09d5bbe808fec12e5f943596570d33a1731/uw_wheniwork/messages.py#L58-L67
[ "def", "delete_messages", "(", "self", ",", "messages", ")", ":", "url", "=", "\"/2/messages/?%s\"", "%", "urlencode", "(", "[", "(", "'ids'", ",", "\",\"", ".", "join", "(", "messages", ")", ")", "]", ")", "data", "=", "self", ".", "_delete_resource", "(", "url", ")", "return", "data" ]
0d3ca09d5bbe808fec12e5f943596570d33a1731
valid
Sites.get_site
Returns site data. http://dev.wheniwork.com/#get-existing-site
uw_wheniwork/sites.py
def get_site(self, site_id): """ Returns site data. http://dev.wheniwork.com/#get-existing-site """ url = "/2/sites/%s" % site_id return self.site_from_json(self._get_resource(url)["site"])
def get_site(self, site_id): """ Returns site data. http://dev.wheniwork.com/#get-existing-site """ url = "/2/sites/%s" % site_id return self.site_from_json(self._get_resource(url)["site"])
[ "Returns", "site", "data", "." ]
uw-it-cte/uw-restclients-wheniwork
python
https://github.com/uw-it-cte/uw-restclients-wheniwork/blob/0d3ca09d5bbe808fec12e5f943596570d33a1731/uw_wheniwork/sites.py#L6-L14
[ "def", "get_site", "(", "self", ",", "site_id", ")", ":", "url", "=", "\"/2/sites/%s\"", "%", "site_id", "return", "self", ".", "site_from_json", "(", "self", ".", "_get_resource", "(", "url", ")", "[", "\"site\"", "]", ")" ]
0d3ca09d5bbe808fec12e5f943596570d33a1731
valid
Sites.get_sites
Returns a list of sites. http://dev.wheniwork.com/#listing-sites
uw_wheniwork/sites.py
def get_sites(self): """ Returns a list of sites. http://dev.wheniwork.com/#listing-sites """ url = "/2/sites" data = self._get_resource(url) sites = [] for entry in data['sites']: sites.append(self.site_from_json(entry)) return sites
def get_sites(self): """ Returns a list of sites. http://dev.wheniwork.com/#listing-sites """ url = "/2/sites" data = self._get_resource(url) sites = [] for entry in data['sites']: sites.append(self.site_from_json(entry)) return sites
[ "Returns", "a", "list", "of", "sites", "." ]
uw-it-cte/uw-restclients-wheniwork
python
https://github.com/uw-it-cte/uw-restclients-wheniwork/blob/0d3ca09d5bbe808fec12e5f943596570d33a1731/uw_wheniwork/sites.py#L16-L29
[ "def", "get_sites", "(", "self", ")", ":", "url", "=", "\"/2/sites\"", "data", "=", "self", ".", "_get_resource", "(", "url", ")", "sites", "=", "[", "]", "for", "entry", "in", "data", "[", "'sites'", "]", ":", "sites", ".", "append", "(", "self", ".", "site_from_json", "(", "entry", ")", ")", "return", "sites" ]
0d3ca09d5bbe808fec12e5f943596570d33a1731
valid
Sites.create_site
Creates a site http://dev.wheniwork.com/#create-update-site
uw_wheniwork/sites.py
def create_site(self, params={}): """ Creates a site http://dev.wheniwork.com/#create-update-site """ url = "/2/sites/" body = params data = self._post_resource(url, body) return self.site_from_json(data["site"])
def create_site(self, params={}): """ Creates a site http://dev.wheniwork.com/#create-update-site """ url = "/2/sites/" body = params data = self._post_resource(url, body) return self.site_from_json(data["site"])
[ "Creates", "a", "site" ]
uw-it-cte/uw-restclients-wheniwork
python
https://github.com/uw-it-cte/uw-restclients-wheniwork/blob/0d3ca09d5bbe808fec12e5f943596570d33a1731/uw_wheniwork/sites.py#L31-L41
[ "def", "create_site", "(", "self", ",", "params", "=", "{", "}", ")", ":", "url", "=", "\"/2/sites/\"", "body", "=", "params", "data", "=", "self", ".", "_post_resource", "(", "url", ",", "body", ")", "return", "self", ".", "site_from_json", "(", "data", "[", "\"site\"", "]", ")" ]
0d3ca09d5bbe808fec12e5f943596570d33a1731
valid
admin_link_move_up
Returns a link to a view that moves the passed in object up in rank. :param obj: Object to move :param link_text: Text to display in the link. Defaults to "up" :returns: HTML link code to view for moving the object
awl/rankedmodel/admintools.py
def admin_link_move_up(obj, link_text='up'): """Returns a link to a view that moves the passed in object up in rank. :param obj: Object to move :param link_text: Text to display in the link. Defaults to "up" :returns: HTML link code to view for moving the object """ if obj.rank == 1: return '' content_type = ContentType.objects.get_for_model(obj) link = reverse('awl-rankedmodel-move', args=(content_type.id, obj.id, obj.rank - 1)) return '<a href="%s">%s</a>' % (link, link_text)
def admin_link_move_up(obj, link_text='up'): """Returns a link to a view that moves the passed in object up in rank. :param obj: Object to move :param link_text: Text to display in the link. Defaults to "up" :returns: HTML link code to view for moving the object """ if obj.rank == 1: return '' content_type = ContentType.objects.get_for_model(obj) link = reverse('awl-rankedmodel-move', args=(content_type.id, obj.id, obj.rank - 1)) return '<a href="%s">%s</a>' % (link, link_text)
[ "Returns", "a", "link", "to", "a", "view", "that", "moves", "the", "passed", "in", "object", "up", "in", "rank", "." ]
cltrudeau/django-awl
python
https://github.com/cltrudeau/django-awl/blob/70d469ef9a161c1170b53aa017cf02d7c15eb90c/awl/rankedmodel/admintools.py#L10-L27
[ "def", "admin_link_move_up", "(", "obj", ",", "link_text", "=", "'up'", ")", ":", "if", "obj", ".", "rank", "==", "1", ":", "return", "''", "content_type", "=", "ContentType", ".", "objects", ".", "get_for_model", "(", "obj", ")", "link", "=", "reverse", "(", "'awl-rankedmodel-move'", ",", "args", "=", "(", "content_type", ".", "id", ",", "obj", ".", "id", ",", "obj", ".", "rank", "-", "1", ")", ")", "return", "'<a href=\"%s\">%s</a>'", "%", "(", "link", ",", "link_text", ")" ]
70d469ef9a161c1170b53aa017cf02d7c15eb90c
valid
admin_link_move_down
Returns a link to a view that moves the passed in object down in rank. :param obj: Object to move :param link_text: Text to display in the link. Defaults to "down" :returns: HTML link code to view for moving the object
awl/rankedmodel/admintools.py
def admin_link_move_down(obj, link_text='down'): """Returns a link to a view that moves the passed in object down in rank. :param obj: Object to move :param link_text: Text to display in the link. Defaults to "down" :returns: HTML link code to view for moving the object """ if obj.rank == obj.grouped_filter().count(): return '' content_type = ContentType.objects.get_for_model(obj) link = reverse('awl-rankedmodel-move', args=(content_type.id, obj.id, obj.rank + 1)) return '<a href="%s">%s</a>' % (link, link_text)
def admin_link_move_down(obj, link_text='down'): """Returns a link to a view that moves the passed in object down in rank. :param obj: Object to move :param link_text: Text to display in the link. Defaults to "down" :returns: HTML link code to view for moving the object """ if obj.rank == obj.grouped_filter().count(): return '' content_type = ContentType.objects.get_for_model(obj) link = reverse('awl-rankedmodel-move', args=(content_type.id, obj.id, obj.rank + 1)) return '<a href="%s">%s</a>' % (link, link_text)
[ "Returns", "a", "link", "to", "a", "view", "that", "moves", "the", "passed", "in", "object", "down", "in", "rank", "." ]
cltrudeau/django-awl
python
https://github.com/cltrudeau/django-awl/blob/70d469ef9a161c1170b53aa017cf02d7c15eb90c/awl/rankedmodel/admintools.py#L30-L47
[ "def", "admin_link_move_down", "(", "obj", ",", "link_text", "=", "'down'", ")", ":", "if", "obj", ".", "rank", "==", "obj", ".", "grouped_filter", "(", ")", ".", "count", "(", ")", ":", "return", "''", "content_type", "=", "ContentType", ".", "objects", ".", "get_for_model", "(", "obj", ")", "link", "=", "reverse", "(", "'awl-rankedmodel-move'", ",", "args", "=", "(", "content_type", ".", "id", ",", "obj", ".", "id", ",", "obj", ".", "rank", "+", "1", ")", ")", "return", "'<a href=\"%s\">%s</a>'", "%", "(", "link", ",", "link_text", ")" ]
70d469ef9a161c1170b53aa017cf02d7c15eb90c
valid
showfig
Shows a figure with a typical orientation so that x and y axes are set up as expected.
scisalt/matplotlib/showfig.py
def showfig(fig, aspect="auto"): """ Shows a figure with a typical orientation so that x and y axes are set up as expected. """ ax = fig.gca() # Swap y axis if needed alim = list(ax.axis()) if alim[3] < alim[2]: temp = alim[2] alim[2] = alim[3] alim[3] = temp ax.axis(alim) ax.set_aspect(aspect) fig.show()
def showfig(fig, aspect="auto"): """ Shows a figure with a typical orientation so that x and y axes are set up as expected. """ ax = fig.gca() # Swap y axis if needed alim = list(ax.axis()) if alim[3] < alim[2]: temp = alim[2] alim[2] = alim[3] alim[3] = temp ax.axis(alim) ax.set_aspect(aspect) fig.show()
[ "Shows", "a", "figure", "with", "a", "typical", "orientation", "so", "that", "x", "and", "y", "axes", "are", "set", "up", "as", "expected", "." ]
joelfrederico/SciSalt
python
https://github.com/joelfrederico/SciSalt/blob/7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f/scisalt/matplotlib/showfig.py#L1-L17
[ "def", "showfig", "(", "fig", ",", "aspect", "=", "\"auto\"", ")", ":", "ax", "=", "fig", ".", "gca", "(", ")", "# Swap y axis if needed", "alim", "=", "list", "(", "ax", ".", "axis", "(", ")", ")", "if", "alim", "[", "3", "]", "<", "alim", "[", "2", "]", ":", "temp", "=", "alim", "[", "2", "]", "alim", "[", "2", "]", "=", "alim", "[", "3", "]", "alim", "[", "3", "]", "=", "temp", "ax", ".", "axis", "(", "alim", ")", "ax", ".", "set_aspect", "(", "aspect", ")", "fig", ".", "show", "(", ")" ]
7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f
valid
_setup_index
Shifts indicies as needed to account for one based indexing Positive indicies need to be reduced by one to match with zero based indexing. Zero is not a valid input, and as such will throw a value error. Arguments: index - index to shift
cuts/cutter.py
def _setup_index(index): """Shifts indicies as needed to account for one based indexing Positive indicies need to be reduced by one to match with zero based indexing. Zero is not a valid input, and as such will throw a value error. Arguments: index - index to shift """ index = int(index) if index > 0: index -= 1 elif index == 0: # Zero indicies should not be allowed by default. raise ValueError return index
def _setup_index(index): """Shifts indicies as needed to account for one based indexing Positive indicies need to be reduced by one to match with zero based indexing. Zero is not a valid input, and as such will throw a value error. Arguments: index - index to shift """ index = int(index) if index > 0: index -= 1 elif index == 0: # Zero indicies should not be allowed by default. raise ValueError return index
[ "Shifts", "indicies", "as", "needed", "to", "account", "for", "one", "based", "indexing" ]
jpweiser/cuts
python
https://github.com/jpweiser/cuts/blob/5baf7f2e145045942ee8dcaccbc47f8f821fcb56/cuts/cutter.py#L21-L38
[ "def", "_setup_index", "(", "index", ")", ":", "index", "=", "int", "(", "index", ")", "if", "index", ">", "0", ":", "index", "-=", "1", "elif", "index", "==", "0", ":", "# Zero indicies should not be allowed by default.", "raise", "ValueError", "return", "index" ]
5baf7f2e145045942ee8dcaccbc47f8f821fcb56
valid
Cutter.cut
Returns selected positions from cut input source in desired arrangement. Argument: line - input to cut
cuts/cutter.py
def cut(self, line): """Returns selected positions from cut input source in desired arrangement. Argument: line - input to cut """ result = [] line = self.line(line) for i, field in enumerate(self.positions): try: index = _setup_index(field) try: result += line[index] except IndexError: result.append(self.invalid_pos) except ValueError: result.append(str(field)) except TypeError: result.extend(self._cut_range(line, int(field[0]), i)) return ''.join(result)
def cut(self, line): """Returns selected positions from cut input source in desired arrangement. Argument: line - input to cut """ result = [] line = self.line(line) for i, field in enumerate(self.positions): try: index = _setup_index(field) try: result += line[index] except IndexError: result.append(self.invalid_pos) except ValueError: result.append(str(field)) except TypeError: result.extend(self._cut_range(line, int(field[0]), i)) return ''.join(result)
[ "Returns", "selected", "positions", "from", "cut", "input", "source", "in", "desired", "arrangement", "." ]
jpweiser/cuts
python
https://github.com/jpweiser/cuts/blob/5baf7f2e145045942ee8dcaccbc47f8f821fcb56/cuts/cutter.py#L60-L82
[ "def", "cut", "(", "self", ",", "line", ")", ":", "result", "=", "[", "]", "line", "=", "self", ".", "line", "(", "line", ")", "for", "i", ",", "field", "in", "enumerate", "(", "self", ".", "positions", ")", ":", "try", ":", "index", "=", "_setup_index", "(", "field", ")", "try", ":", "result", "+=", "line", "[", "index", "]", "except", "IndexError", ":", "result", ".", "append", "(", "self", ".", "invalid_pos", ")", "except", "ValueError", ":", "result", ".", "append", "(", "str", "(", "field", ")", ")", "except", "TypeError", ":", "result", ".", "extend", "(", "self", ".", "_cut_range", "(", "line", ",", "int", "(", "field", "[", "0", "]", ")", ",", "i", ")", ")", "return", "''", ".", "join", "(", "result", ")" ]
5baf7f2e145045942ee8dcaccbc47f8f821fcb56
valid
Cutter._setup_positions
Processes positions to account for ranges Arguments: positions - list of positions and/or ranges to process
cuts/cutter.py
def _setup_positions(self, positions): """Processes positions to account for ranges Arguments: positions - list of positions and/or ranges to process """ updated_positions = [] for i, position in enumerate(positions): ranger = re.search(r'(?P<start>-?\d*):(?P<end>\d*)', position) if ranger: if i > 0: updated_positions.append(self.separator) start = group_val(ranger.group('start')) end = group_val(ranger.group('end')) if start and end: updated_positions.extend(self._extendrange(start, end + 1)) # Since the number of positions on a line is unknown, # send input to cause exception that can be caught and call # _cut_range helper function elif ranger.group('start'): updated_positions.append([start]) else: updated_positions.extend(self._extendrange(1, end + 1)) else: updated_positions.append(positions[i]) try: if int(position) and int(positions[i+1]): updated_positions.append(self.separator) except (ValueError, IndexError): pass return updated_positions
def _setup_positions(self, positions): """Processes positions to account for ranges Arguments: positions - list of positions and/or ranges to process """ updated_positions = [] for i, position in enumerate(positions): ranger = re.search(r'(?P<start>-?\d*):(?P<end>\d*)', position) if ranger: if i > 0: updated_positions.append(self.separator) start = group_val(ranger.group('start')) end = group_val(ranger.group('end')) if start and end: updated_positions.extend(self._extendrange(start, end + 1)) # Since the number of positions on a line is unknown, # send input to cause exception that can be caught and call # _cut_range helper function elif ranger.group('start'): updated_positions.append([start]) else: updated_positions.extend(self._extendrange(1, end + 1)) else: updated_positions.append(positions[i]) try: if int(position) and int(positions[i+1]): updated_positions.append(self.separator) except (ValueError, IndexError): pass return updated_positions
[ "Processes", "positions", "to", "account", "for", "ranges" ]
jpweiser/cuts
python
https://github.com/jpweiser/cuts/blob/5baf7f2e145045942ee8dcaccbc47f8f821fcb56/cuts/cutter.py#L84-L118
[ "def", "_setup_positions", "(", "self", ",", "positions", ")", ":", "updated_positions", "=", "[", "]", "for", "i", ",", "position", "in", "enumerate", "(", "positions", ")", ":", "ranger", "=", "re", ".", "search", "(", "r'(?P<start>-?\\d*):(?P<end>\\d*)'", ",", "position", ")", "if", "ranger", ":", "if", "i", ">", "0", ":", "updated_positions", ".", "append", "(", "self", ".", "separator", ")", "start", "=", "group_val", "(", "ranger", ".", "group", "(", "'start'", ")", ")", "end", "=", "group_val", "(", "ranger", ".", "group", "(", "'end'", ")", ")", "if", "start", "and", "end", ":", "updated_positions", ".", "extend", "(", "self", ".", "_extendrange", "(", "start", ",", "end", "+", "1", ")", ")", "# Since the number of positions on a line is unknown,", "# send input to cause exception that can be caught and call", "# _cut_range helper function", "elif", "ranger", ".", "group", "(", "'start'", ")", ":", "updated_positions", ".", "append", "(", "[", "start", "]", ")", "else", ":", "updated_positions", ".", "extend", "(", "self", ".", "_extendrange", "(", "1", ",", "end", "+", "1", ")", ")", "else", ":", "updated_positions", ".", "append", "(", "positions", "[", "i", "]", ")", "try", ":", "if", "int", "(", "position", ")", "and", "int", "(", "positions", "[", "i", "+", "1", "]", ")", ":", "updated_positions", ".", "append", "(", "self", ".", "separator", ")", "except", "(", "ValueError", ",", "IndexError", ")", ":", "pass", "return", "updated_positions" ]
5baf7f2e145045942ee8dcaccbc47f8f821fcb56
valid
Cutter._cut_range
Performs cut for range from start position to end Arguments: line - input to cut start - start of range current_position - current position in main cut function
cuts/cutter.py
def _cut_range(self, line, start, current_position): """Performs cut for range from start position to end Arguments: line - input to cut start - start of range current_position - current position in main cut function """ result = [] try: for j in range(start, len(line)): index = _setup_index(j) try: result.append(line[index]) except IndexError: result.append(self.invalid_pos) finally: result.append(self.separator) result.append(line[-1]) except IndexError: pass try: int(self.positions[current_position+1]) result.append(self.separator) except (ValueError, IndexError): pass return result
def _cut_range(self, line, start, current_position): """Performs cut for range from start position to end Arguments: line - input to cut start - start of range current_position - current position in main cut function """ result = [] try: for j in range(start, len(line)): index = _setup_index(j) try: result.append(line[index]) except IndexError: result.append(self.invalid_pos) finally: result.append(self.separator) result.append(line[-1]) except IndexError: pass try: int(self.positions[current_position+1]) result.append(self.separator) except (ValueError, IndexError): pass return result
[ "Performs", "cut", "for", "range", "from", "start", "position", "to", "end" ]
jpweiser/cuts
python
https://github.com/jpweiser/cuts/blob/5baf7f2e145045942ee8dcaccbc47f8f821fcb56/cuts/cutter.py#L121-L149
[ "def", "_cut_range", "(", "self", ",", "line", ",", "start", ",", "current_position", ")", ":", "result", "=", "[", "]", "try", ":", "for", "j", "in", "range", "(", "start", ",", "len", "(", "line", ")", ")", ":", "index", "=", "_setup_index", "(", "j", ")", "try", ":", "result", ".", "append", "(", "line", "[", "index", "]", ")", "except", "IndexError", ":", "result", ".", "append", "(", "self", ".", "invalid_pos", ")", "finally", ":", "result", ".", "append", "(", "self", ".", "separator", ")", "result", ".", "append", "(", "line", "[", "-", "1", "]", ")", "except", "IndexError", ":", "pass", "try", ":", "int", "(", "self", ".", "positions", "[", "current_position", "+", "1", "]", ")", "result", ".", "append", "(", "self", ".", "separator", ")", "except", "(", "ValueError", ",", "IndexError", ")", ":", "pass", "return", "result" ]
5baf7f2e145045942ee8dcaccbc47f8f821fcb56
valid
Cutter._extendrange
Creates list of values in a range with output delimiters. Arguments: start - range start end - range end
cuts/cutter.py
def _extendrange(self, start, end): """Creates list of values in a range with output delimiters. Arguments: start - range start end - range end """ range_positions = [] for i in range(start, end): if i != 0: range_positions.append(str(i)) if i < end: range_positions.append(self.separator) return range_positions
def _extendrange(self, start, end): """Creates list of values in a range with output delimiters. Arguments: start - range start end - range end """ range_positions = [] for i in range(start, end): if i != 0: range_positions.append(str(i)) if i < end: range_positions.append(self.separator) return range_positions
[ "Creates", "list", "of", "values", "in", "a", "range", "with", "output", "delimiters", "." ]
jpweiser/cuts
python
https://github.com/jpweiser/cuts/blob/5baf7f2e145045942ee8dcaccbc47f8f821fcb56/cuts/cutter.py#L153-L166
[ "def", "_extendrange", "(", "self", ",", "start", ",", "end", ")", ":", "range_positions", "=", "[", "]", "for", "i", "in", "range", "(", "start", ",", "end", ")", ":", "if", "i", "!=", "0", ":", "range_positions", ".", "append", "(", "str", "(", "i", ")", ")", "if", "i", "<", "end", ":", "range_positions", ".", "append", "(", "self", ".", "separator", ")", "return", "range_positions" ]
5baf7f2e145045942ee8dcaccbc47f8f821fcb56
valid
lock_file
Locks the file by writing a '.lock' file. Returns True when the file is locked and False when the file was locked already
lrcloud/__main__.py
def lock_file(filename): """Locks the file by writing a '.lock' file. Returns True when the file is locked and False when the file was locked already""" lockfile = "%s.lock"%filename if isfile(lockfile): return False else: with open(lockfile, "w"): pass return True
def lock_file(filename): """Locks the file by writing a '.lock' file. Returns True when the file is locked and False when the file was locked already""" lockfile = "%s.lock"%filename if isfile(lockfile): return False else: with open(lockfile, "w"): pass return True
[ "Locks", "the", "file", "by", "writing", "a", ".", "lock", "file", ".", "Returns", "True", "when", "the", "file", "is", "locked", "and", "False", "when", "the", "file", "was", "locked", "already" ]
madsbk/lrcloud
python
https://github.com/madsbk/lrcloud/blob/8d99be3e1abdf941642e9a1c86b7d775dc373c0b/lrcloud/__main__.py#L30-L41
[ "def", "lock_file", "(", "filename", ")", ":", "lockfile", "=", "\"%s.lock\"", "%", "filename", "if", "isfile", "(", "lockfile", ")", ":", "return", "False", "else", ":", "with", "open", "(", "lockfile", ",", "\"w\"", ")", ":", "pass", "return", "True" ]
8d99be3e1abdf941642e9a1c86b7d775dc373c0b
valid
unlock_file
Unlocks the file by remove a '.lock' file. Returns True when the file is unlocked and False when the file was unlocked already
lrcloud/__main__.py
def unlock_file(filename): """Unlocks the file by remove a '.lock' file. Returns True when the file is unlocked and False when the file was unlocked already""" lockfile = "%s.lock"%filename if isfile(lockfile): os.remove(lockfile) return True else: return False
def unlock_file(filename): """Unlocks the file by remove a '.lock' file. Returns True when the file is unlocked and False when the file was unlocked already""" lockfile = "%s.lock"%filename if isfile(lockfile): os.remove(lockfile) return True else: return False
[ "Unlocks", "the", "file", "by", "remove", "a", ".", "lock", "file", ".", "Returns", "True", "when", "the", "file", "is", "unlocked", "and", "False", "when", "the", "file", "was", "unlocked", "already" ]
madsbk/lrcloud
python
https://github.com/madsbk/lrcloud/blob/8d99be3e1abdf941642e9a1c86b7d775dc373c0b/lrcloud/__main__.py#L44-L54
[ "def", "unlock_file", "(", "filename", ")", ":", "lockfile", "=", "\"%s.lock\"", "%", "filename", "if", "isfile", "(", "lockfile", ")", ":", "os", ".", "remove", "(", "lockfile", ")", "return", "True", "else", ":", "return", "False" ]
8d99be3e1abdf941642e9a1c86b7d775dc373c0b
valid
copy_smart_previews
Copy Smart Previews from local to cloud or vica versa when 'local2cloud==False' NB: nothing happens if source dir doesn't exist
lrcloud/__main__.py
def copy_smart_previews(local_catalog, cloud_catalog, local2cloud=True): """Copy Smart Previews from local to cloud or vica versa when 'local2cloud==False' NB: nothing happens if source dir doesn't exist""" lcat_noext = local_catalog[0:local_catalog.rfind(".lrcat")] ccat_noext = cloud_catalog[0:cloud_catalog.rfind(".lrcat")] lsmart = join(dirname(local_catalog),"%s Smart Previews.lrdata"%basename(lcat_noext)) csmart = join(dirname(cloud_catalog),"%s Smart Previews.lrdata"%basename(ccat_noext)) if local2cloud and os.path.isdir(lsmart): logging.info("Copy Smart Previews - local to cloud: %s => %s"%(lsmart, csmart)) distutils.dir_util.copy_tree(lsmart,csmart, update=1) elif os.path.isdir(csmart): logging.info("Copy Smart Previews - cloud to local: %s => %s"%(csmart, lsmart)) distutils.dir_util.copy_tree(csmart,lsmart, update=1)
def copy_smart_previews(local_catalog, cloud_catalog, local2cloud=True): """Copy Smart Previews from local to cloud or vica versa when 'local2cloud==False' NB: nothing happens if source dir doesn't exist""" lcat_noext = local_catalog[0:local_catalog.rfind(".lrcat")] ccat_noext = cloud_catalog[0:cloud_catalog.rfind(".lrcat")] lsmart = join(dirname(local_catalog),"%s Smart Previews.lrdata"%basename(lcat_noext)) csmart = join(dirname(cloud_catalog),"%s Smart Previews.lrdata"%basename(ccat_noext)) if local2cloud and os.path.isdir(lsmart): logging.info("Copy Smart Previews - local to cloud: %s => %s"%(lsmart, csmart)) distutils.dir_util.copy_tree(lsmart,csmart, update=1) elif os.path.isdir(csmart): logging.info("Copy Smart Previews - cloud to local: %s => %s"%(csmart, lsmart)) distutils.dir_util.copy_tree(csmart,lsmart, update=1)
[ "Copy", "Smart", "Previews", "from", "local", "to", "cloud", "or", "vica", "versa", "when", "local2cloud", "==", "False", "NB", ":", "nothing", "happens", "if", "source", "dir", "doesn", "t", "exist" ]
madsbk/lrcloud
python
https://github.com/madsbk/lrcloud/blob/8d99be3e1abdf941642e9a1c86b7d775dc373c0b/lrcloud/__main__.py#L57-L71
[ "def", "copy_smart_previews", "(", "local_catalog", ",", "cloud_catalog", ",", "local2cloud", "=", "True", ")", ":", "lcat_noext", "=", "local_catalog", "[", "0", ":", "local_catalog", ".", "rfind", "(", "\".lrcat\"", ")", "]", "ccat_noext", "=", "cloud_catalog", "[", "0", ":", "cloud_catalog", ".", "rfind", "(", "\".lrcat\"", ")", "]", "lsmart", "=", "join", "(", "dirname", "(", "local_catalog", ")", ",", "\"%s Smart Previews.lrdata\"", "%", "basename", "(", "lcat_noext", ")", ")", "csmart", "=", "join", "(", "dirname", "(", "cloud_catalog", ")", ",", "\"%s Smart Previews.lrdata\"", "%", "basename", "(", "ccat_noext", ")", ")", "if", "local2cloud", "and", "os", ".", "path", ".", "isdir", "(", "lsmart", ")", ":", "logging", ".", "info", "(", "\"Copy Smart Previews - local to cloud: %s => %s\"", "%", "(", "lsmart", ",", "csmart", ")", ")", "distutils", ".", "dir_util", ".", "copy_tree", "(", "lsmart", ",", "csmart", ",", "update", "=", "1", ")", "elif", "os", ".", "path", ".", "isdir", "(", "csmart", ")", ":", "logging", ".", "info", "(", "\"Copy Smart Previews - cloud to local: %s => %s\"", "%", "(", "csmart", ",", "lsmart", ")", ")", "distutils", ".", "dir_util", ".", "copy_tree", "(", "csmart", ",", "lsmart", ",", "update", "=", "1", ")" ]
8d99be3e1abdf941642e9a1c86b7d775dc373c0b
valid
hashsum
Return a hash of the file From <http://stackoverflow.com/a/7829658>
lrcloud/__main__.py
def hashsum(filename): """Return a hash of the file From <http://stackoverflow.com/a/7829658>""" with open(filename, mode='rb') as f: d = hashlib.sha1() for buf in iter(partial(f.read, 2**20), b''): d.update(buf) return d.hexdigest()
def hashsum(filename): """Return a hash of the file From <http://stackoverflow.com/a/7829658>""" with open(filename, mode='rb') as f: d = hashlib.sha1() for buf in iter(partial(f.read, 2**20), b''): d.update(buf) return d.hexdigest()
[ "Return", "a", "hash", "of", "the", "file", "From", "<http", ":", "//", "stackoverflow", ".", "com", "/", "a", "/", "7829658", ">" ]
madsbk/lrcloud
python
https://github.com/madsbk/lrcloud/blob/8d99be3e1abdf941642e9a1c86b7d775dc373c0b/lrcloud/__main__.py#L74-L81
[ "def", "hashsum", "(", "filename", ")", ":", "with", "open", "(", "filename", ",", "mode", "=", "'rb'", ")", "as", "f", ":", "d", "=", "hashlib", ".", "sha1", "(", ")", "for", "buf", "in", "iter", "(", "partial", "(", "f", ".", "read", ",", "2", "**", "20", ")", ",", "b''", ")", ":", "d", ".", "update", "(", "buf", ")", "return", "d", ".", "hexdigest", "(", ")" ]
8d99be3e1abdf941642e9a1c86b7d775dc373c0b
valid
cmd_init_push_to_cloud
Initiate the local catalog and push it the cloud
lrcloud/__main__.py
def cmd_init_push_to_cloud(args): """Initiate the local catalog and push it the cloud""" (lcat, ccat) = (args.local_catalog, args.cloud_catalog) logging.info("[init-push-to-cloud]: %s => %s"%(lcat, ccat)) if not isfile(lcat): args.error("[init-push-to-cloud] The local catalog does not exist: %s"%lcat) if isfile(ccat): args.error("[init-push-to-cloud] The cloud catalog already exist: %s"%ccat) (lmeta, cmeta) = ("%s.lrcloud"%lcat, "%s.lrcloud"%ccat) if isfile(lmeta): args.error("[init-push-to-cloud] The local meta-data already exist: %s"%lmeta) if isfile(cmeta): args.error("[init-push-to-cloud] The cloud meta-data already exist: %s"%cmeta) #Let's "lock" the local catalog logging.info("Locking local catalog: %s"%(lcat)) if not lock_file(lcat): raise RuntimeError("The catalog %s is locked!"%lcat) #Copy catalog from local to cloud, which becomes the new "base" changeset util.copy(lcat, ccat) # Write meta-data both to local and cloud mfile = MetaFile(lmeta) utcnow = datetime.utcnow().strftime(DATETIME_FORMAT)[:-4] mfile['catalog']['hash'] = hashsum(lcat) mfile['catalog']['modification_utc'] = utcnow mfile['catalog']['filename'] = lcat mfile['last_push']['filename'] = ccat mfile['last_push']['hash'] = hashsum(lcat) mfile['last_push']['modification_utc'] = utcnow mfile.flush() mfile = MetaFile(cmeta) mfile['changeset']['is_base'] = True mfile['changeset']['hash'] = hashsum(lcat) mfile['changeset']['modification_utc'] = utcnow mfile['changeset']['filename'] = basename(ccat) mfile.flush() #Let's copy Smart Previews if not args.no_smart_previews: copy_smart_previews(lcat, ccat, local2cloud=True) #Finally,let's unlock the catalog files logging.info("Unlocking local catalog: %s"%(lcat)) unlock_file(lcat) logging.info("[init-push-to-cloud]: Success!")
def cmd_init_push_to_cloud(args): """Initiate the local catalog and push it the cloud""" (lcat, ccat) = (args.local_catalog, args.cloud_catalog) logging.info("[init-push-to-cloud]: %s => %s"%(lcat, ccat)) if not isfile(lcat): args.error("[init-push-to-cloud] The local catalog does not exist: %s"%lcat) if isfile(ccat): args.error("[init-push-to-cloud] The cloud catalog already exist: %s"%ccat) (lmeta, cmeta) = ("%s.lrcloud"%lcat, "%s.lrcloud"%ccat) if isfile(lmeta): args.error("[init-push-to-cloud] The local meta-data already exist: %s"%lmeta) if isfile(cmeta): args.error("[init-push-to-cloud] The cloud meta-data already exist: %s"%cmeta) #Let's "lock" the local catalog logging.info("Locking local catalog: %s"%(lcat)) if not lock_file(lcat): raise RuntimeError("The catalog %s is locked!"%lcat) #Copy catalog from local to cloud, which becomes the new "base" changeset util.copy(lcat, ccat) # Write meta-data both to local and cloud mfile = MetaFile(lmeta) utcnow = datetime.utcnow().strftime(DATETIME_FORMAT)[:-4] mfile['catalog']['hash'] = hashsum(lcat) mfile['catalog']['modification_utc'] = utcnow mfile['catalog']['filename'] = lcat mfile['last_push']['filename'] = ccat mfile['last_push']['hash'] = hashsum(lcat) mfile['last_push']['modification_utc'] = utcnow mfile.flush() mfile = MetaFile(cmeta) mfile['changeset']['is_base'] = True mfile['changeset']['hash'] = hashsum(lcat) mfile['changeset']['modification_utc'] = utcnow mfile['changeset']['filename'] = basename(ccat) mfile.flush() #Let's copy Smart Previews if not args.no_smart_previews: copy_smart_previews(lcat, ccat, local2cloud=True) #Finally,let's unlock the catalog files logging.info("Unlocking local catalog: %s"%(lcat)) unlock_file(lcat) logging.info("[init-push-to-cloud]: Success!")
[ "Initiate", "the", "local", "catalog", "and", "push", "it", "the", "cloud" ]
madsbk/lrcloud
python
https://github.com/madsbk/lrcloud/blob/8d99be3e1abdf941642e9a1c86b7d775dc373c0b/lrcloud/__main__.py#L166-L216
[ "def", "cmd_init_push_to_cloud", "(", "args", ")", ":", "(", "lcat", ",", "ccat", ")", "=", "(", "args", ".", "local_catalog", ",", "args", ".", "cloud_catalog", ")", "logging", ".", "info", "(", "\"[init-push-to-cloud]: %s => %s\"", "%", "(", "lcat", ",", "ccat", ")", ")", "if", "not", "isfile", "(", "lcat", ")", ":", "args", ".", "error", "(", "\"[init-push-to-cloud] The local catalog does not exist: %s\"", "%", "lcat", ")", "if", "isfile", "(", "ccat", ")", ":", "args", ".", "error", "(", "\"[init-push-to-cloud] The cloud catalog already exist: %s\"", "%", "ccat", ")", "(", "lmeta", ",", "cmeta", ")", "=", "(", "\"%s.lrcloud\"", "%", "lcat", ",", "\"%s.lrcloud\"", "%", "ccat", ")", "if", "isfile", "(", "lmeta", ")", ":", "args", ".", "error", "(", "\"[init-push-to-cloud] The local meta-data already exist: %s\"", "%", "lmeta", ")", "if", "isfile", "(", "cmeta", ")", ":", "args", ".", "error", "(", "\"[init-push-to-cloud] The cloud meta-data already exist: %s\"", "%", "cmeta", ")", "#Let's \"lock\" the local catalog", "logging", ".", "info", "(", "\"Locking local catalog: %s\"", "%", "(", "lcat", ")", ")", "if", "not", "lock_file", "(", "lcat", ")", ":", "raise", "RuntimeError", "(", "\"The catalog %s is locked!\"", "%", "lcat", ")", "#Copy catalog from local to cloud, which becomes the new \"base\" changeset", "util", ".", "copy", "(", "lcat", ",", "ccat", ")", "# Write meta-data both to local and cloud", "mfile", "=", "MetaFile", "(", "lmeta", ")", "utcnow", "=", "datetime", ".", "utcnow", "(", ")", ".", "strftime", "(", "DATETIME_FORMAT", ")", "[", ":", "-", "4", "]", "mfile", "[", "'catalog'", "]", "[", "'hash'", "]", "=", "hashsum", "(", "lcat", ")", "mfile", "[", "'catalog'", "]", "[", "'modification_utc'", "]", "=", "utcnow", "mfile", "[", "'catalog'", "]", "[", "'filename'", "]", "=", "lcat", "mfile", "[", "'last_push'", "]", "[", "'filename'", "]", "=", "ccat", "mfile", "[", "'last_push'", "]", "[", "'hash'", "]", "=", "hashsum", "(", "lcat", ")", "mfile", "[", "'last_push'", "]", "[", "'modification_utc'", "]", "=", "utcnow", "mfile", ".", "flush", "(", ")", "mfile", "=", "MetaFile", "(", "cmeta", ")", "mfile", "[", "'changeset'", "]", "[", "'is_base'", "]", "=", "True", "mfile", "[", "'changeset'", "]", "[", "'hash'", "]", "=", "hashsum", "(", "lcat", ")", "mfile", "[", "'changeset'", "]", "[", "'modification_utc'", "]", "=", "utcnow", "mfile", "[", "'changeset'", "]", "[", "'filename'", "]", "=", "basename", "(", "ccat", ")", "mfile", ".", "flush", "(", ")", "#Let's copy Smart Previews", "if", "not", "args", ".", "no_smart_previews", ":", "copy_smart_previews", "(", "lcat", ",", "ccat", ",", "local2cloud", "=", "True", ")", "#Finally,let's unlock the catalog files", "logging", ".", "info", "(", "\"Unlocking local catalog: %s\"", "%", "(", "lcat", ")", ")", "unlock_file", "(", "lcat", ")", "logging", ".", "info", "(", "\"[init-push-to-cloud]: Success!\"", ")" ]
8d99be3e1abdf941642e9a1c86b7d775dc373c0b
valid
cmd_init_pull_from_cloud
Initiate the local catalog by downloading the cloud catalog
lrcloud/__main__.py
def cmd_init_pull_from_cloud(args): """Initiate the local catalog by downloading the cloud catalog""" (lcat, ccat) = (args.local_catalog, args.cloud_catalog) logging.info("[init-pull-from-cloud]: %s => %s"%(ccat, lcat)) if isfile(lcat): args.error("[init-pull-from-cloud] The local catalog already exist: %s"%lcat) if not isfile(ccat): args.error("[init-pull-from-cloud] The cloud catalog does not exist: %s"%ccat) (lmeta, cmeta) = ("%s.lrcloud"%lcat, "%s.lrcloud"%ccat) if isfile(lmeta): args.error("[init-pull-from-cloud] The local meta-data already exist: %s"%lmeta) if not isfile(cmeta): args.error("[init-pull-from-cloud] The cloud meta-data does not exist: %s"%cmeta) #Let's "lock" the local catalog logging.info("Locking local catalog: %s"%(lcat)) if not lock_file(lcat): raise RuntimeError("The catalog %s is locked!"%lcat) #Copy base from cloud to local util.copy(ccat, lcat) #Apply changesets cloudDAG = ChangesetDAG(ccat) path = cloudDAG.path(cloudDAG.root.hash, cloudDAG.leafs[0].hash) util.apply_changesets(args, path, lcat) # Write meta-data both to local and cloud mfile = MetaFile(lmeta) utcnow = datetime.utcnow().strftime(DATETIME_FORMAT)[:-4] mfile['catalog']['hash'] = hashsum(lcat) mfile['catalog']['modification_utc'] = utcnow mfile['catalog']['filename'] = lcat mfile['last_push']['filename'] = cloudDAG.leafs[0].mfile['changeset']['filename'] mfile['last_push']['hash'] = cloudDAG.leafs[0].mfile['changeset']['hash'] mfile['last_push']['modification_utc'] = cloudDAG.leafs[0].mfile['changeset']['modification_utc'] mfile.flush() #Let's copy Smart Previews if not args.no_smart_previews: copy_smart_previews(lcat, ccat, local2cloud=False) #Finally, let's unlock the catalog files logging.info("Unlocking local catalog: %s"%(lcat)) unlock_file(lcat) logging.info("[init-pull-from-cloud]: Success!")
def cmd_init_pull_from_cloud(args): """Initiate the local catalog by downloading the cloud catalog""" (lcat, ccat) = (args.local_catalog, args.cloud_catalog) logging.info("[init-pull-from-cloud]: %s => %s"%(ccat, lcat)) if isfile(lcat): args.error("[init-pull-from-cloud] The local catalog already exist: %s"%lcat) if not isfile(ccat): args.error("[init-pull-from-cloud] The cloud catalog does not exist: %s"%ccat) (lmeta, cmeta) = ("%s.lrcloud"%lcat, "%s.lrcloud"%ccat) if isfile(lmeta): args.error("[init-pull-from-cloud] The local meta-data already exist: %s"%lmeta) if not isfile(cmeta): args.error("[init-pull-from-cloud] The cloud meta-data does not exist: %s"%cmeta) #Let's "lock" the local catalog logging.info("Locking local catalog: %s"%(lcat)) if not lock_file(lcat): raise RuntimeError("The catalog %s is locked!"%lcat) #Copy base from cloud to local util.copy(ccat, lcat) #Apply changesets cloudDAG = ChangesetDAG(ccat) path = cloudDAG.path(cloudDAG.root.hash, cloudDAG.leafs[0].hash) util.apply_changesets(args, path, lcat) # Write meta-data both to local and cloud mfile = MetaFile(lmeta) utcnow = datetime.utcnow().strftime(DATETIME_FORMAT)[:-4] mfile['catalog']['hash'] = hashsum(lcat) mfile['catalog']['modification_utc'] = utcnow mfile['catalog']['filename'] = lcat mfile['last_push']['filename'] = cloudDAG.leafs[0].mfile['changeset']['filename'] mfile['last_push']['hash'] = cloudDAG.leafs[0].mfile['changeset']['hash'] mfile['last_push']['modification_utc'] = cloudDAG.leafs[0].mfile['changeset']['modification_utc'] mfile.flush() #Let's copy Smart Previews if not args.no_smart_previews: copy_smart_previews(lcat, ccat, local2cloud=False) #Finally, let's unlock the catalog files logging.info("Unlocking local catalog: %s"%(lcat)) unlock_file(lcat) logging.info("[init-pull-from-cloud]: Success!")
[ "Initiate", "the", "local", "catalog", "by", "downloading", "the", "cloud", "catalog" ]
madsbk/lrcloud
python
https://github.com/madsbk/lrcloud/blob/8d99be3e1abdf941642e9a1c86b7d775dc373c0b/lrcloud/__main__.py#L219-L268
[ "def", "cmd_init_pull_from_cloud", "(", "args", ")", ":", "(", "lcat", ",", "ccat", ")", "=", "(", "args", ".", "local_catalog", ",", "args", ".", "cloud_catalog", ")", "logging", ".", "info", "(", "\"[init-pull-from-cloud]: %s => %s\"", "%", "(", "ccat", ",", "lcat", ")", ")", "if", "isfile", "(", "lcat", ")", ":", "args", ".", "error", "(", "\"[init-pull-from-cloud] The local catalog already exist: %s\"", "%", "lcat", ")", "if", "not", "isfile", "(", "ccat", ")", ":", "args", ".", "error", "(", "\"[init-pull-from-cloud] The cloud catalog does not exist: %s\"", "%", "ccat", ")", "(", "lmeta", ",", "cmeta", ")", "=", "(", "\"%s.lrcloud\"", "%", "lcat", ",", "\"%s.lrcloud\"", "%", "ccat", ")", "if", "isfile", "(", "lmeta", ")", ":", "args", ".", "error", "(", "\"[init-pull-from-cloud] The local meta-data already exist: %s\"", "%", "lmeta", ")", "if", "not", "isfile", "(", "cmeta", ")", ":", "args", ".", "error", "(", "\"[init-pull-from-cloud] The cloud meta-data does not exist: %s\"", "%", "cmeta", ")", "#Let's \"lock\" the local catalog", "logging", ".", "info", "(", "\"Locking local catalog: %s\"", "%", "(", "lcat", ")", ")", "if", "not", "lock_file", "(", "lcat", ")", ":", "raise", "RuntimeError", "(", "\"The catalog %s is locked!\"", "%", "lcat", ")", "#Copy base from cloud to local", "util", ".", "copy", "(", "ccat", ",", "lcat", ")", "#Apply changesets", "cloudDAG", "=", "ChangesetDAG", "(", "ccat", ")", "path", "=", "cloudDAG", ".", "path", "(", "cloudDAG", ".", "root", ".", "hash", ",", "cloudDAG", ".", "leafs", "[", "0", "]", ".", "hash", ")", "util", ".", "apply_changesets", "(", "args", ",", "path", ",", "lcat", ")", "# Write meta-data both to local and cloud", "mfile", "=", "MetaFile", "(", "lmeta", ")", "utcnow", "=", "datetime", ".", "utcnow", "(", ")", ".", "strftime", "(", "DATETIME_FORMAT", ")", "[", ":", "-", "4", "]", "mfile", "[", "'catalog'", "]", "[", "'hash'", "]", "=", "hashsum", "(", "lcat", ")", "mfile", "[", "'catalog'", "]", "[", "'modification_utc'", "]", "=", "utcnow", "mfile", "[", "'catalog'", "]", "[", "'filename'", "]", "=", "lcat", "mfile", "[", "'last_push'", "]", "[", "'filename'", "]", "=", "cloudDAG", ".", "leafs", "[", "0", "]", ".", "mfile", "[", "'changeset'", "]", "[", "'filename'", "]", "mfile", "[", "'last_push'", "]", "[", "'hash'", "]", "=", "cloudDAG", ".", "leafs", "[", "0", "]", ".", "mfile", "[", "'changeset'", "]", "[", "'hash'", "]", "mfile", "[", "'last_push'", "]", "[", "'modification_utc'", "]", "=", "cloudDAG", ".", "leafs", "[", "0", "]", ".", "mfile", "[", "'changeset'", "]", "[", "'modification_utc'", "]", "mfile", ".", "flush", "(", ")", "#Let's copy Smart Previews", "if", "not", "args", ".", "no_smart_previews", ":", "copy_smart_previews", "(", "lcat", ",", "ccat", ",", "local2cloud", "=", "False", ")", "#Finally, let's unlock the catalog files", "logging", ".", "info", "(", "\"Unlocking local catalog: %s\"", "%", "(", "lcat", ")", ")", "unlock_file", "(", "lcat", ")", "logging", ".", "info", "(", "\"[init-pull-from-cloud]: Success!\"", ")" ]
8d99be3e1abdf941642e9a1c86b7d775dc373c0b
valid
cmd_normal
Normal procedure: * Pull from cloud (if necessary) * Run Lightroom * Push to cloud
lrcloud/__main__.py
def cmd_normal(args): """Normal procedure: * Pull from cloud (if necessary) * Run Lightroom * Push to cloud """ logging.info("cmd_normal") (lcat, ccat) = (args.local_catalog, args.cloud_catalog) (lmeta, cmeta) = ("%s.lrcloud"%lcat, "%s.lrcloud"%ccat) if not isfile(lcat): args.error("The local catalog does not exist: %s"%lcat) if not isfile(ccat): args.error("The cloud catalog does not exist: %s"%ccat) #Let's "lock" the local catalog logging.info("Locking local catalog: %s"%(lcat)) if not lock_file(lcat): raise RuntimeError("The catalog %s is locked!"%lcat) #Backup the local catalog (overwriting old backup) logging.info("Removed old backup: %s.backup"%lcat) util.remove("%s.backup"%lcat) util.copy(lcat, "%s.backup"%lcat) lmfile = MetaFile(lmeta) cmfile = MetaFile(cmeta) #Apply changesets cloudDAG = ChangesetDAG(ccat) path = cloudDAG.path(lmfile['last_push']['hash'], cloudDAG.leafs[0].hash) util.apply_changesets(args, path, lcat) #Let's copy Smart Previews if not args.no_smart_previews: copy_smart_previews(lcat, ccat, local2cloud=False) #Backup the local catalog (overwriting old backup) logging.info("Removed old backup: %s.backup"%lcat) util.remove("%s.backup"%lcat) util.copy(lcat, "%s.backup"%lcat) #Let's unlock the local catalog so that Lightroom can read it logging.info("Unlocking local catalog: %s"%(lcat)) unlock_file(lcat) #Now we can start Lightroom if args.lightroom_exec_debug: logging.info("Debug Lightroom appending '%s' to %s"%(args.lightroom_exec_debug, lcat)) with open(lcat, "a") as f: f.write("%s\n"%args.lightroom_exec_debug) elif args.lightroom_exec: logging.info("Starting Lightroom: %s %s"%(args.lightroom_exec, lcat)) subprocess.call([args.lightroom_exec, lcat]) tmpdir = tempfile.mkdtemp() tmp_patch = join(tmpdir, "tmp.patch") diff_cmd = args.diff_cmd.replace("$in1", "%s.backup"%lcat)\ .replace("$in2", lcat)\ .replace("$out", tmp_patch) logging.info("Diff: %s"%diff_cmd) subprocess.call(diff_cmd, shell=True) patch = "%s_%s.zip"%(ccat, hashsum(tmp_patch)) util.copy(tmp_patch, patch) # Write cloud meta-data mfile = MetaFile("%s.lrcloud"%patch) utcnow = datetime.utcnow().strftime(DATETIME_FORMAT)[:-4] mfile['changeset']['is_base'] = False mfile['changeset']['hash'] = hashsum(tmp_patch) mfile['changeset']['modification_utc'] = utcnow mfile['changeset']['filename'] = basename(patch) mfile['parent']['is_base'] = cloudDAG.leafs[0].mfile['changeset']['is_base'] mfile['parent']['hash'] = cloudDAG.leafs[0].mfile['changeset']['hash'] mfile['parent']['modification_utc'] = cloudDAG.leafs[0].mfile['changeset']['modification_utc'] mfile['parent']['filename'] = basename(cloudDAG.leafs[0].mfile['changeset']['filename']) mfile.flush() # Write local meta-data mfile = MetaFile(lmeta) mfile['catalog']['hash'] = hashsum(lcat) mfile['catalog']['modification_utc'] = utcnow mfile['last_push']['filename'] = patch mfile['last_push']['hash'] = hashsum(tmp_patch) mfile['last_push']['modification_utc'] = utcnow mfile.flush() shutil.rmtree(tmpdir, ignore_errors=True) #Let's copy Smart Previews if not args.no_smart_previews: copy_smart_previews(lcat, ccat, local2cloud=True) #Finally, let's unlock the catalog files logging.info("Unlocking local catalog: %s"%(lcat)) unlock_file(lcat)
def cmd_normal(args): """Normal procedure: * Pull from cloud (if necessary) * Run Lightroom * Push to cloud """ logging.info("cmd_normal") (lcat, ccat) = (args.local_catalog, args.cloud_catalog) (lmeta, cmeta) = ("%s.lrcloud"%lcat, "%s.lrcloud"%ccat) if not isfile(lcat): args.error("The local catalog does not exist: %s"%lcat) if not isfile(ccat): args.error("The cloud catalog does not exist: %s"%ccat) #Let's "lock" the local catalog logging.info("Locking local catalog: %s"%(lcat)) if not lock_file(lcat): raise RuntimeError("The catalog %s is locked!"%lcat) #Backup the local catalog (overwriting old backup) logging.info("Removed old backup: %s.backup"%lcat) util.remove("%s.backup"%lcat) util.copy(lcat, "%s.backup"%lcat) lmfile = MetaFile(lmeta) cmfile = MetaFile(cmeta) #Apply changesets cloudDAG = ChangesetDAG(ccat) path = cloudDAG.path(lmfile['last_push']['hash'], cloudDAG.leafs[0].hash) util.apply_changesets(args, path, lcat) #Let's copy Smart Previews if not args.no_smart_previews: copy_smart_previews(lcat, ccat, local2cloud=False) #Backup the local catalog (overwriting old backup) logging.info("Removed old backup: %s.backup"%lcat) util.remove("%s.backup"%lcat) util.copy(lcat, "%s.backup"%lcat) #Let's unlock the local catalog so that Lightroom can read it logging.info("Unlocking local catalog: %s"%(lcat)) unlock_file(lcat) #Now we can start Lightroom if args.lightroom_exec_debug: logging.info("Debug Lightroom appending '%s' to %s"%(args.lightroom_exec_debug, lcat)) with open(lcat, "a") as f: f.write("%s\n"%args.lightroom_exec_debug) elif args.lightroom_exec: logging.info("Starting Lightroom: %s %s"%(args.lightroom_exec, lcat)) subprocess.call([args.lightroom_exec, lcat]) tmpdir = tempfile.mkdtemp() tmp_patch = join(tmpdir, "tmp.patch") diff_cmd = args.diff_cmd.replace("$in1", "%s.backup"%lcat)\ .replace("$in2", lcat)\ .replace("$out", tmp_patch) logging.info("Diff: %s"%diff_cmd) subprocess.call(diff_cmd, shell=True) patch = "%s_%s.zip"%(ccat, hashsum(tmp_patch)) util.copy(tmp_patch, patch) # Write cloud meta-data mfile = MetaFile("%s.lrcloud"%patch) utcnow = datetime.utcnow().strftime(DATETIME_FORMAT)[:-4] mfile['changeset']['is_base'] = False mfile['changeset']['hash'] = hashsum(tmp_patch) mfile['changeset']['modification_utc'] = utcnow mfile['changeset']['filename'] = basename(patch) mfile['parent']['is_base'] = cloudDAG.leafs[0].mfile['changeset']['is_base'] mfile['parent']['hash'] = cloudDAG.leafs[0].mfile['changeset']['hash'] mfile['parent']['modification_utc'] = cloudDAG.leafs[0].mfile['changeset']['modification_utc'] mfile['parent']['filename'] = basename(cloudDAG.leafs[0].mfile['changeset']['filename']) mfile.flush() # Write local meta-data mfile = MetaFile(lmeta) mfile['catalog']['hash'] = hashsum(lcat) mfile['catalog']['modification_utc'] = utcnow mfile['last_push']['filename'] = patch mfile['last_push']['hash'] = hashsum(tmp_patch) mfile['last_push']['modification_utc'] = utcnow mfile.flush() shutil.rmtree(tmpdir, ignore_errors=True) #Let's copy Smart Previews if not args.no_smart_previews: copy_smart_previews(lcat, ccat, local2cloud=True) #Finally, let's unlock the catalog files logging.info("Unlocking local catalog: %s"%(lcat)) unlock_file(lcat)
[ "Normal", "procedure", ":", "*", "Pull", "from", "cloud", "(", "if", "necessary", ")", "*", "Run", "Lightroom", "*", "Push", "to", "cloud" ]
madsbk/lrcloud
python
https://github.com/madsbk/lrcloud/blob/8d99be3e1abdf941642e9a1c86b7d775dc373c0b/lrcloud/__main__.py#L271-L369
[ "def", "cmd_normal", "(", "args", ")", ":", "logging", ".", "info", "(", "\"cmd_normal\"", ")", "(", "lcat", ",", "ccat", ")", "=", "(", "args", ".", "local_catalog", ",", "args", ".", "cloud_catalog", ")", "(", "lmeta", ",", "cmeta", ")", "=", "(", "\"%s.lrcloud\"", "%", "lcat", ",", "\"%s.lrcloud\"", "%", "ccat", ")", "if", "not", "isfile", "(", "lcat", ")", ":", "args", ".", "error", "(", "\"The local catalog does not exist: %s\"", "%", "lcat", ")", "if", "not", "isfile", "(", "ccat", ")", ":", "args", ".", "error", "(", "\"The cloud catalog does not exist: %s\"", "%", "ccat", ")", "#Let's \"lock\" the local catalog", "logging", ".", "info", "(", "\"Locking local catalog: %s\"", "%", "(", "lcat", ")", ")", "if", "not", "lock_file", "(", "lcat", ")", ":", "raise", "RuntimeError", "(", "\"The catalog %s is locked!\"", "%", "lcat", ")", "#Backup the local catalog (overwriting old backup)", "logging", ".", "info", "(", "\"Removed old backup: %s.backup\"", "%", "lcat", ")", "util", ".", "remove", "(", "\"%s.backup\"", "%", "lcat", ")", "util", ".", "copy", "(", "lcat", ",", "\"%s.backup\"", "%", "lcat", ")", "lmfile", "=", "MetaFile", "(", "lmeta", ")", "cmfile", "=", "MetaFile", "(", "cmeta", ")", "#Apply changesets", "cloudDAG", "=", "ChangesetDAG", "(", "ccat", ")", "path", "=", "cloudDAG", ".", "path", "(", "lmfile", "[", "'last_push'", "]", "[", "'hash'", "]", ",", "cloudDAG", ".", "leafs", "[", "0", "]", ".", "hash", ")", "util", ".", "apply_changesets", "(", "args", ",", "path", ",", "lcat", ")", "#Let's copy Smart Previews", "if", "not", "args", ".", "no_smart_previews", ":", "copy_smart_previews", "(", "lcat", ",", "ccat", ",", "local2cloud", "=", "False", ")", "#Backup the local catalog (overwriting old backup)", "logging", ".", "info", "(", "\"Removed old backup: %s.backup\"", "%", "lcat", ")", "util", ".", "remove", "(", "\"%s.backup\"", "%", "lcat", ")", "util", ".", "copy", "(", "lcat", ",", "\"%s.backup\"", "%", "lcat", ")", "#Let's unlock the local catalog so that Lightroom can read it", "logging", ".", "info", "(", "\"Unlocking local catalog: %s\"", "%", "(", "lcat", ")", ")", "unlock_file", "(", "lcat", ")", "#Now we can start Lightroom", "if", "args", ".", "lightroom_exec_debug", ":", "logging", ".", "info", "(", "\"Debug Lightroom appending '%s' to %s\"", "%", "(", "args", ".", "lightroom_exec_debug", ",", "lcat", ")", ")", "with", "open", "(", "lcat", ",", "\"a\"", ")", "as", "f", ":", "f", ".", "write", "(", "\"%s\\n\"", "%", "args", ".", "lightroom_exec_debug", ")", "elif", "args", ".", "lightroom_exec", ":", "logging", ".", "info", "(", "\"Starting Lightroom: %s %s\"", "%", "(", "args", ".", "lightroom_exec", ",", "lcat", ")", ")", "subprocess", ".", "call", "(", "[", "args", ".", "lightroom_exec", ",", "lcat", "]", ")", "tmpdir", "=", "tempfile", ".", "mkdtemp", "(", ")", "tmp_patch", "=", "join", "(", "tmpdir", ",", "\"tmp.patch\"", ")", "diff_cmd", "=", "args", ".", "diff_cmd", ".", "replace", "(", "\"$in1\"", ",", "\"%s.backup\"", "%", "lcat", ")", ".", "replace", "(", "\"$in2\"", ",", "lcat", ")", ".", "replace", "(", "\"$out\"", ",", "tmp_patch", ")", "logging", ".", "info", "(", "\"Diff: %s\"", "%", "diff_cmd", ")", "subprocess", ".", "call", "(", "diff_cmd", ",", "shell", "=", "True", ")", "patch", "=", "\"%s_%s.zip\"", "%", "(", "ccat", ",", "hashsum", "(", "tmp_patch", ")", ")", "util", ".", "copy", "(", "tmp_patch", ",", "patch", ")", "# Write cloud meta-data", "mfile", "=", "MetaFile", "(", "\"%s.lrcloud\"", "%", "patch", ")", "utcnow", "=", "datetime", ".", "utcnow", "(", ")", ".", "strftime", "(", "DATETIME_FORMAT", ")", "[", ":", "-", "4", "]", "mfile", "[", "'changeset'", "]", "[", "'is_base'", "]", "=", "False", "mfile", "[", "'changeset'", "]", "[", "'hash'", "]", "=", "hashsum", "(", "tmp_patch", ")", "mfile", "[", "'changeset'", "]", "[", "'modification_utc'", "]", "=", "utcnow", "mfile", "[", "'changeset'", "]", "[", "'filename'", "]", "=", "basename", "(", "patch", ")", "mfile", "[", "'parent'", "]", "[", "'is_base'", "]", "=", "cloudDAG", ".", "leafs", "[", "0", "]", ".", "mfile", "[", "'changeset'", "]", "[", "'is_base'", "]", "mfile", "[", "'parent'", "]", "[", "'hash'", "]", "=", "cloudDAG", ".", "leafs", "[", "0", "]", ".", "mfile", "[", "'changeset'", "]", "[", "'hash'", "]", "mfile", "[", "'parent'", "]", "[", "'modification_utc'", "]", "=", "cloudDAG", ".", "leafs", "[", "0", "]", ".", "mfile", "[", "'changeset'", "]", "[", "'modification_utc'", "]", "mfile", "[", "'parent'", "]", "[", "'filename'", "]", "=", "basename", "(", "cloudDAG", ".", "leafs", "[", "0", "]", ".", "mfile", "[", "'changeset'", "]", "[", "'filename'", "]", ")", "mfile", ".", "flush", "(", ")", "# Write local meta-data", "mfile", "=", "MetaFile", "(", "lmeta", ")", "mfile", "[", "'catalog'", "]", "[", "'hash'", "]", "=", "hashsum", "(", "lcat", ")", "mfile", "[", "'catalog'", "]", "[", "'modification_utc'", "]", "=", "utcnow", "mfile", "[", "'last_push'", "]", "[", "'filename'", "]", "=", "patch", "mfile", "[", "'last_push'", "]", "[", "'hash'", "]", "=", "hashsum", "(", "tmp_patch", ")", "mfile", "[", "'last_push'", "]", "[", "'modification_utc'", "]", "=", "utcnow", "mfile", ".", "flush", "(", ")", "shutil", ".", "rmtree", "(", "tmpdir", ",", "ignore_errors", "=", "True", ")", "#Let's copy Smart Previews", "if", "not", "args", ".", "no_smart_previews", ":", "copy_smart_previews", "(", "lcat", ",", "ccat", ",", "local2cloud", "=", "True", ")", "#Finally, let's unlock the catalog files", "logging", ".", "info", "(", "\"Unlocking local catalog: %s\"", "%", "(", "lcat", ")", ")", "unlock_file", "(", "lcat", ")" ]
8d99be3e1abdf941642e9a1c86b7d775dc373c0b
valid
parse_arguments
Return arguments
lrcloud/__main__.py
def parse_arguments(argv=None): """Return arguments""" def default_config_path(): """Returns the platform specific default location of the configure file""" if os.name == "nt": return join(os.getenv('APPDATA'), "lrcloud.ini") else: return join(os.path.expanduser("~"), ".lrcloud.ini") parser = argparse.ArgumentParser( description='Cloud extension to Lightroom', formatter_class=argparse.ArgumentDefaultsHelpFormatter) cmd_group = parser.add_mutually_exclusive_group() cmd_group.add_argument( '--init-push-to-cloud', help='Initiate the local catalog and push it to the cloud', action="store_true" ) cmd_group.add_argument( '--init-pull-from-cloud', help='Download the cloud catalog and initiate a corresponding local catalog', action="store_true" ) parser.add_argument( '--cloud-catalog', help='The cloud/shared catalog file e.g. located in Google Drive or Dropbox', type=lambda x: os.path.expanduser(x) ) parser.add_argument( '--local-catalog', help='The local Lightroom catalog file', type=lambda x: os.path.expanduser(x) ) lr_exec = parser.add_mutually_exclusive_group() lr_exec.add_argument( '--lightroom-exec', help='The Lightroom executable file', type=str ) lr_exec.add_argument( '--lightroom-exec-debug', help='Instead of running Lightroom, append data to the end of the catalog file', type=str ) parser.add_argument( '-v', '--verbose', help='Increase output verbosity', action="store_true" ) parser.add_argument( '--no-smart-previews', help="Don't Sync Smart Previews", action="store_true" ) parser.add_argument( '--config-file', help="Path to the configure (.ini) file", type=str, default=default_config_path() ) parser.add_argument( '--diff-cmd', help="The command that given two files, $in1 and $in2, " "produces a diff file $out", type=str, #default="./jdiff -f $in1 $in2 $out" #default="bsdiff $in1 $in2 $out" ) parser.add_argument( '--patch-cmd', help="The command that given a file, $in1, and a path, " "$patch, produces a file $out", type=str, #default="./jptch $in1 $patch $out" #default="bspatch $in1 $out $patch" ) args = parser.parse_args(args=argv) args.error = parser.error if args.config_file in ['', 'none', 'None', "''", '""']: args.config_file = None if args.verbose: logging.basicConfig(level=logging.INFO) config_parser.read(args) (lcat, ccat) = (args.local_catalog, args.cloud_catalog) if lcat is None: parser.error("No local catalog specified, use --local-catalog") if ccat is None: parser.error("No cloud catalog specified, use --cloud-catalog") return args
def parse_arguments(argv=None): """Return arguments""" def default_config_path(): """Returns the platform specific default location of the configure file""" if os.name == "nt": return join(os.getenv('APPDATA'), "lrcloud.ini") else: return join(os.path.expanduser("~"), ".lrcloud.ini") parser = argparse.ArgumentParser( description='Cloud extension to Lightroom', formatter_class=argparse.ArgumentDefaultsHelpFormatter) cmd_group = parser.add_mutually_exclusive_group() cmd_group.add_argument( '--init-push-to-cloud', help='Initiate the local catalog and push it to the cloud', action="store_true" ) cmd_group.add_argument( '--init-pull-from-cloud', help='Download the cloud catalog and initiate a corresponding local catalog', action="store_true" ) parser.add_argument( '--cloud-catalog', help='The cloud/shared catalog file e.g. located in Google Drive or Dropbox', type=lambda x: os.path.expanduser(x) ) parser.add_argument( '--local-catalog', help='The local Lightroom catalog file', type=lambda x: os.path.expanduser(x) ) lr_exec = parser.add_mutually_exclusive_group() lr_exec.add_argument( '--lightroom-exec', help='The Lightroom executable file', type=str ) lr_exec.add_argument( '--lightroom-exec-debug', help='Instead of running Lightroom, append data to the end of the catalog file', type=str ) parser.add_argument( '-v', '--verbose', help='Increase output verbosity', action="store_true" ) parser.add_argument( '--no-smart-previews', help="Don't Sync Smart Previews", action="store_true" ) parser.add_argument( '--config-file', help="Path to the configure (.ini) file", type=str, default=default_config_path() ) parser.add_argument( '--diff-cmd', help="The command that given two files, $in1 and $in2, " "produces a diff file $out", type=str, #default="./jdiff -f $in1 $in2 $out" #default="bsdiff $in1 $in2 $out" ) parser.add_argument( '--patch-cmd', help="The command that given a file, $in1, and a path, " "$patch, produces a file $out", type=str, #default="./jptch $in1 $patch $out" #default="bspatch $in1 $out $patch" ) args = parser.parse_args(args=argv) args.error = parser.error if args.config_file in ['', 'none', 'None', "''", '""']: args.config_file = None if args.verbose: logging.basicConfig(level=logging.INFO) config_parser.read(args) (lcat, ccat) = (args.local_catalog, args.cloud_catalog) if lcat is None: parser.error("No local catalog specified, use --local-catalog") if ccat is None: parser.error("No cloud catalog specified, use --cloud-catalog") return args
[ "Return", "arguments" ]
madsbk/lrcloud
python
https://github.com/madsbk/lrcloud/blob/8d99be3e1abdf941642e9a1c86b7d775dc373c0b/lrcloud/__main__.py#L372-L468
[ "def", "parse_arguments", "(", "argv", "=", "None", ")", ":", "def", "default_config_path", "(", ")", ":", "\"\"\"Returns the platform specific default location of the configure file\"\"\"", "if", "os", ".", "name", "==", "\"nt\"", ":", "return", "join", "(", "os", ".", "getenv", "(", "'APPDATA'", ")", ",", "\"lrcloud.ini\"", ")", "else", ":", "return", "join", "(", "os", ".", "path", ".", "expanduser", "(", "\"~\"", ")", ",", "\".lrcloud.ini\"", ")", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "'Cloud extension to Lightroom'", ",", "formatter_class", "=", "argparse", ".", "ArgumentDefaultsHelpFormatter", ")", "cmd_group", "=", "parser", ".", "add_mutually_exclusive_group", "(", ")", "cmd_group", ".", "add_argument", "(", "'--init-push-to-cloud'", ",", "help", "=", "'Initiate the local catalog and push it to the cloud'", ",", "action", "=", "\"store_true\"", ")", "cmd_group", ".", "add_argument", "(", "'--init-pull-from-cloud'", ",", "help", "=", "'Download the cloud catalog and initiate a corresponding local catalog'", ",", "action", "=", "\"store_true\"", ")", "parser", ".", "add_argument", "(", "'--cloud-catalog'", ",", "help", "=", "'The cloud/shared catalog file e.g. located in Google Drive or Dropbox'", ",", "type", "=", "lambda", "x", ":", "os", ".", "path", ".", "expanduser", "(", "x", ")", ")", "parser", ".", "add_argument", "(", "'--local-catalog'", ",", "help", "=", "'The local Lightroom catalog file'", ",", "type", "=", "lambda", "x", ":", "os", ".", "path", ".", "expanduser", "(", "x", ")", ")", "lr_exec", "=", "parser", ".", "add_mutually_exclusive_group", "(", ")", "lr_exec", ".", "add_argument", "(", "'--lightroom-exec'", ",", "help", "=", "'The Lightroom executable file'", ",", "type", "=", "str", ")", "lr_exec", ".", "add_argument", "(", "'--lightroom-exec-debug'", ",", "help", "=", "'Instead of running Lightroom, append data to the end of the catalog file'", ",", "type", "=", "str", ")", "parser", ".", "add_argument", "(", "'-v'", ",", "'--verbose'", ",", "help", "=", "'Increase output verbosity'", ",", "action", "=", "\"store_true\"", ")", "parser", ".", "add_argument", "(", "'--no-smart-previews'", ",", "help", "=", "\"Don't Sync Smart Previews\"", ",", "action", "=", "\"store_true\"", ")", "parser", ".", "add_argument", "(", "'--config-file'", ",", "help", "=", "\"Path to the configure (.ini) file\"", ",", "type", "=", "str", ",", "default", "=", "default_config_path", "(", ")", ")", "parser", ".", "add_argument", "(", "'--diff-cmd'", ",", "help", "=", "\"The command that given two files, $in1 and $in2, \"", "\"produces a diff file $out\"", ",", "type", "=", "str", ",", "#default=\"./jdiff -f $in1 $in2 $out\"", "#default=\"bsdiff $in1 $in2 $out\"", ")", "parser", ".", "add_argument", "(", "'--patch-cmd'", ",", "help", "=", "\"The command that given a file, $in1, and a path, \"", "\"$patch, produces a file $out\"", ",", "type", "=", "str", ",", "#default=\"./jptch $in1 $patch $out\"", "#default=\"bspatch $in1 $out $patch\"", ")", "args", "=", "parser", ".", "parse_args", "(", "args", "=", "argv", ")", "args", ".", "error", "=", "parser", ".", "error", "if", "args", ".", "config_file", "in", "[", "''", ",", "'none'", ",", "'None'", ",", "\"''\"", ",", "'\"\"'", "]", ":", "args", ".", "config_file", "=", "None", "if", "args", ".", "verbose", ":", "logging", ".", "basicConfig", "(", "level", "=", "logging", ".", "INFO", ")", "config_parser", ".", "read", "(", "args", ")", "(", "lcat", ",", "ccat", ")", "=", "(", "args", ".", "local_catalog", ",", "args", ".", "cloud_catalog", ")", "if", "lcat", "is", "None", ":", "parser", ".", "error", "(", "\"No local catalog specified, use --local-catalog\"", ")", "if", "ccat", "is", "None", ":", "parser", ".", "error", "(", "\"No cloud catalog specified, use --cloud-catalog\"", ")", "return", "args" ]
8d99be3e1abdf941642e9a1c86b7d775dc373c0b