idx int64 0 251k | question stringlengths 53 3.53k | target stringlengths 5 1.23k | len_question int64 20 893 | len_target int64 3 238 |
|---|---|---|---|---|
26,200 | def path_param ( name , ns ) : if ns . identifier_type == "uuid" : param_type = "string" param_format = "uuid" else : param_type = "string" param_format = None kwargs = { "name" : name , "in" : "path" , "required" : True , "type" : param_type , } if param_format : kwargs [ "format" ] = param_format return swagger . PathParameterSubSchema ( * * kwargs ) | Build a path parameter definition . | 118 | 6 |
26,201 | def build_operation ( operation , ns , rule , func ) : swagger_operation = swagger . Operation ( operationId = operation_name ( operation , ns ) , parameters = swagger . ParametersList ( [ ] ) , responses = swagger . Responses ( ) , tags = [ ns . subject_name ] , ) # custom header parameter swagger_operation . parameters . append ( header_param ( "X-Response-Skip-Null" ) ) # path parameters swagger_operation . parameters . extend ( [ path_param ( argument , ns ) for argument in rule . arguments ] ) # query string parameters qs_schema = get_qs_schema ( func ) if qs_schema : swagger_operation . parameters . extend ( [ query_param ( name , field ) for name , field in qs_schema . fields . items ( ) ] ) # body parameter request_schema = get_request_schema ( func ) if request_schema : swagger_operation . parameters . append ( body_param ( request_schema ) ) # sort parameters for predictable output swagger_operation . parameters . sort ( key = lambda parameter : parameter [ "name" ] ) add_responses ( swagger_operation , operation , ns , func ) return swagger_operation | Build an operation definition . | 278 | 5 |
26,202 | def add_responses ( swagger_operation , operation , ns , func ) : # default error swagger_operation . responses [ "default" ] = build_response ( description = "An error occurred" , resource = type_name ( name_for ( ErrorSchema ( ) ) ) , ) if getattr ( func , "__doc__" , None ) : description = func . __doc__ . strip ( ) . splitlines ( ) [ 0 ] else : description = "{} {}" . format ( operation . value . name , ns . subject_name ) if operation in ( Operation . Upload , Operation . UploadFor ) : swagger_operation . consumes = [ "multipart/form-data" ] # resource request request_resource = get_request_schema ( func ) if isinstance ( request_resource , str ) : if not hasattr ( swagger_operation , "consumes" ) : swagger_operation . consumes = [ ] swagger_operation . consumes . append ( request_resource ) # resources response response_resource = get_response_schema ( func ) if isinstance ( response_resource , str ) : if not hasattr ( swagger_operation , "produces" ) : swagger_operation . produces = [ ] swagger_operation . produces . append ( response_resource ) elif not response_resource : response_code = ( 204 if operation . value . default_code == 200 else operation . value . default_code ) swagger_operation . responses [ str ( response_code ) ] = build_response ( description = description , ) else : swagger_operation . responses [ str ( operation . value . default_code ) ] = build_response ( description = description , resource = response_resource , ) | Add responses to an operation . | 375 | 6 |
26,203 | def build_response ( description , resource = None ) : response = swagger . Response ( description = description , ) if resource is not None : response . schema = swagger . JsonReference ( { "$ref" : "#/definitions/{}" . format ( type_name ( name_for ( resource ) ) ) , } ) return response | Build a response definition . | 73 | 5 |
26,204 | def iter_endpoints ( graph , match_func ) : for rule in graph . flask . url_map . iter_rules ( ) : try : operation , ns = Namespace . parse_endpoint ( rule . endpoint , get_converter ( rule ) ) except ( IndexError , ValueError , InternalServerError ) : # operation follows a different convention (e.g. "static") continue else : # match_func gets access to rule to support path version filtering if match_func ( operation , ns , rule ) : func = graph . flask . view_functions [ rule . endpoint ] yield operation , ns , rule , func | Iterate through matching endpoints . | 135 | 7 |
26,205 | def get_converter ( rule ) : for converter , _ , _ in parse_rule ( str ( rule ) ) : if converter is not None : return converter return None | Parse rule will extract the converter from the rule as a generator | 37 | 13 |
26,206 | def request ( schema ) : def wrapper ( func ) : setattr ( func , REQUEST , schema ) return func return wrapper | Decorate a function with a request schema . | 26 | 9 |
26,207 | def response ( schema ) : def wrapper ( func ) : setattr ( func , RESPONSE , schema ) return func return wrapper | Decorate a function with a response schema . | 27 | 9 |
26,208 | def qs ( schema ) : def wrapper ( func ) : setattr ( func , QS , schema ) return func return wrapper | Decorate a function with a query string schema . | 27 | 10 |
26,209 | def should_skip_logging ( func ) : disabled = strtobool ( request . headers . get ( "x-request-nolog" , "false" ) ) return disabled or getattr ( func , SKIP_LOGGING , False ) | Should we skip logging for this handler? | 55 | 8 |
26,210 | def logging_levels ( ) : enabled = strtobool ( request . headers . get ( "x-request-debug" , "false" ) ) level = None try : if enabled : level = getLogger ( ) . getEffectiveLevel ( ) getLogger ( ) . setLevel ( DEBUG ) yield finally : if enabled : getLogger ( ) . setLevel ( level ) | Context manager to conditionally set logging levels . | 82 | 9 |
26,211 | def audit ( func ) : @ wraps ( func ) def wrapper ( * args , * * kwargs ) : options = AuditOptions ( include_request_body = DEFAULT_INCLUDE_REQUEST_BODY , include_response_body = DEFAULT_INCLUDE_RESPONSE_BODY , include_path = True , include_query_string = True , ) with logging_levels ( ) : return _audit_request ( options , func , None , * args , * * kwargs ) return wrapper | Record a Flask route function in the audit log . | 117 | 10 |
26,212 | def _audit_request ( options , func , request_context , * args , * * kwargs ) : # noqa: C901 logger = getLogger ( "audit" ) request_info = RequestInfo ( options , func , request_context ) response = None request_info . capture_request ( ) try : # process the request with elapsed_time ( request_info . timing ) : response = func ( * args , * * kwargs ) except Exception as error : request_info . capture_error ( error ) raise else : request_info . capture_response ( response ) return response finally : if not should_skip_logging ( func ) : request_info . log ( logger ) | Run a request function under audit . | 152 | 7 |
26,213 | def parse_response ( response ) : if isinstance ( response , tuple ) : if len ( response ) > 2 : return response [ 0 ] , response [ 1 ] , response [ 2 ] elif len ( response ) > 1 : return response [ 0 ] , response [ 1 ] , { } try : return response . data , response . status_code , response . headers except AttributeError : return response , 200 , { } | Parse a Flask response into a body a status code and headers | 90 | 13 |
26,214 | def configure_audit_decorator ( graph ) : include_request_body = int ( graph . config . audit . include_request_body ) include_response_body = int ( graph . config . audit . include_response_body ) include_path = strtobool ( graph . config . audit . include_path ) include_query_string = strtobool ( graph . config . audit . include_query_string ) def _audit ( func ) : @ wraps ( func ) def wrapper ( * args , * * kwargs ) : options = AuditOptions ( include_request_body = include_request_body , include_response_body = include_response_body , include_path = include_path , include_query_string = include_query_string , ) return _audit_request ( options , func , graph . request_context , * args , * * kwargs ) return wrapper return _audit | Configure the audit decorator . | 203 | 7 |
26,215 | def configure_route_decorator ( graph ) : enable_audit = graph . config . route . enable_audit enable_basic_auth = graph . config . route . enable_basic_auth enable_context_logger = graph . config . route . enable_context_logger enable_cors = graph . config . route . enable_cors # routes depends on converters graph . use ( * graph . config . route . converters ) def route ( path , operation , ns ) : """ :param path: a URI path, possibly derived from a property of the `ns` :param operation: an `Operation` enum value :param ns: a `Namespace` instance """ def decorator ( func ) : endpoint = ns . endpoint_for ( operation ) endpoint_path = graph . build_route_path ( path , ns . prefix ) if enable_cors : func = cross_origin ( supports_credentials = True ) ( func ) if enable_basic_auth or ns . enable_basic_auth : func = graph . basic_auth . required ( func ) if enable_context_logger and ns . controller is not None : func = context_logger ( graph . request_context , func , parent = ns . controller , ) # set the opaque component data_func to look at the flask request context func = graph . opaque . initialize ( graph . request_context ) ( func ) if graph . route_metrics . enabled : func = graph . route_metrics ( endpoint ) ( func ) # keep audit decoration last (before registering the route) so that # errors raised by other decorators are captured in the audit trail if enable_audit : func = graph . audit ( func ) graph . app . route ( endpoint_path , endpoint = endpoint , methods = [ operation . value . method ] , ) ( func ) return func return decorator return route | Configure a flask route decorator that operates on Operation and Namespace objects . | 401 | 16 |
26,216 | def extract_status_code ( error ) : try : return int ( error . code ) except ( AttributeError , TypeError , ValueError ) : try : return int ( error . status_code ) except ( AttributeError , TypeError , ValueError ) : try : return int ( error . errno ) except ( AttributeError , TypeError , ValueError ) : return 500 | Extract an error code from a message . | 81 | 9 |
26,217 | def extract_error_message ( error ) : try : return error . description or error . __class__ . __name__ except AttributeError : try : return str ( error . message ) or error . __class__ . __name__ except AttributeError : return str ( error ) or error . __class__ . __name__ | Extract a useful message from an error . | 70 | 9 |
26,218 | def make_json_error ( error ) : message = extract_error_message ( error ) status_code = extract_status_code ( error ) context = extract_context ( error ) retryable = extract_retryable ( error ) headers = extract_headers ( error ) # Flask will not log user exception (fortunately), but will log an error # for exceptions that escape out of the application entirely (e.g. if the # error handler raises an error) error_logger . debug ( "Handling {} error: {}" . format ( status_code , message , ) ) # Serialize into JSON response response_data = { "code" : status_code , "context" : context , "message" : message , "retryable" : retryable , } # Don't pass in the error schema because it will suppress any extra fields return dump_response_data ( None , response_data , status_code , headers ) | Handle errors by logging and | 201 | 5 |
26,219 | def configure_error_handlers ( graph ) : # override all of the werkzeug HTTPExceptions for code in default_exceptions . keys ( ) : graph . flask . register_error_handler ( code , make_json_error ) # register catch all for user exceptions graph . flask . register_error_handler ( Exception , make_json_error ) | Register error handlers . | 78 | 4 |
26,220 | def to_json_type ( self ) : document_dict = self . _json_safe ( self . _document ) self . _remove_keys ( document_dict , self . _private_fields ) return document_dict | Return a dictionary for the document with values converted to JSON safe types . | 48 | 14 |
26,221 | def _json_safe ( cls , value ) : # Date if type ( value ) == date : return str ( value ) # Datetime elif type ( value ) == datetime : return value . strftime ( '%Y-%m-%d %H:%M:%S' ) # Object Id elif isinstance ( value , ObjectId ) : return str ( value ) # Frame elif isinstance ( value , _BaseFrame ) : return value . to_json_type ( ) # Lists elif isinstance ( value , ( list , tuple ) ) : return [ cls . _json_safe ( v ) for v in value ] # Dictionaries elif isinstance ( value , dict ) : return { k : cls . _json_safe ( v ) for k , v in value . items ( ) } return value | Return a JSON safe value | 182 | 5 |
26,222 | def _path_to_keys ( cls , path ) : # Paths are cached for performance keys = _BaseFrame . _path_to_keys_cache . get ( path ) if keys is None : keys = _BaseFrame . _path_to_keys_cache [ path ] = path . split ( '.' ) return keys | Return a list of keys for a given path | 72 | 9 |
26,223 | def _path_to_value ( cls , path , parent_dict ) : keys = cls . _path_to_keys ( path ) # Traverse to the tip of the path child_dict = parent_dict for key in keys [ : - 1 ] : child_dict = child_dict . get ( key ) if child_dict is None : return return child_dict . get ( keys [ - 1 ] ) | Return a value from a dictionary at the given path | 91 | 10 |
26,224 | def _remove_keys ( cls , parent_dict , paths ) : for path in paths : keys = cls . _path_to_keys ( path ) # Traverse to the tip of the path child_dict = parent_dict for key in keys [ : - 1 ] : child_dict = child_dict . get ( key ) if child_dict is None : break if child_dict is None : continue # Remove the key if keys [ - 1 ] in child_dict : child_dict . pop ( keys [ - 1 ] ) | Remove a list of keys from a dictionary . | 116 | 9 |
26,225 | def insert ( self ) : from mongoframes . queries import to_refs # Send insert signal signal ( 'insert' ) . send ( self . __class__ , frames = [ self ] ) # Prepare the document to be inserted document = to_refs ( self . _document ) # Insert the document and update the Id self . _id = self . get_collection ( ) . insert_one ( document ) . inserted_id # Send inserted signal signal ( 'inserted' ) . send ( self . __class__ , frames = [ self ] ) | Insert this document | 120 | 3 |
26,226 | def update ( self , * fields ) : from mongoframes . queries import to_refs assert '_id' in self . _document , "Can't update documents without `_id`" # Send update signal signal ( 'update' ) . send ( self . __class__ , frames = [ self ] ) # Check for selective updates if len ( fields ) > 0 : document = { } for field in fields : document [ field ] = self . _path_to_value ( field , self . _document ) else : document = self . _document # Prepare the document to be updated document = to_refs ( document ) document . pop ( '_id' , None ) # Update the document self . get_collection ( ) . update_one ( { '_id' : self . _id } , { '$set' : document } ) # Send updated signal signal ( 'updated' ) . send ( self . __class__ , frames = [ self ] ) | Update this document . Optionally a specific list of fields to update can be specified . | 209 | 17 |
26,227 | def upsert ( self , * fields ) : # If no `_id` is provided then we insert the document if not self . _id : return self . insert ( ) # If an `_id` is provided then we need to check if it exists before # performing the `upsert`. # if self . count ( { '_id' : self . _id } ) == 0 : self . insert ( ) else : self . update ( * fields ) | Update or Insert this document depending on whether it exists or not . The presense of an _id value in the document is used to determine if the document exists . | 97 | 33 |
26,228 | def delete ( self ) : assert '_id' in self . _document , "Can't delete documents without `_id`" # Send delete signal signal ( 'delete' ) . send ( self . __class__ , frames = [ self ] ) # Delete the document self . get_collection ( ) . delete_one ( { '_id' : self . _id } ) # Send deleted signal signal ( 'deleted' ) . send ( self . __class__ , frames = [ self ] ) | Delete this document | 107 | 3 |
26,229 | def insert_many ( cls , documents ) : from mongoframes . queries import to_refs # Ensure all documents have been converted to frames frames = cls . _ensure_frames ( documents ) # Send insert signal signal ( 'insert' ) . send ( cls , frames = frames ) # Prepare the documents to be inserted documents = [ to_refs ( f . _document ) for f in frames ] # Bulk insert ids = cls . get_collection ( ) . insert_many ( documents ) . inserted_ids # Apply the Ids to the frames for i , id in enumerate ( ids ) : frames [ i ] . _id = id # Send inserted signal signal ( 'inserted' ) . send ( cls , frames = frames ) return frames | Insert a list of documents | 168 | 5 |
26,230 | def update_many ( cls , documents , * fields ) : from mongoframes . queries import to_refs # Ensure all documents have been converted to frames frames = cls . _ensure_frames ( documents ) all_count = len ( documents ) assert len ( [ f for f in frames if '_id' in f . _document ] ) == all_count , "Can't update documents without `_id`s" # Send update signal signal ( 'update' ) . send ( cls , frames = frames ) # Prepare the documents to be updated # Check for selective updates if len ( fields ) > 0 : documents = [ ] for frame in frames : document = { '_id' : frame . _id } for field in fields : document [ field ] = cls . _path_to_value ( field , frame . _document ) documents . append ( to_refs ( document ) ) else : documents = [ to_refs ( f . _document ) for f in frames ] # Update the documents for document in documents : _id = document . pop ( '_id' ) cls . get_collection ( ) . update ( { '_id' : _id } , { '$set' : document } ) # Send updated signal signal ( 'updated' ) . send ( cls , frames = frames ) | Update multiple documents . Optionally a specific list of fields to update can be specified . | 287 | 17 |
26,231 | def delete_many ( cls , documents ) : # Ensure all documents have been converted to frames frames = cls . _ensure_frames ( documents ) all_count = len ( documents ) assert len ( [ f for f in frames if '_id' in f . _document ] ) == all_count , "Can't delete documents without `_id`s" # Send delete signal signal ( 'delete' ) . send ( cls , frames = frames ) # Prepare the documents to be deleted ids = [ f . _id for f in frames ] # Delete the documents cls . get_collection ( ) . delete_many ( { '_id' : { '$in' : ids } } ) # Send deleted signal signal ( 'deleted' ) . send ( cls , frames = frames ) | Delete multiple documents | 174 | 3 |
26,232 | def _ensure_frames ( cls , documents ) : frames = [ ] for document in documents : if not isinstance ( document , Frame ) : frames . append ( cls ( document ) ) else : frames . append ( document ) return frames | Ensure all items in a list are frames by converting those that aren t . | 52 | 16 |
26,233 | def reload ( self , * * kwargs ) : frame = self . one ( { '_id' : self . _id } , * * kwargs ) self . _document = frame . _document | Reload the document | 45 | 4 |
26,234 | def count ( cls , filter = None , * * kwargs ) : from mongoframes . queries import Condition , Group , to_refs if isinstance ( filter , ( Condition , Group ) ) : filter = filter . to_dict ( ) return cls . get_collection ( ) . count ( to_refs ( filter ) , * * kwargs ) | Return a count of documents matching the filter | 82 | 8 |
26,235 | def ids ( cls , filter = None , * * kwargs ) : from mongoframes . queries import Condition , Group , to_refs # Find the documents if isinstance ( filter , ( Condition , Group ) ) : filter = filter . to_dict ( ) documents = cls . get_collection ( ) . find ( to_refs ( filter ) , projection = { '_id' : True } , * * kwargs ) return [ d [ '_id' ] for d in list ( documents ) ] | Return a list of Ids for documents matching the filter | 116 | 11 |
26,236 | def one ( cls , filter = None , * * kwargs ) : from mongoframes . queries import Condition , Group , to_refs # Flatten the projection kwargs [ 'projection' ] , references , subs = cls . _flatten_projection ( kwargs . get ( 'projection' , cls . _default_projection ) ) # Find the document if isinstance ( filter , ( Condition , Group ) ) : filter = filter . to_dict ( ) document = cls . get_collection ( ) . find_one ( to_refs ( filter ) , * * kwargs ) # Make sure we found a document if not document : return # Dereference the document (if required) if references : cls . _dereference ( [ document ] , references ) # Add sub-frames to the document (if required) if subs : cls . _apply_sub_frames ( [ document ] , subs ) return cls ( document ) | Return the first document matching the filter | 215 | 7 |
26,237 | def many ( cls , filter = None , * * kwargs ) : from mongoframes . queries import Condition , Group , to_refs # Flatten the projection kwargs [ 'projection' ] , references , subs = cls . _flatten_projection ( kwargs . get ( 'projection' , cls . _default_projection ) ) # Find the documents if isinstance ( filter , ( Condition , Group ) ) : filter = filter . to_dict ( ) documents = list ( cls . get_collection ( ) . find ( to_refs ( filter ) , * * kwargs ) ) # Dereference the documents (if required) if references : cls . _dereference ( documents , references ) # Add sub-frames to the documents (if required) if subs : cls . _apply_sub_frames ( documents , subs ) return [ cls ( d ) for d in documents ] | Return a list of documents matching the filter | 206 | 8 |
26,238 | def _apply_sub_frames ( cls , documents , subs ) : # Dereference each reference for path , projection in subs . items ( ) : # Get the SubFrame class we'll use to wrap the embedded document sub = None expect_map = False if '$sub' in projection : sub = projection . pop ( '$sub' ) elif '$sub.' in projection : sub = projection . pop ( '$sub.' ) expect_map = True else : continue # Add sub-frames to the documents raw_subs = [ ] for document in documents : value = cls . _path_to_value ( path , document ) if value is None : continue if isinstance ( value , dict ) : if expect_map : # Dictionary of embedded documents raw_subs += value . values ( ) for k , v in value . items ( ) : if isinstance ( v , list ) : value [ k ] = [ sub ( u ) for u in v if isinstance ( u , dict ) ] else : value [ k ] = sub ( v ) # Single embedded document else : raw_subs . append ( value ) value = sub ( value ) elif isinstance ( value , list ) : # List of embedded documents raw_subs += value value = [ sub ( v ) for v in value if isinstance ( v , dict ) ] else : raise TypeError ( 'Not a supported sub-frame type' ) child_document = document keys = cls . _path_to_keys ( path ) for key in keys [ : - 1 ] : child_document = child_document [ key ] child_document [ keys [ - 1 ] ] = value # Apply the projection to the list of sub frames if projection : sub . _apply_projection ( raw_subs , projection ) | Convert embedded documents to sub - frames for one or more documents | 384 | 13 |
26,239 | def _dereference ( cls , documents , references ) : # Dereference each reference for path , projection in references . items ( ) : # Check there is a $ref in the projection, else skip it if '$ref' not in projection : continue # Collect Ids of documents to dereference ids = set ( ) for document in documents : value = cls . _path_to_value ( path , document ) if not value : continue if isinstance ( value , list ) : ids . update ( value ) elif isinstance ( value , dict ) : ids . update ( value . values ( ) ) else : ids . add ( value ) # Find the referenced documents ref = projection . pop ( '$ref' ) frames = ref . many ( { '_id' : { '$in' : list ( ids ) } } , projection = projection ) frames = { f . _id : f for f in frames } # Add dereferenced frames to the document for document in documents : value = cls . _path_to_value ( path , document ) if not value : continue if isinstance ( value , list ) : # List of references value = [ frames [ id ] for id in value if id in frames ] elif isinstance ( value , dict ) : # Dictionary of references value = { key : frames . get ( id ) for key , id in value . items ( ) } else : value = frames . get ( value , None ) child_document = document keys = cls . _path_to_keys ( path ) for key in keys [ : - 1 ] : child_document = child_document [ key ] child_document [ keys [ - 1 ] ] = value | Dereference one or more documents | 366 | 7 |
26,240 | def listen ( cls , event , func ) : signal ( event ) . connect ( func , sender = cls ) | Add a callback for a signal against the class | 25 | 9 |
26,241 | def stop_listening ( cls , event , func ) : signal ( event ) . disconnect ( func , sender = cls ) | Remove a callback for a signal against the class | 28 | 9 |
26,242 | def get_db ( cls ) : if cls . _db : return getattr ( cls . _client , cls . _db ) return cls . _client . get_default_database ( ) | Return the database for the collection | 46 | 6 |
26,243 | def _default_service_formatter ( service_url , width , height , background , foreground , options ) : # Build the base URL image_tmp = '{service_url}/{width}x{height}/{background}/{foreground}/' image_url = image_tmp . format ( service_url = service_url , width = width , height = height , background = background , foreground = foreground ) # Add any options if options : image_url += '?' + urlencode ( options ) return image_url | Generate an image URL for a service | 116 | 8 |
26,244 | def _body ( self , paragraphs ) : body = [ ] for i in range ( paragraphs ) : paragraph = self . _paragraph ( random . randint ( 1 , 10 ) ) body . append ( paragraph ) return '\n' . join ( body ) | Generate a body of text | 54 | 6 |
26,245 | def _paragraph ( self , sentences ) : paragraph = [ ] for i in range ( sentences ) : sentence = self . _sentence ( random . randint ( 5 , 16 ) ) paragraph . append ( sentence ) return ' ' . join ( paragraph ) | Generate a paragraph | 53 | 4 |
26,246 | def _sentence ( self , words ) : db = self . database # Generate 2 words to start a sentence with seed = random . randint ( 0 , db [ 'word_count' ] - 3 ) seed_word , next_word = db [ 'words' ] [ seed ] , db [ 'words' ] [ seed + 1 ] w1 , w2 = seed_word , next_word # Generate the complete sentence sentence = [ ] for i in range ( 0 , words - 1 ) : sentence . append ( w1 ) w1 , w2 = w2 , random . choice ( db [ 'freqs' ] [ ( w1 , w2 ) ] ) sentence . append ( w2 ) # Make the sentence respectable sentence = ' ' . join ( sentence ) # Capitalize the sentence sentence = sentence . capitalize ( ) # Remove additional sentence ending puntuation sentence = sentence . replace ( '.' , '' ) sentence = sentence . replace ( '!' , '' ) sentence = sentence . replace ( '?' , '' ) sentence = sentence . replace ( ':' , '' ) # Remove quote tags sentence = sentence . replace ( '.' , '' ) sentence = sentence . replace ( '!' , '' ) sentence = sentence . replace ( '?' , '' ) sentence = sentence . replace ( ':' , '' ) sentence = sentence . replace ( '"' , '' ) # If the last character is not an alphanumeric remove it sentence = re . sub ( '[^a-zA-Z0-9]$' , '' , sentence ) # Remove excess space sentence = re . sub ( '\s+' , ' ' , sentence ) # Add a full stop sentence += '.' return sentence | Generate a sentence | 359 | 4 |
26,247 | def init_word_db ( cls , name , text ) : # Prep the words text = text . replace ( '\n' , ' ' ) . replace ( '\r' , ' ' ) words = [ w . strip ( ) for w in text . split ( ' ' ) if w . strip ( ) ] assert len ( words ) > 2 , 'Database text sources must contain 3 or more words.' # Build the database freqs = { } for i in range ( len ( words ) - 2 ) : # Create a triplet from the current word w1 = words [ i ] w2 = words [ i + 1 ] w3 = words [ i + 2 ] # Add the triplet to the database key = ( w1 , w2 ) if key in freqs : freqs [ key ] . append ( w3 ) else : freqs [ key ] = [ w3 ] # Store the database so it can be used cls . _dbs [ name ] = { 'freqs' : freqs , 'words' : words , 'word_count' : len ( words ) - 2 } | Initialize a database of words for the maker with the given name | 237 | 13 |
26,248 | def p ( i , sample_size , weights ) : # Determine the initial pick values weight_i = weights [ i ] weights_sum = sum ( weights ) # Build a list of weights that don't contain the weight `i`. This list will # be used to build the possible picks before weight `i`. other_weights = list ( weights ) del other_weights [ i ] # Calculate the probability probability_of_i = 0 for picks in range ( 0 , sample_size ) : # Build the list of possible permutations for this pick in the sample permutations = list ( itertools . permutations ( other_weights , picks ) ) # Calculate the probability for this permutation permutation_probabilities = [ ] for permutation in permutations : # Calculate the probability for each pick in the permutation pick_probabilities = [ ] pick_weight_sum = weights_sum for pick in permutation : pick_probabilities . append ( pick / pick_weight_sum ) # Each time we pick we update the sum of the weight the next # pick is from. pick_weight_sum -= pick # Add the probability of picking i as the last pick pick_probabilities += [ weight_i / pick_weight_sum ] # Multiply all the probabilities for the permutation together permutation_probability = reduce ( lambda x , y : x * y , pick_probabilities ) permutation_probabilities . append ( permutation_probability ) # Add together all the probabilities for all permutations together probability_of_i += sum ( permutation_probabilities ) return probability_of_i | Given a weighted set and sample size return the probabilty that the weight i will be present in the sample . | 352 | 23 |
26,249 | def get_fake ( locale = None ) : if locale is None : locale = Faker . default_locale if not hasattr ( Maker , '_fake_' + locale ) : Faker . _fake = faker . Factory . create ( locale ) return Faker . _fake | Return a shared faker factory used to generate fake data | 61 | 11 |
26,250 | def _get_unique ( self , * args ) : # Generate a unique values value = '' attempts = 0 while True : attempts += 1 value = self . _maker ( * args ) if value not in self . _used_values : break assert attempts < self . _max_attempts , 'Too many attempts to generate a unique value' # Add the value to the set of used values self . _used_values . add ( value ) return value | Generate a unique value using the assigned maker | 97 | 9 |
26,251 | def assemble ( cls ) : document = { } for field_name , maker in cls . _instructions . items ( ) : with maker . target ( document ) : document [ field_name ] = maker ( ) return document | Assemble a single document using the blueprint | 50 | 8 |
26,252 | def finish ( cls , document ) : target_document = { } document_copy = { } for field_name , value in document . items ( ) : maker = cls . _instructions [ field_name ] target_document = document . copy ( ) with maker . target ( target_document ) : document_copy [ field_name ] = maker ( value ) target_document [ field_name ] = document_copy [ field_name ] return document_copy | Take a assembled document and convert all assembled values to finished values . | 101 | 13 |
26,253 | def reassemble ( cls , fields , document ) : for field_name in cls . _instructions : if field_name in fields : maker = cls . _instructions [ field_name ] with maker . target ( document ) : document [ field_name ] = maker ( ) | Take a previously assembled document and reassemble the given set of fields for it in place . | 65 | 19 |
26,254 | def is_diff ( self ) : if not isinstance ( self . details , dict ) : return False for key in [ 'additions' , 'updates' , 'deletions' ] : if self . details . get ( key , None ) : return True return False | Return True if there are any differences logged | 59 | 8 |
26,255 | def diff_to_html ( cls , details ) : changes = [ ] # Check that there are details to convert to HMTL if not details : return '' def _frame ( value ) : """ Handle converted `Frame` references where the human identifier is stored against the `_str` key. """ if isinstance ( value , dict ) and '_str' in value : return value [ '_str' ] elif isinstance ( value , list ) : return ', ' . join ( [ _frame ( v ) for v in value ] ) return str ( value ) # Additions fields = sorted ( details . get ( 'additions' , { } ) ) for field in fields : new_value = _frame ( details [ 'additions' ] [ field ] ) if isinstance ( new_value , list ) : new_value = ', ' . join ( [ _frame ( v ) for v in new_value ] ) change = cls . _templates [ 'add' ] . format ( field = field , new_value = new_value ) changes . append ( change ) # Updates fields = sorted ( details . get ( 'updates' , { } ) ) for field in fields : original_value = _frame ( details [ 'updates' ] [ field ] [ 0 ] ) if isinstance ( original_value , list ) : original_value = ', ' . join ( [ _frame ( v ) for v in original_value ] ) new_value = _frame ( details [ 'updates' ] [ field ] [ 1 ] ) if isinstance ( new_value , list ) : new_value = ', ' . join ( [ _frame ( v ) for v in new_value ] ) change = cls . _templates [ 'update' ] . format ( field = field , original_value = original_value , new_value = new_value ) changes . append ( change ) # Deletions fields = sorted ( details . get ( 'deletions' , { } ) ) for field in fields : original_value = _frame ( details [ 'deletions' ] [ field ] ) if isinstance ( original_value , list ) : original_value = ', ' . join ( [ _frame ( v ) for v in original_value ] ) change = cls . _templates [ 'delete' ] . format ( field = field , original_value = original_value ) changes . append ( change ) return '\n' . join ( changes ) | Return an entry s details in HTML format | 532 | 8 |
26,256 | def diff_safe ( cls , value ) : if isinstance ( value , Frame ) : return { '_str' : str ( value ) , '_id' : value . _id } elif isinstance ( value , ( list , tuple ) ) : return [ cls . diff_safe ( v ) for v in value ] return value | Return a value that can be safely stored as a diff | 74 | 11 |
26,257 | def comparable ( self ) : document_dict = self . compare_safe ( self . _document ) # Remove uncompared fields self . _remove_keys ( document_dict , self . _uncompared_fields ) # Remove any empty values clean_document_dict = { } for k , v in document_dict . items ( ) : if not v and not isinstance ( v , ( int , float ) ) : continue clean_document_dict [ k ] = v # Convert any referenced fields to Frames for ref_field , ref_cls in self . _compared_refs . items ( ) : ref = getattr ( self , ref_field ) if not ref : continue # Check for fields which contain a list of references if isinstance ( ref , list ) : if isinstance ( ref [ 0 ] , Frame ) : continue # Dereference the list of reference IDs setattr ( clean_document_dict , ref_field , ref_cls . many ( In ( Q . _id , ref ) ) ) else : if isinstance ( ref , Frame ) : continue # Dereference the reference ID setattr ( clean_document_dict , ref_field , ref_cls . byId ( ref ) ) return clean_document_dict | Return a dictionary that can be compared | 267 | 7 |
26,258 | def logged_delete ( self , user ) : self . delete ( ) # Log the change entry = ChangeLogEntry ( { 'type' : 'DELETED' , 'documents' : [ self ] , 'user' : user } ) entry . insert ( ) return entry | Delete the document and log the event in the change log | 59 | 11 |
26,259 | def logged_insert ( self , user ) : # Insert the frame's document self . insert ( ) # Log the insert entry = ChangeLogEntry ( { 'type' : 'ADDED' , 'documents' : [ self ] , 'user' : user } ) entry . insert ( ) return entry | Create and insert the document and log the event in the change log | 64 | 13 |
26,260 | def logged_update ( self , user , data , * fields ) : # Get a copy of the frames comparable data before the update original = self . comparable # Update the frame _fields = fields if len ( fields ) == 0 : _fields = data . keys ( ) for field in _fields : if field in data : setattr ( self , field , data [ field ] ) self . update ( * fields ) # Create an entry and perform a diff entry = ChangeLogEntry ( { 'type' : 'UPDATED' , 'documents' : [ self ] , 'user' : user } ) entry . add_diff ( original , self . comparable ) # Check there's a change to apply/log if not entry . is_diff : return entry . insert ( ) return entry | Update the document with the dictionary of data provided and log the event in the change log . | 164 | 18 |
26,261 | def compare_safe ( cls , value ) : # Date if type ( value ) == date : return str ( value ) # Lists elif isinstance ( value , ( list , tuple ) ) : return [ cls . compare_safe ( v ) for v in value ] # Dictionaries elif isinstance ( value , dict ) : return { k : cls . compare_safe ( v ) for k , v in value . items ( ) } return value | Return a value that can be safely compared | 98 | 8 |
26,262 | def ElemMatch ( q , * conditions ) : new_condition = { } for condition in conditions : deep_merge ( condition . to_dict ( ) , new_condition ) return Condition ( q . _path , new_condition , '$elemMatch' ) | The ElemMatch operator matches documents that contain an array field with at least one element that matches all the specified query criteria . | 58 | 25 |
26,263 | def SortBy ( * qs ) : sort = [ ] for q in qs : if q . _path . endswith ( '.desc' ) : sort . append ( ( q . _path [ : - 5 ] , DESCENDING ) ) else : sort . append ( ( q . _path , ASCENDING ) ) return sort | Convert a list of Q objects into list of sort instructions | 74 | 12 |
26,264 | def deep_merge ( source , dest ) : for key , value in source . items ( ) : if key in dest : if isinstance ( value , dict ) and isinstance ( dest [ key ] , dict ) : deep_merge ( value , dest [ key ] ) continue elif isinstance ( value , list ) and isinstance ( dest [ key ] , list ) : for item in value : if item not in dest [ key ] : dest [ key ] . append ( item ) continue dest [ key ] = value | Deep merges source dict into dest dict . | 111 | 9 |
26,265 | def to_refs ( value ) : from mongoframes . frames import Frame , SubFrame # Frame if isinstance ( value , Frame ) : return value . _id # SubFrame elif isinstance ( value , SubFrame ) : return to_refs ( value . _document ) # Lists elif isinstance ( value , ( list , tuple ) ) : return [ to_refs ( v ) for v in value ] # Dictionaries elif isinstance ( value , dict ) : return { k : to_refs ( v ) for k , v in value . items ( ) } return value | Convert all Frame instances within the given value to Ids | 131 | 12 |
26,266 | def assemble ( self , blueprint , quota ) : # Reset the blueprint blueprint . reset ( ) # Assemble the documents documents = [ ] for i in range ( 0 , int ( quota ) ) : documents . append ( blueprint . assemble ( ) ) return documents | Assemble a quota of documents | 53 | 6 |
26,267 | def finish ( self , blueprint , documents ) : # Reset the blueprint blueprint . reset ( ) # Finish the documents finished = [ ] for document in documents : finished . append ( blueprint . finish ( document ) ) return finished | Finish a list of pre - assembled documents | 45 | 8 |
26,268 | def populate ( self , blueprint , documents ) : # Finish the documents documents = self . finish ( blueprint , documents ) # Convert the documents to frame instances frames = [ ] for document in documents : # Separate out any meta fields meta_document = { } for field_name in blueprint . _meta_fields : meta_document [ field_name ] = document [ field_name ] document . pop ( field_name ) # Initialize the frame frame = blueprint . get_frame_cls ( ) ( document ) # Apply any meta fields for key , value in meta_document . items ( ) : setattr ( frame , key , value ) frames . append ( frame ) # Insert the documents blueprint . on_fake ( frames ) frames = blueprint . get_frame_cls ( ) . insert_many ( frames ) blueprint . on_faked ( frames ) return frames | Populate the database with documents | 183 | 6 |
26,269 | def reassemble ( self , blueprint , fields , documents ) : # Reset the blueprint blueprint . reset ( ) # Reassemble the documents for document in documents : blueprint . reassemble ( fields , document ) | Reassemble the given set of fields for a list of pre - assembed documents . | 44 | 18 |
26,270 | def can_publish ( self ) : with self . published_context ( ) : published = self . one ( Q . _uid == self . _uid , projection = { 'revision' : True } ) if not published : return True with self . draft_context ( ) : draft = self . one ( Q . _uid == self . _uid , projection = { 'revision' : True } ) return draft . revision > published . revision | Return True if there is a draft version of the document that s ready to be published . | 95 | 18 |
26,271 | def can_revert ( self ) : if self . can_publish : with self . published_context ( ) : return self . count ( Q . _uid == self . _uid ) > 0 return False | Return True if we can revert the draft version of the document to the currently published version . | 45 | 18 |
26,272 | def get_publisher_doc ( self ) : with self . draft_context ( ) : # Select the draft document from the database draft = self . one ( Q . _uid == self . _uid ) publisher_doc = draft . _document # Remove any keys from the document that should not be transferred # when publishing. self . _remove_keys ( publisher_doc , self . _unpublished_fields ) return publisher_doc | Return a publish safe version of the frame s document | 91 | 10 |
26,273 | def publish ( self ) : publisher_doc = self . get_publisher_doc ( ) with self . published_context ( ) : # Select the published document published = self . one ( Q . _uid == self . _uid ) # If there's no published version of the document create one if not published : published = self . __class__ ( ) # Update the document for field , value in publisher_doc . items ( ) : setattr ( published , field , value ) # Save published version published . upsert ( ) # Set the revisions number for draft/published version, we use PyMongo # directly as it's more convienent to use the shared `_uid`. now = datetime . now ( ) with self . draft_context ( ) : self . get_collection ( ) . update ( { '_uid' : self . _uid } , { '$set' : { 'revision' : now } } ) with self . published_context ( ) : self . get_collection ( ) . update ( { '_uid' : self . _uid } , { '$set' : { 'revision' : now } } ) | Publish the current document . | 246 | 6 |
26,274 | def new_revision ( self , * fields ) : # Ensure this document is a draft if not self . _id : assert g . get ( 'draft' ) , 'Only draft documents can be assigned new revisions' else : with self . draft_context ( ) : assert self . count ( Q . _id == self . _id ) == 1 , 'Only draft documents can be assigned new revisions' # Set the revision if len ( fields ) > 0 : fields . append ( 'revision' ) self . revision = datetime . now ( ) # Update the document self . upsert ( * fields ) | Save a new revision of the document | 128 | 7 |
26,275 | def delete ( self ) : with self . draft_context ( ) : draft = self . one ( Q . _uid == self . _uid ) if draft : super ( PublisherFrame , draft ) . delete ( ) with self . published_context ( ) : published = self . one ( Q . _uid == self . _uid ) if published : super ( PublisherFrame , published ) . delete ( ) | Delete this document and any counterpart document | 84 | 7 |
26,276 | def revert ( self ) : with self . draft_context ( ) : draft = self . one ( Q . _uid == self . _uid ) with self . published_context ( ) : published = self . one ( Q . _uid == self . _uid ) for field , value in draft . _document . items ( ) : if field in self . _unpublished_fields : continue setattr ( draft , field , getattr ( published , field ) ) # Revert the revision draft . revision = published . revision draft . update ( ) | Revert the document to currently published version | 114 | 9 |
26,277 | def get_collection ( cls ) : # By default the collection returned will be the published collection, # however if the `draft` flag has been set against the global context # (e.g `g`) then the collection returned will contain draft documents. if g . get ( 'draft' ) : return getattr ( cls . get_db ( ) , '{collection}_draft' . format ( collection = cls . _collection ) ) return getattr ( cls . get_db ( ) , cls . _collection ) | Return a reference to the database collection for the class | 115 | 10 |
26,278 | def draft_context ( cls ) : previous_state = g . get ( 'draft' ) try : g . draft = True yield finally : g . draft = previous_state | Set the context to draft | 38 | 5 |
26,279 | def published_context ( cls ) : previous_state = g . get ( 'draft' ) try : g . draft = False yield finally : g . draft = previous_state | Set the context to published | 38 | 5 |
26,280 | def initialize_registry ( args : argparse . Namespace , backend : StorageBackend , log : logging . Logger ) : try : backend . reset ( args . force ) except ExistingBackendError : return 1 log . info ( "Resetting the index ..." ) backend . index . reset ( ) try : backend . index . upload ( "reset" , { } ) except ValueError : return 1 log . info ( "Successfully initialized" ) | Initialize the registry and the index . | 96 | 8 |
26,281 | def publish_model ( args : argparse . Namespace , backend : StorageBackend , log : logging . Logger ) : path = os . path . abspath ( args . model ) try : model = GenericModel ( source = path , dummy = True ) except ValueError as e : log . critical ( '"model" must be a path: %s' , e ) return 1 except Exception as e : log . critical ( "Failed to load the model: %s: %s" % ( type ( e ) . __name__ , e ) ) return 1 base_meta = model . meta try : model_url = backend . upload_model ( path , base_meta , args . force ) except ModelAlreadyExistsError : return 1 log . info ( "Uploaded as %s" , model_url ) with open ( os . path . join ( args . meta ) , encoding = "utf-8" ) as _in : extra_meta = json . load ( _in ) model_type , model_uuid = base_meta [ "model" ] , base_meta [ "uuid" ] meta = extract_model_meta ( base_meta , extra_meta , model_url ) log . info ( "Updating the models index..." ) try : template_model = backend . index . load_template ( args . template_model ) template_readme = backend . index . load_template ( args . template_readme ) except ValueError : return 1 backend . index . add_model ( model_type , model_uuid , meta , template_model , args . update_default ) backend . index . update_readme ( template_readme ) try : backend . index . upload ( "add" , { "model" : model_type , "uuid" : model_uuid } ) except ValueError : # TODO: replace with PorcelainError, see related TODO in index.py:181 return 1 log . info ( "Successfully published." ) | Push the model to Google Cloud Storage and updates the index file . | 429 | 13 |
26,282 | def list_models ( args : argparse . Namespace ) : try : git_index = GitIndex ( remote = args . index_repo , username = args . username , password = args . password , cache = args . cache , log_level = args . log_level ) except ValueError : return 1 for model_type , models in git_index . models . items ( ) : print ( model_type ) default = git_index . meta [ model_type ] [ "default" ] for uuid , model in sorted ( models . items ( ) , key = lambda m : parse_datetime ( m [ 1 ] [ "created_at" ] ) , reverse = True ) : print ( " %s %s" % ( "*" if default == uuid else " " , uuid ) , model [ "created_at" ] ) | Output the list of known models in the registry . | 183 | 10 |
26,283 | def install_environment ( args : argparse . Namespace , backend : StorageBackend , log : logging . Logger ) : model = _load_generic_model ( args . input , backend , log ) if model is None : return 1 packages = [ "%s==%s" % ( pkg , ver ) for pkg , ver in model . environment [ "packages" ] ] cmdline = [ sys . executable , "-m" , "pip" , "install" ] + args . pip + packages log . info ( " " . join ( cmdline ) ) subprocess . check_call ( cmdline ) if args . reproduce : for dataset in model . datasets : download_http ( dataset [ 0 ] , dataset [ 1 ] , log ) | Install the packages mentioned in the model s metadata . | 160 | 10 |
26,284 | def dump_model ( args : argparse . Namespace , backend : StorageBackend , log : logging . Logger ) : model = _load_generic_model ( args . input , backend , log ) if model is None : return 1 print ( model ) | Print the information about the model . | 55 | 7 |
26,285 | 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 . | 64 | 14 |
26,286 | 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 : # flake8: noqa raise ValueError ( "Invalid args" ) from None else : kwargs = { } if git_index is None : git_index = GitIndex ( ) kwargs [ "index" ] = git_index return __registry__ [ name ] ( * * kwargs ) | Initialize a new StorageBackend by it s name and the specified model registry . | 155 | 17 |
26,287 | 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 ( ) ) ) return None except ValueError : log . critical ( "Invalid backend arguments: %s" , args ) return None | Initialize a new Backend return None if there was a known problem . | 121 | 15 |
26,288 | 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 not getattr ( args , "backend" , False ) : backend = None else : try : git_index = GitIndex ( remote = args . index_repo , username = args . username , password = args . password , cache = args . cache , exists = index_exists , signoff = args . signoff , log_level = args . log_level ) except ValueError : return 1 backend = create_backend_noexc ( log , args . backend , git_index , args . args ) if backend is None : return 1 return func ( args , backend , log ) return wrapped_supply_backend if callable ( optional ) : return supply_backend_inner ( optional ) return supply_backend_inner | Decorator to pass the initialized backend to the decorated callable . \ Used by command line entries . If the backend cannot be created return 1 . | 246 | 30 |
26,289 | 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_without_packages ( ) , "extra" : None , "license" : license , "metrics" : { } , "model" : name , "parent" : None , "references" : [ ] , "series" : None , "tags" : [ ] , "uuid" : str ( uuid . uuid4 ( ) ) , "version" : [ 1 , 0 , 0 ] , } | Create the metadata tree for the given model name and the list of dependencies . | 182 | 15 |
26,290 | 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 [ "model" ] . update ( { k : extra_meta [ k ] for k in ( "code" , "datasets" , "references" , "tags" , "extra" ) } ) response = requests . get ( model_url , stream = True ) meta [ "model" ] [ "size" ] = humanize . naturalsize ( int ( response . headers [ "content-length" ] ) ) meta [ "model" ] [ "url" ] = model_url meta [ "model" ] [ "created_at" ] = format_datetime ( meta [ "model" ] [ "created_at" ] ) return meta | Merge the metadata from the backend and the extra metadata into a dict which is suitable for \ index . json . | 251 | 23 |
26,291 | 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 . uint32 else : dtype = numpy . uint64 return arr . astype ( dtype ) | Return a copy of an integer numpy array with the minimum bitness . | 139 | 15 |
26,292 | 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 ) return property ( get ) | Temporary property builder . | 106 | 5 |
26,293 | 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_version must be either a list or a tuple, got %s" % type ( new_version ) ) meta [ "version" ] = list ( new_version ) if first_time : meta [ "parent" ] = meta [ "uuid" ] meta [ "uuid" ] = str ( uuid . uuid4 ( ) ) return self | Inherit the new model from the current one - used for versioning . \ This operation is in - place . | 166 | 24 |
26,294 | 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 . VENDOR ) | Return the default cache directory where downloaded models are stored . | 90 | 11 |
26,295 | 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 . | 64 | 11 |
26,296 | 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 . | 51 | 7 |
26,297 | 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 = series if isinstance ( output , str ) and create_missing_dirs : dirs = os . path . split ( output ) [ 0 ] if dirs : os . makedirs ( dirs , exist_ok = True ) self . set_dep ( * deps ) tree = self . _generate_tree ( ) self . _write_tree ( tree , output ) self . _initial_version = self . version return self | Serialize the model to a file . | 181 | 8 |
26,298 | 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 isfileobj = not isinstance ( output , str ) if not isfileobj : self . _source = output path = output output = open ( output , "wb" ) os . chmod ( path , file_mode ) pos = 0 else : pos = output . tell ( ) try : with asdf . AsdfFile ( final_tree ) as file : queue = [ ( "" , tree ) ] while queue : path , element = queue . pop ( ) if isinstance ( element , dict ) : for key , val in element . items ( ) : queue . append ( ( path + "/" + key , val ) ) elif isinstance ( element , ( list , tuple ) ) : for child in element : queue . append ( ( path , child ) ) elif isinstance ( element , numpy . ndarray ) : path += "/" if path not in self . _compression_prefixes : self . _log . debug ( "%s -> %s compression" , path , self . ARRAY_COMPRESSION ) file . set_array_compression ( element , self . ARRAY_COMPRESSION ) else : self . _log . debug ( "%s -> compression disabled" , path ) file . write_to ( output ) self . _size = output . seek ( 0 , os . SEEK_END ) - pos finally : if not isfileobj : output . close ( ) | Write the model to disk . | 398 | 6 |
26,299 | 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 ) ] override_files . append ( OVERRIDE_FILE ) def import_path ( path ) : if sys . version_info < ( 3 , 5 , 0 ) : from importlib . machinery import SourceFileLoader return SourceFileLoader ( __name__ , path ) . load_module ( ) import importlib . util spec = importlib . util . spec_from_file_location ( __name__ , path ) module = importlib . util . module_from_spec ( spec ) spec . loader . exec_module ( module ) return module for override_file in override_files : if not os . path . isfile ( override_file ) : continue mod = import_path ( override_file ) globals ( ) . update ( { n : getattr ( mod , n ) for n in dir ( mod ) if not n . startswith ( "__" ) } ) | Scan over all the involved directories and load configs from them . | 283 | 13 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.