idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
37,800
async def send_file ( filename : FilePath , mimetype : Optional [ str ] = None , as_attachment : bool = False , attachment_filename : Optional [ str ] = None , add_etags : bool = True , cache_timeout : Optional [ int ] = None , conditional : bool = False , last_modified : Optional [ datetime ] = None , ) -> Response : file_path = file_path_to_path ( filename ) if attachment_filename is None : attachment_filename = file_path . name if mimetype is None : mimetype = mimetypes . guess_type ( attachment_filename ) [ 0 ] or DEFAULT_MIMETYPE file_body = current_app . response_class . file_body_class ( file_path ) response = current_app . response_class ( file_body , mimetype = mimetype ) if as_attachment : response . headers . add ( 'Content-Disposition' , 'attachment' , filename = attachment_filename ) if last_modified is not None : response . last_modified = last_modified else : response . last_modified = datetime . fromtimestamp ( file_path . stat ( ) . st_mtime ) response . cache_control . public = True cache_timeout = cache_timeout or current_app . get_send_file_max_age ( file_path ) if cache_timeout is not None : response . cache_control . max_age = cache_timeout response . expires = datetime . utcnow ( ) + timedelta ( seconds = cache_timeout ) if add_etags : response . set_etag ( '{}-{}-{}' . format ( file_path . stat ( ) . st_mtime , file_path . stat ( ) . st_size , adler32 ( bytes ( file_path ) ) , ) , ) if conditional : await response . make_conditional ( request . range ) return response
Return a Reponse to send the filename given .
37,801
def _render_frame ( self ) : frame = self . frame ( ) output = '\r{0}' . format ( frame ) self . clear ( ) try : self . _stream . write ( output ) except UnicodeEncodeError : self . _stream . write ( encode_utf_8_text ( output ) )
Renders the frame on the line after clearing it .
37,802
def get_environment ( ) : try : from IPython import get_ipython except ImportError : return 'terminal' try : shell = get_ipython ( ) . __class__ . __name__ if shell == 'ZMQInteractiveShell' : return 'jupyter' elif shell == 'TerminalInteractiveShell' : return 'ipython' else : return 'terminal' except NameError : return 'terminal'
Get the environment in which halo is running
37,803
def is_text_type ( text ) : if isinstance ( text , six . text_type ) or isinstance ( text , six . string_types ) : return True return False
Check if given parameter is a string or not
37,804
def find_stateless_by_name ( name ) : try : dsa_app = StatelessApp . objects . get ( app_name = name ) return dsa_app . as_dash_app ( ) except : pass dash_app = get_stateless_by_name ( name ) dsa_app = StatelessApp ( app_name = name ) dsa_app . save ( ) return dash_app
Find stateless app given its name
37,805
def as_dash_app ( self ) : dateless_dash_app = getattr ( self , '_stateless_dash_app_instance' , None ) if not dateless_dash_app : dateless_dash_app = get_stateless_by_name ( self . app_name ) setattr ( self , '_stateless_dash_app_instance' , dateless_dash_app ) return dateless_dash_app
Return a DjangoDash instance of the dash application
37,806
def handle_current_state ( self ) : if getattr ( self , '_current_state_hydrated_changed' , False ) and self . save_on_change : new_base_state = json . dumps ( getattr ( self , '_current_state_hydrated' , { } ) ) if new_base_state != self . base_state : self . base_state = new_base_state self . save ( )
Check to see if the current hydrated state and the saved state are different .
37,807
def have_current_state_entry ( self , wid , key ) : 'Return True if there is a cached current state for this app' cscoll = self . current_state ( ) c_state = cscoll . get ( wid , { } ) return key in c_state
Return True if there is a cached current state for this app
37,808
def current_state ( self ) : c_state = getattr ( self , '_current_state_hydrated' , None ) if not c_state : c_state = json . loads ( self . base_state ) setattr ( self , '_current_state_hydrated' , c_state ) setattr ( self , '_current_state_hydrated_changed' , False ) return c_state
Return the current internal state of the model instance .
37,809
def as_dash_instance ( self , cache_id = None ) : 'Return a dash application instance for this model instance' dash_app = self . stateless_app . as_dash_app ( ) base = self . current_state ( ) return dash_app . do_form_dash_instance ( replacements = base , specific_identifier = self . slug , cache_id = cache_id )
Return a dash application instance for this model instance
37,810
def _get_base_state ( self ) : base_app_inst = self . stateless_app . as_dash_app ( ) . as_dash_instance ( ) base_resp = base_app_inst . locate_endpoint_function ( 'dash-layout' ) ( ) base_obj = json . loads ( base_resp . data . decode ( 'utf-8' ) ) obj = { } base_app_inst . walk_tree_and_extract ( base_obj , obj ) return obj
Get the base state of the object as defined by the app . layout code as a python dict
37,811
def populate_values ( self ) : obj = self . _get_base_state ( ) self . base_state = json . dumps ( obj )
Add values from the underlying dash layout configuration
37,812
def locate_item ( ident , stateless = False , cache_id = None ) : if stateless : dash_app = find_stateless_by_name ( ident ) else : dash_app = get_object_or_404 ( DashApp , slug = ident ) app = dash_app . as_dash_instance ( cache_id = cache_id ) return dash_app , app
Locate a dash application given either the slug of an instance or the name for a stateless app
37,813
def send_to_pipe_channel ( channel_name , label , value ) : 'Send message through pipe to client component' async_to_sync ( async_send_to_pipe_channel ) ( channel_name = channel_name , label = label , value = value )
Send message through pipe to client component
37,814
async def async_send_to_pipe_channel ( channel_name , label , value ) : 'Send message asynchronously through pipe to client component' pcn = _form_pipe_channel_name ( channel_name ) channel_layer = get_channel_layer ( ) await channel_layer . group_send ( pcn , { "type" : "pipe.value" , "label" : label , "value" : value } )
Send message asynchronously through pipe to client component
37,815
def pipe_value ( self , message ) : 'Send a new value into the ws pipe' jmsg = json . dumps ( message ) self . send ( jmsg )
Send a new value into the ws pipe
37,816
def update_pipe_channel ( self , uid , channel_name , label ) : pipe_group_name = _form_pipe_channel_name ( channel_name ) if self . channel_layer : current = self . channel_maps . get ( uid , None ) if current != pipe_group_name : if current : async_to_sync ( self . channel_layer . group_discard ) ( current , self . channel_name ) self . channel_maps [ uid ] = pipe_group_name async_to_sync ( self . channel_layer . group_add ) ( pipe_group_name , self . channel_name )
Update this consumer to listen on channel_name for the js widget associated with uid
37,817
def store_initial_arguments ( request , initial_arguments = None ) : 'Store initial arguments, if any, and return a cache identifier' if initial_arguments is None : return None cache_id = "dpd-initial-args-%s" % str ( uuid . uuid4 ( ) ) . replace ( '-' , '' ) if initial_argument_location ( ) : cache . set ( cache_id , initial_arguments , cache_timeout_initial_arguments ( ) ) else : request . session [ cache_id ] = initial_arguments return cache_id
Store initial arguments if any and return a cache identifier
37,818
def get_initial_arguments ( request , cache_id = None ) : 'Extract initial arguments for the dash app' if cache_id is None : return None if initial_argument_location ( ) : return cache . get ( cache_id ) return request . session [ cache_id ]
Extract initial arguments for the dash app
37,819
def dependencies ( request , ident , stateless = False , ** kwargs ) : 'Return the dependencies' _ , app = DashApp . locate_item ( ident , stateless ) with app . app_context ( ) : view_func = app . locate_endpoint_function ( 'dash-dependencies' ) resp = view_func ( ) return HttpResponse ( resp . data , content_type = resp . mimetype )
Return the dependencies
37,820
def layout ( request , ident , stateless = False , cache_id = None , ** kwargs ) : 'Return the layout of the dash application' _ , app = DashApp . locate_item ( ident , stateless ) view_func = app . locate_endpoint_function ( 'dash-layout' ) resp = view_func ( ) initial_arguments = get_initial_arguments ( request , cache_id ) response_data , mimetype = app . augment_initial_layout ( resp , initial_arguments ) return HttpResponse ( response_data , content_type = mimetype )
Return the layout of the dash application
37,821
def update ( request , ident , stateless = False , ** kwargs ) : 'Generate update json response' dash_app , app = DashApp . locate_item ( ident , stateless ) request_body = json . loads ( request . body . decode ( 'utf-8' ) ) if app . use_dash_dispatch ( ) : view_func = app . locate_endpoint_function ( 'dash-update-component' ) import flask with app . test_request_context ( ) : flask . request . _cached_json = ( request_body , flask . request . _cached_json [ True ] ) resp = view_func ( ) else : app_state = request . session . get ( "django_plotly_dash" , dict ( ) ) arg_map = { 'dash_app_id' : ident , 'dash_app' : dash_app , 'user' : request . user , 'session_state' : app_state } resp = app . dispatch_with_args ( request_body , arg_map ) request . session [ 'django_plotly_dash' ] = app_state dash_app . handle_current_state ( ) if str ( resp ) == 'EDGECASEEXIT' : return HttpResponse ( "" ) try : rdata = resp . data rtype = resp . mimetype except : rdata = resp rtype = "application/json" return HttpResponse ( rdata , content_type = rtype )
Generate update json response
37,822
def main_view ( request , ident , stateless = False , cache_id = None , ** kwargs ) : 'Main view for a dash app' _ , app = DashApp . locate_item ( ident , stateless , cache_id = cache_id ) view_func = app . locate_endpoint_function ( ) resp = view_func ( ) return HttpResponse ( resp )
Main view for a dash app
37,823
def app_assets ( request , ** kwargs ) : 'Return a local dash app asset, served up through the Django static framework' get_params = request . GET . urlencode ( ) extra_part = "" if get_params : redone_url = "/static/dash/assets/%s?%s" % ( extra_part , get_params ) else : redone_url = "/static/dash/assets/%s" % extra_part return HttpResponseRedirect ( redirect_to = redone_url )
Return a local dash app asset served up through the Django static framework
37,824
def add_to_session ( request , template_name = "index.html" , ** kwargs ) : 'Add some info to a session in a place that django-plotly-dash can pass to a callback' django_plotly_dash = request . session . get ( "django_plotly_dash" , dict ( ) ) session_add_count = django_plotly_dash . get ( 'add_counter' , 0 ) django_plotly_dash [ 'add_counter' ] = session_add_count + 1 request . session [ 'django_plotly_dash' ] = django_plotly_dash return TemplateResponse ( request , template_name , { } )
Add some info to a session in a place that django - plotly - dash can pass to a callback
37,825
def asset_redirection ( request , path , ident = None , stateless = False , ** kwargs ) : 'Redirect static assets for a component' X , app = DashApp . locate_item ( ident , stateless ) static_path = X . get_asset_static_url ( path ) return redirect ( static_path )
Redirect static assets for a component
37,826
def dash_example_1_view ( request , template_name = "demo_six.html" , ** kwargs ) : 'Example view that inserts content into the dash context passed to the dash application' context = { } dash_context = request . session . get ( "django_plotly_dash" , dict ( ) ) dash_context [ 'django_to_dash_context' ] = "I am Dash receiving context from Django" request . session [ 'django_plotly_dash' ] = dash_context return render ( request , template_name = template_name , context = context )
Example view that inserts content into the dash context passed to the dash application
37,827
def session_state_view ( request , template_name , ** kwargs ) : 'Example view that exhibits the use of sessions to store state' session = request . session demo_count = session . get ( 'django_plotly_dash' , { } ) ind_use = demo_count . get ( 'ind_use' , 0 ) ind_use += 1 demo_count [ 'ind_use' ] = ind_use context = { 'ind_use' : ind_use } session [ 'django_plotly_dash' ] = demo_count return render ( request , template_name = template_name , context = context )
Example view that exhibits the use of sessions to store state
37,828
def adjust_response ( self , response ) : 'Locate placeholder magic strings and replace with content' try : c1 = self . _replace ( response . content , self . header_placeholder , self . embedded_holder . css ) response . content = self . _replace ( c1 , self . footer_placeholder , "\n" . join ( [ self . embedded_holder . config , self . embedded_holder . scripts ] ) ) except AttributeError : pass return response
Locate placeholder magic strings and replace with content
37,829
def callback_c ( * args , ** kwargs ) : 'Update the output following a change of the input selection' session_state = kwargs [ 'session_state' ] calls_so_far = session_state . get ( 'calls_so_far' , 0 ) session_state [ 'calls_so_far' ] = calls_so_far + 1 user_counts = session_state . get ( 'user_counts' , None ) user_name = str ( kwargs [ 'user' ] ) if user_counts is None : user_counts = { user_name : 1 } session_state [ 'user_counts' ] = user_counts else : user_counts [ user_name ] = user_counts . get ( user_name , 0 ) + 1 return "Args are [%s] and kwargs are %s" % ( "," . join ( args ) , str ( kwargs ) )
Update the output following a change of the input selection
37,830
def callback_liveIn_button_press ( red_clicks , blue_clicks , green_clicks , rc_timestamp , bc_timestamp , gc_timestamp , ** kwargs ) : 'Input app button pressed, so do something interesting' if not rc_timestamp : rc_timestamp = 0 if not bc_timestamp : bc_timestamp = 0 if not gc_timestamp : gc_timestamp = 0 if ( rc_timestamp + bc_timestamp + gc_timestamp ) < 1 : change_col = None timestamp = 0 else : if rc_timestamp > bc_timestamp : change_col = "red" timestamp = rc_timestamp else : change_col = "blue" timestamp = bc_timestamp if gc_timestamp > timestamp : timestamp = gc_timestamp change_col = "green" value = { 'red_clicks' : red_clicks , 'blue_clicks' : blue_clicks , 'green_clicks' : green_clicks , 'click_colour' : change_col , 'click_timestamp' : timestamp , 'user' : str ( kwargs . get ( 'user' , 'UNKNOWN' ) ) } send_to_pipe_channel ( channel_name = "live_button_counter" , label = "named_counts" , value = value ) return "Number of local clicks so far is %s red and %s blue; last change is %s at %s" % ( red_clicks , blue_clicks , change_col , datetime . fromtimestamp ( 0.001 * timestamp ) )
Input app button pressed so do something interesting
37,831
def generate_liveOut_layout ( ) : 'Generate the layout per-app, generating each tine a new uuid for the state_uid argument' return html . Div ( [ dpd . Pipe ( id = "named_count_pipe" , value = None , label = "named_counts" , channel_name = "live_button_counter" ) , html . Div ( id = "internal_state" , children = "No state has been computed yet" , style = { 'display' : 'none' } ) , dcc . Graph ( id = "timeseries_plot" ) , dcc . Input ( value = str ( uuid . uuid4 ( ) ) , id = "state_uid" , style = { 'display' : 'none' } , ) ] )
Generate the layout per - app generating each tine a new uuid for the state_uid argument
37,832
def callback_liveOut_pipe_in ( named_count , state_uid , ** kwargs ) : 'Handle something changing the value of the input pipe or the associated state uid' cache_key = _get_cache_key ( state_uid ) state = cache . get ( cache_key ) if not state : state = { } if not named_count : named_count = { } user = named_count . get ( 'user' , None ) click_colour = named_count . get ( 'click_colour' , None ) click_timestamp = named_count . get ( 'click_timestamp' , 0 ) if click_colour : colour_set = state . get ( click_colour , None ) if not colour_set : colour_set = [ ( None , 0 , 100 ) for i in range ( 5 ) ] _ , last_ts , prev = colour_set [ - 1 ] if not click_timestamp or click_timestamp < 1 : click_timestamp = 0 for _ , the_colour_set in state . items ( ) : _ , lts , _ = the_colour_set [ - 1 ] if lts > click_timestamp : click_timestamp = lts click_timestamp = click_timestamp + 1000 if click_timestamp > last_ts : colour_set . append ( ( user , click_timestamp , prev * random . lognormvariate ( 0.0 , 0.1 ) ) , ) colour_set = colour_set [ - 100 : ] state [ click_colour ] = colour_set cache . set ( cache_key , state , 3600 ) return "(%s,%s)" % ( cache_key , click_timestamp )
Handle something changing the value of the input pipe or the associated state uid
37,833
def callback_show_timeseries ( internal_state_string , state_uid , ** kwargs ) : 'Build a timeseries from the internal state' cache_key = _get_cache_key ( state_uid ) state = cache . get ( cache_key ) if not state : state = { } colour_series = { } colors = { 'red' : '#FF0000' , 'blue' : '#0000FF' , 'green' : '#00FF00' , 'yellow' : '#FFFF00' , 'cyan' : '#00FFFF' , 'magenta' : '#FF00FF' , 'black' : '#000000' , } for colour , values in state . items ( ) : timestamps = [ datetime . fromtimestamp ( int ( 0.001 * ts ) ) for _ , ts , _ in values if ts > 0 ] levels = [ level for _ , ts , level in values if ts > 0 ] if colour in colors : colour_series [ colour ] = pd . Series ( levels , index = timestamps ) . groupby ( level = 0 ) . first ( ) df = pd . DataFrame ( colour_series ) . fillna ( method = "ffill" ) . reset_index ( ) [ - 25 : ] traces = [ go . Scatter ( y = df [ colour ] , x = df [ 'index' ] , name = colour , line = dict ( color = colors . get ( colour , '#000000' ) ) , ) for colour in colour_series ] return { 'data' : traces , }
Build a timeseries from the internal state
37,834
def session_demo_danger_callback ( da_children , session_state = None , ** kwargs ) : 'Update output based just on state' if not session_state : return "Session state not yet available" return "Session state contains: " + str ( session_state . get ( 'bootstrap_demo_state' , "NOTHING" ) ) + " and the page render count is " + str ( session_state . get ( "ind_use" , "NOT SET" ) )
Update output based just on state
37,835
def session_demo_alert_callback ( n_clicks , session_state = None , ** kwargs ) : 'Output text based on both app state and session state' if session_state is None : raise NotImplementedError ( "Cannot handle a missing session state" ) csf = session_state . get ( 'bootstrap_demo_state' , None ) if not csf : csf = dict ( clicks = 0 ) session_state [ 'bootstrap_demo_state' ] = csf else : csf [ 'clicks' ] = n_clicks return "Button has been clicked %s times since the page was rendered" % n_clicks
Output text based on both app state and session state
37,836
def add_usable_app ( name , app ) : 'Add app to local registry by name' name = slugify ( name ) global usable_apps usable_apps [ name ] = app return name
Add app to local registry by name
37,837
def get_base_pathname ( self , specific_identifier , cache_id ) : 'Base path name of this instance, taking into account any state or statelessness' if not specific_identifier : app_pathname = "%s:app-%s" % ( app_name , main_view_label ) ndid = self . _uid else : app_pathname = "%s:%s" % ( app_name , main_view_label ) ndid = specific_identifier kwargs = { 'ident' : ndid } if cache_id : kwargs [ 'cache_id' ] = cache_id app_pathname = app_pathname + "--args" full_url = reverse ( app_pathname , kwargs = kwargs ) if full_url [ - 1 ] != '/' : full_url = full_url + '/' return ndid , full_url
Base path name of this instance taking into account any state or statelessness
37,838
def do_form_dash_instance ( self , replacements = None , specific_identifier = None , cache_id = None ) : 'Perform the act of constructing a Dash instance taking into account state' ndid , base_pathname = self . get_base_pathname ( specific_identifier , cache_id ) return self . form_dash_instance ( replacements , ndid , base_pathname )
Perform the act of constructing a Dash instance taking into account state
37,839
def form_dash_instance ( self , replacements = None , ndid = None , base_pathname = None ) : 'Construct a Dash instance taking into account state' if ndid is None : ndid = self . _uid rd = WrappedDash ( base_pathname = base_pathname , expanded_callbacks = self . _expanded_callbacks , replacements = replacements , ndid = ndid , serve_locally = self . _serve_locally ) rd . layout = self . layout rd . config [ 'suppress_callback_exceptions' ] = self . _suppress_callback_exceptions for cb , func in self . _callback_sets : rd . callback ( ** cb ) ( func ) for s in self . css . items : rd . css . append_css ( s ) for s in self . scripts . items : rd . scripts . append_script ( s ) return rd
Construct a Dash instance taking into account state
37,840
def callback ( self , output , inputs = None , state = None , events = None ) : 'Form a callback function by wrapping, in the same way as the underlying Dash application would' callback_set = { 'output' : output , 'inputs' : inputs and inputs or dict ( ) , 'state' : state and state or dict ( ) , 'events' : events and events or dict ( ) } def wrap_func ( func , callback_set = callback_set , callback_sets = self . _callback_sets ) : callback_sets . append ( ( callback_set , func ) ) return func return wrap_func
Form a callback function by wrapping in the same way as the underlying Dash application would
37,841
def expanded_callback ( self , output , inputs = [ ] , state = [ ] , events = [ ] ) : self . _expanded_callbacks = True return self . callback ( output , inputs , state , events )
Form an expanded callback .
37,842
def augment_initial_layout ( self , base_response , initial_arguments = None ) : 'Add application state to initial values' if self . use_dash_layout ( ) and not initial_arguments and False : return base_response . data , base_response . mimetype baseDataInBytes = base_response . data baseData = json . loads ( baseDataInBytes . decode ( 'utf-8' ) ) if initial_arguments : if isinstance ( initial_arguments , str ) : initial_arguments = json . loads ( initial_arguments ) reworked_data = self . walk_tree_and_replace ( baseData , initial_arguments ) response_data = json . dumps ( reworked_data , cls = PlotlyJSONEncoder ) return response_data , base_response . mimetype
Add application state to initial values
37,843
def walk_tree_and_extract ( self , data , target ) : 'Walk tree of properties and extract identifiers and associated values' if isinstance ( data , dict ) : for key in [ 'children' , 'props' , ] : self . walk_tree_and_extract ( data . get ( key , None ) , target ) ident = data . get ( 'id' , None ) if ident is not None : idVals = target . get ( ident , { } ) for key , value in data . items ( ) : if key not in [ 'props' , 'options' , 'children' , 'id' ] : idVals [ key ] = value if idVals : target [ ident ] = idVals if isinstance ( data , list ) : for element in data : self . walk_tree_and_extract ( element , target )
Walk tree of properties and extract identifiers and associated values
37,844
def walk_tree_and_replace ( self , data , overrides ) : if isinstance ( data , dict ) : response = { } replacements = { } thisID = data . get ( 'id' , None ) if thisID is not None : replacements = overrides . get ( thisID , None ) if overrides else None if not replacements : replacements = self . _replacements . get ( thisID , { } ) for k , v in data . items ( ) : r = replacements . get ( k , None ) if r is None : r = self . walk_tree_and_replace ( v , overrides ) response [ k ] = r return response if isinstance ( data , list ) : return [ self . walk_tree_and_replace ( x , overrides ) for x in data ] return data
Walk the tree . Rely on json decoding to insert instances of dict and list ie we use a dna test for anatine rather than our eyes and ears ...
37,845
def locate_endpoint_function ( self , name = None ) : 'Locate endpoint function given name of view' if name is not None : ep = "%s_%s" % ( self . _base_pathname , name ) else : ep = self . _base_pathname return self . _notflask . endpoints [ ep ] [ 'view_func' ]
Locate endpoint function given name of view
37,846
def layout ( self , value ) : 'Overloaded layout function to fix component names as needed' if self . _adjust_id : self . _fix_component_id ( value ) return Dash . layout . fset ( self , value )
Overloaded layout function to fix component names as needed
37,847
def _fix_component_id ( self , component ) : 'Fix name of component ad all of its children' theID = getattr ( component , "id" , None ) if theID is not None : setattr ( component , "id" , self . _fix_id ( theID ) ) try : for c in component . children : self . _fix_component_id ( c ) except : pass
Fix name of component ad all of its children
37,848
def _fix_callback_item ( self , item ) : 'Update component identifier' item . component_id = self . _fix_id ( item . component_id ) return item
Update component identifier
37,849
def callback ( self , output , inputs = [ ] , state = [ ] , events = [ ] ) : 'Invoke callback, adjusting variable names as needed' if isinstance ( output , ( list , tuple ) ) : fixed_outputs = [ self . _fix_callback_item ( x ) for x in output ] 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
37,850
def dispatch ( self ) : 'Perform dispatch, using request embedded within flask global state' 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,851
def dispatch_with_args ( self , body , argMap ) : 'Perform callback dispatching, with enhanced arguments and recording of response' 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 ) 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
37,852
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 .
37,853
def plotly_direct ( context , name = None , slug = None , da = None ) : 'Direct insertion of a Dash app' da , app = _locate_daapp ( name , slug , da ) view_func = app . locate_endpoint_function ( ) 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
37,854
def plotly_app_identifier ( name = None , slug = None , da = None , postfix = None ) : 'Return a slug-friendly identifier' 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
37,855
def plotly_class ( name = None , slug = None , da = None , prefix = None , postfix = None , template_type = None ) : 'Return a string of space-separated class names' 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
37,856
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 ( ':' ) ) if rowdata [ - 1 ] [ 0 ] . isdigit ( ) : points . append ( i ) points . append ( i ) wyckoff = [ ] for i in range ( len ( points ) - 1 ) : symbol = rowdata [ points [ i ] ] [ 1 ] if i + 1 in hP_nums : symbol = symbol . replace ( 'R' , 'H' , 1 ) wyckoff . append ( { 'symbol' : symbol . strip ( ) } ) for i in range ( len ( points ) - 1 ) : count = 0 wyckoff [ i ] [ 'wyckoff' ] = [ ] for j in range ( points [ i ] + 1 , points [ i + 1 ] ) : 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 ] : 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 ] ) 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
37,857
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
37,858
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" 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 .
37,859
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
37,860
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 .
37,861
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 .
37,862
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 .
37,863
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 .
37,864
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 ( ) def generate_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 .
37,865
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 .
37,866
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" ] except KeyError : raise ConfigurationError ( 'Config must define "connections" section' ) try : apps_config = config [ "apps" ] 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 .
37,867
def in_transaction ( connection_name : Optional [ str ] = None ) -> BaseTransactionWrapper : connection = _get_connection ( connection_name ) return connection . _in_transaction ( )
Transaction context manager .
37,868
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 .
37,869
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 .
37,870
def limit ( self , limit : int ) -> "QuerySet" : queryset = self . _clone ( ) queryset . _limit = limit return queryset
Limits QuerySet to given length .
37,871
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 .
37,872
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 .
37,873
def values_list ( self , * fields_ : str , flat : bool = False ) -> "ValuesListQuery" : 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 .
37,874
def values ( self , * args : str , ** kwargs : str ) -> "ValuesQuery" : fields_for_select = { } 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 .
37,875
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 .
37,876
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 .
37,877
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 .
37,878
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 .
37,879
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 .
37,880
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 .
37,881
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 .
37,882
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 .
37,883
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 .
37,884
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,885
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 .
37,886
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 .
37,887
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 .
37,888
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 .
37,889
def reset ( self ) : "Initialises all needed variables to default values" 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 ] ) } ) self . set_identifier ( str ( uuid . uuid4 ( ) ) ) self . prefixes = [ ] self . namespaces = { }
Initialises all needed variables to default values
37,890
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
37,891
def set_title ( self , title ) : self . title = title self . add_metadata ( 'DC' , 'title' , self . title )
Set title . You can set multiple titles .
37,892
def set_cover ( self , file_name , content , create_page = True ) : 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 .
37,893
def add_author ( self , author , file_as = None , role = None , uid = 'creator' ) : "Add author for this document" 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
37,894
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 ( ) : if isinstance ( item , EpubHtml ) : item . id = 'chapter_%d' % self . _id_html self . _id_html += 1 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 .
37,895
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 .
37,896
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 .
37,897
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 .
37,898
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 .
37,899
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 == '-' : 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 .