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
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
src-d/modelforge
modelforge/backends.py
register_backend
def register_backend(cls: Type[StorageBackend]): """Decorator to register another StorageBackend using it's `NAME`.""" if not issubclass(cls, StorageBackend): raise TypeError("cls must be a subclass of StorageBackend") __registry__[cls.NAME] = cls return cls
python
def register_backend(cls: Type[StorageBackend]): """Decorator to register another StorageBackend using it's `NAME`.""" if not issubclass(cls, StorageBackend): raise TypeError("cls must be a subclass of StorageBackend") __registry__[cls.NAME] = cls return cls
[ "def", "register_backend", "(", "cls", ":", "Type", "[", "StorageBackend", "]", ")", ":", "if", "not", "issubclass", "(", "cls", ",", "StorageBackend", ")", ":", "raise", "TypeError", "(", "\"cls must be a subclass of StorageBackend\"", ")", "__registry__", "[", ...
Decorator to register another StorageBackend using it's `NAME`.
[ "Decorator", "to", "register", "another", "StorageBackend", "using", "it", "s", "NAME", "." ]
4f73c2bf0318261ac01bc8b6c0d4250a5d303418
https://github.com/src-d/modelforge/blob/4f73c2bf0318261ac01bc8b6c0d4250a5d303418/modelforge/backends.py#L13-L18
train
26,400
src-d/modelforge
modelforge/backends.py
create_backend
def create_backend(name: str=None, git_index: GitIndex=None, args: str=None) -> StorageBackend: """Initialize a new StorageBackend by it's name and the specified model registry.""" if name is None: name = config.BACKEND if not args: args = config.BACKEND_ARGS if args: try: ...
python
def create_backend(name: str=None, git_index: GitIndex=None, args: str=None) -> StorageBackend: """Initialize a new StorageBackend by it's name and the specified model registry.""" if name is None: name = config.BACKEND if not args: args = config.BACKEND_ARGS if args: try: ...
[ "def", "create_backend", "(", "name", ":", "str", "=", "None", ",", "git_index", ":", "GitIndex", "=", "None", ",", "args", ":", "str", "=", "None", ")", "->", "StorageBackend", ":", "if", "name", "is", "None", ":", "name", "=", "config", ".", "BACKE...
Initialize a new StorageBackend by it's name and the specified model registry.
[ "Initialize", "a", "new", "StorageBackend", "by", "it", "s", "name", "and", "the", "specified", "model", "registry", "." ]
4f73c2bf0318261ac01bc8b6c0d4250a5d303418
https://github.com/src-d/modelforge/blob/4f73c2bf0318261ac01bc8b6c0d4250a5d303418/modelforge/backends.py#L21-L37
train
26,401
src-d/modelforge
modelforge/backends.py
create_backend_noexc
def create_backend_noexc(log: logging.Logger, name: str=None, git_index: GitIndex=None, args: str=None) -> Optional[StorageBackend]: """Initialize a new Backend, return None if there was a known problem.""" try: return create_backend(name, git_index, args) except KeyError: ...
python
def create_backend_noexc(log: logging.Logger, name: str=None, git_index: GitIndex=None, args: str=None) -> Optional[StorageBackend]: """Initialize a new Backend, return None if there was a known problem.""" try: return create_backend(name, git_index, args) except KeyError: ...
[ "def", "create_backend_noexc", "(", "log", ":", "logging", ".", "Logger", ",", "name", ":", "str", "=", "None", ",", "git_index", ":", "GitIndex", "=", "None", ",", "args", ":", "str", "=", "None", ")", "->", "Optional", "[", "StorageBackend", "]", ":"...
Initialize a new Backend, return None if there was a known problem.
[ "Initialize", "a", "new", "Backend", "return", "None", "if", "there", "was", "a", "known", "problem", "." ]
4f73c2bf0318261ac01bc8b6c0d4250a5d303418
https://github.com/src-d/modelforge/blob/4f73c2bf0318261ac01bc8b6c0d4250a5d303418/modelforge/backends.py#L40-L51
train
26,402
src-d/modelforge
modelforge/backends.py
supply_backend
def supply_backend(optional: Union[callable, bool]=False, index_exists: bool=True): """ Decorator to pass the initialized backend to the decorated callable. \ Used by command line entries. If the backend cannot be created, return 1. :param optional: Either a decorated function or a value which indicate...
python
def supply_backend(optional: Union[callable, bool]=False, index_exists: bool=True): """ Decorator to pass the initialized backend to the decorated callable. \ Used by command line entries. If the backend cannot be created, return 1. :param optional: Either a decorated function or a value which indicate...
[ "def", "supply_backend", "(", "optional", ":", "Union", "[", "callable", ",", "bool", "]", "=", "False", ",", "index_exists", ":", "bool", "=", "True", ")", ":", "real_optional", "=", "False", "if", "callable", "(", "optional", ")", "else", "optional", "...
Decorator to pass the initialized backend to the decorated callable. \ Used by command line entries. If the backend cannot be created, return 1. :param optional: Either a decorated function or a value which indicates whether we should \ construct the backend object if it does not exist in ...
[ "Decorator", "to", "pass", "the", "initialized", "backend", "to", "the", "decorated", "callable", ".", "\\", "Used", "by", "command", "line", "entries", ".", "If", "the", "backend", "cannot", "be", "created", "return", "1", "." ]
4f73c2bf0318261ac01bc8b6c0d4250a5d303418
https://github.com/src-d/modelforge/blob/4f73c2bf0318261ac01bc8b6c0d4250a5d303418/modelforge/backends.py#L54-L87
train
26,403
src-d/modelforge
modelforge/meta.py
generate_new_meta
def generate_new_meta(name: str, description: str, vendor: str, license: str) -> dict: """ Create the metadata tree for the given model name and the list of dependencies. :param name: Name of the model. :param description: Description of the model. :param vendor: Name of the party which is responsi...
python
def generate_new_meta(name: str, description: str, vendor: str, license: str) -> dict: """ Create the metadata tree for the given model name and the list of dependencies. :param name: Name of the model. :param description: Description of the model. :param vendor: Name of the party which is responsi...
[ "def", "generate_new_meta", "(", "name", ":", "str", ",", "description", ":", "str", ",", "vendor", ":", "str", ",", "license", ":", "str", ")", "->", "dict", ":", "check_license", "(", "license", ")", "return", "{", "\"code\"", ":", "None", ",", "\"cr...
Create the metadata tree for the given model name and the list of dependencies. :param name: Name of the model. :param description: Description of the model. :param vendor: Name of the party which is responsible for support of the model. :param license: License identifier. :return: dict with the me...
[ "Create", "the", "metadata", "tree", "for", "the", "given", "model", "name", "and", "the", "list", "of", "dependencies", "." ]
4f73c2bf0318261ac01bc8b6c0d4250a5d303418
https://github.com/src-d/modelforge/blob/4f73c2bf0318261ac01bc8b6c0d4250a5d303418/modelforge/meta.py#L24-L53
train
26,404
src-d/modelforge
modelforge/meta.py
extract_model_meta
def extract_model_meta(base_meta: dict, extra_meta: dict, model_url: str) -> dict: """ Merge the metadata from the backend and the extra metadata into a dict which is suitable for \ `index.json`. :param base_meta: tree["meta"] :class:`dict` containing data from the backend. :param extra_meta: dict ...
python
def extract_model_meta(base_meta: dict, extra_meta: dict, model_url: str) -> dict: """ Merge the metadata from the backend and the extra metadata into a dict which is suitable for \ `index.json`. :param base_meta: tree["meta"] :class:`dict` containing data from the backend. :param extra_meta: dict ...
[ "def", "extract_model_meta", "(", "base_meta", ":", "dict", ",", "extra_meta", ":", "dict", ",", "model_url", ":", "str", ")", "->", "dict", ":", "meta", "=", "{", "\"default\"", ":", "{", "\"default\"", ":", "base_meta", "[", "\"uuid\"", "]", ",", "\"de...
Merge the metadata from the backend and the extra metadata into a dict which is suitable for \ `index.json`. :param base_meta: tree["meta"] :class:`dict` containing data from the backend. :param extra_meta: dict containing data from the user, similar to `template_meta.json`. :param model_url: public UR...
[ "Merge", "the", "metadata", "from", "the", "backend", "and", "the", "extra", "metadata", "into", "a", "dict", "which", "is", "suitable", "for", "\\", "index", ".", "json", "." ]
4f73c2bf0318261ac01bc8b6c0d4250a5d303418
https://github.com/src-d/modelforge/blob/4f73c2bf0318261ac01bc8b6c0d4250a5d303418/modelforge/meta.py#L73-L95
train
26,405
src-d/modelforge
modelforge/model.py
squeeze_bits
def squeeze_bits(arr: numpy.ndarray) -> numpy.ndarray: """Return a copy of an integer numpy array with the minimum bitness.""" assert arr.dtype.kind in ("i", "u") if arr.dtype.kind == "i": assert arr.min() >= 0 mlbl = int(arr.max()).bit_length() if mlbl <= 8: dtype = numpy.uint8 ...
python
def squeeze_bits(arr: numpy.ndarray) -> numpy.ndarray: """Return a copy of an integer numpy array with the minimum bitness.""" assert arr.dtype.kind in ("i", "u") if arr.dtype.kind == "i": assert arr.min() >= 0 mlbl = int(arr.max()).bit_length() if mlbl <= 8: dtype = numpy.uint8 ...
[ "def", "squeeze_bits", "(", "arr", ":", "numpy", ".", "ndarray", ")", "->", "numpy", ".", "ndarray", ":", "assert", "arr", ".", "dtype", ".", "kind", "in", "(", "\"i\"", ",", "\"u\"", ")", "if", "arr", ".", "dtype", ".", "kind", "==", "\"i\"", ":",...
Return a copy of an integer numpy array with the minimum bitness.
[ "Return", "a", "copy", "of", "an", "integer", "numpy", "array", "with", "the", "minimum", "bitness", "." ]
4f73c2bf0318261ac01bc8b6c0d4250a5d303418
https://github.com/src-d/modelforge/blob/4f73c2bf0318261ac01bc8b6c0d4250a5d303418/modelforge/model.py#L572-L586
train
26,406
src-d/modelforge
modelforge/model.py
Model.metaprop
def metaprop(name: str, doc: str, readonly=False): """Temporary property builder.""" def get(self): return self.meta[name] get.__doc__ = "Get %s%s." % (doc, " (readonly)" if readonly else "") if not readonly: def set(self, value): self.meta[name] ...
python
def metaprop(name: str, doc: str, readonly=False): """Temporary property builder.""" def get(self): return self.meta[name] get.__doc__ = "Get %s%s." % (doc, " (readonly)" if readonly else "") if not readonly: def set(self, value): self.meta[name] ...
[ "def", "metaprop", "(", "name", ":", "str", ",", "doc", ":", "str", ",", "readonly", "=", "False", ")", ":", "def", "get", "(", "self", ")", ":", "return", "self", ".", "meta", "[", "name", "]", "get", ".", "__doc__", "=", "\"Get %s%s.\"", "%", "...
Temporary property builder.
[ "Temporary", "property", "builder", "." ]
4f73c2bf0318261ac01bc8b6c0d4250a5d303418
https://github.com/src-d/modelforge/blob/4f73c2bf0318261ac01bc8b6c0d4250a5d303418/modelforge/model.py#L190-L202
train
26,407
src-d/modelforge
modelforge/model.py
Model.derive
def derive(self, new_version: Union[tuple, list]=None) -> "Model": """ Inherit the new model from the current one - used for versioning. \ This operation is in-place. :param new_version: The version of the new model. :return: The derived model - self. """ meta = ...
python
def derive(self, new_version: Union[tuple, list]=None) -> "Model": """ Inherit the new model from the current one - used for versioning. \ This operation is in-place. :param new_version: The version of the new model. :return: The derived model - self. """ meta = ...
[ "def", "derive", "(", "self", ",", "new_version", ":", "Union", "[", "tuple", ",", "list", "]", "=", "None", ")", "->", "\"Model\"", ":", "meta", "=", "self", ".", "meta", "first_time", "=", "self", ".", "_initial_version", "==", "self", ".", "version"...
Inherit the new model from the current one - used for versioning. \ This operation is in-place. :param new_version: The version of the new model. :return: The derived model - self.
[ "Inherit", "the", "new", "model", "from", "the", "current", "one", "-", "used", "for", "versioning", ".", "\\", "This", "operation", "is", "in", "-", "place", "." ]
4f73c2bf0318261ac01bc8b6c0d4250a5d303418
https://github.com/src-d/modelforge/blob/4f73c2bf0318261ac01bc8b6c0d4250a5d303418/modelforge/model.py#L237-L257
train
26,408
src-d/modelforge
modelforge/model.py
Model.cache_dir
def cache_dir() -> str: """Return the default cache directory where downloaded models are stored.""" if config.VENDOR is None: raise RuntimeError("modelforge is not configured; look at modelforge.configuration. " "Depending on your objective you may or may not ...
python
def cache_dir() -> str: """Return the default cache directory where downloaded models are stored.""" if config.VENDOR is None: raise RuntimeError("modelforge is not configured; look at modelforge.configuration. " "Depending on your objective you may or may not ...
[ "def", "cache_dir", "(", ")", "->", "str", ":", "if", "config", ".", "VENDOR", "is", "None", ":", "raise", "RuntimeError", "(", "\"modelforge is not configured; look at modelforge.configuration. \"", "\"Depending on your objective you may or may not want to create a \"", "\"mod...
Return the default cache directory where downloaded models are stored.
[ "Return", "the", "default", "cache", "directory", "where", "downloaded", "models", "are", "stored", "." ]
4f73c2bf0318261ac01bc8b6c0d4250a5d303418
https://github.com/src-d/modelforge/blob/4f73c2bf0318261ac01bc8b6c0d4250a5d303418/modelforge/model.py#L335-L341
train
26,409
src-d/modelforge
modelforge/model.py
Model.get_dep
def get_dep(self, name: str) -> str: """ Return the uuid of the dependency identified with "name". :param name: :return: UUID """ deps = self.meta["dependencies"] for d in deps: if d["model"] == name: return d raise KeyError("%...
python
def get_dep(self, name: str) -> str: """ Return the uuid of the dependency identified with "name". :param name: :return: UUID """ deps = self.meta["dependencies"] for d in deps: if d["model"] == name: return d raise KeyError("%...
[ "def", "get_dep", "(", "self", ",", "name", ":", "str", ")", "->", "str", ":", "deps", "=", "self", ".", "meta", "[", "\"dependencies\"", "]", "for", "d", "in", "deps", ":", "if", "d", "[", "\"model\"", "]", "==", "name", ":", "return", "d", "rai...
Return the uuid of the dependency identified with "name". :param name: :return: UUID
[ "Return", "the", "uuid", "of", "the", "dependency", "identified", "with", "name", "." ]
4f73c2bf0318261ac01bc8b6c0d4250a5d303418
https://github.com/src-d/modelforge/blob/4f73c2bf0318261ac01bc8b6c0d4250a5d303418/modelforge/model.py#L343-L354
train
26,410
src-d/modelforge
modelforge/model.py
Model.set_dep
def set_dep(self, *deps) -> "Model": """ Register the dependencies for this model. :param deps: The parent models: objects or meta dicts. :return: self """ self.meta["dependencies"] = [ (d.meta if not isinstance(d, dict) else d) for d in deps] return ...
python
def set_dep(self, *deps) -> "Model": """ Register the dependencies for this model. :param deps: The parent models: objects or meta dicts. :return: self """ self.meta["dependencies"] = [ (d.meta if not isinstance(d, dict) else d) for d in deps] return ...
[ "def", "set_dep", "(", "self", ",", "*", "deps", ")", "->", "\"Model\"", ":", "self", ".", "meta", "[", "\"dependencies\"", "]", "=", "[", "(", "d", ".", "meta", "if", "not", "isinstance", "(", "d", ",", "dict", ")", "else", "d", ")", "for", "d",...
Register the dependencies for this model. :param deps: The parent models: objects or meta dicts. :return: self
[ "Register", "the", "dependencies", "for", "this", "model", "." ]
4f73c2bf0318261ac01bc8b6c0d4250a5d303418
https://github.com/src-d/modelforge/blob/4f73c2bf0318261ac01bc8b6c0d4250a5d303418/modelforge/model.py#L356-L365
train
26,411
src-d/modelforge
modelforge/model.py
Model.save
def save(self, output: Union[str, BinaryIO], series: Optional[str] = None, deps: Iterable=tuple(), create_missing_dirs: bool=True) -> "Model": """ Serialize the model to a file. :param output: Path to the file or a file object. :param series: Name of the model series. If it...
python
def save(self, output: Union[str, BinaryIO], series: Optional[str] = None, deps: Iterable=tuple(), create_missing_dirs: bool=True) -> "Model": """ Serialize the model to a file. :param output: Path to the file or a file object. :param series: Name of the model series. If it...
[ "def", "save", "(", "self", ",", "output", ":", "Union", "[", "str", ",", "BinaryIO", "]", ",", "series", ":", "Optional", "[", "str", "]", "=", "None", ",", "deps", ":", "Iterable", "=", "tuple", "(", ")", ",", "create_missing_dirs", ":", "bool", ...
Serialize the model to a file. :param output: Path to the file or a file object. :param series: Name of the model series. If it is None, it will be taken from \ the current value; if the current value is empty, an error is raised. :param deps: List of the dependencies. ...
[ "Serialize", "the", "model", "to", "a", "file", "." ]
4f73c2bf0318261ac01bc8b6c0d4250a5d303418
https://github.com/src-d/modelforge/blob/4f73c2bf0318261ac01bc8b6c0d4250a5d303418/modelforge/model.py#L374-L401
train
26,412
src-d/modelforge
modelforge/model.py
Model._write_tree
def _write_tree(self, tree: dict, output: Union[str, BinaryIO], file_mode: int=0o666) -> None: """ Write the model to disk. :param tree: The data dict - will be the ASDF tree. :param output: The output file path or a file object. :param file_mode: The output file's permissions. ...
python
def _write_tree(self, tree: dict, output: Union[str, BinaryIO], file_mode: int=0o666) -> None: """ Write the model to disk. :param tree: The data dict - will be the ASDF tree. :param output: The output file path or a file object. :param file_mode: The output file's permissions. ...
[ "def", "_write_tree", "(", "self", ",", "tree", ":", "dict", ",", "output", ":", "Union", "[", "str", ",", "BinaryIO", "]", ",", "file_mode", ":", "int", "=", "0o666", ")", "->", "None", ":", "self", ".", "meta", "[", "\"created_at\"", "]", "=", "g...
Write the model to disk. :param tree: The data dict - will be the ASDF tree. :param output: The output file path or a file object. :param file_mode: The output file's permissions. :return: None
[ "Write", "the", "model", "to", "disk", "." ]
4f73c2bf0318261ac01bc8b6c0d4250a5d303418
https://github.com/src-d/modelforge/blob/4f73c2bf0318261ac01bc8b6c0d4250a5d303418/modelforge/model.py#L403-L449
train
26,413
src-d/modelforge
modelforge/configuration.py
refresh
def refresh(): """Scan over all the involved directories and load configs from them.""" override_files = [] for stack in traceback.extract_stack(): f = os.path.join(os.path.dirname(stack[0]), OVERRIDE_FILE) if f not in override_files: override_files.insert(0, f) if OVERRIDE_F...
python
def refresh(): """Scan over all the involved directories and load configs from them.""" override_files = [] for stack in traceback.extract_stack(): f = os.path.join(os.path.dirname(stack[0]), OVERRIDE_FILE) if f not in override_files: override_files.insert(0, f) if OVERRIDE_F...
[ "def", "refresh", "(", ")", ":", "override_files", "=", "[", "]", "for", "stack", "in", "traceback", ".", "extract_stack", "(", ")", ":", "f", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "stack", "[", "0", "]...
Scan over all the involved directories and load configs from them.
[ "Scan", "over", "all", "the", "involved", "directories", "and", "load", "configs", "from", "them", "." ]
4f73c2bf0318261ac01bc8b6c0d4250a5d303418
https://github.com/src-d/modelforge/blob/4f73c2bf0318261ac01bc8b6c0d4250a5d303418/modelforge/configuration.py#L17-L42
train
26,414
src-d/modelforge
modelforge/gcs_backend.py
GCSBackend.create_client
def create_client(self) -> "google.cloud.storage.Client": """ Construct GCS API client. """ # Client should be imported here because grpc starts threads during import # and if you call fork after that, a child process will be hang during exit from google.cloud.storage imp...
python
def create_client(self) -> "google.cloud.storage.Client": """ Construct GCS API client. """ # Client should be imported here because grpc starts threads during import # and if you call fork after that, a child process will be hang during exit from google.cloud.storage imp...
[ "def", "create_client", "(", "self", ")", "->", "\"google.cloud.storage.Client\"", ":", "# Client should be imported here because grpc starts threads during import", "# and if you call fork after that, a child process will be hang during exit", "from", "google", ".", "cloud", ".", "sto...
Construct GCS API client.
[ "Construct", "GCS", "API", "client", "." ]
4f73c2bf0318261ac01bc8b6c0d4250a5d303418
https://github.com/src-d/modelforge/blob/4f73c2bf0318261ac01bc8b6c0d4250a5d303418/modelforge/gcs_backend.py#L82-L93
train
26,415
src-d/modelforge
modelforge/gcs_backend.py
GCSBackend.connect
def connect(self) -> "google.cloud.storage.Bucket": """ Connect to the assigned bucket. """ log = self._log log.info("Connecting to the bucket...") client = self.create_client() return client.lookup_bucket(self.bucket_name)
python
def connect(self) -> "google.cloud.storage.Bucket": """ Connect to the assigned bucket. """ log = self._log log.info("Connecting to the bucket...") client = self.create_client() return client.lookup_bucket(self.bucket_name)
[ "def", "connect", "(", "self", ")", "->", "\"google.cloud.storage.Bucket\"", ":", "log", "=", "self", ".", "_log", "log", ".", "info", "(", "\"Connecting to the bucket...\"", ")", "client", "=", "self", ".", "create_client", "(", ")", "return", "client", ".", ...
Connect to the assigned bucket.
[ "Connect", "to", "the", "assigned", "bucket", "." ]
4f73c2bf0318261ac01bc8b6c0d4250a5d303418
https://github.com/src-d/modelforge/blob/4f73c2bf0318261ac01bc8b6c0d4250a5d303418/modelforge/gcs_backend.py#L95-L102
train
26,416
src-d/modelforge
modelforge/gcs_backend.py
GCSBackend.reset
def reset(self, force): """Connect to the assigned bucket or create if needed. Clear all the blobs inside.""" client = self.create_client() bucket = client.lookup_bucket(self.bucket_name) if bucket is not None: if not force: self._log.error("Bucket already exi...
python
def reset(self, force): """Connect to the assigned bucket or create if needed. Clear all the blobs inside.""" client = self.create_client() bucket = client.lookup_bucket(self.bucket_name) if bucket is not None: if not force: self._log.error("Bucket already exi...
[ "def", "reset", "(", "self", ",", "force", ")", ":", "client", "=", "self", ".", "create_client", "(", ")", "bucket", "=", "client", ".", "lookup_bucket", "(", "self", ".", "bucket_name", ")", "if", "bucket", "is", "not", "None", ":", "if", "not", "f...
Connect to the assigned bucket or create if needed. Clear all the blobs inside.
[ "Connect", "to", "the", "assigned", "bucket", "or", "create", "if", "needed", ".", "Clear", "all", "the", "blobs", "inside", "." ]
4f73c2bf0318261ac01bc8b6c0d4250a5d303418
https://github.com/src-d/modelforge/blob/4f73c2bf0318261ac01bc8b6c0d4250a5d303418/modelforge/gcs_backend.py#L104-L117
train
26,417
src-d/modelforge
modelforge/gcs_backend.py
GCSBackend.upload_model
def upload_model(self, path: str, meta: dict, force: bool): """Put the model to GCS.""" bucket = self.connect() if bucket is None: raise BackendRequiredError blob = bucket.blob("models/%s/%s.asdf" % (meta["model"], meta["uuid"])) if blob.exists() and not force: ...
python
def upload_model(self, path: str, meta: dict, force: bool): """Put the model to GCS.""" bucket = self.connect() if bucket is None: raise BackendRequiredError blob = bucket.blob("models/%s/%s.asdf" % (meta["model"], meta["uuid"])) if blob.exists() and not force: ...
[ "def", "upload_model", "(", "self", ",", "path", ":", "str", ",", "meta", ":", "dict", ",", "force", ":", "bool", ")", ":", "bucket", "=", "self", ".", "connect", "(", ")", "if", "bucket", "is", "None", ":", "raise", "BackendRequiredError", "blob", "...
Put the model to GCS.
[ "Put", "the", "model", "to", "GCS", "." ]
4f73c2bf0318261ac01bc8b6c0d4250a5d303418
https://github.com/src-d/modelforge/blob/4f73c2bf0318261ac01bc8b6c0d4250a5d303418/modelforge/gcs_backend.py#L119-L150
train
26,418
src-d/modelforge
modelforge/gcs_backend.py
GCSBackend.fetch_model
def fetch_model(self, source: str, file: Union[str, BinaryIO], chunk_size: int=DEFAULT_DOWNLOAD_CHUNK_SIZE) -> None: """Download the model from GCS.""" download_http(source, file, self._log, chunk_size)
python
def fetch_model(self, source: str, file: Union[str, BinaryIO], chunk_size: int=DEFAULT_DOWNLOAD_CHUNK_SIZE) -> None: """Download the model from GCS.""" download_http(source, file, self._log, chunk_size)
[ "def", "fetch_model", "(", "self", ",", "source", ":", "str", ",", "file", ":", "Union", "[", "str", ",", "BinaryIO", "]", ",", "chunk_size", ":", "int", "=", "DEFAULT_DOWNLOAD_CHUNK_SIZE", ")", "->", "None", ":", "download_http", "(", "source", ",", "fi...
Download the model from GCS.
[ "Download", "the", "model", "from", "GCS", "." ]
4f73c2bf0318261ac01bc8b6c0d4250a5d303418
https://github.com/src-d/modelforge/blob/4f73c2bf0318261ac01bc8b6c0d4250a5d303418/modelforge/gcs_backend.py#L152-L155
train
26,419
src-d/modelforge
modelforge/gcs_backend.py
GCSBackend.delete_model
def delete_model(self, meta: dict): """Delete the model from GCS.""" bucket = self.connect() if bucket is None: raise BackendRequiredError blob_name = "models/%s/%s.asdf" % (meta["model"], meta["uuid"]) self._log.info(blob_name) try: self._log.info...
python
def delete_model(self, meta: dict): """Delete the model from GCS.""" bucket = self.connect() if bucket is None: raise BackendRequiredError blob_name = "models/%s/%s.asdf" % (meta["model"], meta["uuid"]) self._log.info(blob_name) try: self._log.info...
[ "def", "delete_model", "(", "self", ",", "meta", ":", "dict", ")", ":", "bucket", "=", "self", ".", "connect", "(", ")", "if", "bucket", "is", "None", ":", "raise", "BackendRequiredError", "blob_name", "=", "\"models/%s/%s.asdf\"", "%", "(", "meta", "[", ...
Delete the model from GCS.
[ "Delete", "the", "model", "from", "GCS", "." ]
4f73c2bf0318261ac01bc8b6c0d4250a5d303418
https://github.com/src-d/modelforge/blob/4f73c2bf0318261ac01bc8b6c0d4250a5d303418/modelforge/gcs_backend.py#L157-L168
train
26,420
src-d/modelforge
modelforge/storage_backend.py
download_http
def download_http(source: str, file: Union[str, BinaryIO], log: logging.Logger, chunk_size: int=DEFAULT_DOWNLOAD_CHUNK_SIZE) -> None: """ Download a file from an HTTP source. :param source: URL to fetch. :param file: Where to store the downloaded data. :param log: Logger. :par...
python
def download_http(source: str, file: Union[str, BinaryIO], log: logging.Logger, chunk_size: int=DEFAULT_DOWNLOAD_CHUNK_SIZE) -> None: """ Download a file from an HTTP source. :param source: URL to fetch. :param file: Where to store the downloaded data. :param log: Logger. :par...
[ "def", "download_http", "(", "source", ":", "str", ",", "file", ":", "Union", "[", "str", ",", "BinaryIO", "]", ",", "log", ":", "logging", ".", "Logger", ",", "chunk_size", ":", "int", "=", "DEFAULT_DOWNLOAD_CHUNK_SIZE", ")", "->", "None", ":", "log", ...
Download a file from an HTTP source. :param source: URL to fetch. :param file: Where to store the downloaded data. :param log: Logger. :param chunk_size: Size of download buffer.
[ "Download", "a", "file", "from", "an", "HTTP", "source", "." ]
4f73c2bf0318261ac01bc8b6c0d4250a5d303418
https://github.com/src-d/modelforge/blob/4f73c2bf0318261ac01bc8b6c0d4250a5d303418/modelforge/storage_backend.py#L111-L146
train
26,421
src-d/modelforge
modelforge/storage_backend.py
StorageBackend.upload_model
def upload_model(self, path: str, meta: dict, force: bool) -> str: """ Put the given file to the remote storage. :param path: Path to the model file. :param meta: Metadata of the model. :param force: Overwrite an existing model. :return: URL of the uploaded model. ...
python
def upload_model(self, path: str, meta: dict, force: bool) -> str: """ Put the given file to the remote storage. :param path: Path to the model file. :param meta: Metadata of the model. :param force: Overwrite an existing model. :return: URL of the uploaded model. ...
[ "def", "upload_model", "(", "self", ",", "path", ":", "str", ",", "meta", ":", "dict", ",", "force", ":", "bool", ")", "->", "str", ":", "raise", "NotImplementedError" ]
Put the given file to the remote storage. :param path: Path to the model file. :param meta: Metadata of the model. :param force: Overwrite an existing model. :return: URL of the uploaded model. :raises BackendRequiredError: If supplied bucket is unusable. :raises ModelAl...
[ "Put", "the", "given", "file", "to", "the", "remote", "storage", "." ]
4f73c2bf0318261ac01bc8b6c0d4250a5d303418
https://github.com/src-d/modelforge/blob/4f73c2bf0318261ac01bc8b6c0d4250a5d303418/modelforge/storage_backend.py#L48-L59
train
26,422
src-d/modelforge
modelforge/slogging.py
setup
def setup(level: Union[str, int], structured: bool, config_path: str = None): """ Make stdout and stderr unicode friendly in case of misconfigured \ environments, initializes the logging, structured logging and \ enables colored logs if it is appropriate. :param level: The global logging level. ...
python
def setup(level: Union[str, int], structured: bool, config_path: str = None): """ Make stdout and stderr unicode friendly in case of misconfigured \ environments, initializes the logging, structured logging and \ enables colored logs if it is appropriate. :param level: The global logging level. ...
[ "def", "setup", "(", "level", ":", "Union", "[", "str", ",", "int", "]", ",", "structured", ":", "bool", ",", "config_path", ":", "str", "=", "None", ")", ":", "global", "logs_are_structured", "logs_are_structured", "=", "structured", "if", "not", "isinsta...
Make stdout and stderr unicode friendly in case of misconfigured \ environments, initializes the logging, structured logging and \ enables colored logs if it is appropriate. :param level: The global logging level. :param structured: Output JSON logs to stdout. :param config_path: Path to a yaml fil...
[ "Make", "stdout", "and", "stderr", "unicode", "friendly", "in", "case", "of", "misconfigured", "\\", "environments", "initializes", "the", "logging", "structured", "logging", "and", "\\", "enables", "colored", "logs", "if", "it", "is", "appropriate", "." ]
4f73c2bf0318261ac01bc8b6c0d4250a5d303418
https://github.com/src-d/modelforge/blob/4f73c2bf0318261ac01bc8b6c0d4250a5d303418/modelforge/slogging.py#L164-L209
train
26,423
src-d/modelforge
modelforge/slogging.py
set_context
def set_context(context): """Assign the logging context - an abstract object - to the current thread.""" try: handler = logging.getLogger().handlers[0] except IndexError: # logging is not initialized return if not isinstance(handler, StructuredHandler): return handler...
python
def set_context(context): """Assign the logging context - an abstract object - to the current thread.""" try: handler = logging.getLogger().handlers[0] except IndexError: # logging is not initialized return if not isinstance(handler, StructuredHandler): return handler...
[ "def", "set_context", "(", "context", ")", ":", "try", ":", "handler", "=", "logging", ".", "getLogger", "(", ")", ".", "handlers", "[", "0", "]", "except", "IndexError", ":", "# logging is not initialized", "return", "if", "not", "isinstance", "(", "handler...
Assign the logging context - an abstract object - to the current thread.
[ "Assign", "the", "logging", "context", "-", "an", "abstract", "object", "-", "to", "the", "current", "thread", "." ]
4f73c2bf0318261ac01bc8b6c0d4250a5d303418
https://github.com/src-d/modelforge/blob/4f73c2bf0318261ac01bc8b6c0d4250a5d303418/modelforge/slogging.py#L212-L225
train
26,424
src-d/modelforge
modelforge/slogging.py
add_logging_args
def add_logging_args(parser: argparse.ArgumentParser, patch: bool = True, erase_args: bool = True) -> None: """ Add command line flags specific to logging. :param parser: `argparse` parser where to add new flags. :param erase_args: Automatically remove logging-related flags from pa...
python
def add_logging_args(parser: argparse.ArgumentParser, patch: bool = True, erase_args: bool = True) -> None: """ Add command line flags specific to logging. :param parser: `argparse` parser where to add new flags. :param erase_args: Automatically remove logging-related flags from pa...
[ "def", "add_logging_args", "(", "parser", ":", "argparse", ".", "ArgumentParser", ",", "patch", ":", "bool", "=", "True", ",", "erase_args", ":", "bool", "=", "True", ")", "->", "None", ":", "parser", ".", "add_argument", "(", "\"--log-level\"", ",", "defa...
Add command line flags specific to logging. :param parser: `argparse` parser where to add new flags. :param erase_args: Automatically remove logging-related flags from parsed args. :param patch: Patch parse_args() to automatically setup logging.
[ "Add", "command", "line", "flags", "specific", "to", "logging", "." ]
4f73c2bf0318261ac01bc8b6c0d4250a5d303418
https://github.com/src-d/modelforge/blob/4f73c2bf0318261ac01bc8b6c0d4250a5d303418/modelforge/slogging.py#L228-L257
train
26,425
src-d/modelforge
modelforge/slogging.py
NumpyLogRecord.array2string
def array2string(arr: numpy.ndarray) -> str: """Format numpy array as a string.""" shape = str(arr.shape)[1:-1] if shape.endswith(","): shape = shape[:-1] return numpy.array2string(arr, threshold=11) + "%s[%s]" % (arr.dtype, shape)
python
def array2string(arr: numpy.ndarray) -> str: """Format numpy array as a string.""" shape = str(arr.shape)[1:-1] if shape.endswith(","): shape = shape[:-1] return numpy.array2string(arr, threshold=11) + "%s[%s]" % (arr.dtype, shape)
[ "def", "array2string", "(", "arr", ":", "numpy", ".", "ndarray", ")", "->", "str", ":", "shape", "=", "str", "(", "arr", ".", "shape", ")", "[", "1", ":", "-", "1", "]", "if", "shape", ".", "endswith", "(", "\",\"", ")", ":", "shape", "=", "sha...
Format numpy array as a string.
[ "Format", "numpy", "array", "as", "a", "string", "." ]
4f73c2bf0318261ac01bc8b6c0d4250a5d303418
https://github.com/src-d/modelforge/blob/4f73c2bf0318261ac01bc8b6c0d4250a5d303418/modelforge/slogging.py#L64-L69
train
26,426
src-d/modelforge
modelforge/slogging.py
NumpyLogRecord.getMessage
def getMessage(self): """ Return the message for this LogRecord. Return the message for this LogRecord after merging any user-supplied \ arguments with the message. """ if isinstance(self.msg, numpy.ndarray): msg = self.array2string(self.msg) else: ...
python
def getMessage(self): """ Return the message for this LogRecord. Return the message for this LogRecord after merging any user-supplied \ arguments with the message. """ if isinstance(self.msg, numpy.ndarray): msg = self.array2string(self.msg) else: ...
[ "def", "getMessage", "(", "self", ")", ":", "if", "isinstance", "(", "self", ".", "msg", ",", "numpy", ".", "ndarray", ")", ":", "msg", "=", "self", ".", "array2string", "(", "self", ".", "msg", ")", "else", ":", "msg", "=", "str", "(", "self", "...
Return the message for this LogRecord. Return the message for this LogRecord after merging any user-supplied \ arguments with the message.
[ "Return", "the", "message", "for", "this", "LogRecord", "." ]
4f73c2bf0318261ac01bc8b6c0d4250a5d303418
https://github.com/src-d/modelforge/blob/4f73c2bf0318261ac01bc8b6c0d4250a5d303418/modelforge/slogging.py#L71-L94
train
26,427
src-d/modelforge
modelforge/slogging.py
AwesomeFormatter.formatMessage
def formatMessage(self, record: logging.LogRecord) -> str: """Convert the already filled log record to a string.""" level_color = "0" text_color = "0" fmt = "" if record.levelno <= logging.DEBUG: fmt = "\033[0;37m" + logging.BASIC_FORMAT + "\033[0m" elif recor...
python
def formatMessage(self, record: logging.LogRecord) -> str: """Convert the already filled log record to a string.""" level_color = "0" text_color = "0" fmt = "" if record.levelno <= logging.DEBUG: fmt = "\033[0;37m" + logging.BASIC_FORMAT + "\033[0m" elif recor...
[ "def", "formatMessage", "(", "self", ",", "record", ":", "logging", ".", "LogRecord", ")", "->", "str", ":", "level_color", "=", "\"0\"", "text_color", "=", "\"0\"", "fmt", "=", "\"\"", "if", "record", ".", "levelno", "<=", "logging", ".", "DEBUG", ":", ...
Convert the already filled log record to a string.
[ "Convert", "the", "already", "filled", "log", "record", "to", "a", "string", "." ]
4f73c2bf0318261ac01bc8b6c0d4250a5d303418
https://github.com/src-d/modelforge/blob/4f73c2bf0318261ac01bc8b6c0d4250a5d303418/modelforge/slogging.py#L106-L128
train
26,428
src-d/modelforge
modelforge/slogging.py
StructuredHandler.emit
def emit(self, record: logging.LogRecord): """Print the log record formatted as JSON to stdout.""" created = datetime.datetime.fromtimestamp(record.created, timezone) obj = { "level": record.levelname.lower(), "msg": record.msg % record.args, "source": "%s:%d"...
python
def emit(self, record: logging.LogRecord): """Print the log record formatted as JSON to stdout.""" created = datetime.datetime.fromtimestamp(record.created, timezone) obj = { "level": record.levelname.lower(), "msg": record.msg % record.args, "source": "%s:%d"...
[ "def", "emit", "(", "self", ",", "record", ":", "logging", ".", "LogRecord", ")", ":", "created", "=", "datetime", ".", "datetime", ".", "fromtimestamp", "(", "record", ".", "created", ",", "timezone", ")", "obj", "=", "{", "\"level\"", ":", "record", ...
Print the log record formatted as JSON to stdout.
[ "Print", "the", "log", "record", "formatted", "as", "JSON", "to", "stdout", "." ]
4f73c2bf0318261ac01bc8b6c0d4250a5d303418
https://github.com/src-d/modelforge/blob/4f73c2bf0318261ac01bc8b6c0d4250a5d303418/modelforge/slogging.py#L139-L157
train
26,429
src-d/modelforge
modelforge/models.py
register_model
def register_model(cls: Type[Model]): """ Include the given model class into the registry. :param cls: The class of the registered model. :return: None """ if not issubclass(cls, Model): raise TypeError("model bust be a subclass of Model") if issubclass(cls, GenericModel): r...
python
def register_model(cls: Type[Model]): """ Include the given model class into the registry. :param cls: The class of the registered model. :return: None """ if not issubclass(cls, Model): raise TypeError("model bust be a subclass of Model") if issubclass(cls, GenericModel): r...
[ "def", "register_model", "(", "cls", ":", "Type", "[", "Model", "]", ")", ":", "if", "not", "issubclass", "(", "cls", ",", "Model", ")", ":", "raise", "TypeError", "(", "\"model bust be a subclass of Model\"", ")", "if", "issubclass", "(", "cls", ",", "Gen...
Include the given model class into the registry. :param cls: The class of the registered model. :return: None
[ "Include", "the", "given", "model", "class", "into", "the", "registry", "." ]
4f73c2bf0318261ac01bc8b6c0d4250a5d303418
https://github.com/src-d/modelforge/blob/4f73c2bf0318261ac01bc8b6c0d4250a5d303418/modelforge/models.py#L10-L22
train
26,430
src-d/modelforge
modelforge/index.py
GitIndex.fetch
def fetch(self): """Load from the associated Git repository.""" os.makedirs(os.path.dirname(self.cached_repo), exist_ok=True) if not os.path.exists(self.cached_repo): self._log.warning("Index not found, caching %s in %s", self.repo, self.cached_repo) git.clone(self.remote...
python
def fetch(self): """Load from the associated Git repository.""" os.makedirs(os.path.dirname(self.cached_repo), exist_ok=True) if not os.path.exists(self.cached_repo): self._log.warning("Index not found, caching %s in %s", self.repo, self.cached_repo) git.clone(self.remote...
[ "def", "fetch", "(", "self", ")", ":", "os", ".", "makedirs", "(", "os", ".", "path", ".", "dirname", "(", "self", ".", "cached_repo", ")", ",", "exist_ok", "=", "True", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "self", ".", "cache...
Load from the associated Git repository.
[ "Load", "from", "the", "associated", "Git", "repository", "." ]
4f73c2bf0318261ac01bc8b6c0d4250a5d303418
https://github.com/src-d/modelforge/blob/4f73c2bf0318261ac01bc8b6c0d4250a5d303418/modelforge/index.py#L102-L114
train
26,431
src-d/modelforge
modelforge/index.py
GitIndex.update_readme
def update_readme(self, template_readme: Template): """Generate the new README file locally.""" readme = os.path.join(self.cached_repo, "README.md") if os.path.exists(readme): os.remove(readme) links = {model_type: {} for model_type in self.models.keys()} for model_ty...
python
def update_readme(self, template_readme: Template): """Generate the new README file locally.""" readme = os.path.join(self.cached_repo, "README.md") if os.path.exists(readme): os.remove(readme) links = {model_type: {} for model_type in self.models.keys()} for model_ty...
[ "def", "update_readme", "(", "self", ",", "template_readme", ":", "Template", ")", ":", "readme", "=", "os", ".", "path", ".", "join", "(", "self", ".", "cached_repo", ",", "\"README.md\"", ")", "if", "os", ".", "path", ".", "exists", "(", "readme", ")...
Generate the new README file locally.
[ "Generate", "the", "new", "README", "file", "locally", "." ]
4f73c2bf0318261ac01bc8b6c0d4250a5d303418
https://github.com/src-d/modelforge/blob/4f73c2bf0318261ac01bc8b6c0d4250a5d303418/modelforge/index.py#L166-L178
train
26,432
src-d/modelforge
modelforge/index.py
GitIndex.reset
def reset(self): """Initialize the remote Git repository.""" paths = [] for filename in os.listdir(self.cached_repo): if filename.startswith(".git"): continue path = os.path.join(self.cached_repo, filename) if os.path.isfile(path): ...
python
def reset(self): """Initialize the remote Git repository.""" paths = [] for filename in os.listdir(self.cached_repo): if filename.startswith(".git"): continue path = os.path.join(self.cached_repo, filename) if os.path.isfile(path): ...
[ "def", "reset", "(", "self", ")", ":", "paths", "=", "[", "]", "for", "filename", "in", "os", ".", "listdir", "(", "self", ".", "cached_repo", ")", ":", "if", "filename", ".", "startswith", "(", "\".git\"", ")", ":", "continue", "path", "=", "os", ...
Initialize the remote Git repository.
[ "Initialize", "the", "remote", "Git", "repository", "." ]
4f73c2bf0318261ac01bc8b6c0d4250a5d303418
https://github.com/src-d/modelforge/blob/4f73c2bf0318261ac01bc8b6c0d4250a5d303418/modelforge/index.py#L180-L193
train
26,433
src-d/modelforge
modelforge/index.py
GitIndex.upload
def upload(self, cmd: str, meta: dict): """Push the current state of the registry to Git.""" index = os.path.join(self.cached_repo, self.INDEX_FILE) if os.path.exists(index): os.remove(index) self._log.info("Writing the new index.json ...") with open(index, "w") as _o...
python
def upload(self, cmd: str, meta: dict): """Push the current state of the registry to Git.""" index = os.path.join(self.cached_repo, self.INDEX_FILE) if os.path.exists(index): os.remove(index) self._log.info("Writing the new index.json ...") with open(index, "w") as _o...
[ "def", "upload", "(", "self", ",", "cmd", ":", "str", ",", "meta", ":", "dict", ")", ":", "index", "=", "os", ".", "path", ".", "join", "(", "self", ".", "cached_repo", ",", "self", ".", "INDEX_FILE", ")", "if", "os", ".", "path", ".", "exists", ...
Push the current state of the registry to Git.
[ "Push", "the", "current", "state", "of", "the", "registry", "to", "Git", "." ]
4f73c2bf0318261ac01bc8b6c0d4250a5d303418
https://github.com/src-d/modelforge/blob/4f73c2bf0318261ac01bc8b6c0d4250a5d303418/modelforge/index.py#L195-L229
train
26,434
src-d/modelforge
modelforge/index.py
GitIndex.load_template
def load_template(self, template: str) -> Template: """Load a Jinja2 template from the source directory.""" env = dict(trim_blocks=True, lstrip_blocks=True, keep_trailing_newline=False) jinja2_ext = ".jinja2" if not template.endswith(jinja2_ext): self._log.error("Template fil...
python
def load_template(self, template: str) -> Template: """Load a Jinja2 template from the source directory.""" env = dict(trim_blocks=True, lstrip_blocks=True, keep_trailing_newline=False) jinja2_ext = ".jinja2" if not template.endswith(jinja2_ext): self._log.error("Template fil...
[ "def", "load_template", "(", "self", ",", "template", ":", "str", ")", "->", "Template", ":", "env", "=", "dict", "(", "trim_blocks", "=", "True", ",", "lstrip_blocks", "=", "True", ",", "keep_trailing_newline", "=", "False", ")", "jinja2_ext", "=", "\".ji...
Load a Jinja2 template from the source directory.
[ "Load", "a", "Jinja2", "template", "from", "the", "source", "directory", "." ]
4f73c2bf0318261ac01bc8b6c0d4250a5d303418
https://github.com/src-d/modelforge/blob/4f73c2bf0318261ac01bc8b6c0d4250a5d303418/modelforge/index.py#L231-L247
train
26,435
src-d/modelforge
modelforge/progress_bar.py
progress_bar
def progress_bar(enumerable, logger, **kwargs): """ Show the progress bar in the terminal, if the logging level matches and we are interactive. :param enumerable: The iterator of which we indicate the progress. :param logger: The bound logging.Logger. :param kwargs: Keyword arguments to pass to cli...
python
def progress_bar(enumerable, logger, **kwargs): """ Show the progress bar in the terminal, if the logging level matches and we are interactive. :param enumerable: The iterator of which we indicate the progress. :param logger: The bound logging.Logger. :param kwargs: Keyword arguments to pass to cli...
[ "def", "progress_bar", "(", "enumerable", ",", "logger", ",", "*", "*", "kwargs", ")", ":", "if", "not", "logger", ".", "isEnabledFor", "(", "logging", ".", "INFO", ")", "or", "sys", ".", "stdin", ".", "closed", "or", "not", "sys", ".", "stdin", ".",...
Show the progress bar in the terminal, if the logging level matches and we are interactive. :param enumerable: The iterator of which we indicate the progress. :param logger: The bound logging.Logger. :param kwargs: Keyword arguments to pass to clint.textui.progress.bar. :return: The wrapped iterator.
[ "Show", "the", "progress", "bar", "in", "the", "terminal", "if", "the", "logging", "level", "matches", "and", "we", "are", "interactive", "." ]
4f73c2bf0318261ac01bc8b6c0d4250a5d303418
https://github.com/src-d/modelforge/blob/4f73c2bf0318261ac01bc8b6c0d4250a5d303418/modelforge/progress_bar.py#L7-L18
train
26,436
src-d/modelforge
modelforge/environment.py
collect_environment
def collect_environment(no_cache: bool = False) -> dict: """ Return the version of the Python executable, the versions of the currently loaded packages \ and the running platform. The result is cached unless `no_cache` is True. """ global _env if _env is None or no_cache: _env = col...
python
def collect_environment(no_cache: bool = False) -> dict: """ Return the version of the Python executable, the versions of the currently loaded packages \ and the running platform. The result is cached unless `no_cache` is True. """ global _env if _env is None or no_cache: _env = col...
[ "def", "collect_environment", "(", "no_cache", ":", "bool", "=", "False", ")", "->", "dict", ":", "global", "_env", "if", "_env", "is", "None", "or", "no_cache", ":", "_env", "=", "collect_environment_without_packages", "(", ")", "_env", "[", "\"packages\"", ...
Return the version of the Python executable, the versions of the currently loaded packages \ and the running platform. The result is cached unless `no_cache` is True.
[ "Return", "the", "version", "of", "the", "Python", "executable", "the", "versions", "of", "the", "currently", "loaded", "packages", "\\", "and", "the", "running", "platform", "." ]
4f73c2bf0318261ac01bc8b6c0d4250a5d303418
https://github.com/src-d/modelforge/blob/4f73c2bf0318261ac01bc8b6c0d4250a5d303418/modelforge/environment.py#L28-L39
train
26,437
src-d/modelforge
modelforge/environment.py
collect_loaded_packages
def collect_loaded_packages() -> List[Tuple[str, str]]: """ Return the currently loaded package names and their versions. """ dists = get_installed_distributions() get_dist_files = DistFilesFinder() file_table = {} for dist in dists: for file in get_dist_files(dist): file...
python
def collect_loaded_packages() -> List[Tuple[str, str]]: """ Return the currently loaded package names and their versions. """ dists = get_installed_distributions() get_dist_files = DistFilesFinder() file_table = {} for dist in dists: for file in get_dist_files(dist): file...
[ "def", "collect_loaded_packages", "(", ")", "->", "List", "[", "Tuple", "[", "str", ",", "str", "]", "]", ":", "dists", "=", "get_installed_distributions", "(", ")", "get_dist_files", "=", "DistFilesFinder", "(", ")", "file_table", "=", "{", "}", "for", "d...
Return the currently loaded package names and their versions.
[ "Return", "the", "currently", "loaded", "package", "names", "and", "their", "versions", "." ]
4f73c2bf0318261ac01bc8b6c0d4250a5d303418
https://github.com/src-d/modelforge/blob/4f73c2bf0318261ac01bc8b6c0d4250a5d303418/modelforge/environment.py#L42-L61
train
26,438
criteo/gourde
gourde/gourde.py
Gourde.setup_blueprint
def setup_blueprint(self): """Initialize the blueprint.""" # Register endpoints. self.blueprint.add_url_rule("/", "status", self.status) self.blueprint.add_url_rule("/healthy", "health", self.healthy) self.blueprint.add_url_rule("/ready", "ready", self.ready) self.bluepr...
python
def setup_blueprint(self): """Initialize the blueprint.""" # Register endpoints. self.blueprint.add_url_rule("/", "status", self.status) self.blueprint.add_url_rule("/healthy", "health", self.healthy) self.blueprint.add_url_rule("/ready", "ready", self.ready) self.bluepr...
[ "def", "setup_blueprint", "(", "self", ")", ":", "# Register endpoints.", "self", ".", "blueprint", ".", "add_url_rule", "(", "\"/\"", ",", "\"status\"", ",", "self", ".", "status", ")", "self", ".", "blueprint", ".", "add_url_rule", "(", "\"/healthy\"", ",", ...
Initialize the blueprint.
[ "Initialize", "the", "blueprint", "." ]
9a274e534a2af5d2b2a5e99f10c59010adb94863
https://github.com/criteo/gourde/blob/9a274e534a2af5d2b2a5e99f10c59010adb94863/gourde/gourde.py#L69-L76
train
26,439
criteo/gourde
gourde/gourde.py
Gourde._add_routes
def _add_routes(self): """Add some nice default routes.""" if self.app.has_static_folder: self.add_url_rule("/favicon.ico", "favicon", self.favicon) self.add_url_rule("/", "__default_redirect_to_status", self.redirect_to_status)
python
def _add_routes(self): """Add some nice default routes.""" if self.app.has_static_folder: self.add_url_rule("/favicon.ico", "favicon", self.favicon) self.add_url_rule("/", "__default_redirect_to_status", self.redirect_to_status)
[ "def", "_add_routes", "(", "self", ")", ":", "if", "self", ".", "app", ".", "has_static_folder", ":", "self", ".", "add_url_rule", "(", "\"/favicon.ico\"", ",", "\"favicon\"", ",", "self", ".", "favicon", ")", "self", ".", "add_url_rule", "(", "\"/\"", ","...
Add some nice default routes.
[ "Add", "some", "nice", "default", "routes", "." ]
9a274e534a2af5d2b2a5e99f10c59010adb94863
https://github.com/criteo/gourde/blob/9a274e534a2af5d2b2a5e99f10c59010adb94863/gourde/gourde.py#L78-L82
train
26,440
criteo/gourde
gourde/gourde.py
Gourde.get_argparser
def get_argparser(parser=None): """Customize a parser to get the correct options.""" parser = parser or argparse.ArgumentParser() parser.add_argument("--host", default="0.0.0.0", help="Host listen address") parser.add_argument("--port", "-p", default=9050, help="Listen port", type=int) ...
python
def get_argparser(parser=None): """Customize a parser to get the correct options.""" parser = parser or argparse.ArgumentParser() parser.add_argument("--host", default="0.0.0.0", help="Host listen address") parser.add_argument("--port", "-p", default=9050, help="Listen port", type=int) ...
[ "def", "get_argparser", "(", "parser", "=", "None", ")", ":", "parser", "=", "parser", "or", "argparse", ".", "ArgumentParser", "(", ")", "parser", ".", "add_argument", "(", "\"--host\"", ",", "default", "=", "\"0.0.0.0\"", ",", "help", "=", "\"Host listen a...
Customize a parser to get the correct options.
[ "Customize", "a", "parser", "to", "get", "the", "correct", "options", "." ]
9a274e534a2af5d2b2a5e99f10c59010adb94863
https://github.com/criteo/gourde/blob/9a274e534a2af5d2b2a5e99f10c59010adb94863/gourde/gourde.py#L115-L152
train
26,441
criteo/gourde
gourde/gourde.py
Gourde.setup_prometheus
def setup_prometheus(self, registry=None): """Setup Prometheus.""" kwargs = {} if registry: kwargs["registry"] = registry self.metrics = PrometheusMetrics(self.app, **kwargs) try: version = pkg_resources.require(self.app.name)[0].version except pkg...
python
def setup_prometheus(self, registry=None): """Setup Prometheus.""" kwargs = {} if registry: kwargs["registry"] = registry self.metrics = PrometheusMetrics(self.app, **kwargs) try: version = pkg_resources.require(self.app.name)[0].version except pkg...
[ "def", "setup_prometheus", "(", "self", ",", "registry", "=", "None", ")", ":", "kwargs", "=", "{", "}", "if", "registry", ":", "kwargs", "[", "\"registry\"", "]", "=", "registry", "self", ".", "metrics", "=", "PrometheusMetrics", "(", "self", ".", "app"...
Setup Prometheus.
[ "Setup", "Prometheus", "." ]
9a274e534a2af5d2b2a5e99f10c59010adb94863
https://github.com/criteo/gourde/blob/9a274e534a2af5d2b2a5e99f10c59010adb94863/gourde/gourde.py#L169-L182
train
26,442
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): """Add a new url route. Args: See flask.Flask.add_url_route(). """ 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
train
26,443
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...
python
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...
[ "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
train
26,444
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.logg...
python
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.logg...
[ "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
train
26,445
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) ...
python
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) ...
[ "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
train
26,446
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, **optio...
python
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, **optio...
[ "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
train
26,447
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) ...
python
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) ...
[ "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
train
26,448
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): sel...
python
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): sel...
[ "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
train
26,449
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...
python
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...
[ "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
train
26,450
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): """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)
[ "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
train
26,451
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 ...
python
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 ...
[ "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 para...
[ "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
train
26,452
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 ...
python
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 ...
[ "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
train
26,453
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 ...
python
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 ...
[ "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
train
26,454
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...
python
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...
[ "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
train
26,455
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, http...
python
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, http...
[ "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/jsh...
[ "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
train
26,456
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 = ...
python
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 = ...
[ "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
train
26,457
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): """ Saves prj WKT to given file. """ 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
train
26,458
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): """ Returns the current head version. """ 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
train
26,459
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 meta...
python
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 meta...
[ "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
train
26,460
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: ...
python
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: ...
[ "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
train
26,461
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 th...
python
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 th...
[ "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
train
26,462
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): """ 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
[ "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
train
26,463
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): """ 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 )
[ "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
train
26,464
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): """ Count the number of models matching some criterion. """ 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
train
26,465
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) que...
python
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) que...
[ "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
train
26,466
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 = se...
python
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 = se...
[ "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
train
26,467
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): """ Filter a query with user-supplied arguments. """ 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
train
26,468
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( ...
python
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( ...
[ "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
train
26,469
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...
python
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...
[ "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
train
26,470
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): """ Construct a query for the model. """ 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
train
26,471
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(commi...
python
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(commi...
[ "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
train
26,472
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 director...
python
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 director...
[ "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...
[ "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
train
26,473
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 a...
python
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 a...
[ "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...
[ "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
train
26,474
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( connec...
python
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( connec...
[ "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
train
26,475
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_...
python
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_...
[ "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 defau...
[ "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
train
26,476
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): ...
python
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): ...
[ "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
train
26,477
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 ...
python
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 ...
[ "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 ...
[ "Entry", "point", "for", "invoking", "Alembic", "s", "CommandLine", "." ]
43dd793b1fc9b84e4056700f350e79e0df5ff501
https://github.com/globality-corp/microcosm-postgres/blob/43dd793b1fc9b84e4056700f350e79e0df5ff501/microcosm_postgres/migrate.py#L208-L231
train
26,478
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(...
python
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(...
[ "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
train
26,479
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_objec...
python
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_objec...
[ "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
train
26,480
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(e...
python
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(e...
[ "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
train
26,481
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 = defaultdi...
python
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 = defaultdi...
[ "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
train
26,482
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 o...
python
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 o...
[ "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
train
26,483
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 li...
python
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 li...
[ "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
train
26,484
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` d...
python
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` d...
[ "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`)....
[ "Intercept", "SQLAlchemy", "s", "instance", "init", "event", "." ]
43dd793b1fc9b84e4056700f350e79e0df5ff501
https://github.com/globality-corp/microcosm-postgres/blob/43dd793b1fc9b84e4056700f350e79e0df5ff501/microcosm_postgres/encryption/models.py#L14-L44
train
26,485
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): """ Intercept SQLAlchemy's instance load event. """ 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
train
26,486
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 c...
python
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 c...
[ "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
train
26,487
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 "__tablenam...
python
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 "__tablenam...
[ "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
train
26,488
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,...
python
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,...
[ "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
train
26,489
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=no...
python
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=no...
[ "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
train
26,490
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): """ 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)
[ "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
train
26,491
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): """ 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))
[ "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
train
26,492
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 datab...
python
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 datab...
[ "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
train
26,493
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 -- databa...
python
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 -- databa...
[ "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
train
26,494
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}://{use...
python
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}://{use...
[ "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
train
26,495
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( ...
python
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( ...
[ "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
train
26,496
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): """ 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, ...
[ "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
train
26,497
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(val...
python
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(val...
[ "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
train
26,498
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): """ 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
[ "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
train
26,499