idx int64 0 251k | question stringlengths 53 3.53k | target stringlengths 5 1.23k | len_question int64 20 893 | len_target int64 3 238 |
|---|---|---|---|---|
225,800 | def _fix_callback_item ( self , item ) : item . component_id = self . _fix_id ( item . component_id ) return item | Update component identifier | 34 | 3 |
225,801 | def callback ( self , output , inputs = [ ] , state = [ ] , events = [ ] ) : # pylint: disable=dangerous-default-value if isinstance ( output , ( list , tuple ) ) : fixed_outputs = [ self . _fix_callback_item ( x ) for x in output ] # Temporary check; can be removed once the library has been extended raise NotImplementedError ( "django-plotly-dash cannot handle multiple callback outputs at present" ) else : fixed_outputs = self . _fix_callback_item ( output ) return super ( WrappedDash , self ) . callback ( fixed_outputs , [ self . _fix_callback_item ( x ) for x in inputs ] , [ self . _fix_callback_item ( x ) for x in state ] ) | Invoke callback adjusting variable names as needed | 179 | 8 |
225,802 | def dispatch ( self ) : import flask body = flask . request . get_json ( ) return self . dispatch_with_args ( body , argMap = dict ( ) ) | Perform dispatch using request embedded within flask global state | 37 | 10 |
225,803 | def dispatch_with_args ( self , body , argMap ) : inputs = body . get ( 'inputs' , [ ] ) state = body . get ( 'state' , [ ] ) output = body [ 'output' ] try : output_id = output [ 'id' ] output_property = output [ 'property' ] target_id = "%s.%s" % ( output_id , output_property ) except : target_id = output output_id , output_property = output . split ( "." ) args = [ ] da = argMap . get ( 'dash_app' , None ) for component_registration in self . callback_map [ target_id ] [ 'inputs' ] : for c in inputs : if c [ 'property' ] == component_registration [ 'property' ] and c [ 'id' ] == component_registration [ 'id' ] : v = c . get ( 'value' , None ) args . append ( v ) if da : da . update_current_state ( c [ 'id' ] , c [ 'property' ] , v ) for component_registration in self . callback_map [ target_id ] [ 'state' ] : for c in state : if c [ 'property' ] == component_registration [ 'property' ] and c [ 'id' ] == component_registration [ 'id' ] : v = c . get ( 'value' , None ) args . append ( v ) if da : da . update_current_state ( c [ 'id' ] , c [ 'property' ] , v ) # Special: intercept case of insufficient arguments # This happens when a propery has been updated with a pipe component # TODO see if this can be attacked from the client end if len ( args ) < len ( self . callback_map [ target_id ] [ 'inputs' ] ) : return 'EDGECASEEXIT' res = self . callback_map [ target_id ] [ 'callback' ] ( * args , * * argMap ) if da and da . have_current_state_entry ( output_id , output_property ) : response = json . loads ( res . data . decode ( 'utf-8' ) ) value = response . get ( 'response' , { } ) . get ( 'props' , { } ) . get ( output_property , None ) da . update_current_state ( output_id , output_property , value ) return res | Perform callback dispatching with enhanced arguments and recording of response | 538 | 12 |
225,804 | def extra_html_properties ( self , prefix = None , postfix = None , template_type = None ) : prefix = prefix if prefix else "django-plotly-dash" post_part = "-%s" % postfix if postfix else "" template_type = template_type if template_type else "iframe" slugified_id = self . slugified_id ( ) return "%(prefix)s %(prefix)s-%(template_type)s %(prefix)s-app-%(slugified_id)s%(post_part)s" % { 'slugified_id' : slugified_id , 'post_part' : post_part , 'template_type' : template_type , 'prefix' : prefix , } | Return extra html properties to allow individual apps to be styled separately . | 170 | 13 |
225,805 | def plotly_direct ( context , name = None , slug = None , da = None ) : da , app = _locate_daapp ( name , slug , da ) view_func = app . locate_endpoint_function ( ) # Load embedded holder inserted by middleware eh = context . request . dpd_content_handler . embedded_holder app . set_embedded ( eh ) try : resp = view_func ( ) finally : app . exit_embedded ( ) return locals ( ) | Direct insertion of a Dash app | 108 | 6 |
225,806 | def plotly_app_identifier ( name = None , slug = None , da = None , postfix = None ) : da , app = _locate_daapp ( name , slug , da ) slugified_id = app . slugified_id ( ) if postfix : return "%s-%s" % ( slugified_id , postfix ) return slugified_id | Return a slug - friendly identifier | 83 | 6 |
225,807 | def plotly_class ( name = None , slug = None , da = None , prefix = None , postfix = None , template_type = None ) : da , app = _locate_daapp ( name , slug , da ) return app . extra_html_properties ( prefix = prefix , postfix = postfix , template_type = template_type ) | Return a string of space - separated class names | 78 | 9 |
225,808 | def parse_wyckoff_csv ( wyckoff_file ) : rowdata = [ ] points = [ ] hP_nums = [ 433 , 436 , 444 , 450 , 452 , 458 , 460 ] for i , line in enumerate ( wyckoff_file ) : if line . strip ( ) == 'end of data' : break rowdata . append ( line . strip ( ) . split ( ':' ) ) # 2:P -1 ::::::: <-- store line number if first element is number if rowdata [ - 1 ] [ 0 ] . isdigit ( ) : points . append ( i ) points . append ( i ) wyckoff = [ ] for i in range ( len ( points ) - 1 ) : # 0 to 529 symbol = rowdata [ points [ i ] ] [ 1 ] # e.g. "C 1 2 1" if i + 1 in hP_nums : symbol = symbol . replace ( 'R' , 'H' , 1 ) wyckoff . append ( { 'symbol' : symbol . strip ( ) } ) # When the number of positions is larger than 4, # the positions are written in the next line. # So those positions are connected. for i in range ( len ( points ) - 1 ) : count = 0 wyckoff [ i ] [ 'wyckoff' ] = [ ] for j in range ( points [ i ] + 1 , points [ i + 1 ] ) : # Hook if the third element is a number (multiplicity), e.g., # # 232:P 2/b 2/m 2/b::::::: <- ignored # ::8:r:1:(x,y,z):(-x,y,-z):(x,-y+1/2,-z):(-x,-y+1/2,z) # :::::(-x,-y,-z):(x,-y,z):(-x,y+1/2,z):(x,y+1/2,-z) <- ignored # ::4:q:..m:(x,0,z):(-x,0,-z):(x,1/2,-z):(-x,1/2,z) # ::4:p:..2:(0,y,1/2):(0,-y+1/2,1/2):(0,-y,1/2):(0,y+1/2,1/2) # ::4:o:..2:(1/2,y,0):(1/2,-y+1/2,0):(1/2,-y,0):(1/2,y+1/2,0) # ... if rowdata [ j ] [ 2 ] . isdigit ( ) : pos = [ ] w = { 'letter' : rowdata [ j ] [ 3 ] . strip ( ) , 'multiplicity' : int ( rowdata [ j ] [ 2 ] ) , 'site_symmetry' : rowdata [ j ] [ 4 ] . strip ( ) , 'positions' : pos } wyckoff [ i ] [ 'wyckoff' ] . append ( w ) for k in range ( 4 ) : if rowdata [ j ] [ k + 5 ] : # check if '(x,y,z)' or '' count += 1 pos . append ( rowdata [ j ] [ k + 5 ] ) else : for k in range ( 4 ) : if rowdata [ j ] [ k + 5 ] : count += 1 pos . append ( rowdata [ j ] [ k + 5 ] ) # assertion for w in wyckoff [ i ] [ 'wyckoff' ] : n_pos = len ( w [ 'positions' ] ) n_pos *= len ( lattice_symbols [ wyckoff [ i ] [ 'symbol' ] [ 0 ] ] ) assert n_pos == w [ 'multiplicity' ] return wyckoff | Parse Wyckoff . csv | 860 | 8 |
225,809 | def get_site_symmetries ( wyckoff ) : ssyms = [ ] for w in wyckoff : ssyms += [ "\"%-6s\"" % w_s [ 'site_symmetry' ] for w_s in w [ 'wyckoff' ] ] damp_array_site_symmetries ( ssyms ) | List up site symmetries | 84 | 6 |
225,810 | def transform_model ( cls ) -> None : if cls . name != "Model" : appname = "models" for mcls in cls . get_children ( ) : if isinstance ( mcls , ClassDef ) : for attr in mcls . get_children ( ) : if isinstance ( attr , Assign ) : if attr . targets [ 0 ] . name == "app" : appname = attr . value . value mname = "{}.{}" . format ( appname , cls . name ) MODELS [ mname ] = cls for relname , relval in FUTURE_RELATIONS . get ( mname , [ ] ) : cls . locals [ relname ] = relval for attr in cls . get_children ( ) : if isinstance ( attr , Assign ) : try : attrname = attr . value . func . attrname except AttributeError : pass else : if attrname in [ "ForeignKeyField" , "ManyToManyField" ] : tomodel = attr . value . args [ 0 ] . value relname = "" if attr . value . keywords : for keyword in attr . value . keywords : if keyword . arg == "related_name" : relname = keyword . value . value if not relname : relname = cls . name . lower ( ) + "s" # Injected model attributes need to also have the relation manager if attrname == "ManyToManyField" : relval = [ attr . value . func , MANAGER . ast_from_module_name ( "tortoise.fields" ) . lookup ( "ManyToManyRelationManager" ) [ 1 ] [ 0 ] , ] else : relval = [ attr . value . func , MANAGER . ast_from_module_name ( "tortoise.fields" ) . lookup ( "RelationQueryContainer" ) [ 1 ] [ 0 ] , ] if tomodel in MODELS : MODELS [ tomodel ] . locals [ relname ] = relval else : FUTURE_RELATIONS . setdefault ( tomodel , [ ] ) . append ( ( relname , relval ) ) cls . locals [ "_meta" ] = [ MANAGER . ast_from_module_name ( "tortoise.models" ) . lookup ( "MetaInfo" ) [ 1 ] [ 0 ] . instantiate_class ( ) ] if "id" not in cls . locals : cls . locals [ "id" ] = [ nodes . ClassDef ( "id" , None ) ] | Anything that uses the ModelMeta needs _meta and id . Also keep track of relationships and make them in the related model class . | 570 | 26 |
225,811 | def apply_type_shim ( cls , _context = None ) -> Iterator : if cls . name in [ "IntField" , "SmallIntField" ] : base_nodes = scoped_nodes . builtin_lookup ( "int" ) elif cls . name in [ "CharField" , "TextField" ] : base_nodes = scoped_nodes . builtin_lookup ( "str" ) elif cls . name == "BooleanField" : base_nodes = scoped_nodes . builtin_lookup ( "bool" ) elif cls . name == "FloatField" : base_nodes = scoped_nodes . builtin_lookup ( "float" ) elif cls . name == "DecimalField" : base_nodes = MANAGER . ast_from_module_name ( "decimal" ) . lookup ( "Decimal" ) elif cls . name == "DatetimeField" : base_nodes = MANAGER . ast_from_module_name ( "datetime" ) . lookup ( "datetime" ) elif cls . name == "DateField" : base_nodes = MANAGER . ast_from_module_name ( "datetime" ) . lookup ( "date" ) elif cls . name == "ForeignKeyField" : base_nodes = MANAGER . ast_from_module_name ( "tortoise.fields" ) . lookup ( "BackwardFKRelation" ) elif cls . name == "ManyToManyField" : base_nodes = MANAGER . ast_from_module_name ( "tortoise.fields" ) . lookup ( "ManyToManyRelationManager" ) else : return iter ( [ cls ] ) return iter ( [ cls ] + base_nodes [ 1 ] ) | Morphs model fields to representative type | 420 | 8 |
225,812 | def list_encoder ( values , instance , field : Field ) : return [ field . to_db_value ( element , instance ) for element in values ] | Encodes an iterable of a given field into a database - compatible format . | 34 | 16 |
225,813 | async def add ( self , * instances , using_db = None ) -> None : if not instances : return if self . instance . id is None : raise OperationalError ( "You should first call .save() on {model}" . format ( model = self . instance ) ) db = using_db if using_db else self . model . _meta . db through_table = Table ( self . field . through ) select_query = ( db . query_class . from_ ( through_table ) . where ( getattr ( through_table , self . field . backward_key ) == self . instance . id ) . select ( self . field . backward_key , self . field . forward_key ) ) query = db . query_class . into ( through_table ) . columns ( getattr ( through_table , self . field . forward_key ) , getattr ( through_table , self . field . backward_key ) , ) if len ( instances ) == 1 : criterion = getattr ( through_table , self . field . forward_key ) == instances [ 0 ] . id else : criterion = getattr ( through_table , self . field . forward_key ) . isin ( [ i . id for i in instances ] ) select_query = select_query . where ( criterion ) already_existing_relations_raw = await db . execute_query ( str ( select_query ) ) already_existing_relations = { ( r [ self . field . backward_key ] , r [ self . field . forward_key ] ) for r in already_existing_relations_raw } insert_is_required = False for instance_to_add in instances : if instance_to_add . id is None : raise OperationalError ( "You should first call .save() on {model}" . format ( model = instance_to_add ) ) if ( self . instance . id , instance_to_add . id ) in already_existing_relations : continue query = query . insert ( instance_to_add . id , self . instance . id ) insert_is_required = True if insert_is_required : await db . execute_query ( str ( query ) ) | Adds one or more of instances to the relation . | 469 | 10 |
225,814 | async def clear ( self , using_db = None ) -> None : db = using_db if using_db else self . model . _meta . db through_table = Table ( self . field . through ) query = ( db . query_class . from_ ( through_table ) . where ( getattr ( through_table , self . field . backward_key ) == self . instance . id ) . delete ( ) ) await db . execute_query ( str ( query ) ) | Clears ALL relations . | 104 | 5 |
225,815 | async def remove ( self , * instances , using_db = None ) -> None : db = using_db if using_db else self . model . _meta . db if not instances : raise OperationalError ( "remove() called on no instances" ) through_table = Table ( self . field . through ) if len ( instances ) == 1 : condition = ( getattr ( through_table , self . field . forward_key ) == instances [ 0 ] . id ) & ( getattr ( through_table , self . field . backward_key ) == self . instance . id ) else : condition = ( getattr ( through_table , self . field . backward_key ) == self . instance . id ) & ( getattr ( through_table , self . field . forward_key ) . isin ( [ i . id for i in instances ] ) ) query = db . query_class . from_ ( through_table ) . where ( condition ) . delete ( ) await db . execute_query ( str ( query ) ) | Removes one or more of instances from the relation . | 220 | 11 |
225,816 | def register_tortoise ( app : Quart , config : Optional [ dict ] = None , config_file : Optional [ str ] = None , db_url : Optional [ str ] = None , modules : Optional [ Dict [ str , List [ str ] ] ] = None , generate_schemas : bool = False , ) -> None : @ app . before_serving async def init_orm ( ) : await Tortoise . init ( config = config , config_file = config_file , db_url = db_url , modules = modules ) print ( "Tortoise-ORM started, {}, {}" . format ( Tortoise . _connections , Tortoise . apps ) ) if generate_schemas : print ( "Tortoise-ORM generating schema" ) await Tortoise . generate_schemas ( ) @ app . after_serving async def close_orm ( ) : await Tortoise . close_connections ( ) print ( "Tortoise-ORM shutdown" ) @ app . cli . command ( ) # type: ignore def generate_schemas ( ) : # pylint: disable=E0102 """Populate DB with Tortoise-ORM schemas.""" async def inner ( ) : await Tortoise . init ( config = config , config_file = config_file , db_url = db_url , modules = modules ) await Tortoise . generate_schemas ( ) await Tortoise . close_connections ( ) logging . basicConfig ( level = logging . DEBUG ) loop = asyncio . get_event_loop ( ) loop . run_until_complete ( inner ( ) ) | Registers before_serving and after_serving hooks to set - up and tear - down Tortoise - ORM inside a Quart service . It also registers a CLI command generate_schemas that will generate the schemas . | 354 | 46 |
225,817 | def run_async ( coro : Coroutine ) -> None : loop = asyncio . get_event_loop ( ) try : loop . run_until_complete ( coro ) finally : loop . run_until_complete ( Tortoise . close_connections ( ) ) | Simple async runner that cleans up DB connections on exit . This is meant for simple scripts . | 60 | 18 |
225,818 | async def init ( cls , config : Optional [ dict ] = None , config_file : Optional [ str ] = None , _create_db : bool = False , db_url : Optional [ str ] = None , modules : Optional [ Dict [ str , List [ str ] ] ] = None , ) -> None : if cls . _inited : await cls . close_connections ( ) await cls . _reset_apps ( ) if int ( bool ( config ) + bool ( config_file ) + bool ( db_url ) ) != 1 : raise ConfigurationError ( 'You should init either from "config", "config_file" or "db_url"' ) if config_file : config = cls . _get_config_from_config_file ( config_file ) if db_url : if not modules : raise ConfigurationError ( 'You must specify "db_url" and "modules" together' ) config = generate_config ( db_url , modules ) try : connections_config = config [ "connections" ] # type: ignore except KeyError : raise ConfigurationError ( 'Config must define "connections" section' ) try : apps_config = config [ "apps" ] # type: ignore except KeyError : raise ConfigurationError ( 'Config must define "apps" section' ) logger . info ( "Tortoise-ORM startup\n connections: %s\n apps: %s" , str ( connections_config ) , str ( apps_config ) , ) await cls . _init_connections ( connections_config , _create_db ) cls . _init_apps ( apps_config ) cls . _inited = True | Sets up Tortoise - ORM . | 364 | 9 |
225,819 | def in_transaction ( connection_name : Optional [ str ] = None ) -> BaseTransactionWrapper : connection = _get_connection ( connection_name ) return connection . _in_transaction ( ) | Transaction context manager . | 44 | 4 |
225,820 | def atomic ( connection_name : Optional [ str ] = None ) -> Callable : def wrapper ( func ) : @ wraps ( func ) async def wrapped ( * args , * * kwargs ) : connection = _get_connection ( connection_name ) async with connection . _in_transaction ( ) : return await func ( * args , * * kwargs ) return wrapped return wrapper | Transaction decorator . | 83 | 4 |
225,821 | async def start_transaction ( connection_name : Optional [ str ] = None ) -> BaseTransactionWrapper : connection = _get_connection ( connection_name ) transaction = connection . _in_transaction ( ) await transaction . start ( ) return transaction | Function to manually control your transaction . | 55 | 7 |
225,822 | def limit ( self , limit : int ) -> "QuerySet" : queryset = self . _clone ( ) queryset . _limit = limit return queryset | Limits QuerySet to given length . | 37 | 8 |
225,823 | def offset ( self , offset : int ) -> "QuerySet" : queryset = self . _clone ( ) queryset . _offset = offset if self . capabilities . requires_limit and queryset . _limit is None : queryset . _limit = 1000000 return queryset | Query offset for QuerySet . | 64 | 6 |
225,824 | def annotate ( self , * * kwargs ) -> "QuerySet" : queryset = self . _clone ( ) for key , aggregation in kwargs . items ( ) : if not isinstance ( aggregation , Aggregate ) : raise TypeError ( "value is expected to be Aggregate instance" ) queryset . _annotations [ key ] = aggregation from tortoise . models import get_filters_for_field queryset . _custom_filters . update ( get_filters_for_field ( key , None , key ) ) return queryset | Annotate result with aggregation result . | 125 | 8 |
225,825 | def values_list ( self , * fields_ : str , flat : bool = False ) -> "ValuesListQuery" : # pylint: disable=W0621 return ValuesListQuery ( db = self . _db , model = self . model , q_objects = self . _q_objects , flat = flat , fields_for_select_list = fields_ , distinct = self . _distinct , limit = self . _limit , offset = self . _offset , orderings = self . _orderings , annotations = self . _annotations , custom_filters = self . _custom_filters , ) | Make QuerySet returns list of tuples for given args instead of objects . If flat = True and only one arg is passed can return flat list . | 133 | 30 |
225,826 | def values ( self , * args : str , * * kwargs : str ) -> "ValuesQuery" : fields_for_select = { } # type: Dict[str, str] for field in args : if field in fields_for_select : raise FieldError ( "Duplicate key {}" . format ( field ) ) fields_for_select [ field ] = field for return_as , field in kwargs . items ( ) : if return_as in fields_for_select : raise FieldError ( "Duplicate key {}" . format ( return_as ) ) fields_for_select [ return_as ] = field return ValuesQuery ( db = self . _db , model = self . model , q_objects = self . _q_objects , fields_for_select = fields_for_select , distinct = self . _distinct , limit = self . _limit , offset = self . _offset , orderings = self . _orderings , annotations = self . _annotations , custom_filters = self . _custom_filters , ) | Make QuerySet return dicts instead of objects . | 233 | 10 |
225,827 | def delete ( self ) -> "DeleteQuery" : return DeleteQuery ( db = self . _db , model = self . model , q_objects = self . _q_objects , annotations = self . _annotations , custom_filters = self . _custom_filters , ) | Delete all objects in QuerySet . | 61 | 7 |
225,828 | def update ( self , * * kwargs ) -> "UpdateQuery" : return UpdateQuery ( db = self . _db , model = self . model , update_kwargs = kwargs , q_objects = self . _q_objects , annotations = self . _annotations , custom_filters = self . _custom_filters , ) | Update all objects in QuerySet with given kwargs . | 76 | 12 |
225,829 | def count ( self ) -> "CountQuery" : return CountQuery ( db = self . _db , model = self . model , q_objects = self . _q_objects , annotations = self . _annotations , custom_filters = self . _custom_filters , ) | Return count of objects in queryset instead of objects . | 61 | 12 |
225,830 | def first ( self ) -> "QuerySet" : queryset = self . _clone ( ) queryset . _limit = 1 queryset . _single = True return queryset | Limit queryset to one object and return one object instead of list . | 41 | 15 |
225,831 | def get ( self , * args , * * kwargs ) -> "QuerySet" : queryset = self . filter ( * args , * * kwargs ) queryset . _limit = 2 queryset . _get = True return queryset | Fetch exactly one object matching the parameters . | 57 | 9 |
225,832 | async def explain ( self ) -> Any : if self . _db is None : self . _db = self . model . _meta . db return await self . _db . executor_class ( model = self . model , db = self . _db ) . execute_explain ( self . _make_query ( ) ) | Fetch and return information about the query execution plan . | 71 | 11 |
225,833 | def using_db ( self , _db : BaseDBAsyncClient ) -> "QuerySet" : queryset = self . _clone ( ) queryset . _db = _db return queryset | Executes query in provided db client . Useful for transactions workaround . | 44 | 13 |
225,834 | def _check_unique_together ( cls ) : if cls . _meta . unique_together is None : return if not isinstance ( cls . _meta . unique_together , ( tuple , list ) ) : raise ConfigurationError ( "'{}.unique_together' must be a list or tuple." . format ( cls . __name__ ) ) elif any ( not isinstance ( unique_fields , ( tuple , list ) ) for unique_fields in cls . _meta . unique_together ) : raise ConfigurationError ( "All '{}.unique_together' elements must be lists or tuples." . format ( cls . __name__ ) ) else : for fields_tuple in cls . _meta . unique_together : for field_name in fields_tuple : field = cls . _meta . fields_map . get ( field_name ) if not field : raise ConfigurationError ( "'{}.unique_together' has no '{}' " "field." . format ( cls . __name__ , field_name ) ) if isinstance ( field , ManyToManyField ) : raise ConfigurationError ( "'{}.unique_together' '{}' field refers " "to ManyToMany field." . format ( cls . __name__ , field_name ) ) | Check the value of unique_together option . | 281 | 9 |
225,835 | def write_epub ( name , book , options = None ) : epub = EpubWriter ( name , book , options ) epub . process ( ) try : epub . write ( ) except IOError : pass | Creates epub file with the content defined in EpubBook . | 47 | 14 |
225,836 | def read_epub ( name , options = None ) : reader = EpubReader ( name , options ) book = reader . load ( ) reader . process ( ) return book | Creates new instance of EpubBook with the content defined in the input file . | 37 | 17 |
225,837 | def get_type ( self ) : _ , ext = zip_path . splitext ( self . get_name ( ) ) ext = ext . lower ( ) for uid , ext_list in six . iteritems ( ebooklib . EXTENSIONS ) : if ext in ext_list : return uid return ebooklib . ITEM_UNKNOWN | Guess type according to the file extension . Might not be the best way how to do it but it works for now . | 75 | 25 |
225,838 | def add_link ( self , * * kwgs ) : self . links . append ( kwgs ) if kwgs . get ( 'type' ) == 'text/javascript' : if 'scripted' not in self . properties : self . properties . append ( 'scripted' ) | Add additional link to the document . Links will be embeded only inside of this document . | 64 | 18 |
225,839 | def get_links_of_type ( self , link_type ) : return ( link for link in self . links if link . get ( 'type' , '' ) == link_type ) | Returns list of additional links of specific type . | 41 | 9 |
225,840 | def add_item ( self , item ) : if item . get_type ( ) == ebooklib . ITEM_STYLE : self . add_link ( href = item . get_name ( ) , rel = 'stylesheet' , type = 'text/css' ) if item . get_type ( ) == ebooklib . ITEM_SCRIPT : self . add_link ( src = item . get_name ( ) , type = 'text/javascript' ) | Add other item to this document . It will create additional links according to the item type . | 102 | 18 |
225,841 | def reset ( self ) : self . metadata = { } self . items = [ ] self . spine = [ ] self . guide = [ ] self . pages = [ ] self . toc = [ ] self . bindings = [ ] self . IDENTIFIER_ID = 'id' self . FOLDER_NAME = 'EPUB' self . _id_html = 0 self . _id_image = 0 self . _id_static = 0 self . title = '' self . language = 'en' self . direction = None self . templates = { 'ncx' : NCX_XML , 'nav' : NAV_XML , 'chapter' : CHAPTER_XML , 'cover' : COVER_XML } self . add_metadata ( 'OPF' , 'generator' , '' , { 'name' : 'generator' , 'content' : 'Ebook-lib %s' % '.' . join ( [ str ( s ) for s in VERSION ] ) } ) # default to using a randomly-unique identifier if one is not specified manually self . set_identifier ( str ( uuid . uuid4 ( ) ) ) # custom prefixes and namespaces to be set to the content.opf doc self . prefixes = [ ] self . namespaces = { } | Initialises all needed variables to default values | 284 | 8 |
225,842 | def set_identifier ( self , uid ) : self . uid = uid self . set_unique_metadata ( 'DC' , 'identifier' , self . uid , { 'id' : self . IDENTIFIER_ID } ) | Sets unique id for this epub | 56 | 8 |
225,843 | def set_title ( self , title ) : self . title = title self . add_metadata ( 'DC' , 'title' , self . title ) | Set title . You can set multiple titles . | 33 | 9 |
225,844 | def set_cover ( self , file_name , content , create_page = True ) : # as it is now, it can only be called once c0 = EpubCover ( file_name = file_name ) c0 . content = content self . add_item ( c0 ) if create_page : c1 = EpubCoverHtml ( image_name = file_name ) self . add_item ( c1 ) self . add_metadata ( None , 'meta' , '' , OrderedDict ( [ ( 'name' , 'cover' ) , ( 'content' , 'cover-img' ) ] ) ) | Set cover and create cover document if needed . | 137 | 9 |
225,845 | def add_author ( self , author , file_as = None , role = None , uid = 'creator' ) : self . add_metadata ( 'DC' , 'creator' , author , { 'id' : uid } ) if file_as : self . add_metadata ( None , 'meta' , file_as , { 'refines' : '#' + uid , 'property' : 'file-as' , 'scheme' : 'marc:relators' } ) if role : self . add_metadata ( None , 'meta' , role , { 'refines' : '#' + uid , 'property' : 'role' , 'scheme' : 'marc:relators' } ) | Add author for this document | 162 | 5 |
225,846 | def add_item ( self , item ) : if item . media_type == '' : ( has_guessed , media_type ) = guess_type ( item . get_name ( ) . lower ( ) ) if has_guessed : if media_type is not None : item . media_type = media_type else : item . media_type = has_guessed else : item . media_type = 'application/octet-stream' if not item . get_id ( ) : # make chapter_, image_ and static_ configurable if isinstance ( item , EpubHtml ) : item . id = 'chapter_%d' % self . _id_html self . _id_html += 1 # If there's a page list, append it to the book's page list self . pages += item . pages elif isinstance ( item , EpubImage ) : item . id = 'image_%d' % self . _id_image self . _id_image += 1 else : item . id = 'static_%d' % self . _id_image self . _id_image += 1 item . book = self self . items . append ( item ) return item | Add additional item to the book . If not defined media type and chapter id will be defined for the item . | 258 | 22 |
225,847 | def get_item_with_id ( self , uid ) : for item in self . get_items ( ) : if item . id == uid : return item return None | Returns item for defined UID . | 38 | 6 |
225,848 | def get_item_with_href ( self , href ) : for item in self . get_items ( ) : if item . get_name ( ) == href : return item return None | Returns item for defined HREF . | 40 | 7 |
225,849 | def get_items_of_type ( self , item_type ) : return ( item for item in self . items if item . get_type ( ) == item_type ) | Returns all items of specified type . | 38 | 7 |
225,850 | def get_items_of_media_type ( self , media_type ) : return ( item for item in self . items if item . media_type == media_type ) | Returns all items of specified media type . | 38 | 8 |
225,851 | def main ( ) : import argparse parser = argparse . ArgumentParser ( description = "ftfy (fixes text for you), version %s" % __version__ ) parser . add_argument ( 'filename' , default = '-' , nargs = '?' , help = 'The file whose Unicode is to be fixed. Defaults ' 'to -, meaning standard input.' ) parser . add_argument ( '-o' , '--output' , type = str , default = '-' , help = 'The file to output to. Defaults to -, meaning ' 'standard output.' ) parser . add_argument ( '-g' , '--guess' , action = 'store_true' , help = "Ask ftfy to guess the encoding of your input. " "This is risky. Overrides -e." ) parser . add_argument ( '-e' , '--encoding' , type = str , default = 'utf-8' , help = 'The encoding of the input. Defaults to UTF-8.' ) parser . add_argument ( '-n' , '--normalization' , type = str , default = 'NFC' , help = 'The normalization of Unicode to apply. ' 'Defaults to NFC. Can be "none".' ) parser . add_argument ( '--preserve-entities' , action = 'store_true' , help = "Leave HTML entities as they are. The default " "is to decode them, as long as no HTML tags " "have appeared in the file." ) args = parser . parse_args ( ) encoding = args . encoding if args . guess : encoding = None if args . filename == '-' : # Get a standard input stream made of bytes, so we can decode it as # whatever encoding is necessary. file = sys . stdin . buffer else : file = open ( args . filename , 'rb' ) if args . output == '-' : outfile = sys . stdout else : if os . path . realpath ( args . output ) == os . path . realpath ( args . filename ) : sys . stderr . write ( SAME_FILE_ERROR_TEXT ) sys . exit ( 1 ) outfile = open ( args . output , 'w' , encoding = 'utf-8' ) normalization = args . normalization if normalization . lower ( ) == 'none' : normalization = None if args . preserve_entities : fix_entities = False else : fix_entities = 'auto' try : for line in fix_file ( file , encoding = encoding , fix_entities = fix_entities , normalization = normalization ) : try : outfile . write ( line ) except UnicodeEncodeError : if sys . platform == 'win32' : sys . stderr . write ( ENCODE_ERROR_TEXT_WINDOWS ) else : sys . stderr . write ( ENCODE_ERROR_TEXT_UNIX ) sys . exit ( 1 ) except UnicodeDecodeError as err : sys . stderr . write ( DECODE_ERROR_TEXT % ( encoding , err ) ) sys . exit ( 1 ) | Run ftfy as a command - line utility . | 679 | 10 |
225,852 | def fix_encoding_and_explain ( text ) : best_version = text best_cost = text_cost ( text ) best_plan = [ ] plan_so_far = [ ] while True : prevtext = text text , plan = fix_one_step_and_explain ( text ) plan_so_far . extend ( plan ) cost = text_cost ( text ) for _ , _ , step_cost in plan_so_far : cost += step_cost if cost < best_cost : best_cost = cost best_version = text best_plan = list ( plan_so_far ) if text == prevtext : return best_version , best_plan | Re - decodes text that has been decoded incorrectly and also return a plan indicating all the steps required to fix it . | 148 | 25 |
225,853 | def apply_plan ( text , plan ) : obj = text for operation , encoding , _ in plan : if operation == 'encode' : obj = obj . encode ( encoding ) elif operation == 'decode' : obj = obj . decode ( encoding ) elif operation == 'transcode' : if encoding in TRANSCODERS : obj = TRANSCODERS [ encoding ] ( obj ) else : raise ValueError ( "Unknown transcode operation: %s" % encoding ) else : raise ValueError ( "Unknown plan step: %s" % operation ) return obj | Apply a plan for fixing the encoding of text . | 121 | 10 |
225,854 | def _unescape_fixup ( match ) : text = match . group ( 0 ) if text [ : 2 ] == "&#" : # character reference try : if text [ : 3 ] == "&#x" : codept = int ( text [ 3 : - 1 ] , 16 ) else : codept = int ( text [ 2 : - 1 ] ) if 0x80 <= codept < 0xa0 : # Decode this range of characters as Windows-1252, as Web # browsers do in practice. return bytes ( [ codept ] ) . decode ( 'sloppy-windows-1252' ) else : return chr ( codept ) except ValueError : return text else : # This is a named entity; if it's a known HTML5 entity, replace # it with the appropriate character. try : return entities . html5 [ text [ 1 : ] ] except KeyError : return text | Replace one matched HTML entity with the character it represents if possible . | 195 | 14 |
225,855 | def convert_surrogate_pair ( match ) : pair = match . group ( 0 ) codept = 0x10000 + ( ord ( pair [ 0 ] ) - 0xd800 ) * 0x400 + ( ord ( pair [ 1 ] ) - 0xdc00 ) return chr ( codept ) | Convert a surrogate pair to the single codepoint it represents . | 66 | 14 |
225,856 | def restore_byte_a0 ( byts ) : def replacement ( match ) : "The function to apply when this regex matches." return match . group ( 0 ) . replace ( b'\x20' , b'\xa0' ) return ALTERED_UTF8_RE . sub ( replacement , byts ) | Some mojibake has been additionally altered by a process that said hmm byte A0 that s basically a space! and replaced it with an ASCII space . When the A0 is part of a sequence that we intend to decode as UTF - 8 changing byte A0 to 20 would make it fail to decode . | 69 | 64 |
225,857 | def fix_partial_utf8_punct_in_1252 ( text ) : def latin1_to_w1252 ( match ) : "The function to apply when this regex matches." return match . group ( 0 ) . encode ( 'latin-1' ) . decode ( 'sloppy-windows-1252' ) def w1252_to_utf8 ( match ) : "The function to apply when this regex matches." return match . group ( 0 ) . encode ( 'sloppy-windows-1252' ) . decode ( 'utf-8' ) text = C1_CONTROL_RE . sub ( latin1_to_w1252 , text ) return PARTIAL_UTF8_PUNCT_RE . sub ( w1252_to_utf8 , text ) | Fix particular characters that seem to be found in the wild encoded in UTF - 8 and decoded in Latin - 1 or Windows - 1252 even when this fix can t be consistently applied . | 178 | 38 |
225,858 | def display_ljust ( text , width , fillchar = ' ' ) : if character_width ( fillchar ) != 1 : raise ValueError ( "The padding character must have display width 1" ) text_width = monospaced_width ( text ) if text_width == - 1 : # There's a control character here, so just don't add padding return text padding = max ( 0 , width - text_width ) return text + fillchar * padding | Return text left - justified in a Unicode string whose display width in a monospaced terminal should be at least width character cells . The rest of the string will be padded with fillchar which must be a width - 1 character . | 98 | 46 |
225,859 | def display_center ( text , width , fillchar = ' ' ) : if character_width ( fillchar ) != 1 : raise ValueError ( "The padding character must have display width 1" ) text_width = monospaced_width ( text ) if text_width == - 1 : return text padding = max ( 0 , width - text_width ) left_padding = padding // 2 right_padding = padding - left_padding return fillchar * left_padding + text + fillchar * right_padding | Return text centered in a Unicode string whose display width in a monospaced terminal should be at least width character cells . The rest of the string will be padded with fillchar which must be a width - 1 character . | 108 | 44 |
225,860 | def make_sloppy_codec ( encoding ) : # Make a bytestring of all 256 possible bytes. all_bytes = bytes ( range ( 256 ) ) # Get a list of what they would decode to in Latin-1. sloppy_chars = list ( all_bytes . decode ( 'latin-1' ) ) # Get a list of what they decode to in the given encoding. Use the # replacement character for unassigned bytes. if PY26 : decoded_chars = all_bytes . decode ( encoding , 'replace' ) else : decoded_chars = all_bytes . decode ( encoding , errors = 'replace' ) # Update the sloppy_chars list. Each byte that was successfully decoded # gets its decoded value in the list. The unassigned bytes are left as # they are, which gives their decoding in Latin-1. for i , char in enumerate ( decoded_chars ) : if char != REPLACEMENT_CHAR : sloppy_chars [ i ] = char # For ftfy's own purposes, we're going to allow byte 1A, the "Substitute" # control code, to encode the Unicode replacement character U+FFFD. sloppy_chars [ 0x1a ] = REPLACEMENT_CHAR # Create the data structures that tell the charmap methods how to encode # and decode in this sloppy encoding. decoding_table = '' . join ( sloppy_chars ) encoding_table = codecs . charmap_build ( decoding_table ) # Now produce all the class boilerplate. Look at the Python source for # `encodings.cp1252` for comparison; this is almost exactly the same, # except I made it follow pep8. class Codec ( codecs . Codec ) : def encode ( self , input , errors = 'strict' ) : return codecs . charmap_encode ( input , errors , encoding_table ) def decode ( self , input , errors = 'strict' ) : return codecs . charmap_decode ( input , errors , decoding_table ) class IncrementalEncoder ( codecs . IncrementalEncoder ) : def encode ( self , input , final = False ) : return codecs . charmap_encode ( input , self . errors , encoding_table ) [ 0 ] class IncrementalDecoder ( codecs . IncrementalDecoder ) : def decode ( self , input , final = False ) : return codecs . charmap_decode ( input , self . errors , decoding_table ) [ 0 ] class StreamWriter ( Codec , codecs . StreamWriter ) : pass class StreamReader ( Codec , codecs . StreamReader ) : pass return codecs . CodecInfo ( name = 'sloppy-' + encoding , encode = Codec ( ) . encode , decode = Codec ( ) . decode , incrementalencoder = IncrementalEncoder , incrementaldecoder = IncrementalDecoder , streamreader = StreamReader , streamwriter = StreamWriter , ) | Take a codec name and return a sloppy version of that codec that can encode and decode the unassigned bytes in that encoding . | 640 | 26 |
225,861 | def _make_weirdness_regex ( ) : groups = [ ] # Match diacritical marks, except when they modify a non-cased letter or # another mark. # # You wouldn't put a diacritical mark on a digit or a space, for example. # You might put it on a Latin letter, but in that case there will almost # always be a pre-composed version, and we normalize to pre-composed # versions first. The cases that can't be pre-composed tend to be in # large scripts without case, which are in class C. groups . append ( '[^CM]M' ) # Match non-Latin characters adjacent to Latin characters. # # This is a simplification from ftfy version 2, which compared all # adjacent scripts. However, the ambiguities we need to resolve come from # encodings designed to represent Latin characters. groups . append ( '[Ll][AaC]' ) groups . append ( '[AaC][Ll]' ) # Match IPA letters next to capital letters. # # IPA uses lowercase letters only. Some accented capital letters next to # punctuation can accidentally decode as IPA letters, and an IPA letter # appearing next to a capital letter is a good sign that this happened. groups . append ( '[LA]i' ) groups . append ( 'i[LA]' ) # Match non-combining diacritics. We've already set aside the common ones # like ^ (the CIRCUMFLEX ACCENT, repurposed as a caret, exponent sign, # or happy eye) and assigned them to category 'o'. The remaining ones, # like the diaeresis (¨), are pretty weird to see on their own instead # of combined with a letter. groups . append ( '2' ) # Match C1 control characters, which are almost always the result of # decoding Latin-1 that was meant to be Windows-1252. groups . append ( 'X' ) # Match private use and unassigned characters. groups . append ( 'P' ) groups . append ( '_' ) # Match adjacent characters from any different pair of these categories: # - Modifier marks (M) # - Letter modifiers (m) # - Miscellaneous numbers (N) # - Symbols (1 or 3, because 2 is already weird on its own) exclusive_categories = 'MmN13' for cat1 in exclusive_categories : others_range = '' . join ( c for c in exclusive_categories if c != cat1 ) groups . append ( '{cat1}[{others_range}]' . format ( cat1 = cat1 , others_range = others_range ) ) regex = '|' . join ( groups ) return re . compile ( regex ) | Creates a list of regexes that match weird character sequences . The more matches there are the weirder the text is . | 594 | 26 |
225,862 | def sequence_weirdness ( text ) : text2 = unicodedata . normalize ( 'NFC' , text ) weirdness = len ( WEIRDNESS_RE . findall ( chars_to_classes ( text2 ) ) ) adjustment = ( len ( MOJIBAKE_SYMBOL_RE . findall ( text2 ) ) * 2 - len ( COMMON_SYMBOL_RE . findall ( text2 ) ) ) return weirdness * 2 + adjustment | Determine how often a text has unexpected characters or sequences of characters . This metric is used to disambiguate when text should be re - decoded or left as is . | 105 | 37 |
225,863 | def search_function ( encoding ) : if encoding in _CACHE : return _CACHE [ encoding ] norm_encoding = normalize_encoding ( encoding ) codec = None if norm_encoding in UTF8_VAR_NAMES : from ftfy . bad_codecs . utf8_variants import CODEC_INFO codec = CODEC_INFO elif norm_encoding . startswith ( 'sloppy_' ) : from ftfy . bad_codecs . sloppy import CODECS codec = CODECS . get ( norm_encoding ) if codec is not None : _CACHE [ encoding ] = codec return codec | Register our bad codecs with Python s codecs API . This involves adding a search function that takes in an encoding name and returns a codec for that encoding if it knows one or None if it doesn t . | 150 | 42 |
225,864 | def _buffer_decode ( self , input , errors , final ) : # decoded_segments are the pieces of text we have decoded so far, # and position is our current position in the byte string. (Bytes # before this position have been consumed, and bytes after it have # yet to be decoded.) decoded_segments = [ ] position = 0 while True : # Use _buffer_decode_step to decode a segment of text. decoded , consumed = self . _buffer_decode_step ( input [ position : ] , errors , final ) if consumed == 0 : # Either there's nothing left to decode, or we need to wait # for more input. Either way, we're done for now. break # Append the decoded text to the list, and update our position. decoded_segments . append ( decoded ) position += consumed if final : # _buffer_decode_step must consume all the bytes when `final` is # true. assert position == len ( input ) return '' . join ( decoded_segments ) , position | Decode bytes that may be arriving in a stream following the Codecs API . | 231 | 16 |
225,865 | def _buffer_decode_surrogates ( sup , input , errors , final ) : if len ( input ) < 6 : if final : # We found 0xed near the end of the stream, and there aren't # six bytes to decode. Delegate to the superclass method to # handle it as normal UTF-8. It might be a Hangul character # or an error. return sup ( input , errors , final ) else : # We found a surrogate, the stream isn't over yet, and we don't # know enough of the following bytes to decode anything, so # consume zero bytes and wait. return '' , 0 else : if CESU8_RE . match ( input ) : # Given this is a CESU-8 sequence, do some math to pull out # the intended 20-bit value, and consume six bytes. codepoint = ( ( ( input [ 1 ] & 0x0f ) << 16 ) + ( ( input [ 2 ] & 0x3f ) << 10 ) + ( ( input [ 4 ] & 0x0f ) << 6 ) + ( input [ 5 ] & 0x3f ) + 0x10000 ) return chr ( codepoint ) , 6 else : # This looked like a CESU-8 sequence, but it wasn't one. # 0xed indicates the start of a three-byte sequence, so give # three bytes to the superclass to decode as usual. return sup ( input [ : 3 ] , errors , False ) | When we have improperly encoded surrogates we can still see the bits that they were meant to represent . | 317 | 20 |
225,866 | def fix_text ( text , * , fix_entities = 'auto' , remove_terminal_escapes = True , fix_encoding = True , fix_latin_ligatures = True , fix_character_width = True , uncurl_quotes = True , fix_line_breaks = True , fix_surrogates = True , remove_control_chars = True , remove_bom = True , normalization = 'NFC' , max_decode_length = 10 ** 6 ) : if isinstance ( text , bytes ) : raise UnicodeError ( fixes . BYTES_ERROR_TEXT ) out = [ ] pos = 0 while pos < len ( text ) : textbreak = text . find ( '\n' , pos ) + 1 fix_encoding_this_time = fix_encoding if textbreak == 0 : textbreak = len ( text ) if ( textbreak - pos ) > max_decode_length : fix_encoding_this_time = False substring = text [ pos : textbreak ] if fix_entities == 'auto' and '<' in substring and '>' in substring : # we see angle brackets together; this could be HTML fix_entities = False out . append ( fix_text_segment ( substring , fix_entities = fix_entities , remove_terminal_escapes = remove_terminal_escapes , fix_encoding = fix_encoding_this_time , uncurl_quotes = uncurl_quotes , fix_latin_ligatures = fix_latin_ligatures , fix_character_width = fix_character_width , fix_line_breaks = fix_line_breaks , fix_surrogates = fix_surrogates , remove_control_chars = remove_control_chars , remove_bom = remove_bom , normalization = normalization ) ) pos = textbreak return '' . join ( out ) | r Given Unicode text as input fix inconsistencies and glitches in it such as mojibake . | 429 | 19 |
225,867 | def fix_file ( input_file , encoding = None , * , fix_entities = 'auto' , remove_terminal_escapes = True , fix_encoding = True , fix_latin_ligatures = True , fix_character_width = True , uncurl_quotes = True , fix_line_breaks = True , fix_surrogates = True , remove_control_chars = True , remove_bom = True , normalization = 'NFC' ) : entities = fix_entities for line in input_file : if isinstance ( line , bytes ) : if encoding is None : line , encoding = guess_bytes ( line ) else : line = line . decode ( encoding ) if fix_entities == 'auto' and '<' in line and '>' in line : entities = False yield fix_text_segment ( line , fix_entities = entities , remove_terminal_escapes = remove_terminal_escapes , fix_encoding = fix_encoding , fix_latin_ligatures = fix_latin_ligatures , fix_character_width = fix_character_width , uncurl_quotes = uncurl_quotes , fix_line_breaks = fix_line_breaks , fix_surrogates = fix_surrogates , remove_control_chars = remove_control_chars , remove_bom = remove_bom , normalization = normalization ) | Fix text that is found in a file . | 317 | 9 |
225,868 | def fix_text_segment ( text , * , fix_entities = 'auto' , remove_terminal_escapes = True , fix_encoding = True , fix_latin_ligatures = True , fix_character_width = True , uncurl_quotes = True , fix_line_breaks = True , fix_surrogates = True , remove_control_chars = True , remove_bom = True , normalization = 'NFC' ) : if isinstance ( text , bytes ) : raise UnicodeError ( fixes . BYTES_ERROR_TEXT ) if fix_entities == 'auto' and '<' in text and '>' in text : fix_entities = False while True : origtext = text if remove_terminal_escapes : text = fixes . remove_terminal_escapes ( text ) if fix_encoding : text = fixes . fix_encoding ( text ) if fix_entities : text = fixes . unescape_html ( text ) if fix_latin_ligatures : text = fixes . fix_latin_ligatures ( text ) if fix_character_width : text = fixes . fix_character_width ( text ) if uncurl_quotes : text = fixes . uncurl_quotes ( text ) if fix_line_breaks : text = fixes . fix_line_breaks ( text ) if fix_surrogates : text = fixes . fix_surrogates ( text ) if remove_control_chars : text = fixes . remove_control_chars ( text ) if remove_bom and not remove_control_chars : # Skip this step if we've already done `remove_control_chars`, # because it would be redundant. text = fixes . remove_bom ( text ) if normalization is not None : text = unicodedata . normalize ( normalization , text ) if text == origtext : return text | Apply fixes to text in a single chunk . This could be a line of text within a larger run of fix_text or it could be a larger amount of text that you are certain is in a consistent encoding . | 418 | 43 |
225,869 | def explain_unicode ( text ) : for char in text : if char . isprintable ( ) : display = char else : display = char . encode ( 'unicode-escape' ) . decode ( 'ascii' ) print ( 'U+{code:04X} {display} [{category}] {name}' . format ( display = display_ljust ( display , 7 ) , code = ord ( char ) , category = unicodedata . category ( char ) , name = unicodedata . name ( char , '<unknown>' ) ) ) | A utility method that s useful for debugging mysterious Unicode . | 124 | 11 |
225,870 | def _build_regexes ( ) : # Define a regex that matches ASCII text. encoding_regexes = { 'ascii' : re . compile ( '^[\x00-\x7f]*$' ) } for encoding in CHARMAP_ENCODINGS : # Make a sequence of characters that bytes \x80 to \xFF decode to # in each encoding, as well as byte \x1A, which is used to represent # the replacement character � in the sloppy-* encodings. byte_range = bytes ( list ( range ( 0x80 , 0x100 ) ) + [ 0x1a ] ) charlist = byte_range . decode ( encoding ) # The rest of the ASCII bytes -- bytes \x00 to \x19 and \x1B # to \x7F -- will decode as those ASCII characters in any encoding we # support, so we can just include them as ranges. This also lets us # not worry about escaping regex special characters, because all of # them are in the \x1B to \x7F range. regex = '^[\x00-\x19\x1b-\x7f{0}]*$' . format ( charlist ) encoding_regexes [ encoding ] = re . compile ( regex ) return encoding_regexes | ENCODING_REGEXES contain reasonably fast ways to detect if we could represent a given string in a given encoding . The simplest one is the ascii detector which of course just determines if all characters are between U + 0000 and U + 007F . | 289 | 54 |
225,871 | def _build_width_map ( ) : # Though it's not listed as a fullwidth character, we'll want to convert # U+3000 IDEOGRAPHIC SPACE to U+20 SPACE on the same principle, so start # with that in the dictionary. width_map = { 0x3000 : ' ' } for i in range ( 0xff01 , 0xfff0 ) : char = chr ( i ) alternate = unicodedata . normalize ( 'NFKC' , char ) if alternate != char : width_map [ i ] = alternate return width_map | Build a translate mapping that replaces halfwidth and fullwidth forms with their standard - width forms . | 123 | 19 |
225,872 | def set_vml_accuracy_mode ( mode ) : if use_vml : acc_dict = { None : 0 , 'low' : 1 , 'high' : 2 , 'fast' : 3 } acc_reverse_dict = { 1 : 'low' , 2 : 'high' , 3 : 'fast' } if mode not in acc_dict . keys ( ) : raise ValueError ( "mode argument must be one of: None, 'high', 'low', 'fast'" ) retval = _set_vml_accuracy_mode ( acc_dict . get ( mode , 0 ) ) return acc_reverse_dict . get ( retval ) else : return None | Set the accuracy mode for VML operations . | 149 | 9 |
225,873 | def _init_num_threads ( ) : # Any platform-specific short-circuits if 'sparc' in platform . machine ( ) : log . warning ( 'The number of threads have been set to 1 because problems related ' 'to threading have been reported on some sparc machine. ' 'The number of threads can be changed using the "set_num_threads" ' 'function.' ) set_num_threads ( 1 ) return 1 env_configured = False n_cores = detect_number_of_cores ( ) if 'NUMEXPR_MAX_THREADS' in os . environ : # The user has configured NumExpr in the expected way, so suppress logs. env_configured = True n_cores = MAX_THREADS else : # The use has not set 'NUMEXPR_MAX_THREADS', so likely they have not # configured NumExpr as desired, so we emit info logs. if n_cores > MAX_THREADS : log . info ( 'Note: detected %d virtual cores but NumExpr set to maximum of %d, check "NUMEXPR_MAX_THREADS" environment variable.' % ( n_cores , MAX_THREADS ) ) if n_cores > 8 : # The historical 'safety' limit. log . info ( 'Note: NumExpr detected %d cores but "NUMEXPR_MAX_THREADS" not set, so enforcing safe limit of 8.' % n_cores ) n_cores = 8 # Now we check for 'NUMEXPR_NUM_THREADS' or 'OMP_NUM_THREADS' to set the # actual number of threads used. if 'NUMEXPR_NUM_THREADS' in os . environ : requested_threads = int ( os . environ [ 'NUMEXPR_NUM_THREADS' ] ) elif 'OMP_NUM_THREADS' in os . environ : requested_threads = int ( os . environ [ 'OMP_NUM_THREADS' ] ) else : requested_threads = n_cores if not env_configured : log . info ( 'NumExpr defaulting to %d threads.' % n_cores ) # The C-extension function performs its own checks against `MAX_THREADS` set_num_threads ( requested_threads ) return requested_threads | Detects the environment variable NUMEXPR_MAX_THREADS to set the threadpool size and if necessary the slightly redundant NUMEXPR_NUM_THREADS or OMP_NUM_THREADS env vars to set the initial number of threads used by the virtual machine . | 534 | 60 |
225,874 | def detect_number_of_cores ( ) : # Linux, Unix and MacOS: if hasattr ( os , "sysconf" ) : if "SC_NPROCESSORS_ONLN" in os . sysconf_names : # Linux & Unix: ncpus = os . sysconf ( "SC_NPROCESSORS_ONLN" ) if isinstance ( ncpus , int ) and ncpus > 0 : return ncpus else : # OSX: return int ( subprocess . check_output ( [ "sysctl" , "-n" , "hw.ncpu" ] ) ) # Windows: try : ncpus = int ( os . environ . get ( "NUMBER_OF_PROCESSORS" , "" ) ) if ncpus > 0 : return ncpus except ValueError : pass return 1 | Detects the number of cores on a system . Cribbed from pp . | 187 | 16 |
225,875 | def chunkify ( chunksize ) : def chunkifier ( func ) : def wrap ( * args ) : assert len ( args ) > 0 assert all ( len ( a . flat ) == len ( args [ 0 ] . flat ) for a in args ) nelements = len ( args [ 0 ] . flat ) nchunks , remain = divmod ( nelements , chunksize ) out = np . ndarray ( args [ 0 ] . shape ) for start in range ( 0 , nelements , chunksize ) : #print(start) stop = start + chunksize if start + chunksize > nelements : stop = nelements - start iargs = tuple ( a . flat [ start : stop ] for a in args ) out . flat [ start : stop ] = func ( * iargs ) return out return wrap return chunkifier | Very stupid chunk vectorizer which keeps memory use down . This version requires all inputs to have the same number of elements although it shouldn t be that hard to implement simple broadcasting . | 175 | 35 |
225,876 | def expressionToAST ( ex ) : return ASTNode ( ex . astType , ex . astKind , ex . value , [ expressionToAST ( c ) for c in ex . children ] ) | Take an expression tree made out of expressions . ExpressionNode and convert to an AST tree . | 41 | 18 |
225,877 | def sigPerms ( s ) : codes = 'bilfdc' if not s : yield '' elif s [ 0 ] in codes : start = codes . index ( s [ 0 ] ) for x in codes [ start : ] : for y in sigPerms ( s [ 1 : ] ) : yield x + y elif s [ 0 ] == 's' : # numbers shall not be cast to strings for y in sigPerms ( s [ 1 : ] ) : yield 's' + y else : yield s | Generate all possible signatures derived by upcasting the given signature . | 111 | 13 |
225,878 | def typeCompileAst ( ast ) : children = list ( ast . children ) if ast . astType == 'op' : retsig = ast . typecode ( ) basesig = '' . join ( x . typecode ( ) for x in list ( ast . children ) ) # Find some operation that will work on an acceptable casting of args. for sig in sigPerms ( basesig ) : value = ( ast . value + '_' + retsig + sig ) . encode ( 'ascii' ) if value in interpreter . opcodes : break else : for sig in sigPerms ( basesig ) : funcname = ( ast . value + '_' + retsig + sig ) . encode ( 'ascii' ) if funcname in interpreter . funccodes : value = ( 'func_%sn' % ( retsig + sig ) ) . encode ( 'ascii' ) children += [ ASTNode ( 'raw' , 'none' , interpreter . funccodes [ funcname ] ) ] break else : raise NotImplementedError ( "couldn't find matching opcode for '%s'" % ( ast . value + '_' + retsig + basesig ) ) # First just cast constants, then cast variables if necessary: for i , ( have , want ) in enumerate ( zip ( basesig , sig ) ) : if have != want : kind = typecode_to_kind [ want ] if children [ i ] . astType == 'constant' : children [ i ] = ASTNode ( 'constant' , kind , children [ i ] . value ) else : opname = "cast" children [ i ] = ASTNode ( 'op' , kind , opname , [ children [ i ] ] ) else : value = ast . value children = ast . children return ASTNode ( ast . astType , ast . astKind , value , [ typeCompileAst ( c ) for c in children ] ) | Assign appropiate types to each node in the AST . | 422 | 13 |
225,879 | def stringToExpression ( s , types , context ) : old_ctx = expressions . _context . get_current_context ( ) try : expressions . _context . set_new_context ( context ) # first compile to a code object to determine the names if context . get ( 'truediv' , False ) : flags = __future__ . division . compiler_flag else : flags = 0 c = compile ( s , '<expr>' , 'eval' , flags ) # make VariableNode's for the names names = { } for name in c . co_names : if name == "None" : names [ name ] = None elif name == "True" : names [ name ] = True elif name == "False" : names [ name ] = False else : t = types . get ( name , default_type ) names [ name ] = expressions . VariableNode ( name , type_to_kind [ t ] ) names . update ( expressions . functions ) # now build the expression ex = eval ( c , names ) if expressions . isConstant ( ex ) : ex = expressions . ConstantNode ( ex , expressions . getKind ( ex ) ) elif not isinstance ( ex , expressions . ExpressionNode ) : raise TypeError ( "unsupported expression type: %s" % type ( ex ) ) finally : expressions . _context . set_new_context ( old_ctx ) return ex | Given a string convert it to a tree of ExpressionNode s . | 300 | 13 |
225,880 | def getInputOrder ( ast , input_order = None ) : variables = { } for a in ast . allOf ( 'variable' ) : variables [ a . value ] = a variable_names = set ( variables . keys ( ) ) if input_order : if variable_names != set ( input_order ) : raise ValueError ( "input names (%s) don't match those found in expression (%s)" % ( input_order , variable_names ) ) ordered_names = input_order else : ordered_names = list ( variable_names ) ordered_names . sort ( ) ordered_variables = [ variables [ v ] for v in ordered_names ] return ordered_variables | Derive the input order of the variables in an expression . | 147 | 12 |
225,881 | def assignLeafRegisters ( inodes , registerMaker ) : leafRegisters = { } for node in inodes : key = node . key ( ) if key in leafRegisters : node . reg = leafRegisters [ key ] else : node . reg = leafRegisters [ key ] = registerMaker ( node ) | Assign new registers to each of the leaf nodes . | 68 | 11 |
225,882 | def assignBranchRegisters ( inodes , registerMaker ) : for node in inodes : node . reg = registerMaker ( node , temporary = True ) | Assign temporary registers to each of the branch nodes . | 33 | 11 |
225,883 | def collapseDuplicateSubtrees ( ast ) : seen = { } aliases = [ ] for a in ast . allOf ( 'op' ) : if a in seen : target = seen [ a ] a . astType = 'alias' a . value = target a . children = ( ) aliases . append ( a ) else : seen [ a ] = a # Set values and registers so optimizeTemporariesAllocation # doesn't get confused for a in aliases : while a . value . astType == 'alias' : a . value = a . value . value return aliases | Common subexpression elimination . | 122 | 5 |
225,884 | def optimizeTemporariesAllocation ( ast ) : nodes = [ n for n in ast . postorderWalk ( ) if n . reg . temporary ] users_of = dict ( ( n . reg , set ( ) ) for n in nodes ) node_regs = dict ( ( n , set ( c . reg for c in n . children if c . reg . temporary ) ) for n in nodes ) if nodes and nodes [ - 1 ] is not ast : nodes_to_check = nodes + [ ast ] else : nodes_to_check = nodes for n in nodes_to_check : for c in n . children : if c . reg . temporary : users_of [ c . reg ] . add ( n ) unused = dict ( [ ( tc , set ( ) ) for tc in scalar_constant_kinds ] ) for n in nodes : for c in n . children : reg = c . reg if reg . temporary : users = users_of [ reg ] users . discard ( n ) if not users : unused [ reg . node . astKind ] . add ( reg ) if unused [ n . astKind ] : reg = unused [ n . astKind ] . pop ( ) users_of [ reg ] = users_of [ n . reg ] n . reg = reg | Attempt to minimize the number of temporaries needed by reusing old ones . | 275 | 15 |
225,885 | def setOrderedRegisterNumbers ( order , start ) : for i , node in enumerate ( order ) : node . reg . n = start + i return start + len ( order ) | Given an order of nodes assign register numbers . | 39 | 9 |
225,886 | def setRegisterNumbersForTemporaries ( ast , start ) : seen = 0 signature = '' aliases = [ ] for node in ast . postorderWalk ( ) : if node . astType == 'alias' : aliases . append ( node ) node = node . value if node . reg . immediate : node . reg . n = node . value continue reg = node . reg if reg . n is None : reg . n = start + seen seen += 1 signature += reg . node . typecode ( ) for node in aliases : node . reg = node . value . reg return start + seen , signature | Assign register numbers for temporary registers keeping track of aliases and handling immediate operands . | 125 | 17 |
225,887 | def convertASTtoThreeAddrForm ( ast ) : return [ ( node . value , node . reg ) + tuple ( [ c . reg for c in node . children ] ) for node in ast . allOf ( 'op' ) ] | Convert an AST to a three address form . | 51 | 10 |
225,888 | def compileThreeAddrForm ( program ) : def nToChr ( reg ) : if reg is None : return b'\xff' elif reg . n < 0 : raise ValueError ( "negative value for register number %s" % reg . n ) else : if sys . version_info [ 0 ] < 3 : return chr ( reg . n ) else : # int.to_bytes is not available in Python < 3.2 #return reg.n.to_bytes(1, sys.byteorder) return bytes ( [ reg . n ] ) def quadrupleToString ( opcode , store , a1 = None , a2 = None ) : cop = chr ( interpreter . opcodes [ opcode ] ) . encode ( 'ascii' ) cs = nToChr ( store ) ca1 = nToChr ( a1 ) ca2 = nToChr ( a2 ) return cop + cs + ca1 + ca2 def toString ( args ) : while len ( args ) < 4 : args += ( None , ) opcode , store , a1 , a2 = args [ : 4 ] s = quadrupleToString ( opcode , store , a1 , a2 ) l = [ s ] args = args [ 4 : ] while args : s = quadrupleToString ( b'noop' , * args [ : 3 ] ) l . append ( s ) args = args [ 3 : ] return b'' . join ( l ) prog_str = b'' . join ( [ toString ( t ) for t in program ] ) return prog_str | Given a three address form of the program compile it a string that the VM understands . | 343 | 17 |
225,889 | def precompile ( ex , signature = ( ) , context = { } ) : types = dict ( signature ) input_order = [ name for ( name , type_ ) in signature ] if isinstance ( ex , ( str , unicode ) ) : ex = stringToExpression ( ex , types , context ) # the AST is like the expression, but the node objects don't have # any odd interpretations ast = expressionToAST ( ex ) if ex . astType != 'op' : ast = ASTNode ( 'op' , value = 'copy' , astKind = ex . astKind , children = ( ast , ) ) ast = typeCompileAst ( ast ) aliases = collapseDuplicateSubtrees ( ast ) assignLeafRegisters ( ast . allOf ( 'raw' ) , Immediate ) assignLeafRegisters ( ast . allOf ( 'variable' , 'constant' ) , Register ) assignBranchRegisters ( ast . allOf ( 'op' ) , Register ) # assign registers for aliases for a in aliases : a . reg = a . value . reg input_order = getInputOrder ( ast , input_order ) constants_order , constants = getConstants ( ast ) if isReduction ( ast ) : ast . reg . temporary = False optimizeTemporariesAllocation ( ast ) ast . reg . temporary = False r_output = 0 ast . reg . n = 0 r_inputs = r_output + 1 r_constants = setOrderedRegisterNumbers ( input_order , r_inputs ) r_temps = setOrderedRegisterNumbers ( constants_order , r_constants ) r_end , tempsig = setRegisterNumbersForTemporaries ( ast , r_temps ) threeAddrProgram = convertASTtoThreeAddrForm ( ast ) input_names = tuple ( [ a . value for a in input_order ] ) signature = '' . join ( type_to_typecode [ types . get ( x , default_type ) ] for x in input_names ) return threeAddrProgram , signature , tempsig , constants , input_names | Compile the expression to an intermediate form . | 457 | 9 |
225,890 | def disassemble ( nex ) : rev_opcodes = { } for op in interpreter . opcodes : rev_opcodes [ interpreter . opcodes [ op ] ] = op r_constants = 1 + len ( nex . signature ) r_temps = r_constants + len ( nex . constants ) def getArg ( pc , offset ) : if sys . version_info [ 0 ] < 3 : arg = ord ( nex . program [ pc + offset ] ) op = rev_opcodes . get ( ord ( nex . program [ pc ] ) ) else : arg = nex . program [ pc + offset ] op = rev_opcodes . get ( nex . program [ pc ] ) try : code = op . split ( b'_' ) [ 1 ] [ offset - 1 ] except IndexError : return None if sys . version_info [ 0 ] > 2 : # int.to_bytes is not available in Python < 3.2 #code = code.to_bytes(1, sys.byteorder) code = bytes ( [ code ] ) if arg == 255 : return None if code != b'n' : if arg == 0 : return b'r0' elif arg < r_constants : return ( 'r%d[%s]' % ( arg , nex . input_names [ arg - 1 ] ) ) . encode ( 'ascii' ) elif arg < r_temps : return ( 'c%d[%s]' % ( arg , nex . constants [ arg - r_constants ] ) ) . encode ( 'ascii' ) else : return ( 't%d' % ( arg , ) ) . encode ( 'ascii' ) else : return arg source = [ ] for pc in range ( 0 , len ( nex . program ) , 4 ) : if sys . version_info [ 0 ] < 3 : op = rev_opcodes . get ( ord ( nex . program [ pc ] ) ) else : op = rev_opcodes . get ( nex . program [ pc ] ) dest = getArg ( pc , 1 ) arg1 = getArg ( pc , 2 ) arg2 = getArg ( pc , 3 ) source . append ( ( op , dest , arg1 , arg2 ) ) return source | Given a NumExpr object return a list which is the program disassembled . | 498 | 16 |
225,891 | def getArguments ( names , local_dict = None , global_dict = None ) : call_frame = sys . _getframe ( 2 ) clear_local_dict = False if local_dict is None : local_dict = call_frame . f_locals clear_local_dict = True try : frame_globals = call_frame . f_globals if global_dict is None : global_dict = frame_globals # If `call_frame` is the top frame of the interpreter we can't clear its # `local_dict`, because it is actually the `global_dict`. clear_local_dict = clear_local_dict and not frame_globals is local_dict arguments = [ ] for name in names : try : a = local_dict [ name ] except KeyError : a = global_dict [ name ] arguments . append ( numpy . asarray ( a ) ) finally : # If we generated local_dict via an explicit reference to f_locals, # clear the dict to prevent creating extra ref counts in the caller's scope # See https://github.com/pydata/numexpr/issues/310 if clear_local_dict : local_dict . clear ( ) return arguments | Get the arguments based on the names . | 267 | 8 |
225,892 | def evaluate ( ex , local_dict = None , global_dict = None , out = None , order = 'K' , casting = 'safe' , * * kwargs ) : global _numexpr_last if not isinstance ( ex , ( str , unicode ) ) : raise ValueError ( "must specify expression as a string" ) # Get the names for this expression context = getContext ( kwargs , frame_depth = 1 ) expr_key = ( ex , tuple ( sorted ( context . items ( ) ) ) ) if expr_key not in _names_cache : _names_cache [ expr_key ] = getExprNames ( ex , context ) names , ex_uses_vml = _names_cache [ expr_key ] arguments = getArguments ( names , local_dict , global_dict ) # Create a signature signature = [ ( name , getType ( arg ) ) for ( name , arg ) in zip ( names , arguments ) ] # Look up numexpr if possible. numexpr_key = expr_key + ( tuple ( signature ) , ) try : compiled_ex = _numexpr_cache [ numexpr_key ] except KeyError : compiled_ex = _numexpr_cache [ numexpr_key ] = NumExpr ( ex , signature , * * context ) kwargs = { 'out' : out , 'order' : order , 'casting' : casting , 'ex_uses_vml' : ex_uses_vml } _numexpr_last = dict ( ex = compiled_ex , argnames = names , kwargs = kwargs ) with evaluate_lock : return compiled_ex ( * arguments , * * kwargs ) | Evaluate a simple array expression element - wise using the new iterator . | 367 | 15 |
225,893 | def re_evaluate ( local_dict = None ) : try : compiled_ex = _numexpr_last [ 'ex' ] except KeyError : raise RuntimeError ( "not a previous evaluate() execution found" ) argnames = _numexpr_last [ 'argnames' ] args = getArguments ( argnames , local_dict ) kwargs = _numexpr_last [ 'kwargs' ] with evaluate_lock : return compiled_ex ( * args , * * kwargs ) | Re - evaluate the previous executed array expression without any check . | 107 | 12 |
225,894 | def compute ( ) : if what == "numpy" : y = eval ( expr ) else : y = ne . evaluate ( expr ) return len ( y ) | Compute the polynomial . | 34 | 7 |
225,895 | def partial_row_coordinates ( self , X ) : utils . validation . check_is_fitted ( self , 's_' ) # Check input if self . check_input : utils . check_array ( X , dtype = [ str , np . number ] ) # Prepare input X = self . _prepare_input ( X ) # Define the projection matrix P P = len ( X ) ** 0.5 * self . U_ / self . s_ # Get the projections for each group coords = { } for name , cols in sorted ( self . groups . items ( ) ) : X_partial = X . loc [ : , cols ] if not self . all_nums_ [ name ] : X_partial = self . cat_one_hots_ [ name ] . transform ( X_partial ) Z_partial = X_partial / self . partial_factor_analysis_ [ name ] . s_ [ 0 ] coords [ name ] = len ( self . groups ) * ( Z_partial @ Z_partial . T ) @ P # Convert coords to a MultiIndex DataFrame coords = pd . DataFrame ( { ( name , i ) : group_coords . loc [ : , i ] for name , group_coords in coords . items ( ) for i in range ( group_coords . shape [ 1 ] ) } ) return coords | Returns the row coordinates for each group . | 302 | 8 |
225,896 | def column_correlations ( self , X ) : utils . validation . check_is_fitted ( self , 's_' ) X_global = self . _build_X_global ( X ) row_pc = self . _row_coordinates_from_global ( X_global ) return pd . DataFrame ( { component : { feature : row_pc [ component ] . corr ( X_global [ feature ] . to_dense ( ) ) for feature in X_global . columns } for component in row_pc . columns } ) | Returns the column correlations . | 120 | 5 |
225,897 | def eigenvalues_ ( self ) : utils . validation . check_is_fitted ( self , 's_' ) return np . square ( self . s_ ) . tolist ( ) | The eigenvalues associated with each principal component . | 42 | 10 |
225,898 | def explained_inertia_ ( self ) : utils . validation . check_is_fitted ( self , 'total_inertia_' ) return [ eig / self . total_inertia_ for eig in self . eigenvalues_ ] | The percentage of explained inertia per principal component . | 57 | 9 |
225,899 | def row_coordinates ( self , X ) : utils . validation . check_is_fitted ( self , 'V_' ) _ , row_names , _ , _ = util . make_labels_and_names ( X ) if isinstance ( X , pd . SparseDataFrame ) : X = X . to_coo ( ) . astype ( float ) elif isinstance ( X , pd . DataFrame ) : X = X . to_numpy ( ) if self . copy : X = X . copy ( ) # Normalise the rows so that they sum up to 1 if isinstance ( X , np . ndarray ) : X = X / X . sum ( axis = 1 ) [ : , None ] else : X = X / X . sum ( axis = 1 ) return pd . DataFrame ( data = X @ sparse . diags ( self . col_masses_ . to_numpy ( ) ** - 0.5 ) @ self . V_ . T , index = row_names ) | The row principal coordinates . | 225 | 5 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.