idx int64 0 63k | question stringlengths 53 5.28k | target stringlengths 5 805 |
|---|---|---|
26,400 | def register_backend ( cls : Type [ StorageBackend ] ) : if not issubclass ( cls , StorageBackend ) : raise TypeError ( "cls must be a subclass of StorageBackend" ) __registry__ [ cls . NAME ] = cls return cls | Decorator to register another StorageBackend using it s NAME . |
26,401 | def create_backend ( name : str = None , git_index : GitIndex = None , args : str = None ) -> StorageBackend : if name is None : name = config . BACKEND if not args : args = config . BACKEND_ARGS if args : try : kwargs = dict ( p . split ( "=" ) for p in args . split ( "," ) ) except : raise ValueError ( "Invalid args"... | Initialize a new StorageBackend by it s name and the specified model registry . |
26,402 | def create_backend_noexc ( log : logging . Logger , name : str = None , git_index : GitIndex = None , args : str = None ) -> Optional [ StorageBackend ] : try : return create_backend ( name , git_index , args ) except KeyError : log . critical ( "No such backend: %s (looked in %s)" , name , list ( __registry__ . keys (... | Initialize a new Backend return None if there was a known problem . |
26,403 | def supply_backend ( optional : Union [ callable , bool ] = False , index_exists : bool = True ) : real_optional = False if callable ( optional ) else optional def supply_backend_inner ( func ) : @ wraps ( func ) def wrapped_supply_backend ( args ) : log = logging . getLogger ( func . __name__ ) if real_optional and no... | Decorator to pass the initialized backend to the decorated callable . \ Used by command line entries . If the backend cannot be created return 1 . |
26,404 | def generate_new_meta ( name : str , description : str , vendor : str , license : str ) -> dict : check_license ( license ) return { "code" : None , "created_at" : get_datetime_now ( ) , "datasets" : [ ] , "dependencies" : [ ] , "description" : description , "vendor" : vendor , "environment" : collect_environment_witho... | Create the metadata tree for the given model name and the list of dependencies . |
26,405 | def extract_model_meta ( base_meta : dict , extra_meta : dict , model_url : str ) -> dict : meta = { "default" : { "default" : base_meta [ "uuid" ] , "description" : base_meta [ "description" ] , "code" : extra_meta [ "code" ] } } del base_meta [ "model" ] del base_meta [ "uuid" ] meta [ "model" ] = base_meta meta [ "m... | Merge the metadata from the backend and the extra metadata into a dict which is suitable for \ index . json . |
26,406 | def squeeze_bits ( arr : numpy . ndarray ) -> numpy . ndarray : 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 elif mlbl <= 16 : dtype = numpy . uint16 elif mlbl <= 32 : dtype = numpy ... | Return a copy of an integer numpy array with the minimum bitness . |
26,407 | def metaprop ( name : str , doc : str , readonly = False ) : 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 ] = value set . __doc__ = "Set %s." % doc return property ( get , set ) re... | Temporary property builder . |
26,408 | def derive ( self , new_version : Union [ tuple , list ] = None ) -> "Model" : meta = self . meta first_time = self . _initial_version == self . version if new_version is None : new_version = meta [ "version" ] new_version [ - 1 ] += 1 if not isinstance ( new_version , ( tuple , list ) ) : raise ValueError ( "new_versi... | Inherit the new model from the current one - used for versioning . \ This operation is in - place . |
26,409 | 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 " "modelforgecfg.py file which sets VENDOR and the rest." ) return os . path . join ( "~" , "." + config . VEND... | Return the default cache directory where downloaded models are stored . |
26,410 | def get_dep ( self , name : str ) -> str : deps = self . meta [ "dependencies" ] for d in deps : if d [ "model" ] == name : return d raise KeyError ( "%s not found in %s." % ( name , deps ) ) | Return the uuid of the dependency identified with name . |
26,411 | def set_dep ( self , * deps ) -> "Model" : self . meta [ "dependencies" ] = [ ( d . meta if not isinstance ( d , dict ) else d ) for d in deps ] return self | Register the dependencies for this model . |
26,412 | def save ( self , output : Union [ str , BinaryIO ] , series : Optional [ str ] = None , deps : Iterable = tuple ( ) , create_missing_dirs : bool = True ) -> "Model" : check_license ( self . license ) if series is None : if self . series is None : raise ValueError ( "series must be specified" ) else : self . series = s... | Serialize the model to a file . |
26,413 | def _write_tree ( self , tree : dict , output : Union [ str , BinaryIO ] , file_mode : int = 0o666 ) -> None : self . meta [ "created_at" ] = get_datetime_now ( ) meta = self . meta . copy ( ) meta [ "environment" ] = collect_environment ( ) final_tree = { } final_tree . update ( tree ) final_tree [ "meta" ] = meta isf... | Write the model to disk . |
26,414 | def refresh ( ) : 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_FILE in override_files : del override_files [ override_files . index ( OVERRIDE_FILE... | Scan over all the involved directories and load configs from them . |
26,415 | def create_client ( self ) -> "google.cloud.storage.Client" : from google . cloud . storage import Client if self . credentials : client = Client . from_service_account_json ( self . credentials ) else : client = Client ( ) return client | Construct GCS API client . |
26,416 | def connect ( self ) -> "google.cloud.storage.Bucket" : log = self . _log log . info ( "Connecting to the bucket..." ) client = self . create_client ( ) return client . lookup_bucket ( self . bucket_name ) | Connect to the assigned bucket . |
26,417 | def reset ( self , force ) : client = self . create_client ( ) bucket = client . lookup_bucket ( self . bucket_name ) if bucket is not None : if not force : self . _log . error ( "Bucket already exists, aborting." ) raise ExistingBackendError self . _log . info ( "Bucket already exists, deleting all content." ) for blo... | Connect to the assigned bucket or create if needed . Clear all the blobs inside . |
26,418 | def upload_model ( self , path : str , meta : dict , force : bool ) : 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 : self . _log . error ( "Model %s already exists, abor... | Put the model to GCS . |
26,419 | def fetch_model ( self , source : str , file : Union [ str , BinaryIO ] , chunk_size : int = DEFAULT_DOWNLOAD_CHUNK_SIZE ) -> None : download_http ( source , file , self . _log , chunk_size ) | Download the model from GCS . |
26,420 | def delete_model ( self , meta : dict ) : 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 ( "Deleting model ..." ) bucket . delete_blob ( blob_name ) except NotFo... | Delete the model from GCS . |
26,421 | def download_http ( source : str , file : Union [ str , BinaryIO ] , log : logging . Logger , chunk_size : int = DEFAULT_DOWNLOAD_CHUNK_SIZE ) -> None : log . info ( "Fetching %s..." , source ) r = requests . get ( source , stream = True ) if r . status_code != 200 : log . error ( "An error occurred while fetching the ... | Download a file from an HTTP source . |
26,422 | def upload_model ( self , path : str , meta : dict , force : bool ) -> str : raise NotImplementedError | Put the given file to the remote storage . |
26,423 | def setup ( level : Union [ str , int ] , structured : bool , config_path : str = None ) : global logs_are_structured logs_are_structured = structured if not isinstance ( level , int ) : level = logging . _nameToLevel [ level ] def ensure_utf8_stream ( stream ) : if not isinstance ( stream , io . StringIO ) and hasattr... | Make stdout and stderr unicode friendly in case of misconfigured \ environments initializes the logging structured logging and \ enables colored logs if it is appropriate . |
26,424 | def set_context ( context ) : try : handler = logging . getLogger ( ) . handlers [ 0 ] except IndexError : return if not isinstance ( handler , StructuredHandler ) : return handler . acquire ( ) try : handler . local . context = context finally : handler . release ( ) | Assign the logging context - an abstract object - to the current thread . |
26,425 | def add_logging_args ( parser : argparse . ArgumentParser , patch : bool = True , erase_args : bool = True ) -> None : parser . add_argument ( "--log-level" , default = "INFO" , choices = logging . _nameToLevel , help = "Logging verbosity." ) parser . add_argument ( "--log-structured" , action = "store_true" , help = "... | Add command line flags specific to logging . |
26,426 | def array2string ( arr : numpy . ndarray ) -> str : shape = str ( arr . shape ) [ 1 : - 1 ] if shape . endswith ( "," ) : shape = shape [ : - 1 ] return numpy . array2string ( arr , threshold = 11 ) + "%s[%s]" % ( arr . dtype , shape ) | Format numpy array as a string . |
26,427 | def getMessage ( self ) : if isinstance ( self . msg , numpy . ndarray ) : msg = self . array2string ( self . msg ) else : msg = str ( self . msg ) if self . args : a2s = self . array2string if isinstance ( self . args , Dict ) : args = { k : ( a2s ( v ) if isinstance ( v , numpy . ndarray ) else v ) for ( k , v ) in s... | Return the message for this LogRecord . |
26,428 | def formatMessage ( self , record : logging . LogRecord ) -> str : level_color = "0" text_color = "0" fmt = "" if record . levelno <= logging . DEBUG : fmt = "\033[0;37m" + logging . BASIC_FORMAT + "\033[0m" elif record . levelno <= logging . INFO : level_color = "1;36" lmsg = record . message . lower ( ) if self . GRE... | Convert the already filled log record to a string . |
26,429 | def emit ( self , record : logging . LogRecord ) : created = datetime . datetime . fromtimestamp ( record . created , timezone ) obj = { "level" : record . levelname . lower ( ) , "msg" : record . msg % record . args , "source" : "%s:%d" % ( record . filename , record . lineno ) , "time" : format_datetime ( created ) ,... | Print the log record formatted as JSON to stdout . |
26,430 | def register_model ( cls : Type [ Model ] ) : if not issubclass ( cls , Model ) : raise TypeError ( "model bust be a subclass of Model" ) if issubclass ( cls , GenericModel ) : raise TypeError ( "model must not be a subclass of GenericModel" ) __models__ . add ( cls ) return cls | Include the given model class into the registry . |
26,431 | def fetch ( self ) : 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_url , self . cached_repo , checkout = True )... | Load from the associated Git repository . |
26,432 | def update_readme ( self , template_readme : Template ) : 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_type , model_uuids in self . models . items ( ) : for model... | Generate the new README file locally . |
26,433 | def reset ( self ) : 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 ) : paths . append ( path ) elif os . path . isdir ( path ) : for model in os . listdir ( path ) : ... | Initialize the remote Git repository . |
26,434 | def upload ( self , cmd : str , meta : dict ) : 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 _out : json . dump ( self . contents , _out ) git . add ( self ... | Push the current state of the registry to Git . |
26,435 | def load_template ( self , template : str ) -> Template : 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 file name must end with %s" % jinja2_ext ) raise ValueError if not templat... | Load a Jinja2 template from the source directory . |
26,436 | def progress_bar ( enumerable , logger , ** kwargs ) : if not logger . isEnabledFor ( logging . INFO ) or sys . stdin . closed or not sys . stdin . isatty ( ) : return enumerable return progress . bar ( enumerable , ** kwargs ) | Show the progress bar in the terminal if the logging level matches and we are interactive . |
26,437 | def collect_environment ( no_cache : bool = False ) -> dict : global _env if _env is None or no_cache : _env = collect_environment_without_packages ( ) _env [ "packages" ] = collect_loaded_packages ( ) return _env | Return the version of the Python executable the versions of the currently loaded packages \ and the running platform . |
26,438 | def collect_loaded_packages ( ) -> List [ Tuple [ str , str ] ] : dists = get_installed_distributions ( ) get_dist_files = DistFilesFinder ( ) file_table = { } for dist in dists : for file in get_dist_files ( dist ) : file_table [ file ] = dist used_dists = set ( ) for module in list ( sys . modules . values ( ) ) : tr... | Return the currently loaded package names and their versions . |
26,439 | def setup_blueprint ( self ) : 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 . blueprint . add_url_rule ( "/threads" , "threads" , self . threads_bt ... | Initialize the blueprint . |
26,440 | def _add_routes ( self ) : 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 ) | Add some nice default routes . |
26,441 | def get_argparser ( parser = None ) : 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 ) parser . add_argument ( "--debug" , "-d" , default... | Customize a parser to get the correct options . |
26,442 | def setup_prometheus ( self , registry = None ) : kwargs = { } if registry : kwargs [ "registry" ] = registry self . metrics = PrometheusMetrics ( self . app , ** kwargs ) try : version = pkg_resources . require ( self . app . name ) [ 0 ] . version except pkg_resources . DistributionNotFound : version = "unknown" self... | Setup Prometheus . |
26,443 | def add_url_rule ( self , route , endpoint , handler ) : self . app . add_url_rule ( route , endpoint , handler ) | Add a new url route . |
26,444 | def healthy ( self ) : try : if self . is_healthy ( ) : return "OK" , 200 else : return "FAIL" , 500 except Exception as e : self . app . logger . exception ( e ) return str ( e ) , 500 | Return 200 is healthy else 500 . |
26,445 | def ready ( self ) : try : if self . is_ready ( ) : return "OK" , 200 else : return "FAIL" , 500 except Exception as e : self . app . logger . exception ( ) return str ( e ) , 500 | Return 200 is ready else 500 . |
26,446 | def threads_bt ( self ) : import threading import traceback threads = { } for thread in threading . enumerate ( ) : frames = sys . _current_frames ( ) . get ( thread . ident ) if frames : stack = traceback . format_stack ( frames ) else : stack = [ ] threads [ thread ] = "" . join ( stack ) return flask . render_templa... | Display thread backtraces . |
26,447 | def run_with_werkzeug ( self , ** options ) : threaded = self . threads is not None and ( self . threads > 0 ) self . app . run ( host = self . host , port = self . port , debug = self . debug , threaded = threaded , ** options ) | Run with werkzeug simple wsgi container . |
26,448 | def run_with_twisted ( self , ** options ) : from twisted . internet import reactor from twisted . python import log import flask_twisted twisted = flask_twisted . Twisted ( self . app ) if self . threads : reactor . suggestThreadPoolSize ( self . threads ) if self . log_level : log . startLogging ( sys . stderr ) twis... | Run with twisted . |
26,449 | def run_with_gunicorn ( self , ** options ) : import gunicorn . app . base from gunicorn . six import iteritems import multiprocessing class GourdeApplication ( gunicorn . app . base . BaseApplication ) : def __init__ ( self , app , options = None ) : self . options = options or { } self . application = app super ( Gou... | Run with gunicorn . |
26,450 | def initialize_api ( flask_app ) : if not flask_restplus : return api = flask_restplus . Api ( version = "1.0" , title = "My Example API" ) api . add_resource ( HelloWorld , "/hello" ) blueprint = flask . Blueprint ( "api" , __name__ , url_prefix = "/api" ) api . init_app ( blueprint ) flask_app . register_blueprint ( ... | Initialize an API . |
26,451 | def initialize_app ( flask_app , args ) : gourde . setup ( args ) gourde . is_healthy = is_healthy initialize_api ( flask_app ) | Initialize the App . |
26,452 | def quote ( text , limit = 1000 ) : lines = text . split ( '\n' ) found = _internal . find_quote_position ( lines , _patterns . MAX_WRAP_LINES , limit ) if found != None : return [ ( True , '\n' . join ( lines [ : found + 1 ] ) ) , ( False , '\n' . join ( lines [ found + 1 : ] ) ) ] return [ ( True , text ) ] | 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 . |
26,453 | def extract_headers ( lines , max_wrap_lines ) : hdrs = { } header_name = None extend_lines = 0 lines_processed = 0 for n , line in enumerate ( lines ) : if not line . strip ( ) : header_name = None continue match = HEADER_RE . match ( line ) if match : header_name , header_value = match . groups ( ) header_name = head... | Extracts email headers from the given lines . Returns a dict with the detected headers and the amount of lines that were processed . |
26,454 | def trim_tree_after ( element , include_element = True ) : el = element for parent_el in element . iterancestors ( ) : el . tail = None if el != element or include_element : el = el . getnext ( ) while el is not None : remove_el = el el = el . getnext ( ) parent_el . remove ( remove_el ) el = parent_el | 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 . |
26,455 | def trim_tree_before ( element , include_element = True , keep_head = True ) : el = element for parent_el in element . iterancestors ( ) : parent_el . text = None if el != element or include_element : el = el . getprevious ( ) else : parent_el . text = el . tail while el is not None : remove_el = el el = el . getprevio... | 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 . |
26,456 | def get_epsg ( self ) : cur = self . conn . cursor ( ) cur . execute ( "SELECT epsg_code FROM prj_epsg WHERE prjtext = ?" , ( self . prj , ) ) result = cur . fetchone ( ) if not result and self . call_remote_api : return self . call_api ( ) elif result is not None : self . epsg_code = result [ 0 ] return self . epsg_co... | Attempts to determine the EPSG code for a given PRJ file or other similar text - based spatial reference file . |
26,457 | def from_epsg ( self , epsg_code ) : self . epsg_code = epsg_code assert isinstance ( self . epsg_code , int ) cur = self . conn . cursor ( ) cur . execute ( "SELECT prjtext FROM prj_epsg WHERE epsg_code = ?" , ( self . epsg_code , ) ) result = cur . fetchone ( ) if result is not None : self . prj = result [ 0 ] return... | Loads self . prj by epsg_code . If prjtext not found returns False . |
26,458 | def to_prj ( self , filename ) : with open ( filename , "w" ) as fp : fp . write ( self . prj ) | Saves prj WKT to given file . |
26,459 | def get_current_head_version ( graph ) : script_dir = ScriptDirectory ( "/" , version_locations = [ graph . metadata . get_path ( "migrations" ) ] ) return script_dir . get_current_head ( ) | Returns the current head version . |
26,460 | def create_temporary_table ( from_table , name = None , on_commit = None ) : from_table = from_table . __table__ if hasattr ( from_table , "__table__" ) else from_table name = name or f"temporary_{from_table.name}" temporary_table = copy_table ( from_table , name ) temporary_table . _prefixes = list ( from_table . _pre... | Create a new temporary table from another table . |
26,461 | def get_current_head ( graph ) : session = new_session ( graph ) try : result = session . execute ( "SELECT version_num FROM alembic_version" ) except ProgrammingError : return None else : return result . scalar ( ) finally : session . close ( ) | Get the current database head revision if any . |
26,462 | def flushing ( self ) : try : yield self . session . flush ( ) except ( FlushError , IntegrityError ) as error : error_message = str ( error ) if "duplicate" in error_message : raise DuplicateModelError ( error ) if "already exists" in error_message : raise DuplicateModelError ( error ) if "conflicts with" in error_mes... | Flush the current session handling common errors . |
26,463 | def create ( self , instance ) : with self . flushing ( ) : if instance . id is None : instance . id = self . new_object_id ( ) self . session . add ( instance ) return instance | Create a new model instance . |
26,464 | 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 . |
26,465 | def count ( self , * criterion , ** kwargs ) : query = self . _query ( * criterion ) query = self . _filter ( query , ** kwargs ) return query . count ( ) | Count the number of models matching some criterion . |
26,466 | def search ( self , * criterion , ** kwargs ) : query = self . _query ( * criterion ) query = self . _order_by ( query , ** kwargs ) query = self . _filter ( query , ** kwargs ) query = self . _paginate ( query , ** kwargs ) return query . all ( ) | Return the list of models matching some criterion . |
26,467 | def search_first ( self , * criterion , ** kwargs ) : query = self . _query ( * criterion ) query = self . _order_by ( query , ** kwargs ) query = self . _filter ( query , ** kwargs ) query = self . _paginate ( query , ** kwargs ) return query . first ( ) | Returns the first match based on criteria or None . |
26,468 | def _filter ( self , query , ** kwargs ) : query = self . _auto_filter ( query , ** kwargs ) return query | Filter a query with user - supplied arguments . |
26,469 | def _retrieve ( self , * criterion ) : try : return self . _query ( * criterion ) . one ( ) except NoResultFound as error : raise ModelNotFoundError ( "{} not found" . format ( self . model_class . __name__ , ) , error , ) | Retrieve a model by some criteria . |
26,470 | def _delete ( self , * criterion ) : with self . flushing ( ) : count = self . _query ( * criterion ) . delete ( ) if count == 0 : raise ModelNotFoundError return True | Delete a model by some criterion . |
26,471 | def _query ( self , * criterion ) : return self . session . query ( self . model_class ) . filter ( * criterion ) | Construct a query for the model . |
26,472 | def maybe_transactional ( func ) : @ wraps ( func ) def wrapper ( * args , ** kwargs ) : commit = kwargs . get ( "commit" , True ) with transaction ( commit = commit ) : return func ( * args , ** kwargs ) return wrapper | Variant of transactional that will not commit if there s an argument commit with a falsey value . |
26,473 | def make_alembic_config ( temporary_dir , migrations_dir ) : config = Config ( ) config . set_main_option ( "temporary_dir" , temporary_dir ) config . set_main_option ( "migrations_dir" , migrations_dir ) return config | Alembic uses the alembic . ini file to configure where it looks for everything else . |
26,474 | def make_script_directory ( cls , config ) : temporary_dir = config . get_main_option ( "temporary_dir" ) migrations_dir = config . get_main_option ( "migrations_dir" ) return cls ( dir = temporary_dir , version_locations = [ migrations_dir ] , ) | Alembic uses a script directory to encapsulate its env . py file its migrations directory and its script . py . mako revision template . |
26,475 | def run_online_migration ( self ) : connectable = self . graph . postgres with connectable . connect ( ) as connection : context . configure ( connection = connection , target_metadata = Model . metadata , ** get_alembic_environment_options ( self . graph ) , ) with context . begin_transaction ( ) : context . run_migra... | Run an online migration using microcosm configuration . |
26,476 | def patch_script_directory ( graph ) : temporary_dir = mkdtemp ( ) from_config_original = getattr ( ScriptDirectory , "from_config" ) run_env_original = getattr ( ScriptDirectory , "run_env" ) with open ( join ( temporary_dir , "script.py.mako" ) , "w" ) as file_ : file_ . write ( make_script_py_mako ( ) ) file_ . flus... | Monkey patch the ScriptDirectory class working around configuration assumptions . |
26,477 | def get_migrations_dir ( graph ) : try : migrations_dir = graph . migrations_dir except ( LockedGraphError , NotBoundError ) : migrations_dir = graph . metadata . get_path ( "migrations" ) if not isdir ( migrations_dir ) : raise Exception ( "Migrations dir must exist: {}" . format ( migrations_dir ) ) return migrations... | Resolve the migrations directory path . |
26,478 | def main ( graph , * args ) : migrations_dir = get_migrations_dir ( graph ) cli = CommandLine ( ) options = cli . parser . parse_args ( args if args else argv [ 1 : ] ) if not hasattr ( options , "cmd" ) : cli . parser . error ( "too few arguments" ) if options . cmd [ 0 ] . __name__ == "init" : cli . parser . error ( ... | Entry point for invoking Alembic s CommandLine . |
26,479 | def configure_sessionmaker ( graph ) : engine_routing_strategy = getattr ( graph , graph . config . sessionmaker . engine_routing_strategy ) if engine_routing_strategy . supports_multiple_binds : ScopedFactory . infect ( graph , "postgres" ) class RoutingSession ( Session ) : def get_bind ( self , mapper = None , claus... | Create the SQLAlchemy session class . |
26,480 | def clone ( instance , substitutions , ignore = ( ) ) : substitutions [ instance . id ] = new_object_id ( ) def substitute ( value ) : try : hash ( value ) except Exception : return value else : return substitutions . get ( value , value ) return instance . __class__ ( ** { key : substitute ( value ) for key , value in... | Clone an instance of Model that uses IdentityMixin . |
26,481 | def configure_encryptor ( graph ) : encryptor = graph . multi_tenant_key_registry . make_encryptor ( graph ) for encryptable in EncryptableMixin . __subclasses__ ( ) : encryptable . register ( encryptor ) return encryptor | Create a MultiTenantEncryptor from configured keys . |
26,482 | def toposorted ( nodes , edges ) : incoming = defaultdict ( set ) outgoing = defaultdict ( set ) for edge in edges : incoming [ edge . to_id ] . add ( edge . from_id ) outgoing [ edge . from_id ] . add ( edge . to_id ) working_set = list ( nodes . values ( ) ) results = [ ] while working_set : remaining = [ ] for node ... | Perform a topological sort on the input resources . |
26,483 | def should_copy ( column ) : if not isinstance ( column . type , Serial ) : return True if column . nullable : return True if not column . server_default : return True return False | Determine if a column should be copied . |
26,484 | def encrypt ( self , encryption_context_key : str , plaintext : str ) -> Tuple [ bytes , Sequence [ str ] ] : encryption_context = dict ( microcosm = encryption_context_key , ) cyphertext , header = encrypt ( source = plaintext , materials_manager = self . materials_manager , encryption_context = encryption_context , )... | Encrypt a plaintext string value . |
26,485 | def on_init ( target : "EncryptableMixin" , args , kwargs ) : encryptor = target . __encryptor__ try : encryption_context_key = str ( kwargs [ target . __encryption_context_key__ ] ) except KeyError : return if encryption_context_key not in encryptor : return plaintext = target . plaintext_to_str ( kwargs . pop ( targe... | Intercept SQLAlchemy s instance init event . |
26,486 | def on_load ( target : "EncryptableMixin" , context ) : decrypt , plaintext = decrypt_instance ( target ) if decrypt : target . plaintext = plaintext | Intercept SQLAlchemy s instance load event . |
26,487 | def register ( cls , encryptor : Encryptor ) : cls . __encryptor__ = encryptor listeners = dict ( init = on_init , load = on_load , ) for name , func in listeners . items ( ) : if contains ( cls , name , func ) : remove ( cls , name , func ) listen ( cls , name , func ) | Register this encryptable with an encryptor . |
26,488 | def nodes_map ( self ) : dct = dict ( ) for node in self . nodes . values ( ) : cls = next ( base for base in getmro ( node . __class__ ) if "__tablename__" in base . __dict__ ) key = getattr ( cls , "__alias__" , underscore ( cls . __name__ ) ) dct . setdefault ( key , [ ] ) . append ( node ) return dct | Build a mapping from node type to a list of nodes . |
26,489 | def build_edges ( self ) : self . edges = [ edge if isinstance ( edge , Edge ) else Edge ( * edge ) for node in self . nodes . values ( ) for edge in getattr ( node , "edges" , [ ] ) if edge [ 0 ] in self . nodes and edge [ 1 ] in self . nodes ] return self | Build edges based on node edges property . |
26,490 | def clone ( self , ignore = ( ) ) : nodes = [ clone ( node , self . substitutions , ignore ) for node in toposorted ( self . nodes , self . edges ) ] return DAG ( nodes = nodes , substitutions = self . substitutions ) . build_edges ( ) | Clone this dag using a set of substitutions . |
26,491 | def explain ( self , ** kwargs ) : root = self . retrieve_root ( ** kwargs ) children = self . iter_children ( root , ** kwargs ) dag = DAG . from_nodes ( root , * children ) return self . add_edges ( dag ) | Generate a dry run DAG of that state that WILL be cloned . |
26,492 | def clone ( self , substitutions , ** kwargs ) : dag = self . explain ( ** kwargs ) dag . substitutions . update ( substitutions ) cloned_dag = dag . clone ( ignore = self . ignore ) return self . update_nodes ( self . add_edges ( cloned_dag ) ) | Clone a DAG . |
26,493 | def choose_database_name ( metadata , config ) : if config . database_name is not None : return config . database_name if metadata . testing : return f"{metadata.name}_test_db" return f"{metadata.name}_db" | Choose the database name to use . |
26,494 | def choose_username ( metadata , config ) : if config . username is not None : return config . username if config . read_only : return f"{metadata.name}_ro" return metadata . name | Choose the database username to use . |
26,495 | def choose_uri ( metadata , config ) : database_name = choose_database_name ( metadata , config ) driver = config . driver host , port = config . host , config . port username , password = choose_username ( metadata , config ) , config . password return f"{driver}://{username}:{password}@{host}:{port}/{database_name}" | Choose the database URI to use . |
26,496 | def choose_connect_args ( metadata , config ) : if not config . require_ssl and not config . verify_ssl : return dict ( sslmode = "prefer" , ) if config . require_ssl and not config . verify_ssl : return dict ( sslmode = "require" , ) if not config . ssl_cert_path : raise Exception ( "SSL certificate path (`ssl_cert_pa... | Choose the SSL mode and optional root cert for the connection . |
26,497 | def choose_args ( metadata , config ) : return dict ( connect_args = choose_connect_args ( metadata , config ) , echo = config . echo , max_overflow = config . max_overflow , pool_size = config . pool_size , pool_timeout = config . pool_timeout , ) | Choose database connection arguments . |
26,498 | def _members ( self ) : return { key : value for key , value in self . __dict__ . items ( ) if not key . startswith ( "_" ) and not isinstance ( value , Model ) } | Return a dict of non - private members . |
26,499 | def insert_many ( self , items ) : return SessionContext . session . execute ( self . insert ( values = [ to_dict ( item , self . c ) for item in items ] ) , ) . rowcount | Insert many items at once into a temporary table . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.