id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
51
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
27,900
criteo/gourde
gourde/gourde.py
Gourde.add_url_rule
def add_url_rule(self, route, endpoint, handler): """Add a new url route. Args: See flask.Flask.add_url_route(). """ self.app.add_url_rule(route, endpoint, handler)
python
def add_url_rule(self, route, endpoint, handler): self.app.add_url_rule(route, endpoint, handler)
[ "def", "add_url_rule", "(", "self", ",", "route", ",", "endpoint", ",", "handler", ")", ":", "self", ".", "app", ".", "add_url_rule", "(", "route", ",", "endpoint", ",", "handler", ")" ]
Add a new url route. Args: See flask.Flask.add_url_route().
[ "Add", "a", "new", "url", "route", "." ]
9a274e534a2af5d2b2a5e99f10c59010adb94863
https://github.com/criteo/gourde/blob/9a274e534a2af5d2b2a5e99f10c59010adb94863/gourde/gourde.py#L193-L199
27,901
criteo/gourde
gourde/gourde.py
Gourde.healthy
def healthy(self): """Return 200 is healthy, else 500. Override is_healthy() to change the health check. """ try: if self.is_healthy(): return "OK", 200 else: return "FAIL", 500 except Exception as e: self.app.logger.exception(e) return str(e), 500
python
def healthy(self): try: if self.is_healthy(): return "OK", 200 else: return "FAIL", 500 except Exception as e: self.app.logger.exception(e) return str(e), 500
[ "def", "healthy", "(", "self", ")", ":", "try", ":", "if", "self", ".", "is_healthy", "(", ")", ":", "return", "\"OK\"", ",", "200", "else", ":", "return", "\"FAIL\"", ",", "500", "except", "Exception", "as", "e", ":", "self", ".", "app", ".", "log...
Return 200 is healthy, else 500. Override is_healthy() to change the health check.
[ "Return", "200", "is", "healthy", "else", "500", "." ]
9a274e534a2af5d2b2a5e99f10c59010adb94863
https://github.com/criteo/gourde/blob/9a274e534a2af5d2b2a5e99f10c59010adb94863/gourde/gourde.py#L216-L230
27,902
criteo/gourde
gourde/gourde.py
Gourde.ready
def ready(self): """Return 200 is ready, else 500. Override is_ready() to change the readiness check. """ try: if self.is_ready(): return "OK", 200 else: return "FAIL", 500 except Exception as e: self.app.logger.exception() return str(e), 500
python
def ready(self): try: if self.is_ready(): return "OK", 200 else: return "FAIL", 500 except Exception as e: self.app.logger.exception() return str(e), 500
[ "def", "ready", "(", "self", ")", ":", "try", ":", "if", "self", ".", "is_ready", "(", ")", ":", "return", "\"OK\"", ",", "200", "else", ":", "return", "\"FAIL\"", ",", "500", "except", "Exception", "as", "e", ":", "self", ".", "app", ".", "logger"...
Return 200 is ready, else 500. Override is_ready() to change the readiness check.
[ "Return", "200", "is", "ready", "else", "500", "." ]
9a274e534a2af5d2b2a5e99f10c59010adb94863
https://github.com/criteo/gourde/blob/9a274e534a2af5d2b2a5e99f10c59010adb94863/gourde/gourde.py#L235-L249
27,903
criteo/gourde
gourde/gourde.py
Gourde.threads_bt
def threads_bt(self): """Display thread backtraces.""" import threading import traceback threads = {} for thread in threading.enumerate(): frames = sys._current_frames().get(thread.ident) if frames: stack = traceback.format_stack(frames) else: stack = [] threads[thread] = "".join(stack) return flask.render_template("gourde/threads.html", threads=threads)
python
def threads_bt(self): import threading import traceback threads = {} for thread in threading.enumerate(): frames = sys._current_frames().get(thread.ident) if frames: stack = traceback.format_stack(frames) else: stack = [] threads[thread] = "".join(stack) return flask.render_template("gourde/threads.html", threads=threads)
[ "def", "threads_bt", "(", "self", ")", ":", "import", "threading", "import", "traceback", "threads", "=", "{", "}", "for", "thread", "in", "threading", ".", "enumerate", "(", ")", ":", "frames", "=", "sys", ".", "_current_frames", "(", ")", ".", "get", ...
Display thread backtraces.
[ "Display", "thread", "backtraces", "." ]
9a274e534a2af5d2b2a5e99f10c59010adb94863
https://github.com/criteo/gourde/blob/9a274e534a2af5d2b2a5e99f10c59010adb94863/gourde/gourde.py#L251-L264
27,904
criteo/gourde
gourde/gourde.py
Gourde.run_with_werkzeug
def run_with_werkzeug(self, **options): """Run with werkzeug simple wsgi container.""" threaded = self.threads is not None and (self.threads > 0) self.app.run( host=self.host, port=self.port, debug=self.debug, threaded=threaded, **options )
python
def run_with_werkzeug(self, **options): threaded = self.threads is not None and (self.threads > 0) self.app.run( host=self.host, port=self.port, debug=self.debug, threaded=threaded, **options )
[ "def", "run_with_werkzeug", "(", "self", ",", "*", "*", "options", ")", ":", "threaded", "=", "self", ".", "threads", "is", "not", "None", "and", "(", "self", ".", "threads", ">", "0", ")", "self", ".", "app", ".", "run", "(", "host", "=", "self", ...
Run with werkzeug simple wsgi container.
[ "Run", "with", "werkzeug", "simple", "wsgi", "container", "." ]
9a274e534a2af5d2b2a5e99f10c59010adb94863
https://github.com/criteo/gourde/blob/9a274e534a2af5d2b2a5e99f10c59010adb94863/gourde/gourde.py#L283-L292
27,905
criteo/gourde
gourde/gourde.py
Gourde.run_with_twisted
def run_with_twisted(self, **options): """Run with twisted.""" from twisted.internet import reactor from twisted.python import log import flask_twisted twisted = flask_twisted.Twisted(self.app) if self.threads: reactor.suggestThreadPoolSize(self.threads) if self.log_level: log.startLogging(sys.stderr) twisted.run(host=self.host, port=self.port, debug=self.debug, **options)
python
def run_with_twisted(self, **options): from twisted.internet import reactor from twisted.python import log import flask_twisted twisted = flask_twisted.Twisted(self.app) if self.threads: reactor.suggestThreadPoolSize(self.threads) if self.log_level: log.startLogging(sys.stderr) twisted.run(host=self.host, port=self.port, debug=self.debug, **options)
[ "def", "run_with_twisted", "(", "self", ",", "*", "*", "options", ")", ":", "from", "twisted", ".", "internet", "import", "reactor", "from", "twisted", ".", "python", "import", "log", "import", "flask_twisted", "twisted", "=", "flask_twisted", ".", "Twisted", ...
Run with twisted.
[ "Run", "with", "twisted", "." ]
9a274e534a2af5d2b2a5e99f10c59010adb94863
https://github.com/criteo/gourde/blob/9a274e534a2af5d2b2a5e99f10c59010adb94863/gourde/gourde.py#L294-L305
27,906
criteo/gourde
gourde/gourde.py
Gourde.run_with_gunicorn
def run_with_gunicorn(self, **options): """Run with gunicorn.""" import gunicorn.app.base from gunicorn.six import iteritems import multiprocessing class GourdeApplication(gunicorn.app.base.BaseApplication): def __init__(self, app, options=None): self.options = options or {} self.application = app super(GourdeApplication, self).__init__() def load_config(self): config = dict([(key, value) for key, value in iteritems(self.options) if key in self.cfg.settings and value is not None]) for key, value in iteritems(config): self.cfg.set(key.lower(), value) def load(self): return self.application options = { 'bind': '%s:%s' % (self.host, self.port), 'workers': self.threads or ((multiprocessing.cpu_count() * 2) + 1), 'debug': self.debug, **options, } GourdeApplication(self.app, options).run()
python
def run_with_gunicorn(self, **options): import gunicorn.app.base from gunicorn.six import iteritems import multiprocessing class GourdeApplication(gunicorn.app.base.BaseApplication): def __init__(self, app, options=None): self.options = options or {} self.application = app super(GourdeApplication, self).__init__() def load_config(self): config = dict([(key, value) for key, value in iteritems(self.options) if key in self.cfg.settings and value is not None]) for key, value in iteritems(config): self.cfg.set(key.lower(), value) def load(self): return self.application options = { 'bind': '%s:%s' % (self.host, self.port), 'workers': self.threads or ((multiprocessing.cpu_count() * 2) + 1), 'debug': self.debug, **options, } GourdeApplication(self.app, options).run()
[ "def", "run_with_gunicorn", "(", "self", ",", "*", "*", "options", ")", ":", "import", "gunicorn", ".", "app", ".", "base", "from", "gunicorn", ".", "six", "import", "iteritems", "import", "multiprocessing", "class", "GourdeApplication", "(", "gunicorn", ".", ...
Run with gunicorn.
[ "Run", "with", "gunicorn", "." ]
9a274e534a2af5d2b2a5e99f10c59010adb94863
https://github.com/criteo/gourde/blob/9a274e534a2af5d2b2a5e99f10c59010adb94863/gourde/gourde.py#L307-L335
27,907
criteo/gourde
example/app.py
initialize_api
def initialize_api(flask_app): """Initialize an API.""" if not flask_restplus: return api = flask_restplus.Api(version="1.0", title="My Example API") api.add_resource(HelloWorld, "/hello") blueprint = flask.Blueprint("api", __name__, url_prefix="/api") api.init_app(blueprint) flask_app.register_blueprint(blueprint)
python
def initialize_api(flask_app): if not flask_restplus: return api = flask_restplus.Api(version="1.0", title="My Example API") api.add_resource(HelloWorld, "/hello") blueprint = flask.Blueprint("api", __name__, url_prefix="/api") api.init_app(blueprint) flask_app.register_blueprint(blueprint)
[ "def", "initialize_api", "(", "flask_app", ")", ":", "if", "not", "flask_restplus", ":", "return", "api", "=", "flask_restplus", ".", "Api", "(", "version", "=", "\"1.0\"", ",", "title", "=", "\"My Example API\"", ")", "api", ".", "add_resource", "(", "Hello...
Initialize an API.
[ "Initialize", "an", "API", "." ]
9a274e534a2af5d2b2a5e99f10c59010adb94863
https://github.com/criteo/gourde/blob/9a274e534a2af5d2b2a5e99f10c59010adb94863/example/app.py#L69-L79
27,908
criteo/gourde
example/app.py
initialize_app
def initialize_app(flask_app, args): """Initialize the App.""" # Setup gourde with the args. gourde.setup(args) # Register a custom health check. gourde.is_healthy = is_healthy # Add an optional API initialize_api(flask_app)
python
def initialize_app(flask_app, args): # Setup gourde with the args. gourde.setup(args) # Register a custom health check. gourde.is_healthy = is_healthy # Add an optional API initialize_api(flask_app)
[ "def", "initialize_app", "(", "flask_app", ",", "args", ")", ":", "# Setup gourde with the args.", "gourde", ".", "setup", "(", "args", ")", "# Register a custom health check.", "gourde", ".", "is_healthy", "=", "is_healthy", "# Add an optional API", "initialize_api", "...
Initialize the App.
[ "Initialize", "the", "App", "." ]
9a274e534a2af5d2b2a5e99f10c59010adb94863
https://github.com/criteo/gourde/blob/9a274e534a2af5d2b2a5e99f10c59010adb94863/example/app.py#L82-L91
27,909
closeio/quotequail
quotequail/__init__.py
quote
def quote(text, limit=1000): """ Takes a plain text message as an argument, returns a list of tuples. The first argument of the tuple denotes whether the text should be expanded by default. The second argument is the unmodified corresponding text. Example: [(True, 'expanded text'), (False, '> Some quoted text')] Unless the limit param is set to None, the text will automatically be quoted starting at the line where the limit is reached. """ lines = text.split('\n') found = _internal.find_quote_position(lines, _patterns.MAX_WRAP_LINES, limit) if found != None: return [(True, '\n'.join(lines[:found+1])), (False, '\n'.join(lines[found+1:]))] return [(True, text)]
python
def quote(text, limit=1000): lines = text.split('\n') found = _internal.find_quote_position(lines, _patterns.MAX_WRAP_LINES, limit) if found != None: return [(True, '\n'.join(lines[:found+1])), (False, '\n'.join(lines[found+1:]))] return [(True, text)]
[ "def", "quote", "(", "text", ",", "limit", "=", "1000", ")", ":", "lines", "=", "text", ".", "split", "(", "'\\n'", ")", "found", "=", "_internal", ".", "find_quote_position", "(", "lines", ",", "_patterns", ".", "MAX_WRAP_LINES", ",", "limit", ")", "i...
Takes a plain text message as an argument, returns a list of tuples. The first argument of the tuple denotes whether the text should be expanded by default. The second argument is the unmodified corresponding text. Example: [(True, 'expanded text'), (False, '> Some quoted text')] Unless the limit param is set to None, the text will automatically be quoted starting at the line where the limit is reached.
[ "Takes", "a", "plain", "text", "message", "as", "an", "argument", "returns", "a", "list", "of", "tuples", ".", "The", "first", "argument", "of", "the", "tuple", "denotes", "whether", "the", "text", "should", "be", "expanded", "by", "default", ".", "The", ...
8a3960c033d595b25a8bbc2c340be898e3065b5f
https://github.com/closeio/quotequail/blob/8a3960c033d595b25a8bbc2c340be898e3065b5f/quotequail/__init__.py#L12-L31
27,910
closeio/quotequail
quotequail/_internal.py
extract_headers
def extract_headers(lines, max_wrap_lines): """ Extracts email headers from the given lines. Returns a dict with the detected headers and the amount of lines that were processed. """ hdrs = {} header_name = None # Track overlong headers that extend over multiple lines extend_lines = 0 lines_processed = 0 for n, line in enumerate(lines): if not line.strip(): header_name = None continue match = HEADER_RE.match(line) if match: header_name, header_value = match.groups() header_name = header_name.strip().lower() extend_lines = 0 if header_name in HEADER_MAP: hdrs[HEADER_MAP[header_name]] = header_value.strip() lines_processed = n+1 else: extend_lines += 1 if extend_lines < max_wrap_lines and header_name in HEADER_MAP: hdrs[HEADER_MAP[header_name]] = join_wrapped_lines( [hdrs[HEADER_MAP[header_name]], line.strip()]) lines_processed = n+1 else: # no more headers found break return hdrs, lines_processed
python
def extract_headers(lines, max_wrap_lines): hdrs = {} header_name = None # Track overlong headers that extend over multiple lines extend_lines = 0 lines_processed = 0 for n, line in enumerate(lines): if not line.strip(): header_name = None continue match = HEADER_RE.match(line) if match: header_name, header_value = match.groups() header_name = header_name.strip().lower() extend_lines = 0 if header_name in HEADER_MAP: hdrs[HEADER_MAP[header_name]] = header_value.strip() lines_processed = n+1 else: extend_lines += 1 if extend_lines < max_wrap_lines and header_name in HEADER_MAP: hdrs[HEADER_MAP[header_name]] = join_wrapped_lines( [hdrs[HEADER_MAP[header_name]], line.strip()]) lines_processed = n+1 else: # no more headers found break return hdrs, lines_processed
[ "def", "extract_headers", "(", "lines", ",", "max_wrap_lines", ")", ":", "hdrs", "=", "{", "}", "header_name", "=", "None", "# Track overlong headers that extend over multiple lines", "extend_lines", "=", "0", "lines_processed", "=", "0", "for", "n", ",", "line", ...
Extracts email headers from the given lines. Returns a dict with the detected headers and the amount of lines that were processed.
[ "Extracts", "email", "headers", "from", "the", "given", "lines", ".", "Returns", "a", "dict", "with", "the", "detected", "headers", "and", "the", "amount", "of", "lines", "that", "were", "processed", "." ]
8a3960c033d595b25a8bbc2c340be898e3065b5f
https://github.com/closeio/quotequail/blob/8a3960c033d595b25a8bbc2c340be898e3065b5f/quotequail/_internal.py#L63-L100
27,911
closeio/quotequail
quotequail/_html.py
trim_tree_after
def trim_tree_after(element, include_element=True): """ Removes the document tree following the given element. If include_element is True, the given element is kept in the tree, otherwise it is removed. """ el = element for parent_el in element.iterancestors(): el.tail = None if el != element or include_element: el = el.getnext() while el is not None: remove_el = el el = el.getnext() parent_el.remove(remove_el) el = parent_el
python
def trim_tree_after(element, include_element=True): el = element for parent_el in element.iterancestors(): el.tail = None if el != element or include_element: el = el.getnext() while el is not None: remove_el = el el = el.getnext() parent_el.remove(remove_el) el = parent_el
[ "def", "trim_tree_after", "(", "element", ",", "include_element", "=", "True", ")", ":", "el", "=", "element", "for", "parent_el", "in", "element", ".", "iterancestors", "(", ")", ":", "el", ".", "tail", "=", "None", "if", "el", "!=", "element", "or", ...
Removes the document tree following the given element. If include_element is True, the given element is kept in the tree, otherwise it is removed.
[ "Removes", "the", "document", "tree", "following", "the", "given", "element", ".", "If", "include_element", "is", "True", "the", "given", "element", "is", "kept", "in", "the", "tree", "otherwise", "it", "is", "removed", "." ]
8a3960c033d595b25a8bbc2c340be898e3065b5f
https://github.com/closeio/quotequail/blob/8a3960c033d595b25a8bbc2c340be898e3065b5f/quotequail/_html.py#L19-L33
27,912
closeio/quotequail
quotequail/_html.py
trim_tree_before
def trim_tree_before(element, include_element=True, keep_head=True): """ Removes the document tree preceding the given element. If include_element is True, the given element is kept in the tree, otherwise it is removed. """ el = element for parent_el in element.iterancestors(): parent_el.text = None if el != element or include_element: el = el.getprevious() else: parent_el.text = el.tail while el is not None: remove_el = el el = el.getprevious() tag = remove_el.tag is_head = isinstance(tag, string_class) and tag.lower() == 'head' if not keep_head or not is_head: parent_el.remove(remove_el) el = parent_el
python
def trim_tree_before(element, include_element=True, keep_head=True): el = element for parent_el in element.iterancestors(): parent_el.text = None if el != element or include_element: el = el.getprevious() else: parent_el.text = el.tail while el is not None: remove_el = el el = el.getprevious() tag = remove_el.tag is_head = isinstance(tag, string_class) and tag.lower() == 'head' if not keep_head or not is_head: parent_el.remove(remove_el) el = parent_el
[ "def", "trim_tree_before", "(", "element", ",", "include_element", "=", "True", ",", "keep_head", "=", "True", ")", ":", "el", "=", "element", "for", "parent_el", "in", "element", ".", "iterancestors", "(", ")", ":", "parent_el", ".", "text", "=", "None", ...
Removes the document tree preceding the given element. If include_element is True, the given element is kept in the tree, otherwise it is removed.
[ "Removes", "the", "document", "tree", "preceding", "the", "given", "element", ".", "If", "include_element", "is", "True", "the", "given", "element", "is", "kept", "in", "the", "tree", "otherwise", "it", "is", "removed", "." ]
8a3960c033d595b25a8bbc2c340be898e3065b5f
https://github.com/closeio/quotequail/blob/8a3960c033d595b25a8bbc2c340be898e3065b5f/quotequail/_html.py#L35-L54
27,913
cmollet/sridentify
sridentify/__init__.py
Sridentify.get_epsg
def get_epsg(self): """ Attempts to determine the EPSG code for a given PRJ file or other similar text-based spatial reference file. First, it looks up the PRJ text in the included epsg.db SQLite database, which was manually sourced and cleaned from an ESRI website, https://developers.arcgis.com/javascript/jshelp/pcs.html If it cannot be found there, it next tries the prj2epsg.org API. If an exact match is found, that EPSG code is returned and saved to the database to avoid future external API calls. TODO: If that API cannot find an exact match but several partial matches, those partials will be displayed to the user with the option to select one to save to the database. """ cur = self.conn.cursor() cur.execute("SELECT epsg_code FROM prj_epsg WHERE prjtext = ?", (self.prj,)) # prjtext has a unique constraint on it, we should only ever fetchone() result = cur.fetchone() if not result and self.call_remote_api: return self.call_api() elif result is not None: self.epsg_code = result[0] return self.epsg_code
python
def get_epsg(self): cur = self.conn.cursor() cur.execute("SELECT epsg_code FROM prj_epsg WHERE prjtext = ?", (self.prj,)) # prjtext has a unique constraint on it, we should only ever fetchone() result = cur.fetchone() if not result and self.call_remote_api: return self.call_api() elif result is not None: self.epsg_code = result[0] return self.epsg_code
[ "def", "get_epsg", "(", "self", ")", ":", "cur", "=", "self", ".", "conn", ".", "cursor", "(", ")", "cur", ".", "execute", "(", "\"SELECT epsg_code FROM prj_epsg WHERE prjtext = ?\"", ",", "(", "self", ".", "prj", ",", ")", ")", "# prjtext has a unique constra...
Attempts to determine the EPSG code for a given PRJ file or other similar text-based spatial reference file. First, it looks up the PRJ text in the included epsg.db SQLite database, which was manually sourced and cleaned from an ESRI website, https://developers.arcgis.com/javascript/jshelp/pcs.html If it cannot be found there, it next tries the prj2epsg.org API. If an exact match is found, that EPSG code is returned and saved to the database to avoid future external API calls. TODO: If that API cannot find an exact match but several partial matches, those partials will be displayed to the user with the option to select one to save to the database.
[ "Attempts", "to", "determine", "the", "EPSG", "code", "for", "a", "given", "PRJ", "file", "or", "other", "similar", "text", "-", "based", "spatial", "reference", "file", "." ]
77248bd1e474f014ac8951dacd196fd3417c452c
https://github.com/cmollet/sridentify/blob/77248bd1e474f014ac8951dacd196fd3417c452c/sridentify/__init__.py#L92-L118
27,914
cmollet/sridentify
sridentify/__init__.py
Sridentify.from_epsg
def from_epsg(self, epsg_code): """ Loads self.prj by epsg_code. If prjtext not found returns False. """ self.epsg_code = epsg_code assert isinstance(self.epsg_code, int) cur = self.conn.cursor() cur.execute("SELECT prjtext FROM prj_epsg WHERE epsg_code = ?", (self.epsg_code,)) result = cur.fetchone() if result is not None: self.prj = result[0] return True return False
python
def from_epsg(self, epsg_code): self.epsg_code = epsg_code assert isinstance(self.epsg_code, int) cur = self.conn.cursor() cur.execute("SELECT prjtext FROM prj_epsg WHERE epsg_code = ?", (self.epsg_code,)) result = cur.fetchone() if result is not None: self.prj = result[0] return True return False
[ "def", "from_epsg", "(", "self", ",", "epsg_code", ")", ":", "self", ".", "epsg_code", "=", "epsg_code", "assert", "isinstance", "(", "self", ".", "epsg_code", ",", "int", ")", "cur", "=", "self", ".", "conn", ".", "cursor", "(", ")", "cur", ".", "ex...
Loads self.prj by epsg_code. If prjtext not found returns False.
[ "Loads", "self", ".", "prj", "by", "epsg_code", ".", "If", "prjtext", "not", "found", "returns", "False", "." ]
77248bd1e474f014ac8951dacd196fd3417c452c
https://github.com/cmollet/sridentify/blob/77248bd1e474f014ac8951dacd196fd3417c452c/sridentify/__init__.py#L172-L186
27,915
cmollet/sridentify
sridentify/__init__.py
Sridentify.to_prj
def to_prj(self, filename): """ Saves prj WKT to given file. """ with open(filename, "w") as fp: fp.write(self.prj)
python
def to_prj(self, filename): with open(filename, "w") as fp: fp.write(self.prj)
[ "def", "to_prj", "(", "self", ",", "filename", ")", ":", "with", "open", "(", "filename", ",", "\"w\"", ")", "as", "fp", ":", "fp", ".", "write", "(", "self", ".", "prj", ")" ]
Saves prj WKT to given file.
[ "Saves", "prj", "WKT", "to", "given", "file", "." ]
77248bd1e474f014ac8951dacd196fd3417c452c
https://github.com/cmollet/sridentify/blob/77248bd1e474f014ac8951dacd196fd3417c452c/sridentify/__init__.py#L189-L194
27,916
globality-corp/microcosm-postgres
microcosm_postgres/health.py
get_current_head_version
def get_current_head_version(graph): """ Returns the current head version. """ script_dir = ScriptDirectory("/", version_locations=[graph.metadata.get_path("migrations")]) return script_dir.get_current_head()
python
def get_current_head_version(graph): script_dir = ScriptDirectory("/", version_locations=[graph.metadata.get_path("migrations")]) return script_dir.get_current_head()
[ "def", "get_current_head_version", "(", "graph", ")", ":", "script_dir", "=", "ScriptDirectory", "(", "\"/\"", ",", "version_locations", "=", "[", "graph", ".", "metadata", ".", "get_path", "(", "\"migrations\"", ")", "]", ")", "return", "script_dir", ".", "ge...
Returns the current head version.
[ "Returns", "the", "current", "head", "version", "." ]
43dd793b1fc9b84e4056700f350e79e0df5ff501
https://github.com/globality-corp/microcosm-postgres/blob/43dd793b1fc9b84e4056700f350e79e0df5ff501/microcosm_postgres/health.py#L30-L36
27,917
globality-corp/microcosm-postgres
microcosm_postgres/temporary/factories.py
create_temporary_table
def create_temporary_table(from_table, name=None, on_commit=None): """ Create a new temporary table from another table. """ from_table = from_table.__table__ if hasattr(from_table, "__table__") else from_table name = name or f"temporary_{from_table.name}" # copy the origin table into the metadata with the new name. temporary_table = copy_table(from_table, name) # change create clause to: CREATE TEMPORARY TABLE temporary_table._prefixes = list(from_table._prefixes) temporary_table._prefixes.append("TEMPORARY") # change post create clause to: ON COMMIT DROP if on_commit: temporary_table.dialect_options["postgresql"].update( on_commit=on_commit, ) temporary_table.insert_many = MethodType(insert_many, temporary_table) temporary_table.select_from = MethodType(select_from, temporary_table) temporary_table.upsert_into = MethodType(upsert_into, temporary_table) return temporary_table
python
def create_temporary_table(from_table, name=None, on_commit=None): from_table = from_table.__table__ if hasattr(from_table, "__table__") else from_table name = name or f"temporary_{from_table.name}" # copy the origin table into the metadata with the new name. temporary_table = copy_table(from_table, name) # change create clause to: CREATE TEMPORARY TABLE temporary_table._prefixes = list(from_table._prefixes) temporary_table._prefixes.append("TEMPORARY") # change post create clause to: ON COMMIT DROP if on_commit: temporary_table.dialect_options["postgresql"].update( on_commit=on_commit, ) temporary_table.insert_many = MethodType(insert_many, temporary_table) temporary_table.select_from = MethodType(select_from, temporary_table) temporary_table.upsert_into = MethodType(upsert_into, temporary_table) return temporary_table
[ "def", "create_temporary_table", "(", "from_table", ",", "name", "=", "None", ",", "on_commit", "=", "None", ")", ":", "from_table", "=", "from_table", ".", "__table__", "if", "hasattr", "(", "from_table", ",", "\"__table__\"", ")", "else", "from_table", "name...
Create a new temporary table from another table.
[ "Create", "a", "new", "temporary", "table", "from", "another", "table", "." ]
43dd793b1fc9b84e4056700f350e79e0df5ff501
https://github.com/globality-corp/microcosm-postgres/blob/43dd793b1fc9b84e4056700f350e79e0df5ff501/microcosm_postgres/temporary/factories.py#L11-L37
27,918
globality-corp/microcosm-postgres
microcosm_postgres/operations.py
get_current_head
def get_current_head(graph): """ Get the current database head revision, if any. """ session = new_session(graph) try: result = session.execute("SELECT version_num FROM alembic_version") except ProgrammingError: return None else: return result.scalar() finally: session.close()
python
def get_current_head(graph): session = new_session(graph) try: result = session.execute("SELECT version_num FROM alembic_version") except ProgrammingError: return None else: return result.scalar() finally: session.close()
[ "def", "get_current_head", "(", "graph", ")", ":", "session", "=", "new_session", "(", "graph", ")", "try", ":", "result", "=", "session", ".", "execute", "(", "\"SELECT version_num FROM alembic_version\"", ")", "except", "ProgrammingError", ":", "return", "None",...
Get the current database head revision, if any.
[ "Get", "the", "current", "database", "head", "revision", "if", "any", "." ]
43dd793b1fc9b84e4056700f350e79e0df5ff501
https://github.com/globality-corp/microcosm-postgres/blob/43dd793b1fc9b84e4056700f350e79e0df5ff501/microcosm_postgres/operations.py#L19-L32
27,919
globality-corp/microcosm-postgres
microcosm_postgres/store.py
Store.flushing
def flushing(self): """ Flush the current session, handling common errors. """ try: yield self.session.flush() except (FlushError, IntegrityError) as error: error_message = str(error) # There ought to be a cleaner way to capture this condition if "duplicate" in error_message: raise DuplicateModelError(error) if "already exists" in error_message: raise DuplicateModelError(error) if "conflicts with" in error_message and "identity key" in error_message: raise DuplicateModelError(error) elif "still referenced" in error_message: raise ReferencedModelError(error) elif "is not present" in error_message: raise MissingDependencyError(error) else: raise ModelIntegrityError(error)
python
def flushing(self): try: yield self.session.flush() except (FlushError, IntegrityError) as error: error_message = str(error) # There ought to be a cleaner way to capture this condition if "duplicate" in error_message: raise DuplicateModelError(error) if "already exists" in error_message: raise DuplicateModelError(error) if "conflicts with" in error_message and "identity key" in error_message: raise DuplicateModelError(error) elif "still referenced" in error_message: raise ReferencedModelError(error) elif "is not present" in error_message: raise MissingDependencyError(error) else: raise ModelIntegrityError(error)
[ "def", "flushing", "(", "self", ")", ":", "try", ":", "yield", "self", ".", "session", ".", "flush", "(", ")", "except", "(", "FlushError", ",", "IntegrityError", ")", "as", "error", ":", "error_message", "=", "str", "(", "error", ")", "# There ought to ...
Flush the current session, handling common errors.
[ "Flush", "the", "current", "session", "handling", "common", "errors", "." ]
43dd793b1fc9b84e4056700f350e79e0df5ff501
https://github.com/globality-corp/microcosm-postgres/blob/43dd793b1fc9b84e4056700f350e79e0df5ff501/microcosm_postgres/store.py#L64-L86
27,920
globality-corp/microcosm-postgres
microcosm_postgres/store.py
Store.create
def create(self, instance): """ Create a new model instance. """ with self.flushing(): if instance.id is None: instance.id = self.new_object_id() self.session.add(instance) return instance
python
def create(self, instance): with self.flushing(): if instance.id is None: instance.id = self.new_object_id() self.session.add(instance) return instance
[ "def", "create", "(", "self", ",", "instance", ")", ":", "with", "self", ".", "flushing", "(", ")", ":", "if", "instance", ".", "id", "is", "None", ":", "instance", ".", "id", "=", "self", ".", "new_object_id", "(", ")", "self", ".", "session", "."...
Create a new model instance.
[ "Create", "a", "new", "model", "instance", "." ]
43dd793b1fc9b84e4056700f350e79e0df5ff501
https://github.com/globality-corp/microcosm-postgres/blob/43dd793b1fc9b84e4056700f350e79e0df5ff501/microcosm_postgres/store.py#L88-L97
27,921
globality-corp/microcosm-postgres
microcosm_postgres/store.py
Store.retrieve
def retrieve(self, identifier, *criterion): """ Retrieve a model by primary key and zero or more other criteria. :raises `NotFound` if there is no existing model """ return self._retrieve( self.model_class.id == identifier, *criterion )
python
def retrieve(self, identifier, *criterion): return self._retrieve( self.model_class.id == identifier, *criterion )
[ "def", "retrieve", "(", "self", ",", "identifier", ",", "*", "criterion", ")", ":", "return", "self", ".", "_retrieve", "(", "self", ".", "model_class", ".", "id", "==", "identifier", ",", "*", "criterion", ")" ]
Retrieve a model by primary key and zero or more other criteria. :raises `NotFound` if there is no existing model
[ "Retrieve", "a", "model", "by", "primary", "key", "and", "zero", "or", "more", "other", "criteria", "." ]
43dd793b1fc9b84e4056700f350e79e0df5ff501
https://github.com/globality-corp/microcosm-postgres/blob/43dd793b1fc9b84e4056700f350e79e0df5ff501/microcosm_postgres/store.py#L99-L109
27,922
globality-corp/microcosm-postgres
microcosm_postgres/store.py
Store.count
def count(self, *criterion, **kwargs): """ Count the number of models matching some criterion. """ query = self._query(*criterion) query = self._filter(query, **kwargs) return query.count()
python
def count(self, *criterion, **kwargs): query = self._query(*criterion) query = self._filter(query, **kwargs) return query.count()
[ "def", "count", "(", "self", ",", "*", "criterion", ",", "*", "*", "kwargs", ")", ":", "query", "=", "self", ".", "_query", "(", "*", "criterion", ")", "query", "=", "self", ".", "_filter", "(", "query", ",", "*", "*", "kwargs", ")", "return", "q...
Count the number of models matching some criterion.
[ "Count", "the", "number", "of", "models", "matching", "some", "criterion", "." ]
43dd793b1fc9b84e4056700f350e79e0df5ff501
https://github.com/globality-corp/microcosm-postgres/blob/43dd793b1fc9b84e4056700f350e79e0df5ff501/microcosm_postgres/store.py#L160-L167
27,923
globality-corp/microcosm-postgres
microcosm_postgres/store.py
Store.search
def search(self, *criterion, **kwargs): """ Return the list of models matching some criterion. :param offset: pagination offset, if any :param limit: pagination limit, if any """ query = self._query(*criterion) query = self._order_by(query, **kwargs) query = self._filter(query, **kwargs) # NB: pagination must go last query = self._paginate(query, **kwargs) return query.all()
python
def search(self, *criterion, **kwargs): query = self._query(*criterion) query = self._order_by(query, **kwargs) query = self._filter(query, **kwargs) # NB: pagination must go last query = self._paginate(query, **kwargs) return query.all()
[ "def", "search", "(", "self", ",", "*", "criterion", ",", "*", "*", "kwargs", ")", ":", "query", "=", "self", ".", "_query", "(", "*", "criterion", ")", "query", "=", "self", ".", "_order_by", "(", "query", ",", "*", "*", "kwargs", ")", "query", ...
Return the list of models matching some criterion. :param offset: pagination offset, if any :param limit: pagination limit, if any
[ "Return", "the", "list", "of", "models", "matching", "some", "criterion", "." ]
43dd793b1fc9b84e4056700f350e79e0df5ff501
https://github.com/globality-corp/microcosm-postgres/blob/43dd793b1fc9b84e4056700f350e79e0df5ff501/microcosm_postgres/store.py#L169-L182
27,924
globality-corp/microcosm-postgres
microcosm_postgres/store.py
Store.search_first
def search_first(self, *criterion, **kwargs): """ Returns the first match based on criteria or None. """ query = self._query(*criterion) query = self._order_by(query, **kwargs) query = self._filter(query, **kwargs) # NB: pagination must go last query = self._paginate(query, **kwargs) return query.first()
python
def search_first(self, *criterion, **kwargs): query = self._query(*criterion) query = self._order_by(query, **kwargs) query = self._filter(query, **kwargs) # NB: pagination must go last query = self._paginate(query, **kwargs) return query.first()
[ "def", "search_first", "(", "self", ",", "*", "criterion", ",", "*", "*", "kwargs", ")", ":", "query", "=", "self", ".", "_query", "(", "*", "criterion", ")", "query", "=", "self", ".", "_order_by", "(", "query", ",", "*", "*", "kwargs", ")", "quer...
Returns the first match based on criteria or None.
[ "Returns", "the", "first", "match", "based", "on", "criteria", "or", "None", "." ]
43dd793b1fc9b84e4056700f350e79e0df5ff501
https://github.com/globality-corp/microcosm-postgres/blob/43dd793b1fc9b84e4056700f350e79e0df5ff501/microcosm_postgres/store.py#L184-L194
27,925
globality-corp/microcosm-postgres
microcosm_postgres/store.py
Store._filter
def _filter(self, query, **kwargs): """ Filter a query with user-supplied arguments. """ query = self._auto_filter(query, **kwargs) return query
python
def _filter(self, query, **kwargs): query = self._auto_filter(query, **kwargs) return query
[ "def", "_filter", "(", "self", ",", "query", ",", "*", "*", "kwargs", ")", ":", "query", "=", "self", ".", "_auto_filter", "(", "query", ",", "*", "*", "kwargs", ")", "return", "query" ]
Filter a query with user-supplied arguments.
[ "Filter", "a", "query", "with", "user", "-", "supplied", "arguments", "." ]
43dd793b1fc9b84e4056700f350e79e0df5ff501
https://github.com/globality-corp/microcosm-postgres/blob/43dd793b1fc9b84e4056700f350e79e0df5ff501/microcosm_postgres/store.py#L211-L217
27,926
globality-corp/microcosm-postgres
microcosm_postgres/store.py
Store._retrieve
def _retrieve(self, *criterion): """ Retrieve a model by some criteria. :raises `ModelNotFoundError` if the row cannot be deleted. """ try: return self._query(*criterion).one() except NoResultFound as error: raise ModelNotFoundError( "{} not found".format( self.model_class.__name__, ), error, )
python
def _retrieve(self, *criterion): try: return self._query(*criterion).one() except NoResultFound as error: raise ModelNotFoundError( "{} not found".format( self.model_class.__name__, ), error, )
[ "def", "_retrieve", "(", "self", ",", "*", "criterion", ")", ":", "try", ":", "return", "self", ".", "_query", "(", "*", "criterion", ")", ".", "one", "(", ")", "except", "NoResultFound", "as", "error", ":", "raise", "ModelNotFoundError", "(", "\"{} not ...
Retrieve a model by some criteria. :raises `ModelNotFoundError` if the row cannot be deleted.
[ "Retrieve", "a", "model", "by", "some", "criteria", "." ]
43dd793b1fc9b84e4056700f350e79e0df5ff501
https://github.com/globality-corp/microcosm-postgres/blob/43dd793b1fc9b84e4056700f350e79e0df5ff501/microcosm_postgres/store.py#L239-L254
27,927
globality-corp/microcosm-postgres
microcosm_postgres/store.py
Store._delete
def _delete(self, *criterion): """ Delete a model by some criterion. Avoids race-condition check-then-delete logic by checking the count of affected rows. :raises `ResourceNotFound` if the row cannot be deleted. """ with self.flushing(): count = self._query(*criterion).delete() if count == 0: raise ModelNotFoundError return True
python
def _delete(self, *criterion): with self.flushing(): count = self._query(*criterion).delete() if count == 0: raise ModelNotFoundError return True
[ "def", "_delete", "(", "self", ",", "*", "criterion", ")", ":", "with", "self", ".", "flushing", "(", ")", ":", "count", "=", "self", ".", "_query", "(", "*", "criterion", ")", ".", "delete", "(", ")", "if", "count", "==", "0", ":", "raise", "Mod...
Delete a model by some criterion. Avoids race-condition check-then-delete logic by checking the count of affected rows. :raises `ResourceNotFound` if the row cannot be deleted.
[ "Delete", "a", "model", "by", "some", "criterion", "." ]
43dd793b1fc9b84e4056700f350e79e0df5ff501
https://github.com/globality-corp/microcosm-postgres/blob/43dd793b1fc9b84e4056700f350e79e0df5ff501/microcosm_postgres/store.py#L256-L269
27,928
globality-corp/microcosm-postgres
microcosm_postgres/store.py
Store._query
def _query(self, *criterion): """ Construct a query for the model. """ return self.session.query( self.model_class ).filter( *criterion )
python
def _query(self, *criterion): return self.session.query( self.model_class ).filter( *criterion )
[ "def", "_query", "(", "self", ",", "*", "criterion", ")", ":", "return", "self", ".", "session", ".", "query", "(", "self", ".", "model_class", ")", ".", "filter", "(", "*", "criterion", ")" ]
Construct a query for the model.
[ "Construct", "a", "query", "for", "the", "model", "." ]
43dd793b1fc9b84e4056700f350e79e0df5ff501
https://github.com/globality-corp/microcosm-postgres/blob/43dd793b1fc9b84e4056700f350e79e0df5ff501/microcosm_postgres/store.py#L271-L280
27,929
globality-corp/microcosm-postgres
microcosm_postgres/context.py
maybe_transactional
def maybe_transactional(func): """ Variant of `transactional` that will not commit if there's an argument `commit` with a falsey value. Useful for dry-run style operations. """ @wraps(func) def wrapper(*args, **kwargs): commit = kwargs.get("commit", True) with transaction(commit=commit): return func(*args, **kwargs) return wrapper
python
def maybe_transactional(func): @wraps(func) def wrapper(*args, **kwargs): commit = kwargs.get("commit", True) with transaction(commit=commit): return func(*args, **kwargs) return wrapper
[ "def", "maybe_transactional", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "commit", "=", "kwargs", ".", "get", "(", "\"commit\"", ",", "True", ")", "with", "transaction...
Variant of `transactional` that will not commit if there's an argument `commit` with a falsey value. Useful for dry-run style operations.
[ "Variant", "of", "transactional", "that", "will", "not", "commit", "if", "there", "s", "an", "argument", "commit", "with", "a", "falsey", "value", "." ]
43dd793b1fc9b84e4056700f350e79e0df5ff501
https://github.com/globality-corp/microcosm-postgres/blob/43dd793b1fc9b84e4056700f350e79e0df5ff501/microcosm_postgres/context.py#L83-L95
27,930
globality-corp/microcosm-postgres
microcosm_postgres/migrate.py
make_alembic_config
def make_alembic_config(temporary_dir, migrations_dir): """ Alembic uses the `alembic.ini` file to configure where it looks for everything else. Not only is this file an unnecessary complication around a single-valued configuration, the single-value it chooses to use (the alembic configuration directory), hard-coding the decision that there will be such a directory makes Alembic setup overly verbose. Instead, generate a `Config` object with the values we care about. :returns: a usable instance of `Alembic.config.Config` """ config = Config() config.set_main_option("temporary_dir", temporary_dir) config.set_main_option("migrations_dir", migrations_dir) return config
python
def make_alembic_config(temporary_dir, migrations_dir): config = Config() config.set_main_option("temporary_dir", temporary_dir) config.set_main_option("migrations_dir", migrations_dir) return config
[ "def", "make_alembic_config", "(", "temporary_dir", ",", "migrations_dir", ")", ":", "config", "=", "Config", "(", ")", "config", ".", "set_main_option", "(", "\"temporary_dir\"", ",", "temporary_dir", ")", "config", ".", "set_main_option", "(", "\"migrations_dir\""...
Alembic uses the `alembic.ini` file to configure where it looks for everything else. Not only is this file an unnecessary complication around a single-valued configuration, the single-value it chooses to use (the alembic configuration directory), hard-coding the decision that there will be such a directory makes Alembic setup overly verbose. Instead, generate a `Config` object with the values we care about. :returns: a usable instance of `Alembic.config.Config`
[ "Alembic", "uses", "the", "alembic", ".", "ini", "file", "to", "configure", "where", "it", "looks", "for", "everything", "else", "." ]
43dd793b1fc9b84e4056700f350e79e0df5ff501
https://github.com/globality-corp/microcosm-postgres/blob/43dd793b1fc9b84e4056700f350e79e0df5ff501/microcosm_postgres/migrate.py#L51-L67
27,931
globality-corp/microcosm-postgres
microcosm_postgres/migrate.py
make_script_directory
def make_script_directory(cls, config): """ Alembic uses a "script directory" to encapsulate its `env.py` file, its migrations directory, and its `script.py.mako` revision template. We'd rather not have such a directory at all as the default `env.py` rarely works without manipulation, migrations are better saved in a location within the source tree, and revision templates shouldn't vary between projects. Instead, generate a `ScriptDirectory` object, injecting values from the config. """ temporary_dir = config.get_main_option("temporary_dir") migrations_dir = config.get_main_option("migrations_dir") return cls( dir=temporary_dir, version_locations=[migrations_dir], )
python
def make_script_directory(cls, config): temporary_dir = config.get_main_option("temporary_dir") migrations_dir = config.get_main_option("migrations_dir") return cls( dir=temporary_dir, version_locations=[migrations_dir], )
[ "def", "make_script_directory", "(", "cls", ",", "config", ")", ":", "temporary_dir", "=", "config", ".", "get_main_option", "(", "\"temporary_dir\"", ")", "migrations_dir", "=", "config", ".", "get_main_option", "(", "\"migrations_dir\"", ")", "return", "cls", "(...
Alembic uses a "script directory" to encapsulate its `env.py` file, its migrations directory, and its `script.py.mako` revision template. We'd rather not have such a directory at all as the default `env.py` rarely works without manipulation, migrations are better saved in a location within the source tree, and revision templates shouldn't vary between projects. Instead, generate a `ScriptDirectory` object, injecting values from the config.
[ "Alembic", "uses", "a", "script", "directory", "to", "encapsulate", "its", "env", ".", "py", "file", "its", "migrations", "directory", "and", "its", "script", ".", "py", ".", "mako", "revision", "template", "." ]
43dd793b1fc9b84e4056700f350e79e0df5ff501
https://github.com/globality-corp/microcosm-postgres/blob/43dd793b1fc9b84e4056700f350e79e0df5ff501/microcosm_postgres/migrate.py#L70-L88
27,932
globality-corp/microcosm-postgres
microcosm_postgres/migrate.py
run_online_migration
def run_online_migration(self): """ Run an online migration using microcosm configuration. This function takes the place of the `env.py` file in the Alembic migration. """ connectable = self.graph.postgres with connectable.connect() as connection: context.configure( connection=connection, # assumes that all models extend our base target_metadata=Model.metadata, **get_alembic_environment_options(self.graph), ) with context.begin_transaction(): context.run_migrations()
python
def run_online_migration(self): connectable = self.graph.postgres with connectable.connect() as connection: context.configure( connection=connection, # assumes that all models extend our base target_metadata=Model.metadata, **get_alembic_environment_options(self.graph), ) with context.begin_transaction(): context.run_migrations()
[ "def", "run_online_migration", "(", "self", ")", ":", "connectable", "=", "self", ".", "graph", ".", "postgres", "with", "connectable", ".", "connect", "(", ")", "as", "connection", ":", "context", ".", "configure", "(", "connection", "=", "connection", ",",...
Run an online migration using microcosm configuration. This function takes the place of the `env.py` file in the Alembic migration.
[ "Run", "an", "online", "migration", "using", "microcosm", "configuration", "." ]
43dd793b1fc9b84e4056700f350e79e0df5ff501
https://github.com/globality-corp/microcosm-postgres/blob/43dd793b1fc9b84e4056700f350e79e0df5ff501/microcosm_postgres/migrate.py#L98-L116
27,933
globality-corp/microcosm-postgres
microcosm_postgres/migrate.py
patch_script_directory
def patch_script_directory(graph): """ Monkey patch the `ScriptDirectory` class, working around configuration assumptions. Changes include: - Using a generated, temporary directory (with a generated, temporary `script.py.mako`) instead of the assumed script directory. - Using our `make_script_directory` function instead of the default `ScriptDirectory.from_config`. - Using our `run_online_migration` function instead of the default `ScriptDirectory.run_env`. - Injecting the current object graph. """ temporary_dir = mkdtemp() from_config_original = getattr(ScriptDirectory, "from_config") run_env_original = getattr(ScriptDirectory, "run_env") # use a temporary directory for the revision template with open(join(temporary_dir, "script.py.mako"), "w") as file_: file_.write(make_script_py_mako()) file_.flush() # monkey patch our script directory and migration logic setattr(ScriptDirectory, "from_config", classmethod(make_script_directory)) setattr(ScriptDirectory, "run_env", run_online_migration) setattr(ScriptDirectory, "graph", graph) try: yield temporary_dir finally: # cleanup delattr(ScriptDirectory, "graph") setattr(ScriptDirectory, "run_env", run_env_original) setattr(ScriptDirectory, "from_config", from_config_original) rmtree(temporary_dir)
python
def patch_script_directory(graph): temporary_dir = mkdtemp() from_config_original = getattr(ScriptDirectory, "from_config") run_env_original = getattr(ScriptDirectory, "run_env") # use a temporary directory for the revision template with open(join(temporary_dir, "script.py.mako"), "w") as file_: file_.write(make_script_py_mako()) file_.flush() # monkey patch our script directory and migration logic setattr(ScriptDirectory, "from_config", classmethod(make_script_directory)) setattr(ScriptDirectory, "run_env", run_online_migration) setattr(ScriptDirectory, "graph", graph) try: yield temporary_dir finally: # cleanup delattr(ScriptDirectory, "graph") setattr(ScriptDirectory, "run_env", run_env_original) setattr(ScriptDirectory, "from_config", from_config_original) rmtree(temporary_dir)
[ "def", "patch_script_directory", "(", "graph", ")", ":", "temporary_dir", "=", "mkdtemp", "(", ")", "from_config_original", "=", "getattr", "(", "ScriptDirectory", ",", "\"from_config\"", ")", "run_env_original", "=", "getattr", "(", "ScriptDirectory", ",", "\"run_e...
Monkey patch the `ScriptDirectory` class, working around configuration assumptions. Changes include: - Using a generated, temporary directory (with a generated, temporary `script.py.mako`) instead of the assumed script directory. - Using our `make_script_directory` function instead of the default `ScriptDirectory.from_config`. - Using our `run_online_migration` function instead of the default `ScriptDirectory.run_env`. - Injecting the current object graph.
[ "Monkey", "patch", "the", "ScriptDirectory", "class", "working", "around", "configuration", "assumptions", "." ]
43dd793b1fc9b84e4056700f350e79e0df5ff501
https://github.com/globality-corp/microcosm-postgres/blob/43dd793b1fc9b84e4056700f350e79e0df5ff501/microcosm_postgres/migrate.py#L156-L187
27,934
globality-corp/microcosm-postgres
microcosm_postgres/migrate.py
get_migrations_dir
def get_migrations_dir(graph): """ Resolve the migrations directory path. Either take the directory from a component of the object graph or by using the metaata's path resolution facilities. """ try: migrations_dir = graph.migrations_dir except (LockedGraphError, NotBoundError): migrations_dir = graph.metadata.get_path("migrations") if not isdir(migrations_dir): raise Exception("Migrations dir must exist: {}".format(migrations_dir)) return migrations_dir
python
def get_migrations_dir(graph): try: migrations_dir = graph.migrations_dir except (LockedGraphError, NotBoundError): migrations_dir = graph.metadata.get_path("migrations") if not isdir(migrations_dir): raise Exception("Migrations dir must exist: {}".format(migrations_dir)) return migrations_dir
[ "def", "get_migrations_dir", "(", "graph", ")", ":", "try", ":", "migrations_dir", "=", "graph", ".", "migrations_dir", "except", "(", "LockedGraphError", ",", "NotBoundError", ")", ":", "migrations_dir", "=", "graph", ".", "metadata", ".", "get_path", "(", "\...
Resolve the migrations directory path. Either take the directory from a component of the object graph or by using the metaata's path resolution facilities.
[ "Resolve", "the", "migrations", "directory", "path", "." ]
43dd793b1fc9b84e4056700f350e79e0df5ff501
https://github.com/globality-corp/microcosm-postgres/blob/43dd793b1fc9b84e4056700f350e79e0df5ff501/microcosm_postgres/migrate.py#L190-L205
27,935
globality-corp/microcosm-postgres
microcosm_postgres/migrate.py
main
def main(graph, *args): """ Entry point for invoking Alembic's `CommandLine`. Alembic's CLI defines its own argument parsing and command invocation; we want to use these directly but define configuration our own way. This function takes the behavior of `CommandLine.main()` and reinterprets it with our patching. :param graph: an initialized object graph :param migration_dir: the path to the migrations directory """ migrations_dir = get_migrations_dir(graph) cli = CommandLine() options = cli.parser.parse_args(args if args else argv[1:]) if not hasattr(options, "cmd"): cli.parser.error("too few arguments") if options.cmd[0].__name__ == "init": cli.parser.error("Alembic 'init' command should not be used in the microcosm!") with patch_script_directory(graph) as temporary_dir: config = make_alembic_config(temporary_dir, migrations_dir) cli.run_cmd(config, options)
python
def main(graph, *args): migrations_dir = get_migrations_dir(graph) cli = CommandLine() options = cli.parser.parse_args(args if args else argv[1:]) if not hasattr(options, "cmd"): cli.parser.error("too few arguments") if options.cmd[0].__name__ == "init": cli.parser.error("Alembic 'init' command should not be used in the microcosm!") with patch_script_directory(graph) as temporary_dir: config = make_alembic_config(temporary_dir, migrations_dir) cli.run_cmd(config, options)
[ "def", "main", "(", "graph", ",", "*", "args", ")", ":", "migrations_dir", "=", "get_migrations_dir", "(", "graph", ")", "cli", "=", "CommandLine", "(", ")", "options", "=", "cli", ".", "parser", ".", "parse_args", "(", "args", "if", "args", "else", "a...
Entry point for invoking Alembic's `CommandLine`. Alembic's CLI defines its own argument parsing and command invocation; we want to use these directly but define configuration our own way. This function takes the behavior of `CommandLine.main()` and reinterprets it with our patching. :param graph: an initialized object graph :param migration_dir: the path to the migrations directory
[ "Entry", "point", "for", "invoking", "Alembic", "s", "CommandLine", "." ]
43dd793b1fc9b84e4056700f350e79e0df5ff501
https://github.com/globality-corp/microcosm-postgres/blob/43dd793b1fc9b84e4056700f350e79e0df5ff501/microcosm_postgres/migrate.py#L208-L231
27,936
globality-corp/microcosm-postgres
microcosm_postgres/factories/sessionmaker.py
configure_sessionmaker
def configure_sessionmaker(graph): """ Create the SQLAlchemy session class. """ engine_routing_strategy = getattr(graph, graph.config.sessionmaker.engine_routing_strategy) if engine_routing_strategy.supports_multiple_binds: ScopedFactory.infect(graph, "postgres") class RoutingSession(Session): """ Route session bind to an appropriate engine. See: http://docs.sqlalchemy.org/en/latest/orm/persistence_techniques.html#partitioning-strategies """ def get_bind(self, mapper=None, clause=None): return engine_routing_strategy.get_bind(mapper, clause) return sessionmaker(class_=RoutingSession)
python
def configure_sessionmaker(graph): engine_routing_strategy = getattr(graph, graph.config.sessionmaker.engine_routing_strategy) if engine_routing_strategy.supports_multiple_binds: ScopedFactory.infect(graph, "postgres") class RoutingSession(Session): """ Route session bind to an appropriate engine. See: http://docs.sqlalchemy.org/en/latest/orm/persistence_techniques.html#partitioning-strategies """ def get_bind(self, mapper=None, clause=None): return engine_routing_strategy.get_bind(mapper, clause) return sessionmaker(class_=RoutingSession)
[ "def", "configure_sessionmaker", "(", "graph", ")", ":", "engine_routing_strategy", "=", "getattr", "(", "graph", ",", "graph", ".", "config", ".", "sessionmaker", ".", "engine_routing_strategy", ")", "if", "engine_routing_strategy", ".", "supports_multiple_binds", ":...
Create the SQLAlchemy session class.
[ "Create", "the", "SQLAlchemy", "session", "class", "." ]
43dd793b1fc9b84e4056700f350e79e0df5ff501
https://github.com/globality-corp/microcosm-postgres/blob/43dd793b1fc9b84e4056700f350e79e0df5ff501/microcosm_postgres/factories/sessionmaker.py#L9-L29
27,937
globality-corp/microcosm-postgres
microcosm_postgres/cloning.py
clone
def clone(instance, substitutions, ignore=()): """ Clone an instance of `Model` that uses `IdentityMixin`. :param instance: the instance to clonse :param substitutions: a dictionary of substitutions :param ignore: a tuple of column names to ignore """ substitutions[instance.id] = new_object_id() def substitute(value): try: hash(value) except Exception: return value else: return substitutions.get(value, value) return instance.__class__(**{ key: substitute(value) for key, value in iter_items(instance, ignore) }).create()
python
def clone(instance, substitutions, ignore=()): substitutions[instance.id] = new_object_id() def substitute(value): try: hash(value) except Exception: return value else: return substitutions.get(value, value) return instance.__class__(**{ key: substitute(value) for key, value in iter_items(instance, ignore) }).create()
[ "def", "clone", "(", "instance", ",", "substitutions", ",", "ignore", "=", "(", ")", ")", ":", "substitutions", "[", "instance", ".", "id", "]", "=", "new_object_id", "(", ")", "def", "substitute", "(", "value", ")", ":", "try", ":", "hash", "(", "va...
Clone an instance of `Model` that uses `IdentityMixin`. :param instance: the instance to clonse :param substitutions: a dictionary of substitutions :param ignore: a tuple of column names to ignore
[ "Clone", "an", "instance", "of", "Model", "that", "uses", "IdentityMixin", "." ]
43dd793b1fc9b84e4056700f350e79e0df5ff501
https://github.com/globality-corp/microcosm-postgres/blob/43dd793b1fc9b84e4056700f350e79e0df5ff501/microcosm_postgres/cloning.py#L10-L32
27,938
globality-corp/microcosm-postgres
microcosm_postgres/encryption/factories.py
configure_encryptor
def configure_encryptor(graph): """ Create a MultiTenantEncryptor from configured keys. """ encryptor = graph.multi_tenant_key_registry.make_encryptor(graph) # register the encryptor will each encryptable type for encryptable in EncryptableMixin.__subclasses__(): encryptable.register(encryptor) return encryptor
python
def configure_encryptor(graph): encryptor = graph.multi_tenant_key_registry.make_encryptor(graph) # register the encryptor will each encryptable type for encryptable in EncryptableMixin.__subclasses__(): encryptable.register(encryptor) return encryptor
[ "def", "configure_encryptor", "(", "graph", ")", ":", "encryptor", "=", "graph", ".", "multi_tenant_key_registry", ".", "make_encryptor", "(", "graph", ")", "# register the encryptor will each encryptable type", "for", "encryptable", "in", "EncryptableMixin", ".", "__subc...
Create a MultiTenantEncryptor from configured keys.
[ "Create", "a", "MultiTenantEncryptor", "from", "configured", "keys", "." ]
43dd793b1fc9b84e4056700f350e79e0df5ff501
https://github.com/globality-corp/microcosm-postgres/blob/43dd793b1fc9b84e4056700f350e79e0df5ff501/microcosm_postgres/encryption/factories.py#L4-L15
27,939
globality-corp/microcosm-postgres
microcosm_postgres/toposort.py
toposorted
def toposorted(nodes, edges): """ Perform a topological sort on the input resources. The topological sort uses Kahn's algorithm, which is a stable sort and will preserve this ordering; note that a DFS will produce a worst case ordering from the perspective of batching. """ incoming = defaultdict(set) outgoing = defaultdict(set) for edge in edges: incoming[edge.to_id].add(edge.from_id) outgoing[edge.from_id].add(edge.to_id) working_set = list(nodes.values()) results = [] while working_set: remaining = [] for node in working_set: if incoming[node.id]: # node still has incoming edges remaining.append(node) continue results.append(node) for child in outgoing[node.id]: incoming[child].remove(node.id) if len(working_set) == len(remaining): raise Exception("Cycle detected") working_set = remaining return results
python
def toposorted(nodes, edges): incoming = defaultdict(set) outgoing = defaultdict(set) for edge in edges: incoming[edge.to_id].add(edge.from_id) outgoing[edge.from_id].add(edge.to_id) working_set = list(nodes.values()) results = [] while working_set: remaining = [] for node in working_set: if incoming[node.id]: # node still has incoming edges remaining.append(node) continue results.append(node) for child in outgoing[node.id]: incoming[child].remove(node.id) if len(working_set) == len(remaining): raise Exception("Cycle detected") working_set = remaining return results
[ "def", "toposorted", "(", "nodes", ",", "edges", ")", ":", "incoming", "=", "defaultdict", "(", "set", ")", "outgoing", "=", "defaultdict", "(", "set", ")", "for", "edge", "in", "edges", ":", "incoming", "[", "edge", ".", "to_id", "]", ".", "add", "(...
Perform a topological sort on the input resources. The topological sort uses Kahn's algorithm, which is a stable sort and will preserve this ordering; note that a DFS will produce a worst case ordering from the perspective of batching.
[ "Perform", "a", "topological", "sort", "on", "the", "input", "resources", "." ]
43dd793b1fc9b84e4056700f350e79e0df5ff501
https://github.com/globality-corp/microcosm-postgres/blob/43dd793b1fc9b84e4056700f350e79e0df5ff501/microcosm_postgres/toposort.py#L8-L40
27,940
globality-corp/microcosm-postgres
microcosm_postgres/temporary/copy.py
should_copy
def should_copy(column): """ Determine if a column should be copied. """ if not isinstance(column.type, Serial): return True if column.nullable: return True if not column.server_default: return True # do not create temporary serial values; they will be defaulted on upsert/insert return False
python
def should_copy(column): if not isinstance(column.type, Serial): return True if column.nullable: return True if not column.server_default: return True # do not create temporary serial values; they will be defaulted on upsert/insert return False
[ "def", "should_copy", "(", "column", ")", ":", "if", "not", "isinstance", "(", "column", ".", "type", ",", "Serial", ")", ":", "return", "True", "if", "column", ".", "nullable", ":", "return", "True", "if", "not", "column", ".", "server_default", ":", ...
Determine if a column should be copied.
[ "Determine", "if", "a", "column", "should", "be", "copied", "." ]
43dd793b1fc9b84e4056700f350e79e0df5ff501
https://github.com/globality-corp/microcosm-postgres/blob/43dd793b1fc9b84e4056700f350e79e0df5ff501/microcosm_postgres/temporary/copy.py#L18-L33
27,941
globality-corp/microcosm-postgres
microcosm_postgres/encryption/encryptor.py
SingleTenantEncryptor.encrypt
def encrypt(self, encryption_context_key: str, plaintext: str) -> Tuple[bytes, Sequence[str]]: """ Encrypt a plaintext string value. The return value will include *both* the resulting binary ciphertext and the master key ids used for encryption. In the likely case that the encryptor was initialized with master key aliases, these master key ids returned will represent the unaliased key. """ encryption_context = dict( microcosm=encryption_context_key, ) cyphertext, header = encrypt( source=plaintext, materials_manager=self.materials_manager, encryption_context=encryption_context, ) key_ids = [ self.unpack_key_id(encrypted_data_key.key_provider) for encrypted_data_key in header.encrypted_data_keys ] return cyphertext, key_ids
python
def encrypt(self, encryption_context_key: str, plaintext: str) -> Tuple[bytes, Sequence[str]]: encryption_context = dict( microcosm=encryption_context_key, ) cyphertext, header = encrypt( source=plaintext, materials_manager=self.materials_manager, encryption_context=encryption_context, ) key_ids = [ self.unpack_key_id(encrypted_data_key.key_provider) for encrypted_data_key in header.encrypted_data_keys ] return cyphertext, key_ids
[ "def", "encrypt", "(", "self", ",", "encryption_context_key", ":", "str", ",", "plaintext", ":", "str", ")", "->", "Tuple", "[", "bytes", ",", "Sequence", "[", "str", "]", "]", ":", "encryption_context", "=", "dict", "(", "microcosm", "=", "encryption_cont...
Encrypt a plaintext string value. The return value will include *both* the resulting binary ciphertext and the master key ids used for encryption. In the likely case that the encryptor was initialized with master key aliases, these master key ids returned will represent the unaliased key.
[ "Encrypt", "a", "plaintext", "string", "value", "." ]
43dd793b1fc9b84e4056700f350e79e0df5ff501
https://github.com/globality-corp/microcosm-postgres/blob/43dd793b1fc9b84e4056700f350e79e0df5ff501/microcosm_postgres/encryption/encryptor.py#L27-L52
27,942
globality-corp/microcosm-postgres
microcosm_postgres/encryption/models.py
on_init
def on_init(target: "EncryptableMixin", args, kwargs): """ Intercept SQLAlchemy's instance init event. SQLALchemy allows callback to intercept ORM instance init functions. The calling arguments will be an empty instance of the `target` model, plus the arguments passed to `__init__`. The `kwargs` dictionary is mutable (which is why it is not passed as `**kwargs`). We leverage this callback to conditionally remove the `__plaintext__` value and set the `ciphertext` property. """ encryptor = target.__encryptor__ # encryption context may be nullable try: encryption_context_key = str(kwargs[target.__encryption_context_key__]) except KeyError: return # do not encrypt targets that are not configured for it if encryption_context_key not in encryptor: return plaintext = target.plaintext_to_str(kwargs.pop(target.__plaintext__)) # do not try to encrypt when plaintext is None if plaintext is None: return ciphertext, key_ids = encryptor.encrypt(encryption_context_key, plaintext) target.ciphertext = (ciphertext, key_ids)
python
def on_init(target: "EncryptableMixin", args, kwargs): encryptor = target.__encryptor__ # encryption context may be nullable try: encryption_context_key = str(kwargs[target.__encryption_context_key__]) except KeyError: return # do not encrypt targets that are not configured for it if encryption_context_key not in encryptor: return plaintext = target.plaintext_to_str(kwargs.pop(target.__plaintext__)) # do not try to encrypt when plaintext is None if plaintext is None: return ciphertext, key_ids = encryptor.encrypt(encryption_context_key, plaintext) target.ciphertext = (ciphertext, key_ids)
[ "def", "on_init", "(", "target", ":", "\"EncryptableMixin\"", ",", "args", ",", "kwargs", ")", ":", "encryptor", "=", "target", ".", "__encryptor__", "# encryption context may be nullable", "try", ":", "encryption_context_key", "=", "str", "(", "kwargs", "[", "tar...
Intercept SQLAlchemy's instance init event. SQLALchemy allows callback to intercept ORM instance init functions. The calling arguments will be an empty instance of the `target` model, plus the arguments passed to `__init__`. The `kwargs` dictionary is mutable (which is why it is not passed as `**kwargs`). We leverage this callback to conditionally remove the `__plaintext__` value and set the `ciphertext` property.
[ "Intercept", "SQLAlchemy", "s", "instance", "init", "event", "." ]
43dd793b1fc9b84e4056700f350e79e0df5ff501
https://github.com/globality-corp/microcosm-postgres/blob/43dd793b1fc9b84e4056700f350e79e0df5ff501/microcosm_postgres/encryption/models.py#L14-L44
27,943
globality-corp/microcosm-postgres
microcosm_postgres/encryption/models.py
on_load
def on_load(target: "EncryptableMixin", context): """ Intercept SQLAlchemy's instance load event. """ decrypt, plaintext = decrypt_instance(target) if decrypt: target.plaintext = plaintext
python
def on_load(target: "EncryptableMixin", context): decrypt, plaintext = decrypt_instance(target) if decrypt: target.plaintext = plaintext
[ "def", "on_load", "(", "target", ":", "\"EncryptableMixin\"", ",", "context", ")", ":", "decrypt", ",", "plaintext", "=", "decrypt_instance", "(", "target", ")", "if", "decrypt", ":", "target", ".", "plaintext", "=", "plaintext" ]
Intercept SQLAlchemy's instance load event.
[ "Intercept", "SQLAlchemy", "s", "instance", "load", "event", "." ]
43dd793b1fc9b84e4056700f350e79e0df5ff501
https://github.com/globality-corp/microcosm-postgres/blob/43dd793b1fc9b84e4056700f350e79e0df5ff501/microcosm_postgres/encryption/models.py#L47-L54
27,944
globality-corp/microcosm-postgres
microcosm_postgres/encryption/models.py
EncryptableMixin.register
def register(cls, encryptor: Encryptor): """ Register this encryptable with an encryptor. Instances of this encryptor will be encrypted on initialization and decrypted on load. """ # save the current encryptor statically cls.__encryptor__ = encryptor # NB: we cannot use the before_insert listener in conjunction with a foreign key relationship # for encrypted data; SQLAlchemy will warn about using 'related attribute set' operation so # late in its insert/flush process. listeners = dict( init=on_init, load=on_load, ) for name, func in listeners.items(): # If we initialize the graph multiple times (as in many unit testing scenarios), # we will accumulate listener functions -- with unpredictable results. As protection, # we need to remove existing listeners before adding new ones; this solution only # works if the id (e.g. memory address) of the listener does not change, which means # they cannot be closures around the `encryptor` reference. # # Hence the `__encryptor__` hack above... if contains(cls, name, func): remove(cls, name, func) listen(cls, name, func)
python
def register(cls, encryptor: Encryptor): # save the current encryptor statically cls.__encryptor__ = encryptor # NB: we cannot use the before_insert listener in conjunction with a foreign key relationship # for encrypted data; SQLAlchemy will warn about using 'related attribute set' operation so # late in its insert/flush process. listeners = dict( init=on_init, load=on_load, ) for name, func in listeners.items(): # If we initialize the graph multiple times (as in many unit testing scenarios), # we will accumulate listener functions -- with unpredictable results. As protection, # we need to remove existing listeners before adding new ones; this solution only # works if the id (e.g. memory address) of the listener does not change, which means # they cannot be closures around the `encryptor` reference. # # Hence the `__encryptor__` hack above... if contains(cls, name, func): remove(cls, name, func) listen(cls, name, func)
[ "def", "register", "(", "cls", ",", "encryptor", ":", "Encryptor", ")", ":", "# save the current encryptor statically", "cls", ".", "__encryptor__", "=", "encryptor", "# NB: we cannot use the before_insert listener in conjunction with a foreign key relationship", "# for encrypted d...
Register this encryptable with an encryptor. Instances of this encryptor will be encrypted on initialization and decrypted on load.
[ "Register", "this", "encryptable", "with", "an", "encryptor", "." ]
43dd793b1fc9b84e4056700f350e79e0df5ff501
https://github.com/globality-corp/microcosm-postgres/blob/43dd793b1fc9b84e4056700f350e79e0df5ff501/microcosm_postgres/encryption/models.py#L138-L166
27,945
globality-corp/microcosm-postgres
microcosm_postgres/dag.py
DAG.nodes_map
def nodes_map(self): """ Build a mapping from node type to a list of nodes. A typed mapping helps avoid polymorphism at non-persistent layers. """ dct = dict() for node in self.nodes.values(): cls = next(base for base in getmro(node.__class__) if "__tablename__" in base.__dict__) key = getattr(cls, "__alias__", underscore(cls.__name__)) dct.setdefault(key, []).append(node) return dct
python
def nodes_map(self): dct = dict() for node in self.nodes.values(): cls = next(base for base in getmro(node.__class__) if "__tablename__" in base.__dict__) key = getattr(cls, "__alias__", underscore(cls.__name__)) dct.setdefault(key, []).append(node) return dct
[ "def", "nodes_map", "(", "self", ")", ":", "dct", "=", "dict", "(", ")", "for", "node", "in", "self", ".", "nodes", ".", "values", "(", ")", ":", "cls", "=", "next", "(", "base", "for", "base", "in", "getmro", "(", "node", ".", "__class__", ")", ...
Build a mapping from node type to a list of nodes. A typed mapping helps avoid polymorphism at non-persistent layers.
[ "Build", "a", "mapping", "from", "node", "type", "to", "a", "list", "of", "nodes", "." ]
43dd793b1fc9b84e4056700f350e79e0df5ff501
https://github.com/globality-corp/microcosm-postgres/blob/43dd793b1fc9b84e4056700f350e79e0df5ff501/microcosm_postgres/dag.py#L46-L58
27,946
globality-corp/microcosm-postgres
microcosm_postgres/dag.py
DAG.build_edges
def build_edges(self): """ Build edges based on node `edges` property. Filters out any `Edge` not defined in the DAG. """ self.edges = [ edge if isinstance(edge, Edge) else Edge(*edge) for node in self.nodes.values() for edge in getattr(node, "edges", []) if edge[0] in self.nodes and edge[1] in self.nodes ] return self
python
def build_edges(self): self.edges = [ edge if isinstance(edge, Edge) else Edge(*edge) for node in self.nodes.values() for edge in getattr(node, "edges", []) if edge[0] in self.nodes and edge[1] in self.nodes ] return self
[ "def", "build_edges", "(", "self", ")", ":", "self", ".", "edges", "=", "[", "edge", "if", "isinstance", "(", "edge", ",", "Edge", ")", "else", "Edge", "(", "*", "edge", ")", "for", "node", "in", "self", ".", "nodes", ".", "values", "(", ")", "fo...
Build edges based on node `edges` property. Filters out any `Edge` not defined in the DAG.
[ "Build", "edges", "based", "on", "node", "edges", "property", "." ]
43dd793b1fc9b84e4056700f350e79e0df5ff501
https://github.com/globality-corp/microcosm-postgres/blob/43dd793b1fc9b84e4056700f350e79e0df5ff501/microcosm_postgres/dag.py#L60-L73
27,947
globality-corp/microcosm-postgres
microcosm_postgres/dag.py
DAG.clone
def clone(self, ignore=()): """ Clone this dag using a set of substitutions. Traverse the dag in topological order. """ nodes = [ clone(node, self.substitutions, ignore) for node in toposorted(self.nodes, self.edges) ] return DAG(nodes=nodes, substitutions=self.substitutions).build_edges()
python
def clone(self, ignore=()): nodes = [ clone(node, self.substitutions, ignore) for node in toposorted(self.nodes, self.edges) ] return DAG(nodes=nodes, substitutions=self.substitutions).build_edges()
[ "def", "clone", "(", "self", ",", "ignore", "=", "(", ")", ")", ":", "nodes", "=", "[", "clone", "(", "node", ",", "self", ".", "substitutions", ",", "ignore", ")", "for", "node", "in", "toposorted", "(", "self", ".", "nodes", ",", "self", ".", "...
Clone this dag using a set of substitutions. Traverse the dag in topological order.
[ "Clone", "this", "dag", "using", "a", "set", "of", "substitutions", "." ]
43dd793b1fc9b84e4056700f350e79e0df5ff501
https://github.com/globality-corp/microcosm-postgres/blob/43dd793b1fc9b84e4056700f350e79e0df5ff501/microcosm_postgres/dag.py#L75-L86
27,948
globality-corp/microcosm-postgres
microcosm_postgres/dag.py
DAGCloner.explain
def explain(self, **kwargs): """ Generate a "dry run" DAG of that state that WILL be cloned. """ root = self.retrieve_root(**kwargs) children = self.iter_children(root, **kwargs) dag = DAG.from_nodes(root, *children) return self.add_edges(dag)
python
def explain(self, **kwargs): root = self.retrieve_root(**kwargs) children = self.iter_children(root, **kwargs) dag = DAG.from_nodes(root, *children) return self.add_edges(dag)
[ "def", "explain", "(", "self", ",", "*", "*", "kwargs", ")", ":", "root", "=", "self", ".", "retrieve_root", "(", "*", "*", "kwargs", ")", "children", "=", "self", ".", "iter_children", "(", "root", ",", "*", "*", "kwargs", ")", "dag", "=", "DAG", ...
Generate a "dry run" DAG of that state that WILL be cloned.
[ "Generate", "a", "dry", "run", "DAG", "of", "that", "state", "that", "WILL", "be", "cloned", "." ]
43dd793b1fc9b84e4056700f350e79e0df5ff501
https://github.com/globality-corp/microcosm-postgres/blob/43dd793b1fc9b84e4056700f350e79e0df5ff501/microcosm_postgres/dag.py#L104-L112
27,949
globality-corp/microcosm-postgres
microcosm_postgres/dag.py
DAGCloner.clone
def clone(self, substitutions, **kwargs): """ Clone a DAG. """ dag = self.explain(**kwargs) dag.substitutions.update(substitutions) cloned_dag = dag.clone(ignore=self.ignore) return self.update_nodes(self.add_edges(cloned_dag))
python
def clone(self, substitutions, **kwargs): dag = self.explain(**kwargs) dag.substitutions.update(substitutions) cloned_dag = dag.clone(ignore=self.ignore) return self.update_nodes(self.add_edges(cloned_dag))
[ "def", "clone", "(", "self", ",", "substitutions", ",", "*", "*", "kwargs", ")", ":", "dag", "=", "self", ".", "explain", "(", "*", "*", "kwargs", ")", "dag", ".", "substitutions", ".", "update", "(", "substitutions", ")", "cloned_dag", "=", "dag", "...
Clone a DAG.
[ "Clone", "a", "DAG", "." ]
43dd793b1fc9b84e4056700f350e79e0df5ff501
https://github.com/globality-corp/microcosm-postgres/blob/43dd793b1fc9b84e4056700f350e79e0df5ff501/microcosm_postgres/dag.py#L114-L122
27,950
globality-corp/microcosm-postgres
microcosm_postgres/factories/engine.py
choose_database_name
def choose_database_name(metadata, config): """ Choose the database name to use. As a default, databases should be named after the service that uses them. In addition, database names should be different between unit testing and runtime so that there is no chance of a unit test dropping a real database by accident. """ if config.database_name is not None: # we allow -- but do not encourage -- database name configuration return config.database_name if metadata.testing: # by convention, we provision different databases for unit testing and runtime return f"{metadata.name}_test_db" return f"{metadata.name}_db"
python
def choose_database_name(metadata, config): if config.database_name is not None: # we allow -- but do not encourage -- database name configuration return config.database_name if metadata.testing: # by convention, we provision different databases for unit testing and runtime return f"{metadata.name}_test_db" return f"{metadata.name}_db"
[ "def", "choose_database_name", "(", "metadata", ",", "config", ")", ":", "if", "config", ".", "database_name", "is", "not", "None", ":", "# we allow -- but do not encourage -- database name configuration", "return", "config", ".", "database_name", "if", "metadata", ".",...
Choose the database name to use. As a default, databases should be named after the service that uses them. In addition, database names should be different between unit testing and runtime so that there is no chance of a unit test dropping a real database by accident.
[ "Choose", "the", "database", "name", "to", "use", "." ]
43dd793b1fc9b84e4056700f350e79e0df5ff501
https://github.com/globality-corp/microcosm-postgres/blob/43dd793b1fc9b84e4056700f350e79e0df5ff501/microcosm_postgres/factories/engine.py#L11-L28
27,951
globality-corp/microcosm-postgres
microcosm_postgres/factories/engine.py
choose_username
def choose_username(metadata, config): """ Choose the database username to use. Because databases should not be shared between services, database usernames should be the same as the service that uses them. """ if config.username is not None: # we allow -- but do not encourage -- database username configuration return config.username if config.read_only: # by convention, we provision read-only username for every service return f"{metadata.name}_ro" return metadata.name
python
def choose_username(metadata, config): if config.username is not None: # we allow -- but do not encourage -- database username configuration return config.username if config.read_only: # by convention, we provision read-only username for every service return f"{metadata.name}_ro" return metadata.name
[ "def", "choose_username", "(", "metadata", ",", "config", ")", ":", "if", "config", ".", "username", "is", "not", "None", ":", "# we allow -- but do not encourage -- database username configuration", "return", "config", ".", "username", "if", "config", ".", "read_only...
Choose the database username to use. Because databases should not be shared between services, database usernames should be the same as the service that uses them.
[ "Choose", "the", "database", "username", "to", "use", "." ]
43dd793b1fc9b84e4056700f350e79e0df5ff501
https://github.com/globality-corp/microcosm-postgres/blob/43dd793b1fc9b84e4056700f350e79e0df5ff501/microcosm_postgres/factories/engine.py#L31-L47
27,952
globality-corp/microcosm-postgres
microcosm_postgres/factories/engine.py
choose_uri
def choose_uri(metadata, config): """ Choose the database URI to use. """ database_name = choose_database_name(metadata, config) driver = config.driver host, port = config.host, config.port username, password = choose_username(metadata, config), config.password return f"{driver}://{username}:{password}@{host}:{port}/{database_name}"
python
def choose_uri(metadata, config): database_name = choose_database_name(metadata, config) driver = config.driver host, port = config.host, config.port username, password = choose_username(metadata, config), config.password return f"{driver}://{username}:{password}@{host}:{port}/{database_name}"
[ "def", "choose_uri", "(", "metadata", ",", "config", ")", ":", "database_name", "=", "choose_database_name", "(", "metadata", ",", "config", ")", "driver", "=", "config", ".", "driver", "host", ",", "port", "=", "config", ".", "host", ",", "config", ".", ...
Choose the database URI to use.
[ "Choose", "the", "database", "URI", "to", "use", "." ]
43dd793b1fc9b84e4056700f350e79e0df5ff501
https://github.com/globality-corp/microcosm-postgres/blob/43dd793b1fc9b84e4056700f350e79e0df5ff501/microcosm_postgres/factories/engine.py#L50-L60
27,953
globality-corp/microcosm-postgres
microcosm_postgres/factories/engine.py
choose_connect_args
def choose_connect_args(metadata, config): """ Choose the SSL mode and optional root cert for the connection. """ if not config.require_ssl and not config.verify_ssl: return dict( sslmode="prefer", ) if config.require_ssl and not config.verify_ssl: return dict( sslmode="require", ) if not config.ssl_cert_path: raise Exception("SSL certificate path (`ssl_cert_path`) must be configured for verification") return dict( sslmode="verify-full", sslrootcert=config.ssl_cert_path, )
python
def choose_connect_args(metadata, config): if not config.require_ssl and not config.verify_ssl: return dict( sslmode="prefer", ) if config.require_ssl and not config.verify_ssl: return dict( sslmode="require", ) if not config.ssl_cert_path: raise Exception("SSL certificate path (`ssl_cert_path`) must be configured for verification") return dict( sslmode="verify-full", sslrootcert=config.ssl_cert_path, )
[ "def", "choose_connect_args", "(", "metadata", ",", "config", ")", ":", "if", "not", "config", ".", "require_ssl", "and", "not", "config", ".", "verify_ssl", ":", "return", "dict", "(", "sslmode", "=", "\"prefer\"", ",", ")", "if", "config", ".", "require_...
Choose the SSL mode and optional root cert for the connection.
[ "Choose", "the", "SSL", "mode", "and", "optional", "root", "cert", "for", "the", "connection", "." ]
43dd793b1fc9b84e4056700f350e79e0df5ff501
https://github.com/globality-corp/microcosm-postgres/blob/43dd793b1fc9b84e4056700f350e79e0df5ff501/microcosm_postgres/factories/engine.py#L63-L84
27,954
globality-corp/microcosm-postgres
microcosm_postgres/factories/engine.py
choose_args
def choose_args(metadata, config): """ Choose database connection arguments. """ return dict( connect_args=choose_connect_args(metadata, config), echo=config.echo, max_overflow=config.max_overflow, pool_size=config.pool_size, pool_timeout=config.pool_timeout, )
python
def choose_args(metadata, config): return dict( connect_args=choose_connect_args(metadata, config), echo=config.echo, max_overflow=config.max_overflow, pool_size=config.pool_size, pool_timeout=config.pool_timeout, )
[ "def", "choose_args", "(", "metadata", ",", "config", ")", ":", "return", "dict", "(", "connect_args", "=", "choose_connect_args", "(", "metadata", ",", "config", ")", ",", "echo", "=", "config", ".", "echo", ",", "max_overflow", "=", "config", ".", "max_o...
Choose database connection arguments.
[ "Choose", "database", "connection", "arguments", "." ]
43dd793b1fc9b84e4056700f350e79e0df5ff501
https://github.com/globality-corp/microcosm-postgres/blob/43dd793b1fc9b84e4056700f350e79e0df5ff501/microcosm_postgres/factories/engine.py#L87-L98
27,955
globality-corp/microcosm-postgres
microcosm_postgres/models.py
IdentityMixin._members
def _members(self): """ Return a dict of non-private members. """ return { key: value for key, value in self.__dict__.items() # NB: ignore internal SQLAlchemy state and nested relationships if not key.startswith("_") and not isinstance(value, Model) }
python
def _members(self): return { key: value for key, value in self.__dict__.items() # NB: ignore internal SQLAlchemy state and nested relationships if not key.startswith("_") and not isinstance(value, Model) }
[ "def", "_members", "(", "self", ")", ":", "return", "{", "key", ":", "value", "for", "key", ",", "value", "in", "self", ".", "__dict__", ".", "items", "(", ")", "# NB: ignore internal SQLAlchemy state and nested relationships", "if", "not", "key", ".", "starts...
Return a dict of non-private members.
[ "Return", "a", "dict", "of", "non", "-", "private", "members", "." ]
43dd793b1fc9b84e4056700f350e79e0df5ff501
https://github.com/globality-corp/microcosm-postgres/blob/43dd793b1fc9b84e4056700f350e79e0df5ff501/microcosm_postgres/models.py#L113-L123
27,956
globality-corp/microcosm-postgres
microcosm_postgres/temporary/methods.py
insert_many
def insert_many(self, items): """ Insert many items at once into a temporary table. """ return SessionContext.session.execute( self.insert(values=[ to_dict(item, self.c) for item in items ]), ).rowcount
python
def insert_many(self, items): return SessionContext.session.execute( self.insert(values=[ to_dict(item, self.c) for item in items ]), ).rowcount
[ "def", "insert_many", "(", "self", ",", "items", ")", ":", "return", "SessionContext", ".", "session", ".", "execute", "(", "self", ".", "insert", "(", "values", "=", "[", "to_dict", "(", "item", ",", "self", ".", "c", ")", "for", "item", "in", "item...
Insert many items at once into a temporary table.
[ "Insert", "many", "items", "at", "once", "into", "a", "temporary", "table", "." ]
43dd793b1fc9b84e4056700f350e79e0df5ff501
https://github.com/globality-corp/microcosm-postgres/blob/43dd793b1fc9b84e4056700f350e79e0df5ff501/microcosm_postgres/temporary/methods.py#L23-L33
27,957
globality-corp/microcosm-postgres
microcosm_postgres/temporary/methods.py
upsert_into
def upsert_into(self, table): """ Upsert from a temporarty table into another table. """ return SessionContext.session.execute( insert(table).from_select( self.c, self, ).on_conflict_do_nothing(), ).rowcount
python
def upsert_into(self, table): return SessionContext.session.execute( insert(table).from_select( self.c, self, ).on_conflict_do_nothing(), ).rowcount
[ "def", "upsert_into", "(", "self", ",", "table", ")", ":", "return", "SessionContext", ".", "session", ".", "execute", "(", "insert", "(", "table", ")", ".", "from_select", "(", "self", ".", "c", ",", "self", ",", ")", ".", "on_conflict_do_nothing", "(",...
Upsert from a temporarty table into another table.
[ "Upsert", "from", "a", "temporarty", "table", "into", "another", "table", "." ]
43dd793b1fc9b84e4056700f350e79e0df5ff501
https://github.com/globality-corp/microcosm-postgres/blob/43dd793b1fc9b84e4056700f350e79e0df5ff501/microcosm_postgres/temporary/methods.py#L36-L46
27,958
globality-corp/microcosm-postgres
microcosm_postgres/encryption/providers.py
configure_key_provider
def configure_key_provider(graph, key_ids): """ Configure a key provider. During unit tests, use a static key provider (e.g. without AWS calls). """ if graph.metadata.testing: # use static provider provider = StaticMasterKeyProvider() provider.add_master_keys_from_list(key_ids) return provider # use AWS provider return KMSMasterKeyProvider(key_ids=key_ids)
python
def configure_key_provider(graph, key_ids): if graph.metadata.testing: # use static provider provider = StaticMasterKeyProvider() provider.add_master_keys_from_list(key_ids) return provider # use AWS provider return KMSMasterKeyProvider(key_ids=key_ids)
[ "def", "configure_key_provider", "(", "graph", ",", "key_ids", ")", ":", "if", "graph", ".", "metadata", ".", "testing", ":", "# use static provider", "provider", "=", "StaticMasterKeyProvider", "(", ")", "provider", ".", "add_master_keys_from_list", "(", "key_ids",...
Configure a key provider. During unit tests, use a static key provider (e.g. without AWS calls).
[ "Configure", "a", "key", "provider", "." ]
43dd793b1fc9b84e4056700f350e79e0df5ff501
https://github.com/globality-corp/microcosm-postgres/blob/43dd793b1fc9b84e4056700f350e79e0df5ff501/microcosm_postgres/encryption/providers.py#L40-L54
27,959
globality-corp/microcosm-postgres
microcosm_postgres/encryption/providers.py
configure_materials_manager
def configure_materials_manager(graph, key_provider): """ Configure a crypto materials manager """ if graph.config.materials_manager.enable_cache: return CachingCryptoMaterialsManager( cache=LocalCryptoMaterialsCache(graph.config.materials_manager.cache_capacity), master_key_provider=key_provider, max_age=graph.config.materials_manager.cache_max_age, max_messages_encrypted=graph.config.materials_manager.cache_max_messages_encrypted, ) return DefaultCryptoMaterialsManager(master_key_provider=key_provider)
python
def configure_materials_manager(graph, key_provider): if graph.config.materials_manager.enable_cache: return CachingCryptoMaterialsManager( cache=LocalCryptoMaterialsCache(graph.config.materials_manager.cache_capacity), master_key_provider=key_provider, max_age=graph.config.materials_manager.cache_max_age, max_messages_encrypted=graph.config.materials_manager.cache_max_messages_encrypted, ) return DefaultCryptoMaterialsManager(master_key_provider=key_provider)
[ "def", "configure_materials_manager", "(", "graph", ",", "key_provider", ")", ":", "if", "graph", ".", "config", ".", "materials_manager", ".", "enable_cache", ":", "return", "CachingCryptoMaterialsManager", "(", "cache", "=", "LocalCryptoMaterialsCache", "(", "graph"...
Configure a crypto materials manager
[ "Configure", "a", "crypto", "materials", "manager" ]
43dd793b1fc9b84e4056700f350e79e0df5ff501
https://github.com/globality-corp/microcosm-postgres/blob/43dd793b1fc9b84e4056700f350e79e0df5ff501/microcosm_postgres/encryption/providers.py#L63-L75
27,960
globality-corp/microcosm-postgres
microcosm_postgres/createall.py
main
def main(graph): """ Create and drop databases. """ args = parse_args(graph) if args.drop: drop_all(graph) create_all(graph)
python
def main(graph): args = parse_args(graph) if args.drop: drop_all(graph) create_all(graph)
[ "def", "main", "(", "graph", ")", ":", "args", "=", "parse_args", "(", "graph", ")", "if", "args", ".", "drop", ":", "drop_all", "(", "graph", ")", "create_all", "(", "graph", ")" ]
Create and drop databases.
[ "Create", "and", "drop", "databases", "." ]
43dd793b1fc9b84e4056700f350e79e0df5ff501
https://github.com/globality-corp/microcosm-postgres/blob/43dd793b1fc9b84e4056700f350e79e0df5ff501/microcosm_postgres/createall.py#L16-L25
27,961
jochym/Elastic
elastic/elastic.py
get_lattice_type
def get_lattice_type(cryst): '''Find the symmetry of the crystal using spglib symmetry finder. Derive name of the space group and its number extracted from the result. Based on the group number identify also the lattice type and the Bravais lattice of the crystal. The lattice type numbers are (the numbering starts from 1): Triclinic (1), Monoclinic (2), Orthorombic (3), Tetragonal (4), Trigonal (5), Hexagonal (6), Cubic (7) :param cryst: ASE Atoms object :returns: tuple (lattice type number (1-7), lattice name, space group name, space group number) ''' # Table of lattice types and correcponding group numbers dividing # the ranges. See get_lattice_type method for precise definition. lattice_types = [ [3, "Triclinic"], [16, "Monoclinic"], [75, "Orthorombic"], [143, "Tetragonal"], [168, "Trigonal"], [195, "Hexagonal"], [231, "Cubic"] ] sg = spg.get_spacegroup(cryst) m = re.match(r'([A-Z].*\b)\s*\(([0-9]*)\)', sg) sg_name = m.group(1) sg_nr = int(m.group(2)) for n, l in enumerate(lattice_types): if sg_nr < l[0]: bravais = l[1] lattype = n+1 break return lattype, bravais, sg_name, sg_nr
python
def get_lattice_type(cryst): '''Find the symmetry of the crystal using spglib symmetry finder. Derive name of the space group and its number extracted from the result. Based on the group number identify also the lattice type and the Bravais lattice of the crystal. The lattice type numbers are (the numbering starts from 1): Triclinic (1), Monoclinic (2), Orthorombic (3), Tetragonal (4), Trigonal (5), Hexagonal (6), Cubic (7) :param cryst: ASE Atoms object :returns: tuple (lattice type number (1-7), lattice name, space group name, space group number) ''' # Table of lattice types and correcponding group numbers dividing # the ranges. See get_lattice_type method for precise definition. lattice_types = [ [3, "Triclinic"], [16, "Monoclinic"], [75, "Orthorombic"], [143, "Tetragonal"], [168, "Trigonal"], [195, "Hexagonal"], [231, "Cubic"] ] sg = spg.get_spacegroup(cryst) m = re.match(r'([A-Z].*\b)\s*\(([0-9]*)\)', sg) sg_name = m.group(1) sg_nr = int(m.group(2)) for n, l in enumerate(lattice_types): if sg_nr < l[0]: bravais = l[1] lattype = n+1 break return lattype, bravais, sg_name, sg_nr
[ "def", "get_lattice_type", "(", "cryst", ")", ":", "# Table of lattice types and correcponding group numbers dividing", "# the ranges. See get_lattice_type method for precise definition.", "lattice_types", "=", "[", "[", "3", ",", "\"Triclinic\"", "]", ",", "[", "16", ",", "\...
Find the symmetry of the crystal using spglib symmetry finder. Derive name of the space group and its number extracted from the result. Based on the group number identify also the lattice type and the Bravais lattice of the crystal. The lattice type numbers are (the numbering starts from 1): Triclinic (1), Monoclinic (2), Orthorombic (3), Tetragonal (4), Trigonal (5), Hexagonal (6), Cubic (7) :param cryst: ASE Atoms object :returns: tuple (lattice type number (1-7), lattice name, space group name, space group number)
[ "Find", "the", "symmetry", "of", "the", "crystal", "using", "spglib", "symmetry", "finder", "." ]
8daae37d0c48aab8dfb1de2839dab02314817f95
https://github.com/jochym/Elastic/blob/8daae37d0c48aab8dfb1de2839dab02314817f95/elastic/elastic.py#L305-L345
27,962
jochym/Elastic
elastic/elastic.py
get_bulk_modulus
def get_bulk_modulus(cryst): '''Calculate bulk modulus using the Birch-Murnaghan equation of state. The EOS must be previously calculated by get_BM_EOS routine. The returned bulk modulus is a :math:`B_0` coefficient of the B-M EOS. The units of the result are defined by ASE. To get the result in any particular units (e.g. GPa) you need to divide it by ase.units.<unit name>:: get_bulk_modulus(cryst)/ase.units.GPa :param cryst: ASE Atoms object :returns: float, bulk modulus :math:`B_0` in ASE units. ''' if getattr(cryst, 'bm_eos', None) is None: raise RuntimeError('Missing B-M EOS data.') cryst.bulk_modulus = cryst.bm_eos[1] return cryst.bulk_modulus
python
def get_bulk_modulus(cryst): '''Calculate bulk modulus using the Birch-Murnaghan equation of state. The EOS must be previously calculated by get_BM_EOS routine. The returned bulk modulus is a :math:`B_0` coefficient of the B-M EOS. The units of the result are defined by ASE. To get the result in any particular units (e.g. GPa) you need to divide it by ase.units.<unit name>:: get_bulk_modulus(cryst)/ase.units.GPa :param cryst: ASE Atoms object :returns: float, bulk modulus :math:`B_0` in ASE units. ''' if getattr(cryst, 'bm_eos', None) is None: raise RuntimeError('Missing B-M EOS data.') cryst.bulk_modulus = cryst.bm_eos[1] return cryst.bulk_modulus
[ "def", "get_bulk_modulus", "(", "cryst", ")", ":", "if", "getattr", "(", "cryst", ",", "'bm_eos'", ",", "None", ")", "is", "None", ":", "raise", "RuntimeError", "(", "'Missing B-M EOS data.'", ")", "cryst", ".", "bulk_modulus", "=", "cryst", ".", "bm_eos", ...
Calculate bulk modulus using the Birch-Murnaghan equation of state. The EOS must be previously calculated by get_BM_EOS routine. The returned bulk modulus is a :math:`B_0` coefficient of the B-M EOS. The units of the result are defined by ASE. To get the result in any particular units (e.g. GPa) you need to divide it by ase.units.<unit name>:: get_bulk_modulus(cryst)/ase.units.GPa :param cryst: ASE Atoms object :returns: float, bulk modulus :math:`B_0` in ASE units.
[ "Calculate", "bulk", "modulus", "using", "the", "Birch", "-", "Murnaghan", "equation", "of", "state", "." ]
8daae37d0c48aab8dfb1de2839dab02314817f95
https://github.com/jochym/Elastic/blob/8daae37d0c48aab8dfb1de2839dab02314817f95/elastic/elastic.py#L348-L367
27,963
jochym/Elastic
elastic/elastic.py
get_BM_EOS
def get_BM_EOS(cryst, systems): """Calculate Birch-Murnaghan Equation of State for the crystal. The B-M equation of state is defined by: .. math:: P(V)= \\frac{B_0}{B'_0}\\left[ \\left({\\frac{V}{V_0}}\\right)^{-B'_0} - 1 \\right] It's coefficients are estimated using n single-point structures ganerated from the crystal (cryst) by the scan_volumes function between two relative volumes. The BM EOS is fitted to the computed points by least squares method. The returned value is a list of fitted parameters: :math:`V_0, B_0, B_0'` if the fit succeded. If the fitting fails the ``RuntimeError('Calculation failed')`` is raised. The data from the calculation and fit is stored in the bm_eos and pv members of cryst for future reference. You have to provide properly optimized structures in cryst and systems list. :param cryst: Atoms object, basic structure :param systems: A list of calculated structures :returns: tuple of EOS parameters :math:`V_0, B_0, B_0'`. """ pvdat = array([[r.get_volume(), get_pressure(r.get_stress()), norm(r.get_cell()[:, 0]), norm(r.get_cell()[:, 1]), norm(r.get_cell()[:, 2])] for r in systems]).T # Estimate the initial guess assuming b0p=1 # Limiting volumes v1 = min(pvdat[0]) v2 = max(pvdat[0]) # The pressure is falling with the growing volume p2 = min(pvdat[1]) p1 = max(pvdat[1]) b0 = (p1*v1-p2*v2)/(v2-v1) v0 = v1*(p1+b0)/b0 # Initial guess p0 = [v0, b0, 1] # Fitting try : p1, succ = optimize.curve_fit(BMEOS, pvdat[0], pvdat[1], p0) except (ValueError, RuntimeError, optimize.OptimizeWarning) as ex: raise RuntimeError('Calculation failed') cryst.bm_eos = p1 cryst.pv = pvdat return cryst.bm_eos
python
def get_BM_EOS(cryst, systems): pvdat = array([[r.get_volume(), get_pressure(r.get_stress()), norm(r.get_cell()[:, 0]), norm(r.get_cell()[:, 1]), norm(r.get_cell()[:, 2])] for r in systems]).T # Estimate the initial guess assuming b0p=1 # Limiting volumes v1 = min(pvdat[0]) v2 = max(pvdat[0]) # The pressure is falling with the growing volume p2 = min(pvdat[1]) p1 = max(pvdat[1]) b0 = (p1*v1-p2*v2)/(v2-v1) v0 = v1*(p1+b0)/b0 # Initial guess p0 = [v0, b0, 1] # Fitting try : p1, succ = optimize.curve_fit(BMEOS, pvdat[0], pvdat[1], p0) except (ValueError, RuntimeError, optimize.OptimizeWarning) as ex: raise RuntimeError('Calculation failed') cryst.bm_eos = p1 cryst.pv = pvdat return cryst.bm_eos
[ "def", "get_BM_EOS", "(", "cryst", ",", "systems", ")", ":", "pvdat", "=", "array", "(", "[", "[", "r", ".", "get_volume", "(", ")", ",", "get_pressure", "(", "r", ".", "get_stress", "(", ")", ")", ",", "norm", "(", "r", ".", "get_cell", "(", ")"...
Calculate Birch-Murnaghan Equation of State for the crystal. The B-M equation of state is defined by: .. math:: P(V)= \\frac{B_0}{B'_0}\\left[ \\left({\\frac{V}{V_0}}\\right)^{-B'_0} - 1 \\right] It's coefficients are estimated using n single-point structures ganerated from the crystal (cryst) by the scan_volumes function between two relative volumes. The BM EOS is fitted to the computed points by least squares method. The returned value is a list of fitted parameters: :math:`V_0, B_0, B_0'` if the fit succeded. If the fitting fails the ``RuntimeError('Calculation failed')`` is raised. The data from the calculation and fit is stored in the bm_eos and pv members of cryst for future reference. You have to provide properly optimized structures in cryst and systems list. :param cryst: Atoms object, basic structure :param systems: A list of calculated structures :returns: tuple of EOS parameters :math:`V_0, B_0, B_0'`.
[ "Calculate", "Birch", "-", "Murnaghan", "Equation", "of", "State", "for", "the", "crystal", "." ]
8daae37d0c48aab8dfb1de2839dab02314817f95
https://github.com/jochym/Elastic/blob/8daae37d0c48aab8dfb1de2839dab02314817f95/elastic/elastic.py#L386-L440
27,964
jochym/Elastic
elastic/elastic.py
get_elementary_deformations
def get_elementary_deformations(cryst, n=5, d=2): '''Generate elementary deformations for elastic tensor calculation. The deformations are created based on the symmetry of the crystal and are limited to the non-equivalet axes of the crystal. :param cryst: Atoms object, basic structure :param n: integer, number of deformations per non-equivalent axis :param d: float, size of the maximum deformation in percent and degrees :returns: list of deformed structures ''' # Deformation look-up table # Perhaps the number of deformations for trigonal # system could be reduced to [0,3] but better safe then sorry deform = { "Cubic": [[0, 3], regular], "Hexagonal": [[0, 2, 3, 5], hexagonal], "Trigonal": [[0, 1, 2, 3, 4, 5], trigonal], "Tetragonal": [[0, 2, 3, 5], tetragonal], "Orthorombic": [[0, 1, 2, 3, 4, 5], orthorombic], "Monoclinic": [[0, 1, 2, 3, 4, 5], monoclinic], "Triclinic": [[0, 1, 2, 3, 4, 5], triclinic] } lattyp, brav, sg_name, sg_nr = get_lattice_type(cryst) # Decide which deformations should be used axis, symm = deform[brav] systems = [] for a in axis: if a < 3: # tetragonal deformation for dx in linspace(-d, d, n): systems.append( get_cart_deformed_cell(cryst, axis=a, size=dx)) elif a < 6: # sheer deformation (skip the zero angle) for dx in linspace(d/10.0, d, n): systems.append( get_cart_deformed_cell(cryst, axis=a, size=dx)) return systems
python
def get_elementary_deformations(cryst, n=5, d=2): '''Generate elementary deformations for elastic tensor calculation. The deformations are created based on the symmetry of the crystal and are limited to the non-equivalet axes of the crystal. :param cryst: Atoms object, basic structure :param n: integer, number of deformations per non-equivalent axis :param d: float, size of the maximum deformation in percent and degrees :returns: list of deformed structures ''' # Deformation look-up table # Perhaps the number of deformations for trigonal # system could be reduced to [0,3] but better safe then sorry deform = { "Cubic": [[0, 3], regular], "Hexagonal": [[0, 2, 3, 5], hexagonal], "Trigonal": [[0, 1, 2, 3, 4, 5], trigonal], "Tetragonal": [[0, 2, 3, 5], tetragonal], "Orthorombic": [[0, 1, 2, 3, 4, 5], orthorombic], "Monoclinic": [[0, 1, 2, 3, 4, 5], monoclinic], "Triclinic": [[0, 1, 2, 3, 4, 5], triclinic] } lattyp, brav, sg_name, sg_nr = get_lattice_type(cryst) # Decide which deformations should be used axis, symm = deform[brav] systems = [] for a in axis: if a < 3: # tetragonal deformation for dx in linspace(-d, d, n): systems.append( get_cart_deformed_cell(cryst, axis=a, size=dx)) elif a < 6: # sheer deformation (skip the zero angle) for dx in linspace(d/10.0, d, n): systems.append( get_cart_deformed_cell(cryst, axis=a, size=dx)) return systems
[ "def", "get_elementary_deformations", "(", "cryst", ",", "n", "=", "5", ",", "d", "=", "2", ")", ":", "# Deformation look-up table", "# Perhaps the number of deformations for trigonal", "# system could be reduced to [0,3] but better safe then sorry", "deform", "=", "{", "\"Cu...
Generate elementary deformations for elastic tensor calculation. The deformations are created based on the symmetry of the crystal and are limited to the non-equivalet axes of the crystal. :param cryst: Atoms object, basic structure :param n: integer, number of deformations per non-equivalent axis :param d: float, size of the maximum deformation in percent and degrees :returns: list of deformed structures
[ "Generate", "elementary", "deformations", "for", "elastic", "tensor", "calculation", "." ]
8daae37d0c48aab8dfb1de2839dab02314817f95
https://github.com/jochym/Elastic/blob/8daae37d0c48aab8dfb1de2839dab02314817f95/elastic/elastic.py#L443-L482
27,965
jochym/Elastic
elastic/elastic.py
get_cart_deformed_cell
def get_cart_deformed_cell(base_cryst, axis=0, size=1): '''Return the cell deformed along one of the cartesian directions Creates new deformed structure. The deformation is based on the base structure and is performed along single axis. The axis is specified as follows: 0,1,2 = x,y,z ; sheers: 3,4,5 = yz, xz, xy. The size of the deformation is in percent and degrees, respectively. :param base_cryst: structure to be deformed :param axis: direction of deformation :param size: size of the deformation :returns: new, deformed structure ''' cryst = Atoms(base_cryst) uc = base_cryst.get_cell() s = size/100.0 L = diag(ones(3)) if axis < 3: L[axis, axis] += s else: if axis == 3: L[1, 2] += s elif axis == 4: L[0, 2] += s else: L[0, 1] += s uc = dot(uc, L) cryst.set_cell(uc, scale_atoms=True) # print(cryst.get_cell()) # print(uc) return cryst
python
def get_cart_deformed_cell(base_cryst, axis=0, size=1): '''Return the cell deformed along one of the cartesian directions Creates new deformed structure. The deformation is based on the base structure and is performed along single axis. The axis is specified as follows: 0,1,2 = x,y,z ; sheers: 3,4,5 = yz, xz, xy. The size of the deformation is in percent and degrees, respectively. :param base_cryst: structure to be deformed :param axis: direction of deformation :param size: size of the deformation :returns: new, deformed structure ''' cryst = Atoms(base_cryst) uc = base_cryst.get_cell() s = size/100.0 L = diag(ones(3)) if axis < 3: L[axis, axis] += s else: if axis == 3: L[1, 2] += s elif axis == 4: L[0, 2] += s else: L[0, 1] += s uc = dot(uc, L) cryst.set_cell(uc, scale_atoms=True) # print(cryst.get_cell()) # print(uc) return cryst
[ "def", "get_cart_deformed_cell", "(", "base_cryst", ",", "axis", "=", "0", ",", "size", "=", "1", ")", ":", "cryst", "=", "Atoms", "(", "base_cryst", ")", "uc", "=", "base_cryst", ".", "get_cell", "(", ")", "s", "=", "size", "/", "100.0", "L", "=", ...
Return the cell deformed along one of the cartesian directions Creates new deformed structure. The deformation is based on the base structure and is performed along single axis. The axis is specified as follows: 0,1,2 = x,y,z ; sheers: 3,4,5 = yz, xz, xy. The size of the deformation is in percent and degrees, respectively. :param base_cryst: structure to be deformed :param axis: direction of deformation :param size: size of the deformation :returns: new, deformed structure
[ "Return", "the", "cell", "deformed", "along", "one", "of", "the", "cartesian", "directions" ]
8daae37d0c48aab8dfb1de2839dab02314817f95
https://github.com/jochym/Elastic/blob/8daae37d0c48aab8dfb1de2839dab02314817f95/elastic/elastic.py#L669-L700
27,966
jochym/Elastic
elastic/elastic.py
get_strain
def get_strain(cryst, refcell=None): '''Calculate strain tensor in the Voight notation Computes the strain tensor in the Voight notation as a conventional 6-vector. The calculation is done with respect to the crystal geometry passed in refcell parameter. :param cryst: deformed structure :param refcell: reference, undeformed structure :returns: 6-vector of strain tensor in the Voight notation ''' if refcell is None: refcell = cryst du = cryst.get_cell()-refcell.get_cell() m = refcell.get_cell() m = inv(m) u = dot(m, du) u = (u+u.T)/2 return array([u[0, 0], u[1, 1], u[2, 2], u[2, 1], u[2, 0], u[1, 0]])
python
def get_strain(cryst, refcell=None): '''Calculate strain tensor in the Voight notation Computes the strain tensor in the Voight notation as a conventional 6-vector. The calculation is done with respect to the crystal geometry passed in refcell parameter. :param cryst: deformed structure :param refcell: reference, undeformed structure :returns: 6-vector of strain tensor in the Voight notation ''' if refcell is None: refcell = cryst du = cryst.get_cell()-refcell.get_cell() m = refcell.get_cell() m = inv(m) u = dot(m, du) u = (u+u.T)/2 return array([u[0, 0], u[1, 1], u[2, 2], u[2, 1], u[2, 0], u[1, 0]])
[ "def", "get_strain", "(", "cryst", ",", "refcell", "=", "None", ")", ":", "if", "refcell", "is", "None", ":", "refcell", "=", "cryst", "du", "=", "cryst", ".", "get_cell", "(", ")", "-", "refcell", ".", "get_cell", "(", ")", "m", "=", "refcell", "....
Calculate strain tensor in the Voight notation Computes the strain tensor in the Voight notation as a conventional 6-vector. The calculation is done with respect to the crystal geometry passed in refcell parameter. :param cryst: deformed structure :param refcell: reference, undeformed structure :returns: 6-vector of strain tensor in the Voight notation
[ "Calculate", "strain", "tensor", "in", "the", "Voight", "notation" ]
8daae37d0c48aab8dfb1de2839dab02314817f95
https://github.com/jochym/Elastic/blob/8daae37d0c48aab8dfb1de2839dab02314817f95/elastic/elastic.py#L703-L722
27,967
jochym/Elastic
parcalc/parcalc.py
work_dir
def work_dir(path): ''' Context menager for executing commands in some working directory. Returns to the previous wd when finished. Usage: >>> with work_dir(path): ... subprocess.call('git status') ''' starting_directory = os.getcwd() try: os.chdir(path) yield finally: os.chdir(starting_directory)
python
def work_dir(path): ''' Context menager for executing commands in some working directory. Returns to the previous wd when finished. Usage: >>> with work_dir(path): ... subprocess.call('git status') ''' starting_directory = os.getcwd() try: os.chdir(path) yield finally: os.chdir(starting_directory)
[ "def", "work_dir", "(", "path", ")", ":", "starting_directory", "=", "os", ".", "getcwd", "(", ")", "try", ":", "os", ".", "chdir", "(", "path", ")", "yield", "finally", ":", "os", ".", "chdir", "(", "starting_directory", ")" ]
Context menager for executing commands in some working directory. Returns to the previous wd when finished. Usage: >>> with work_dir(path): ... subprocess.call('git status')
[ "Context", "menager", "for", "executing", "commands", "in", "some", "working", "directory", ".", "Returns", "to", "the", "previous", "wd", "when", "finished", "." ]
8daae37d0c48aab8dfb1de2839dab02314817f95
https://github.com/jochym/Elastic/blob/8daae37d0c48aab8dfb1de2839dab02314817f95/parcalc/parcalc.py#L79-L94
27,968
jochym/Elastic
parcalc/parcalc.py
ClusterVasp.prepare_calc_dir
def prepare_calc_dir(self): ''' Prepare the calculation directory for VASP execution. This needs to be re-implemented for each local setup. The following code reflects just my particular setup. ''' with open("vasprun.conf","w") as f: f.write('NODES="nodes=%s:ppn=%d"\n' % (self.nodes, self.ppn)) f.write('BLOCK=%d\n' % (self.block,)) if self.ncl : f.write('NCL=%d\n' % (1,))
python
def prepare_calc_dir(self): ''' Prepare the calculation directory for VASP execution. This needs to be re-implemented for each local setup. The following code reflects just my particular setup. ''' with open("vasprun.conf","w") as f: f.write('NODES="nodes=%s:ppn=%d"\n' % (self.nodes, self.ppn)) f.write('BLOCK=%d\n' % (self.block,)) if self.ncl : f.write('NCL=%d\n' % (1,))
[ "def", "prepare_calc_dir", "(", "self", ")", ":", "with", "open", "(", "\"vasprun.conf\"", ",", "\"w\"", ")", "as", "f", ":", "f", ".", "write", "(", "'NODES=\"nodes=%s:ppn=%d\"\\n'", "%", "(", "self", ".", "nodes", ",", "self", ".", "ppn", ")", ")", "...
Prepare the calculation directory for VASP execution. This needs to be re-implemented for each local setup. The following code reflects just my particular setup.
[ "Prepare", "the", "calculation", "directory", "for", "VASP", "execution", ".", "This", "needs", "to", "be", "re", "-", "implemented", "for", "each", "local", "setup", ".", "The", "following", "code", "reflects", "just", "my", "particular", "setup", "." ]
8daae37d0c48aab8dfb1de2839dab02314817f95
https://github.com/jochym/Elastic/blob/8daae37d0c48aab8dfb1de2839dab02314817f95/parcalc/parcalc.py#L114-L124
27,969
jochym/Elastic
parcalc/parcalc.py
ClusterVasp.calc_finished
def calc_finished(self): ''' Check if the lockfile is in the calculation directory. It is removed by the script at the end regardless of the success of the calculation. This is totally tied to implementation and you need to implement your own scheme! ''' #print_stack(limit=5) if not self.calc_running : #print('Calc running:',self.calc_running) return True else: # The calc is marked as running check if this is still true # We do it by external scripts. You need to write these # scripts for your own system. # See examples/scripts directory for examples. with work_dir(self.working_dir) : o=check_output(['check-job']) #print('Status',o) if o[0] in b'R' : # Still running - we do nothing to preserve the state return False else : # The job is not running maybe it finished maybe crashed # We hope for the best at this point ad pass to the # Standard update function return True
python
def calc_finished(self): ''' Check if the lockfile is in the calculation directory. It is removed by the script at the end regardless of the success of the calculation. This is totally tied to implementation and you need to implement your own scheme! ''' #print_stack(limit=5) if not self.calc_running : #print('Calc running:',self.calc_running) return True else: # The calc is marked as running check if this is still true # We do it by external scripts. You need to write these # scripts for your own system. # See examples/scripts directory for examples. with work_dir(self.working_dir) : o=check_output(['check-job']) #print('Status',o) if o[0] in b'R' : # Still running - we do nothing to preserve the state return False else : # The job is not running maybe it finished maybe crashed # We hope for the best at this point ad pass to the # Standard update function return True
[ "def", "calc_finished", "(", "self", ")", ":", "#print_stack(limit=5)", "if", "not", "self", ".", "calc_running", ":", "#print('Calc running:',self.calc_running)", "return", "True", "else", ":", "# The calc is marked as running check if this is still true", "# We do it by exter...
Check if the lockfile is in the calculation directory. It is removed by the script at the end regardless of the success of the calculation. This is totally tied to implementation and you need to implement your own scheme!
[ "Check", "if", "the", "lockfile", "is", "in", "the", "calculation", "directory", ".", "It", "is", "removed", "by", "the", "script", "at", "the", "end", "regardless", "of", "the", "success", "of", "the", "calculation", ".", "This", "is", "totally", "tied", ...
8daae37d0c48aab8dfb1de2839dab02314817f95
https://github.com/jochym/Elastic/blob/8daae37d0c48aab8dfb1de2839dab02314817f95/parcalc/parcalc.py#L127-L153
27,970
jochym/Elastic
parcalc/parcalc.py
RemoteCalculator.run_calculation
def run_calculation(self, atoms=None, properties=['energy'], system_changes=all_changes): ''' Internal calculation executor. We cannot use FileIOCalculator directly since we need to support remote execution. This calculator is different from others. It prepares the directory, launches the remote process and raises the exception to signal that we need to come back for results when the job is finished. ''' self.calc.calculate(self, atoms, properties, system_changes) self.write_input(self.atoms, properties, system_changes) if self.command is None: raise RuntimeError('Please configure Remote calculator!') olddir = os.getcwd() errorcode=0 try: os.chdir(self.directory) output = subprocess.check_output(self.command, shell=True) self.jobid=output.split()[0] self.submited=True #print "Job %s submitted. Waiting for it." % (self.jobid) # Waiting loop. To be removed. except subprocess.CalledProcessError as e: errorcode=e.returncode finally: os.chdir(olddir) if errorcode: raise RuntimeError('%s returned an error: %d' % (self.name, errorcode)) self.read_results()
python
def run_calculation(self, atoms=None, properties=['energy'], system_changes=all_changes): ''' Internal calculation executor. We cannot use FileIOCalculator directly since we need to support remote execution. This calculator is different from others. It prepares the directory, launches the remote process and raises the exception to signal that we need to come back for results when the job is finished. ''' self.calc.calculate(self, atoms, properties, system_changes) self.write_input(self.atoms, properties, system_changes) if self.command is None: raise RuntimeError('Please configure Remote calculator!') olddir = os.getcwd() errorcode=0 try: os.chdir(self.directory) output = subprocess.check_output(self.command, shell=True) self.jobid=output.split()[0] self.submited=True #print "Job %s submitted. Waiting for it." % (self.jobid) # Waiting loop. To be removed. except subprocess.CalledProcessError as e: errorcode=e.returncode finally: os.chdir(olddir) if errorcode: raise RuntimeError('%s returned an error: %d' % (self.name, errorcode)) self.read_results()
[ "def", "run_calculation", "(", "self", ",", "atoms", "=", "None", ",", "properties", "=", "[", "'energy'", "]", ",", "system_changes", "=", "all_changes", ")", ":", "self", ".", "calc", ".", "calculate", "(", "self", ",", "atoms", ",", "properties", ",",...
Internal calculation executor. We cannot use FileIOCalculator directly since we need to support remote execution. This calculator is different from others. It prepares the directory, launches the remote process and raises the exception to signal that we need to come back for results when the job is finished.
[ "Internal", "calculation", "executor", ".", "We", "cannot", "use", "FileIOCalculator", "directly", "since", "we", "need", "to", "support", "remote", "execution", ".", "This", "calculator", "is", "different", "from", "others", ".", "It", "prepares", "the", "direc...
8daae37d0c48aab8dfb1de2839dab02314817f95
https://github.com/jochym/Elastic/blob/8daae37d0c48aab8dfb1de2839dab02314817f95/parcalc/parcalc.py#L425-L457
27,971
jochym/Elastic
elastic/cli/elastic.py
gen
def gen(ctx, num, lo, hi, size, struct): '''Generate deformed structures''' frmt = ctx.parent.params['frmt'] action = ctx.parent.params['action'] cryst = ase.io.read(struct, format=frmt) fn_tmpl = action if frmt == 'vasp': fn_tmpl += '_%03d.POSCAR' kwargs = {'vasp5': True, 'direct': True} elif frmt == 'abinit': fn_tmpl += '_%03d.abinit' kwargs = {} if verbose: from elastic.elastic import get_lattice_type nr, brav, sg, sgn = get_lattice_type(cryst) echo('%s lattice (%s): %s' % (brav, sg, cryst.get_chemical_formula())) if action == 'cij': echo('Generating {:d} deformations of {:.1f}(%/degs.) per axis'.format( num, size)) elif action == 'eos': echo('Generating {:d} deformations from {:.3f} to {:.3f} of V0'.format( num, lo, hi)) if action == 'cij': systems = elastic.get_elementary_deformations(cryst, n=num, d=size) elif action == 'eos': systems = elastic.scan_volumes(cryst, n=num, lo=lo, hi=hi) systems.insert(0, cryst) if verbose: echo('Writing %d deformation files.' % len(systems)) for n, s in enumerate(systems): ase.io.write(fn_tmpl % n, s, format=frmt, **kwargs)
python
def gen(ctx, num, lo, hi, size, struct): '''Generate deformed structures''' frmt = ctx.parent.params['frmt'] action = ctx.parent.params['action'] cryst = ase.io.read(struct, format=frmt) fn_tmpl = action if frmt == 'vasp': fn_tmpl += '_%03d.POSCAR' kwargs = {'vasp5': True, 'direct': True} elif frmt == 'abinit': fn_tmpl += '_%03d.abinit' kwargs = {} if verbose: from elastic.elastic import get_lattice_type nr, brav, sg, sgn = get_lattice_type(cryst) echo('%s lattice (%s): %s' % (brav, sg, cryst.get_chemical_formula())) if action == 'cij': echo('Generating {:d} deformations of {:.1f}(%/degs.) per axis'.format( num, size)) elif action == 'eos': echo('Generating {:d} deformations from {:.3f} to {:.3f} of V0'.format( num, lo, hi)) if action == 'cij': systems = elastic.get_elementary_deformations(cryst, n=num, d=size) elif action == 'eos': systems = elastic.scan_volumes(cryst, n=num, lo=lo, hi=hi) systems.insert(0, cryst) if verbose: echo('Writing %d deformation files.' % len(systems)) for n, s in enumerate(systems): ase.io.write(fn_tmpl % n, s, format=frmt, **kwargs)
[ "def", "gen", "(", "ctx", ",", "num", ",", "lo", ",", "hi", ",", "size", ",", "struct", ")", ":", "frmt", "=", "ctx", ".", "parent", ".", "params", "[", "'frmt'", "]", "action", "=", "ctx", ".", "parent", ".", "params", "[", "'action'", "]", "c...
Generate deformed structures
[ "Generate", "deformed", "structures" ]
8daae37d0c48aab8dfb1de2839dab02314817f95
https://github.com/jochym/Elastic/blob/8daae37d0c48aab8dfb1de2839dab02314817f95/elastic/cli/elastic.py#L83-L117
27,972
jochym/Elastic
elastic/cli/elastic.py
proc
def proc(ctx, files): '''Process calculated structures''' def calc_reader(fn, verb): if verb: echo('Reading: {:<60s}\r'.format(fn), nl=False, err=True) return ase.io.read(fn) action = ctx.parent.params['action'] systems = [calc_reader(calc, verbose) for calc in files] if verbose : echo('', err=True) if action == 'cij': cij = elastic.get_elastic_tensor(systems[0], systems=systems[1:]) msv = cij[1][3].max() eps = 1e-4 if verbose: echo('Cij solution\n'+30*'-') echo(' Solution rank: {:2d}{}'.format( cij[1][2], ' (undetermined)' if cij[1][2] < len(cij[0]) else '')) if cij[1][2] == len(cij[0]): echo(' Square of residuals: {:7.2g}'.format(cij[1][1])) echo(' Relative singular values:') for sv in cij[1][3]/msv: echo('{:7.4f}{}'.format( sv, '* ' if (sv) < eps else ' '), nl=False) echo('\n\nElastic tensor (GPa):') for dsc in elastic.elastic.get_cij_order(systems[0]): echo('{: >7s} '.format(dsc), nl=False) echo('\n'+30*'-') for c, sv in zip(cij[0], cij[1][3]/msv): echo('{:7.2f}{}'.format( c/ase.units.GPa, '* ' if sv < eps else ' '), nl=False) echo() elif action == 'eos': eos = elastic.get_BM_EOS(systems[0], systems=systems[1:]) eos[1] /= ase.units.GPa if verbose: echo('# %7s (A^3) %7s (GPa) %7s' % ("V0", "B0", "B0'")) echo(' %7.2f %7.2f %7.2f' % tuple(eos))
python
def proc(ctx, files): '''Process calculated structures''' def calc_reader(fn, verb): if verb: echo('Reading: {:<60s}\r'.format(fn), nl=False, err=True) return ase.io.read(fn) action = ctx.parent.params['action'] systems = [calc_reader(calc, verbose) for calc in files] if verbose : echo('', err=True) if action == 'cij': cij = elastic.get_elastic_tensor(systems[0], systems=systems[1:]) msv = cij[1][3].max() eps = 1e-4 if verbose: echo('Cij solution\n'+30*'-') echo(' Solution rank: {:2d}{}'.format( cij[1][2], ' (undetermined)' if cij[1][2] < len(cij[0]) else '')) if cij[1][2] == len(cij[0]): echo(' Square of residuals: {:7.2g}'.format(cij[1][1])) echo(' Relative singular values:') for sv in cij[1][3]/msv: echo('{:7.4f}{}'.format( sv, '* ' if (sv) < eps else ' '), nl=False) echo('\n\nElastic tensor (GPa):') for dsc in elastic.elastic.get_cij_order(systems[0]): echo('{: >7s} '.format(dsc), nl=False) echo('\n'+30*'-') for c, sv in zip(cij[0], cij[1][3]/msv): echo('{:7.2f}{}'.format( c/ase.units.GPa, '* ' if sv < eps else ' '), nl=False) echo() elif action == 'eos': eos = elastic.get_BM_EOS(systems[0], systems=systems[1:]) eos[1] /= ase.units.GPa if verbose: echo('# %7s (A^3) %7s (GPa) %7s' % ("V0", "B0", "B0'")) echo(' %7.2f %7.2f %7.2f' % tuple(eos))
[ "def", "proc", "(", "ctx", ",", "files", ")", ":", "def", "calc_reader", "(", "fn", ",", "verb", ")", ":", "if", "verb", ":", "echo", "(", "'Reading: {:<60s}\\r'", ".", "format", "(", "fn", ")", ",", "nl", "=", "False", ",", "err", "=", "True", "...
Process calculated structures
[ "Process", "calculated", "structures" ]
8daae37d0c48aab8dfb1de2839dab02314817f95
https://github.com/jochym/Elastic/blob/8daae37d0c48aab8dfb1de2839dab02314817f95/elastic/cli/elastic.py#L123-L163
27,973
django-blog-zinnia/cmsplugin-zinnia
cmsplugin_zinnia/admin.py
EntryPlaceholderAdmin.save_model
def save_model(self, request, entry, form, change): """ Fill the content field with the interpretation of the placeholder """ context = RequestContext(request) try: content = render_placeholder(entry.content_placeholder, context) entry.content = content or '' except KeyError: # https://github.com/django-blog-zinnia/cmsplugin-zinnia/pull/61 entry.content = '' super(EntryPlaceholderAdmin, self).save_model( request, entry, form, change)
python
def save_model(self, request, entry, form, change): context = RequestContext(request) try: content = render_placeholder(entry.content_placeholder, context) entry.content = content or '' except KeyError: # https://github.com/django-blog-zinnia/cmsplugin-zinnia/pull/61 entry.content = '' super(EntryPlaceholderAdmin, self).save_model( request, entry, form, change)
[ "def", "save_model", "(", "self", ",", "request", ",", "entry", ",", "form", ",", "change", ")", ":", "context", "=", "RequestContext", "(", "request", ")", "try", ":", "content", "=", "render_placeholder", "(", "entry", ".", "content_placeholder", ",", "c...
Fill the content field with the interpretation of the placeholder
[ "Fill", "the", "content", "field", "with", "the", "interpretation", "of", "the", "placeholder" ]
7613c0d9ae29affe9ab97527e4b6d5bef124afdc
https://github.com/django-blog-zinnia/cmsplugin-zinnia/blob/7613c0d9ae29affe9ab97527e4b6d5bef124afdc/cmsplugin_zinnia/admin.py#L22-L35
27,974
django-blog-zinnia/cmsplugin-zinnia
cmsplugin_zinnia/menu.py
EntryMenu.get_nodes
def get_nodes(self, request): """ Return menu's node for entries """ nodes = [] archives = [] attributes = {'hidden': HIDE_ENTRY_MENU} for entry in Entry.published.all(): year = entry.creation_date.strftime('%Y') month = entry.creation_date.strftime('%m') month_text = format(entry.creation_date, 'b').capitalize() day = entry.creation_date.strftime('%d') key_archive_year = 'year-%s' % year key_archive_month = 'month-%s-%s' % (year, month) key_archive_day = 'day-%s-%s-%s' % (year, month, day) if key_archive_year not in archives: nodes.append(NavigationNode( year, reverse('zinnia:entry_archive_year', args=[year]), key_archive_year, attr=attributes)) archives.append(key_archive_year) if key_archive_month not in archives: nodes.append(NavigationNode( month_text, reverse('zinnia:entry_archive_month', args=[year, month]), key_archive_month, key_archive_year, attr=attributes)) archives.append(key_archive_month) if key_archive_day not in archives: nodes.append(NavigationNode( day, reverse('zinnia:entry_archive_day', args=[year, month, day]), key_archive_day, key_archive_month, attr=attributes)) archives.append(key_archive_day) nodes.append(NavigationNode(entry.title, entry.get_absolute_url(), entry.pk, key_archive_day)) return nodes
python
def get_nodes(self, request): nodes = [] archives = [] attributes = {'hidden': HIDE_ENTRY_MENU} for entry in Entry.published.all(): year = entry.creation_date.strftime('%Y') month = entry.creation_date.strftime('%m') month_text = format(entry.creation_date, 'b').capitalize() day = entry.creation_date.strftime('%d') key_archive_year = 'year-%s' % year key_archive_month = 'month-%s-%s' % (year, month) key_archive_day = 'day-%s-%s-%s' % (year, month, day) if key_archive_year not in archives: nodes.append(NavigationNode( year, reverse('zinnia:entry_archive_year', args=[year]), key_archive_year, attr=attributes)) archives.append(key_archive_year) if key_archive_month not in archives: nodes.append(NavigationNode( month_text, reverse('zinnia:entry_archive_month', args=[year, month]), key_archive_month, key_archive_year, attr=attributes)) archives.append(key_archive_month) if key_archive_day not in archives: nodes.append(NavigationNode( day, reverse('zinnia:entry_archive_day', args=[year, month, day]), key_archive_day, key_archive_month, attr=attributes)) archives.append(key_archive_day) nodes.append(NavigationNode(entry.title, entry.get_absolute_url(), entry.pk, key_archive_day)) return nodes
[ "def", "get_nodes", "(", "self", ",", "request", ")", ":", "nodes", "=", "[", "]", "archives", "=", "[", "]", "attributes", "=", "{", "'hidden'", ":", "HIDE_ENTRY_MENU", "}", "for", "entry", "in", "Entry", ".", "published", ".", "all", "(", ")", ":",...
Return menu's node for entries
[ "Return", "menu", "s", "node", "for", "entries" ]
7613c0d9ae29affe9ab97527e4b6d5bef124afdc
https://github.com/django-blog-zinnia/cmsplugin-zinnia/blob/7613c0d9ae29affe9ab97527e4b6d5bef124afdc/cmsplugin_zinnia/menu.py#L26-L67
27,975
django-blog-zinnia/cmsplugin-zinnia
cmsplugin_zinnia/menu.py
CategoryMenu.get_nodes
def get_nodes(self, request): """ Return menu's node for categories """ nodes = [] nodes.append(NavigationNode(_('Categories'), reverse('zinnia:category_list'), 'categories')) for category in Category.objects.all(): nodes.append(NavigationNode(category.title, category.get_absolute_url(), category.pk, 'categories')) return nodes
python
def get_nodes(self, request): nodes = [] nodes.append(NavigationNode(_('Categories'), reverse('zinnia:category_list'), 'categories')) for category in Category.objects.all(): nodes.append(NavigationNode(category.title, category.get_absolute_url(), category.pk, 'categories')) return nodes
[ "def", "get_nodes", "(", "self", ",", "request", ")", ":", "nodes", "=", "[", "]", "nodes", ".", "append", "(", "NavigationNode", "(", "_", "(", "'Categories'", ")", ",", "reverse", "(", "'zinnia:category_list'", ")", ",", "'categories'", ")", ")", "for"...
Return menu's node for categories
[ "Return", "menu", "s", "node", "for", "categories" ]
7613c0d9ae29affe9ab97527e4b6d5bef124afdc
https://github.com/django-blog-zinnia/cmsplugin-zinnia/blob/7613c0d9ae29affe9ab97527e4b6d5bef124afdc/cmsplugin_zinnia/menu.py#L76-L88
27,976
django-blog-zinnia/cmsplugin-zinnia
cmsplugin_zinnia/menu.py
AuthorMenu.get_nodes
def get_nodes(self, request): """ Return menu's node for authors """ nodes = [] nodes.append(NavigationNode(_('Authors'), reverse('zinnia:author_list'), 'authors')) for author in Author.published.all(): nodes.append(NavigationNode(author.__str__(), author.get_absolute_url(), author.pk, 'authors')) return nodes
python
def get_nodes(self, request): nodes = [] nodes.append(NavigationNode(_('Authors'), reverse('zinnia:author_list'), 'authors')) for author in Author.published.all(): nodes.append(NavigationNode(author.__str__(), author.get_absolute_url(), author.pk, 'authors')) return nodes
[ "def", "get_nodes", "(", "self", ",", "request", ")", ":", "nodes", "=", "[", "]", "nodes", ".", "append", "(", "NavigationNode", "(", "_", "(", "'Authors'", ")", ",", "reverse", "(", "'zinnia:author_list'", ")", ",", "'authors'", ")", ")", "for", "aut...
Return menu's node for authors
[ "Return", "menu", "s", "node", "for", "authors" ]
7613c0d9ae29affe9ab97527e4b6d5bef124afdc
https://github.com/django-blog-zinnia/cmsplugin-zinnia/blob/7613c0d9ae29affe9ab97527e4b6d5bef124afdc/cmsplugin_zinnia/menu.py#L97-L109
27,977
django-blog-zinnia/cmsplugin-zinnia
cmsplugin_zinnia/menu.py
TagMenu.get_nodes
def get_nodes(self, request): """ Return menu's node for tags """ nodes = [] nodes.append(NavigationNode(_('Tags'), reverse('zinnia:tag_list'), 'tags')) for tag in tags_published(): nodes.append(NavigationNode(tag.name, reverse('zinnia:tag_detail', args=[tag.name]), tag.pk, 'tags')) return nodes
python
def get_nodes(self, request): nodes = [] nodes.append(NavigationNode(_('Tags'), reverse('zinnia:tag_list'), 'tags')) for tag in tags_published(): nodes.append(NavigationNode(tag.name, reverse('zinnia:tag_detail', args=[tag.name]), tag.pk, 'tags')) return nodes
[ "def", "get_nodes", "(", "self", ",", "request", ")", ":", "nodes", "=", "[", "]", "nodes", ".", "append", "(", "NavigationNode", "(", "_", "(", "'Tags'", ")", ",", "reverse", "(", "'zinnia:tag_list'", ")", ",", "'tags'", ")", ")", "for", "tag", "in"...
Return menu's node for tags
[ "Return", "menu", "s", "node", "for", "tags" ]
7613c0d9ae29affe9ab97527e4b6d5bef124afdc
https://github.com/django-blog-zinnia/cmsplugin-zinnia/blob/7613c0d9ae29affe9ab97527e4b6d5bef124afdc/cmsplugin_zinnia/menu.py#L118-L130
27,978
django-blog-zinnia/cmsplugin-zinnia
cmsplugin_zinnia/menu.py
EntryModifier.modify
def modify(self, request, nodes, namespace, root_id, post_cut, breadcrumb): """ Modify nodes of a menu """ if breadcrumb: return nodes for node in nodes: if node.attr.get('hidden'): node.visible = False return nodes
python
def modify(self, request, nodes, namespace, root_id, post_cut, breadcrumb): if breadcrumb: return nodes for node in nodes: if node.attr.get('hidden'): node.visible = False return nodes
[ "def", "modify", "(", "self", ",", "request", ",", "nodes", ",", "namespace", ",", "root_id", ",", "post_cut", ",", "breadcrumb", ")", ":", "if", "breadcrumb", ":", "return", "nodes", "for", "node", "in", "nodes", ":", "if", "node", ".", "attr", ".", ...
Modify nodes of a menu
[ "Modify", "nodes", "of", "a", "menu" ]
7613c0d9ae29affe9ab97527e4b6d5bef124afdc
https://github.com/django-blog-zinnia/cmsplugin-zinnia/blob/7613c0d9ae29affe9ab97527e4b6d5bef124afdc/cmsplugin_zinnia/menu.py#L140-L149
27,979
django-blog-zinnia/cmsplugin-zinnia
cmsplugin_zinnia/placeholder.py
PlaceholderEntry.acquire_context
def acquire_context(self): """ Inspect the stack to acquire the current context used, to render the placeholder. I'm really sorry for this, but if you have a better way, you are welcome ! """ frame = None request = None try: for f in inspect.stack()[1:]: frame = f[0] args, varargs, keywords, alocals = inspect.getargvalues(frame) if not request and 'request' in args: request = alocals['request'] if 'context' in args: return alocals['context'] finally: del frame return RequestContext(request)
python
def acquire_context(self): frame = None request = None try: for f in inspect.stack()[1:]: frame = f[0] args, varargs, keywords, alocals = inspect.getargvalues(frame) if not request and 'request' in args: request = alocals['request'] if 'context' in args: return alocals['context'] finally: del frame return RequestContext(request)
[ "def", "acquire_context", "(", "self", ")", ":", "frame", "=", "None", "request", "=", "None", "try", ":", "for", "f", "in", "inspect", ".", "stack", "(", ")", "[", "1", ":", "]", ":", "frame", "=", "f", "[", "0", "]", "args", ",", "varargs", "...
Inspect the stack to acquire the current context used, to render the placeholder. I'm really sorry for this, but if you have a better way, you are welcome !
[ "Inspect", "the", "stack", "to", "acquire", "the", "current", "context", "used", "to", "render", "the", "placeholder", ".", "I", "m", "really", "sorry", "for", "this", "but", "if", "you", "have", "a", "better", "way", "you", "are", "welcome", "!" ]
7613c0d9ae29affe9ab97527e4b6d5bef124afdc
https://github.com/django-blog-zinnia/cmsplugin-zinnia/blob/7613c0d9ae29affe9ab97527e4b6d5bef124afdc/cmsplugin_zinnia/placeholder.py#L20-L40
27,980
duointeractive/sea-cucumber
seacucumber/util.py
get_boto_ses_connection
def get_boto_ses_connection(): """ Shortcut for instantiating and returning a boto SESConnection object. :rtype: boto.ses.SESConnection :returns: A boto SESConnection object, from which email sending is done. """ access_key_id = getattr( settings, 'CUCUMBER_SES_ACCESS_KEY_ID', getattr(settings, 'AWS_ACCESS_KEY_ID', None)) access_key = getattr( settings, 'CUCUMBER_SES_SECRET_ACCESS_KEY', getattr(settings, 'AWS_SECRET_ACCESS_KEY', None)) region_name = getattr( settings, 'CUCUMBER_SES_REGION_NAME', getattr(settings, 'AWS_SES_REGION_NAME', None)) if region_name != None: return boto.ses.connect_to_region( region_name, aws_access_key_id=access_key_id, aws_secret_access_key=access_key, ) else: return boto.connect_ses( aws_access_key_id=access_key_id, aws_secret_access_key=access_key, )
python
def get_boto_ses_connection(): access_key_id = getattr( settings, 'CUCUMBER_SES_ACCESS_KEY_ID', getattr(settings, 'AWS_ACCESS_KEY_ID', None)) access_key = getattr( settings, 'CUCUMBER_SES_SECRET_ACCESS_KEY', getattr(settings, 'AWS_SECRET_ACCESS_KEY', None)) region_name = getattr( settings, 'CUCUMBER_SES_REGION_NAME', getattr(settings, 'AWS_SES_REGION_NAME', None)) if region_name != None: return boto.ses.connect_to_region( region_name, aws_access_key_id=access_key_id, aws_secret_access_key=access_key, ) else: return boto.connect_ses( aws_access_key_id=access_key_id, aws_secret_access_key=access_key, )
[ "def", "get_boto_ses_connection", "(", ")", ":", "access_key_id", "=", "getattr", "(", "settings", ",", "'CUCUMBER_SES_ACCESS_KEY_ID'", ",", "getattr", "(", "settings", ",", "'AWS_ACCESS_KEY_ID'", ",", "None", ")", ")", "access_key", "=", "getattr", "(", "settings...
Shortcut for instantiating and returning a boto SESConnection object. :rtype: boto.ses.SESConnection :returns: A boto SESConnection object, from which email sending is done.
[ "Shortcut", "for", "instantiating", "and", "returning", "a", "boto", "SESConnection", "object", "." ]
069637e2cbab561116e23b6723cfc30e779fce03
https://github.com/duointeractive/sea-cucumber/blob/069637e2cbab561116e23b6723cfc30e779fce03/seacucumber/util.py#L21-L49
27,981
duointeractive/sea-cucumber
seacucumber/tasks.py
SendEmailTask.run
def run(self, from_email, recipients, message): """ This does the dirty work. Connects to Amazon SES via boto and fires off the message. :param str from_email: The email address the message will show as originating from. :param list recipients: A list of email addresses to send the message to. :param str message: The body of the message. """ self._open_ses_conn() try: # We use the send_raw_email func here because the Django # EmailMessage object we got these values from constructs all of # the headers and such. self.connection.send_raw_email( source=from_email, destinations=recipients, raw_message=dkim_sign(message), ) except SESAddressBlacklistedError, exc: # Blacklisted users are those which delivery failed for in the # last 24 hours. They'll eventually be automatically removed from # the blacklist, but for now, this address is marked as # undeliverable to. logger.warning( 'Attempted to email a blacklisted user: %s' % recipients, exc_info=exc, extra={'trace': True} ) return False except SESDomainEndsWithDotError, exc: # Domains ending in a dot are simply invalid. logger.warning( 'Invalid recipient, ending in dot: %s' % recipients, exc_info=exc, extra={'trace': True} ) return False except SESLocalAddressCharacterError, exc: # Invalid character, usually in the sender "name". logger.warning( 'Local address contains control or whitespace: %s' % recipients, exc_info=exc, extra={'trace': True} ) return False except SESIllegalAddressError, exc: # A clearly mal-formed address. logger.warning( 'Illegal address: %s' % recipients, exc_info=exc, extra={'trace': True} ) return False except Exception, exc: # Something else happened that we haven't explicitly forbade # retry attempts for. #noinspection PyUnresolvedReferences logger.error( 'Something went wrong; retrying: %s' % recipients, exc_info=exc, extra={'trace': True} ) self.retry(exc=exc) else: logger.info('An email has been successfully sent: %s' % recipients) # We shouldn't ever block long enough to see this, but here it is # just in case (for debugging?). return True
python
def run(self, from_email, recipients, message): self._open_ses_conn() try: # We use the send_raw_email func here because the Django # EmailMessage object we got these values from constructs all of # the headers and such. self.connection.send_raw_email( source=from_email, destinations=recipients, raw_message=dkim_sign(message), ) except SESAddressBlacklistedError, exc: # Blacklisted users are those which delivery failed for in the # last 24 hours. They'll eventually be automatically removed from # the blacklist, but for now, this address is marked as # undeliverable to. logger.warning( 'Attempted to email a blacklisted user: %s' % recipients, exc_info=exc, extra={'trace': True} ) return False except SESDomainEndsWithDotError, exc: # Domains ending in a dot are simply invalid. logger.warning( 'Invalid recipient, ending in dot: %s' % recipients, exc_info=exc, extra={'trace': True} ) return False except SESLocalAddressCharacterError, exc: # Invalid character, usually in the sender "name". logger.warning( 'Local address contains control or whitespace: %s' % recipients, exc_info=exc, extra={'trace': True} ) return False except SESIllegalAddressError, exc: # A clearly mal-formed address. logger.warning( 'Illegal address: %s' % recipients, exc_info=exc, extra={'trace': True} ) return False except Exception, exc: # Something else happened that we haven't explicitly forbade # retry attempts for. #noinspection PyUnresolvedReferences logger.error( 'Something went wrong; retrying: %s' % recipients, exc_info=exc, extra={'trace': True} ) self.retry(exc=exc) else: logger.info('An email has been successfully sent: %s' % recipients) # We shouldn't ever block long enough to see this, but here it is # just in case (for debugging?). return True
[ "def", "run", "(", "self", ",", "from_email", ",", "recipients", ",", "message", ")", ":", "self", ".", "_open_ses_conn", "(", ")", "try", ":", "# We use the send_raw_email func here because the Django", "# EmailMessage object we got these values from constructs all of", "#...
This does the dirty work. Connects to Amazon SES via boto and fires off the message. :param str from_email: The email address the message will show as originating from. :param list recipients: A list of email addresses to send the message to. :param str message: The body of the message.
[ "This", "does", "the", "dirty", "work", ".", "Connects", "to", "Amazon", "SES", "via", "boto", "and", "fires", "off", "the", "message", "." ]
069637e2cbab561116e23b6723cfc30e779fce03
https://github.com/duointeractive/sea-cucumber/blob/069637e2cbab561116e23b6723cfc30e779fce03/seacucumber/tasks.py#L28-L99
27,982
duointeractive/sea-cucumber
seacucumber/management/commands/ses_usage.py
Command.handle
def handle(self, *args, **options): """ Renders the output by piecing together a few methods that do the dirty work. """ # AWS SES connection, which can be re-used for each query needed. conn = get_boto_ses_connection() self._print_quota(conn) self._print_daily_stats(conn)
python
def handle(self, *args, **options): # AWS SES connection, which can be re-used for each query needed. conn = get_boto_ses_connection() self._print_quota(conn) self._print_daily_stats(conn)
[ "def", "handle", "(", "self", ",", "*", "args", ",", "*", "*", "options", ")", ":", "# AWS SES connection, which can be re-used for each query needed.", "conn", "=", "get_boto_ses_connection", "(", ")", "self", ".", "_print_quota", "(", "conn", ")", "self", ".", ...
Renders the output by piecing together a few methods that do the dirty work.
[ "Renders", "the", "output", "by", "piecing", "together", "a", "few", "methods", "that", "do", "the", "dirty", "work", "." ]
069637e2cbab561116e23b6723cfc30e779fce03
https://github.com/duointeractive/sea-cucumber/blob/069637e2cbab561116e23b6723cfc30e779fce03/seacucumber/management/commands/ses_usage.py#L14-L22
27,983
duointeractive/sea-cucumber
seacucumber/management/commands/ses_usage.py
Command._print_quota
def _print_quota(self, conn): """ Prints some basic quota statistics. """ quota = conn.get_send_quota() quota = quota['GetSendQuotaResponse']['GetSendQuotaResult'] print "--- SES Quota ---" print " 24 Hour Quota: %s" % quota['Max24HourSend'] print " Sent (Last 24 hours): %s" % quota['SentLast24Hours'] print " Max sending rate: %s/sec" % quota['MaxSendRate']
python
def _print_quota(self, conn): quota = conn.get_send_quota() quota = quota['GetSendQuotaResponse']['GetSendQuotaResult'] print "--- SES Quota ---" print " 24 Hour Quota: %s" % quota['Max24HourSend'] print " Sent (Last 24 hours): %s" % quota['SentLast24Hours'] print " Max sending rate: %s/sec" % quota['MaxSendRate']
[ "def", "_print_quota", "(", "self", ",", "conn", ")", ":", "quota", "=", "conn", ".", "get_send_quota", "(", ")", "quota", "=", "quota", "[", "'GetSendQuotaResponse'", "]", "[", "'GetSendQuotaResult'", "]", "print", "\"--- SES Quota ---\"", "print", "\" 24 Hour...
Prints some basic quota statistics.
[ "Prints", "some", "basic", "quota", "statistics", "." ]
069637e2cbab561116e23b6723cfc30e779fce03
https://github.com/duointeractive/sea-cucumber/blob/069637e2cbab561116e23b6723cfc30e779fce03/seacucumber/management/commands/ses_usage.py#L24-L34
27,984
dwavesystems/dwave-tabu
tabu/sampler.py
TabuSampler.sample
def sample(self, bqm, init_solution=None, tenure=None, scale_factor=1, timeout=20, num_reads=1): """Run a tabu search on a given binary quadratic model. Args: bqm (:obj:`~dimod.BinaryQuadraticModel`): The binary quadratic model (BQM) to be sampled. init_solution (:obj:`~dimod.SampleSet`, optional): Single sample that sets an initial state for all the problem variables. Default is a random initial state. tenure (int, optional): Tabu tenure, which is the length of the tabu list, or number of recently explored solutions kept in memory. Default is a quarter of the number of problem variables up to a maximum value of 20. scale_factor (number, optional): Scaling factor for linear and quadratic biases in the BQM. Internally, the BQM is converted to a QUBO matrix, and elements are stored as long ints using ``internal_q = long int (q * scale_factor)``. timeout (int, optional): Total running time in milliseconds. num_reads (int, optional): Number of reads. Each run of the tabu algorithm generates a sample. Returns: :obj:`~dimod.SampleSet`: A `dimod` :obj:`.~dimod.SampleSet` object. Examples: This example provides samples for a two-variable QUBO model. >>> from tabu import TabuSampler >>> import dimod >>> sampler = TabuSampler() >>> Q = {(0, 0): -1, (1, 1): -1, (0, 1): 2} >>> bqm = dimod.BinaryQuadraticModel.from_qubo(Q, offset=0.0) >>> samples = sampler.sample(bqm) >>> samples.record[0].energy -1.0 """ # input checking and defaults calculation # TODO: one "read" per sample in init_solution sampleset if init_solution is not None: if not isinstance(init_solution, dimod.SampleSet): raise TypeError("'init_solution' should be a 'dimod.SampleSet' instance") if len(init_solution.record) < 1: raise ValueError("'init_solution' should contain at least one sample") if len(init_solution.record[0].sample) != len(bqm): raise ValueError("'init_solution' sample dimension different from BQM") init_sample = self._bqm_sample_to_tabu_sample( init_solution.change_vartype(dimod.BINARY, inplace=False).record[0].sample, bqm.binary) else: init_sample = None if not bqm: return dimod.SampleSet.from_samples([], energy=0, vartype=bqm.vartype) if tenure is None: tenure = max(min(20, len(bqm) // 4), 0) if not isinstance(tenure, int): raise TypeError("'tenure' should be an integer in range [0, num_vars - 1]") if not 0 <= tenure < len(bqm): raise ValueError("'tenure' should be an integer in range [0, num_vars - 1]") if not isinstance(num_reads, int): raise TypeError("'num_reads' should be a positive integer") if num_reads < 1: raise ValueError("'num_reads' should be a positive integer") qubo = self._bqm_to_tabu_qubo(bqm.binary) # run Tabu search samples = [] energies = [] for _ in range(num_reads): if init_sample is None: init_sample = self._bqm_sample_to_tabu_sample(self._random_sample(bqm.binary), bqm.binary) r = TabuSearch(qubo, init_sample, tenure, scale_factor, timeout) sample = self._tabu_sample_to_bqm_sample(list(r.bestSolution()), bqm.binary) energy = bqm.binary.energy(sample) samples.append(sample) energies.append(energy) response = dimod.SampleSet.from_samples( samples, energy=energies, vartype=dimod.BINARY) response.change_vartype(bqm.vartype, inplace=True) return response
python
def sample(self, bqm, init_solution=None, tenure=None, scale_factor=1, timeout=20, num_reads=1): # input checking and defaults calculation # TODO: one "read" per sample in init_solution sampleset if init_solution is not None: if not isinstance(init_solution, dimod.SampleSet): raise TypeError("'init_solution' should be a 'dimod.SampleSet' instance") if len(init_solution.record) < 1: raise ValueError("'init_solution' should contain at least one sample") if len(init_solution.record[0].sample) != len(bqm): raise ValueError("'init_solution' sample dimension different from BQM") init_sample = self._bqm_sample_to_tabu_sample( init_solution.change_vartype(dimod.BINARY, inplace=False).record[0].sample, bqm.binary) else: init_sample = None if not bqm: return dimod.SampleSet.from_samples([], energy=0, vartype=bqm.vartype) if tenure is None: tenure = max(min(20, len(bqm) // 4), 0) if not isinstance(tenure, int): raise TypeError("'tenure' should be an integer in range [0, num_vars - 1]") if not 0 <= tenure < len(bqm): raise ValueError("'tenure' should be an integer in range [0, num_vars - 1]") if not isinstance(num_reads, int): raise TypeError("'num_reads' should be a positive integer") if num_reads < 1: raise ValueError("'num_reads' should be a positive integer") qubo = self._bqm_to_tabu_qubo(bqm.binary) # run Tabu search samples = [] energies = [] for _ in range(num_reads): if init_sample is None: init_sample = self._bqm_sample_to_tabu_sample(self._random_sample(bqm.binary), bqm.binary) r = TabuSearch(qubo, init_sample, tenure, scale_factor, timeout) sample = self._tabu_sample_to_bqm_sample(list(r.bestSolution()), bqm.binary) energy = bqm.binary.energy(sample) samples.append(sample) energies.append(energy) response = dimod.SampleSet.from_samples( samples, energy=energies, vartype=dimod.BINARY) response.change_vartype(bqm.vartype, inplace=True) return response
[ "def", "sample", "(", "self", ",", "bqm", ",", "init_solution", "=", "None", ",", "tenure", "=", "None", ",", "scale_factor", "=", "1", ",", "timeout", "=", "20", ",", "num_reads", "=", "1", ")", ":", "# input checking and defaults calculation", "# TODO: one...
Run a tabu search on a given binary quadratic model. Args: bqm (:obj:`~dimod.BinaryQuadraticModel`): The binary quadratic model (BQM) to be sampled. init_solution (:obj:`~dimod.SampleSet`, optional): Single sample that sets an initial state for all the problem variables. Default is a random initial state. tenure (int, optional): Tabu tenure, which is the length of the tabu list, or number of recently explored solutions kept in memory. Default is a quarter of the number of problem variables up to a maximum value of 20. scale_factor (number, optional): Scaling factor for linear and quadratic biases in the BQM. Internally, the BQM is converted to a QUBO matrix, and elements are stored as long ints using ``internal_q = long int (q * scale_factor)``. timeout (int, optional): Total running time in milliseconds. num_reads (int, optional): Number of reads. Each run of the tabu algorithm generates a sample. Returns: :obj:`~dimod.SampleSet`: A `dimod` :obj:`.~dimod.SampleSet` object. Examples: This example provides samples for a two-variable QUBO model. >>> from tabu import TabuSampler >>> import dimod >>> sampler = TabuSampler() >>> Q = {(0, 0): -1, (1, 1): -1, (0, 1): 2} >>> bqm = dimod.BinaryQuadraticModel.from_qubo(Q, offset=0.0) >>> samples = sampler.sample(bqm) >>> samples.record[0].energy -1.0
[ "Run", "a", "tabu", "search", "on", "a", "given", "binary", "quadratic", "model", "." ]
3397479343426a1e20ebf5b90593043904433eea
https://github.com/dwavesystems/dwave-tabu/blob/3397479343426a1e20ebf5b90593043904433eea/tabu/sampler.py#L53-L139
27,985
ankeshanand/py-gfycat
gfycat/client.py
GfycatClient.upload_from_url
def upload_from_url(self, url): """ Upload a GIF from a URL. """ self.check_token() params = {'fetchUrl': url} r = requests.get(FETCH_URL_ENDPOINT, params=params) if r.status_code != 200: raise GfycatClientError('Error fetching the URL', r.status_code) response = r.json() if 'error' in response: raise GfycatClientError(response['error']) return response
python
def upload_from_url(self, url): self.check_token() params = {'fetchUrl': url} r = requests.get(FETCH_URL_ENDPOINT, params=params) if r.status_code != 200: raise GfycatClientError('Error fetching the URL', r.status_code) response = r.json() if 'error' in response: raise GfycatClientError(response['error']) return response
[ "def", "upload_from_url", "(", "self", ",", "url", ")", ":", "self", ".", "check_token", "(", ")", "params", "=", "{", "'fetchUrl'", ":", "url", "}", "r", "=", "requests", ".", "get", "(", "FETCH_URL_ENDPOINT", ",", "params", "=", "params", ")", "if", ...
Upload a GIF from a URL.
[ "Upload", "a", "GIF", "from", "a", "URL", "." ]
74759a88fc59db1c5b270331b24442bc5f4c38e9
https://github.com/ankeshanand/py-gfycat/blob/74759a88fc59db1c5b270331b24442bc5f4c38e9/gfycat/client.py#L23-L39
27,986
ankeshanand/py-gfycat
gfycat/client.py
GfycatClient.upload_from_file
def upload_from_file(self, filename): """ Upload a local file to Gfycat """ key = str(uuid.uuid4())[:8] form = [('key', key), ('acl', ACL), ('AWSAccessKeyId', AWS_ACCESS_KEY_ID), ('success_action_status', SUCCESS_ACTION_STATUS), ('signature', SIGNATURE), ('Content-Type', CONTENT_TYPE), ('policy', POLICY)] data = dict(form) files = {'file': open(filename, 'rb')} r = requests.post(FILE_UPLOAD_ENDPOINT, data=data, files=files) if r.status_code != 200: raise GfycatClientError('Error uploading the GIF', r.status_code) info = self.uploaded_file_info(key) while 'timeout' in info.get('error', '').lower(): time.sleep(2) info = self.uploaded_file_info(key) if 'error' in info: raise GfycatClientError(info['error']) return info
python
def upload_from_file(self, filename): key = str(uuid.uuid4())[:8] form = [('key', key), ('acl', ACL), ('AWSAccessKeyId', AWS_ACCESS_KEY_ID), ('success_action_status', SUCCESS_ACTION_STATUS), ('signature', SIGNATURE), ('Content-Type', CONTENT_TYPE), ('policy', POLICY)] data = dict(form) files = {'file': open(filename, 'rb')} r = requests.post(FILE_UPLOAD_ENDPOINT, data=data, files=files) if r.status_code != 200: raise GfycatClientError('Error uploading the GIF', r.status_code) info = self.uploaded_file_info(key) while 'timeout' in info.get('error', '').lower(): time.sleep(2) info = self.uploaded_file_info(key) if 'error' in info: raise GfycatClientError(info['error']) return info
[ "def", "upload_from_file", "(", "self", ",", "filename", ")", ":", "key", "=", "str", "(", "uuid", ".", "uuid4", "(", ")", ")", "[", ":", "8", "]", "form", "=", "[", "(", "'key'", ",", "key", ")", ",", "(", "'acl'", ",", "ACL", ")", ",", "(",...
Upload a local file to Gfycat
[ "Upload", "a", "local", "file", "to", "Gfycat" ]
74759a88fc59db1c5b270331b24442bc5f4c38e9
https://github.com/ankeshanand/py-gfycat/blob/74759a88fc59db1c5b270331b24442bc5f4c38e9/gfycat/client.py#L41-L69
27,987
ankeshanand/py-gfycat
gfycat/client.py
GfycatClient.uploaded_file_info
def uploaded_file_info(self, key): """ Get information about an uploaded GIF. """ r = requests.get(FILE_UPLOAD_STATUS_ENDPOINT + key) if r.status_code != 200: raise GfycatClientError('Unable to check the status', r.status_code) return r.json()
python
def uploaded_file_info(self, key): r = requests.get(FILE_UPLOAD_STATUS_ENDPOINT + key) if r.status_code != 200: raise GfycatClientError('Unable to check the status', r.status_code) return r.json()
[ "def", "uploaded_file_info", "(", "self", ",", "key", ")", ":", "r", "=", "requests", ".", "get", "(", "FILE_UPLOAD_STATUS_ENDPOINT", "+", "key", ")", "if", "r", ".", "status_code", "!=", "200", ":", "raise", "GfycatClientError", "(", "'Unable to check the sta...
Get information about an uploaded GIF.
[ "Get", "information", "about", "an", "uploaded", "GIF", "." ]
74759a88fc59db1c5b270331b24442bc5f4c38e9
https://github.com/ankeshanand/py-gfycat/blob/74759a88fc59db1c5b270331b24442bc5f4c38e9/gfycat/client.py#L71-L80
27,988
ankeshanand/py-gfycat
gfycat/client.py
GfycatClient.query_gfy
def query_gfy(self, gfyname): """ Query a gfy name for URLs and more information. """ self.check_token() r = requests.get(QUERY_ENDPOINT + gfyname, headers=self.headers) response = r.json() if r.status_code != 200 and not ERROR_KEY in response: raise GfycatClientError('Bad response from Gfycat', r.status_code) elif ERROR_KEY in response: raise GfycatClientError(response[ERROR_KEY], r.status_code) return response
python
def query_gfy(self, gfyname): self.check_token() r = requests.get(QUERY_ENDPOINT + gfyname, headers=self.headers) response = r.json() if r.status_code != 200 and not ERROR_KEY in response: raise GfycatClientError('Bad response from Gfycat', r.status_code) elif ERROR_KEY in response: raise GfycatClientError(response[ERROR_KEY], r.status_code) return response
[ "def", "query_gfy", "(", "self", ",", "gfyname", ")", ":", "self", ".", "check_token", "(", ")", "r", "=", "requests", ".", "get", "(", "QUERY_ENDPOINT", "+", "gfyname", ",", "headers", "=", "self", ".", "headers", ")", "response", "=", "r", ".", "js...
Query a gfy name for URLs and more information.
[ "Query", "a", "gfy", "name", "for", "URLs", "and", "more", "information", "." ]
74759a88fc59db1c5b270331b24442bc5f4c38e9
https://github.com/ankeshanand/py-gfycat/blob/74759a88fc59db1c5b270331b24442bc5f4c38e9/gfycat/client.py#L82-L98
27,989
ankeshanand/py-gfycat
gfycat/client.py
GfycatClient.check_link
def check_link(self, link): """ Check if a link has been already converted. """ r = requests.get(CHECK_LINK_ENDPOINT + link) if r.status_code != 200: raise GfycatClientError('Unable to check the link', r.status_code) return r.json()
python
def check_link(self, link): r = requests.get(CHECK_LINK_ENDPOINT + link) if r.status_code != 200: raise GfycatClientError('Unable to check the link', r.status_code) return r.json()
[ "def", "check_link", "(", "self", ",", "link", ")", ":", "r", "=", "requests", ".", "get", "(", "CHECK_LINK_ENDPOINT", "+", "link", ")", "if", "r", ".", "status_code", "!=", "200", ":", "raise", "GfycatClientError", "(", "'Unable to check the link'", ",", ...
Check if a link has been already converted.
[ "Check", "if", "a", "link", "has", "been", "already", "converted", "." ]
74759a88fc59db1c5b270331b24442bc5f4c38e9
https://github.com/ankeshanand/py-gfycat/blob/74759a88fc59db1c5b270331b24442bc5f4c38e9/gfycat/client.py#L100-L109
27,990
ankeshanand/py-gfycat
gfycat/client.py
GfycatClient.get_token
def get_token(self): """ Gets the authorization token """ payload = {'grant_type': 'client_credentials', 'client_id': self.client_id, 'client_secret': self.client_secret} r = requests.post(OAUTH_ENDPOINT, data=json.dumps(payload), headers={'content-type': 'application/json'}) response = r.json() if r.status_code != 200 and not ERROR_KEY in response: raise GfycatClientError('Error fetching the OAUTH URL', r.status_code) elif ERROR_KEY in response: raise GfycatClientError(response[ERROR_KEY], r.status_code) self.token_type = response['token_type'] self.access_token = response['access_token'] self.expires_in = response['expires_in'] self.expires_at = time.time() + self.expires_in - 5 self.headers = {'content-type': 'application/json','Authorization': self.token_type + ' ' + self.access_token}
python
def get_token(self): payload = {'grant_type': 'client_credentials', 'client_id': self.client_id, 'client_secret': self.client_secret} r = requests.post(OAUTH_ENDPOINT, data=json.dumps(payload), headers={'content-type': 'application/json'}) response = r.json() if r.status_code != 200 and not ERROR_KEY in response: raise GfycatClientError('Error fetching the OAUTH URL', r.status_code) elif ERROR_KEY in response: raise GfycatClientError(response[ERROR_KEY], r.status_code) self.token_type = response['token_type'] self.access_token = response['access_token'] self.expires_in = response['expires_in'] self.expires_at = time.time() + self.expires_in - 5 self.headers = {'content-type': 'application/json','Authorization': self.token_type + ' ' + self.access_token}
[ "def", "get_token", "(", "self", ")", ":", "payload", "=", "{", "'grant_type'", ":", "'client_credentials'", ",", "'client_id'", ":", "self", ".", "client_id", ",", "'client_secret'", ":", "self", ".", "client_secret", "}", "r", "=", "requests", ".", "post",...
Gets the authorization token
[ "Gets", "the", "authorization", "token" ]
74759a88fc59db1c5b270331b24442bc5f4c38e9
https://github.com/ankeshanand/py-gfycat/blob/74759a88fc59db1c5b270331b24442bc5f4c38e9/gfycat/client.py#L118-L137
27,991
inasafe/inasafe
safe/metadata/base_metadata.py
BaseMetadata.dict
def dict(self): """ dictionary representation of the metadata. :return: dictionary representation of the metadata :rtype: dict """ metadata = {} properties = {} for name, prop in list(self.properties.items()): properties[name] = prop.dict metadata['properties'] = properties return metadata
python
def dict(self): metadata = {} properties = {} for name, prop in list(self.properties.items()): properties[name] = prop.dict metadata['properties'] = properties return metadata
[ "def", "dict", "(", "self", ")", ":", "metadata", "=", "{", "}", "properties", "=", "{", "}", "for", "name", ",", "prop", "in", "list", "(", "self", ".", "properties", ".", "items", "(", ")", ")", ":", "properties", "[", "name", "]", "=", "prop",...
dictionary representation of the metadata. :return: dictionary representation of the metadata :rtype: dict
[ "dictionary", "representation", "of", "the", "metadata", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/metadata/base_metadata.py#L251-L263
27,992
inasafe/inasafe
safe/metadata/base_metadata.py
BaseMetadata.json
def json(self): """ json representation of the metadata. :return: json representation of the metadata :rtype: str """ json_dumps = json.dumps( self.dict, indent=2, sort_keys=True, separators=(',', ': '), cls=MetadataEncoder ) if not json_dumps.endswith('\n'): json_dumps += '\n' return json_dumps
python
def json(self): json_dumps = json.dumps( self.dict, indent=2, sort_keys=True, separators=(',', ': '), cls=MetadataEncoder ) if not json_dumps.endswith('\n'): json_dumps += '\n' return json_dumps
[ "def", "json", "(", "self", ")", ":", "json_dumps", "=", "json", ".", "dumps", "(", "self", ".", "dict", ",", "indent", "=", "2", ",", "sort_keys", "=", "True", ",", "separators", "=", "(", "','", ",", "': '", ")", ",", "cls", "=", "MetadataEncoder...
json representation of the metadata. :return: json representation of the metadata :rtype: str
[ "json", "representation", "of", "the", "metadata", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/metadata/base_metadata.py#L287-L303
27,993
inasafe/inasafe
safe/metadata/base_metadata.py
BaseMetadata._read_json_file
def _read_json_file(self): """ read metadata from a json file. :return: the parsed json dict :rtype: dict """ with open(self.json_uri) as metadata_file: try: metadata = json.load(metadata_file) return metadata except ValueError: message = tr('the file %s does not appear to be valid JSON') message = message % self.json_uri raise MetadataReadError(message)
python
def _read_json_file(self): with open(self.json_uri) as metadata_file: try: metadata = json.load(metadata_file) return metadata except ValueError: message = tr('the file %s does not appear to be valid JSON') message = message % self.json_uri raise MetadataReadError(message)
[ "def", "_read_json_file", "(", "self", ")", ":", "with", "open", "(", "self", ".", "json_uri", ")", "as", "metadata_file", ":", "try", ":", "metadata", "=", "json", ".", "load", "(", "metadata_file", ")", "return", "metadata", "except", "ValueError", ":", ...
read metadata from a json file. :return: the parsed json dict :rtype: dict
[ "read", "metadata", "from", "a", "json", "file", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/metadata/base_metadata.py#L330-L344
27,994
inasafe/inasafe
safe/metadata/base_metadata.py
BaseMetadata._read_json_db
def _read_json_db(self): """ read metadata from a json string stored in a DB. :return: the parsed json dict :rtype: dict """ try: metadata_str = self.db_io.read_metadata_from_uri( self.layer_uri, 'json') except HashNotFoundError: return {} try: metadata = json.loads(metadata_str) return metadata except ValueError: message = tr('the file DB entry for %s does not appear to be ' 'valid JSON') message %= self.layer_uri raise MetadataReadError(message)
python
def _read_json_db(self): try: metadata_str = self.db_io.read_metadata_from_uri( self.layer_uri, 'json') except HashNotFoundError: return {} try: metadata = json.loads(metadata_str) return metadata except ValueError: message = tr('the file DB entry for %s does not appear to be ' 'valid JSON') message %= self.layer_uri raise MetadataReadError(message)
[ "def", "_read_json_db", "(", "self", ")", ":", "try", ":", "metadata_str", "=", "self", ".", "db_io", ".", "read_metadata_from_uri", "(", "self", ".", "layer_uri", ",", "'json'", ")", "except", "HashNotFoundError", ":", "return", "{", "}", "try", ":", "met...
read metadata from a json string stored in a DB. :return: the parsed json dict :rtype: dict
[ "read", "metadata", "from", "a", "json", "string", "stored", "in", "a", "DB", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/metadata/base_metadata.py#L346-L365
27,995
inasafe/inasafe
safe/metadata/base_metadata.py
BaseMetadata._read_xml_file
def _read_xml_file(self): """ read metadata from an xml file. :return: the root element of the xml :rtype: ElementTree.Element """ # this raises a IOError if the file doesn't exist root = ElementTree.parse(self.xml_uri) root.getroot() return root
python
def _read_xml_file(self): # this raises a IOError if the file doesn't exist root = ElementTree.parse(self.xml_uri) root.getroot() return root
[ "def", "_read_xml_file", "(", "self", ")", ":", "# this raises a IOError if the file doesn't exist", "root", "=", "ElementTree", ".", "parse", "(", "self", ".", "xml_uri", ")", "root", ".", "getroot", "(", ")", "return", "root" ]
read metadata from an xml file. :return: the root element of the xml :rtype: ElementTree.Element
[ "read", "metadata", "from", "an", "xml", "file", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/metadata/base_metadata.py#L388-L398
27,996
inasafe/inasafe
safe/metadata/base_metadata.py
BaseMetadata._read_xml_db
def _read_xml_db(self): """ read metadata from an xml string stored in a DB. :return: the root element of the xml :rtype: ElementTree.Element """ try: metadata_str = self.db_io.read_metadata_from_uri( self.layer_uri, 'xml') root = ElementTree.fromstring(metadata_str) return root except HashNotFoundError: return None
python
def _read_xml_db(self): try: metadata_str = self.db_io.read_metadata_from_uri( self.layer_uri, 'xml') root = ElementTree.fromstring(metadata_str) return root except HashNotFoundError: return None
[ "def", "_read_xml_db", "(", "self", ")", ":", "try", ":", "metadata_str", "=", "self", ".", "db_io", ".", "read_metadata_from_uri", "(", "self", ".", "layer_uri", ",", "'xml'", ")", "root", "=", "ElementTree", ".", "fromstring", "(", "metadata_str", ")", "...
read metadata from an xml string stored in a DB. :return: the root element of the xml :rtype: ElementTree.Element
[ "read", "metadata", "from", "an", "xml", "string", "stored", "in", "a", "DB", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/metadata/base_metadata.py#L400-L413
27,997
inasafe/inasafe
safe/metadata/base_metadata.py
BaseMetadata.set
def set(self, name, value, xml_path): """ Create a new metadata property. The accepted type depends on the property type which is determined by the xml_path :param name: the name of the property :type name: str :param value: the value of the property :type value: :param xml_path: the xml path where the property should be stored. This is split on / and the last element is used to determine the property type :type xml_path: str """ xml_type = xml_path.split('/')[-1] # check if the desired type is supported try: property_class = TYPE_CONVERSIONS[xml_type] except KeyError: raise KeyError('The xml type %s is not supported yet' % xml_type) try: metadata_property = property_class(name, value, xml_path) self._properties[name] = metadata_property self.set_last_update_to_now() except TypeError: if self.reading_ancillary_files: # we are parsing files so we want to accept as much as # possible without raising exceptions pass else: raise
python
def set(self, name, value, xml_path): xml_type = xml_path.split('/')[-1] # check if the desired type is supported try: property_class = TYPE_CONVERSIONS[xml_type] except KeyError: raise KeyError('The xml type %s is not supported yet' % xml_type) try: metadata_property = property_class(name, value, xml_path) self._properties[name] = metadata_property self.set_last_update_to_now() except TypeError: if self.reading_ancillary_files: # we are parsing files so we want to accept as much as # possible without raising exceptions pass else: raise
[ "def", "set", "(", "self", ",", "name", ",", "value", ",", "xml_path", ")", ":", "xml_type", "=", "xml_path", ".", "split", "(", "'/'", ")", "[", "-", "1", "]", "# check if the desired type is supported", "try", ":", "property_class", "=", "TYPE_CONVERSIONS"...
Create a new metadata property. The accepted type depends on the property type which is determined by the xml_path :param name: the name of the property :type name: str :param value: the value of the property :type value: :param xml_path: the xml path where the property should be stored. This is split on / and the last element is used to determine the property type :type xml_path: str
[ "Create", "a", "new", "metadata", "property", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/metadata/base_metadata.py#L531-L565
27,998
inasafe/inasafe
safe/metadata/base_metadata.py
BaseMetadata.write_to_file
def write_to_file(self, destination_path): """ Writes the metadata json or xml to a file. :param destination_path: the file path the file format is inferred from the destination_path extension. :type destination_path: str :return: the written metadata :rtype: str """ file_format = os.path.splitext(destination_path)[1][1:] metadata = self.get_writable_metadata(file_format) with open(destination_path, 'w', encoding='utf-8') as f: f.write(metadata) return metadata
python
def write_to_file(self, destination_path): file_format = os.path.splitext(destination_path)[1][1:] metadata = self.get_writable_metadata(file_format) with open(destination_path, 'w', encoding='utf-8') as f: f.write(metadata) return metadata
[ "def", "write_to_file", "(", "self", ",", "destination_path", ")", ":", "file_format", "=", "os", ".", "path", ".", "splitext", "(", "destination_path", ")", "[", "1", "]", "[", "1", ":", "]", "metadata", "=", "self", ".", "get_writable_metadata", "(", "...
Writes the metadata json or xml to a file. :param destination_path: the file path the file format is inferred from the destination_path extension. :type destination_path: str :return: the written metadata :rtype: str
[ "Writes", "the", "metadata", "json", "or", "xml", "to", "a", "file", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/metadata/base_metadata.py#L584-L600
27,999
inasafe/inasafe
safe/metadata/base_metadata.py
BaseMetadata.get_writable_metadata
def get_writable_metadata(self, file_format): """ Convert the metadata to a writable form. :param file_format: the needed format can be json or xml :type file_format: str :return: the dupled metadata :rtype: str """ if file_format == 'json': metadata = self.json elif file_format == 'xml': metadata = self.xml else: raise TypeError('The requested file type (%s) is not yet supported' % file_format) return metadata
python
def get_writable_metadata(self, file_format): if file_format == 'json': metadata = self.json elif file_format == 'xml': metadata = self.xml else: raise TypeError('The requested file type (%s) is not yet supported' % file_format) return metadata
[ "def", "get_writable_metadata", "(", "self", ",", "file_format", ")", ":", "if", "file_format", "==", "'json'", ":", "metadata", "=", "self", ".", "json", "elif", "file_format", "==", "'xml'", ":", "metadata", "=", "self", ".", "xml", "else", ":", "raise",...
Convert the metadata to a writable form. :param file_format: the needed format can be json or xml :type file_format: str :return: the dupled metadata :rtype: str
[ "Convert", "the", "metadata", "to", "a", "writable", "form", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/metadata/base_metadata.py#L625-L641