signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def whereIsYadis ( resp ) : """Given a HTTPResponse , return the location of the Yadis document . May be the URL just retrieved , another URL , or None , if I can ' t find any . [ non - blocking ] @ returns : str or None"""
# Attempt to find out where to go to discover the document # or if we already have it content_type = resp . headers . get ( 'content-type' ) # According to the spec , the content - type header must be an exact # match , or else we have to look for an indirection . if ( content_type and content_type . split ( ';' , 1 ) ...
def index ( self ) : """Returns the first occurrence of the effect in your pedalboard"""
if self . pedalboard is None : raise IndexError ( 'Effect not contains a pedalboard' ) return self . pedalboard . effects . index ( self )
def execute_scriptfunction ( ) -> None : """Execute a HydPy script function . Function | execute _ scriptfunction | is indirectly applied and explained in the documentation on module | hyd | ."""
try : args_given = [ ] kwargs_given = { } for arg in sys . argv [ 1 : ] : if len ( arg ) < 3 : args_given . append ( arg ) else : try : key , value = parse_argument ( arg ) kwargs_given [ key ] = value except ValueError : ...
def save_split_next ( self ) : """Save out blurbs created from " blurb split " . They don ' t have dates , so we have to get creative ."""
filenames = [ ] # the " date " MUST have a leading zero . # this ensures these files sort after all # newly created blurbs . width = int ( math . ceil ( math . log ( len ( self ) , 10 ) ) ) + 1 i = 1 blurb = Blurbs ( ) while self : metadata , body = self . pop ( ) metadata [ 'date' ] = str ( i ) . rjust ( width...
def dumpBlock ( self , block_name ) : """API the list all information related with the block _ name : param block _ name : Name of block to be dumped ( Required ) : type block _ name : str"""
try : return self . dbsBlock . dumpBlock ( block_name ) except HTTPError as he : raise he except dbsException as de : dbsExceptionHandler ( de . eCode , de . message , self . logger . exception , de . serverError ) except Exception as ex : sError = "DBSReaderModel/dumpBlock. %s\n. Exception trace: \n %s...
def assure_migrations_table_setup ( db ) : """Make sure the migrations table is set up in the database ."""
from mig . models import MigrationData if not MigrationData . __table__ . exists ( db . bind ) : MigrationData . metadata . create_all ( db . bind , tables = [ MigrationData . __table__ ] )
def _add_freeform_sp ( self , origin_x , origin_y ) : """Add a freeform ` p : sp ` element having no drawing elements . * origin _ x * and * origin _ y * are specified in slide coordinates , and represent the location of the local coordinates origin on the slide ."""
spTree = self . _shapes . _spTree return spTree . add_freeform_sp ( origin_x + self . _left , origin_y + self . _top , self . _width , self . _height )
def perform ( self , agent_indices , observ ) : """Compute batch of actions and a summary for a batch of observation . Args : agent _ indices : Tensor containing current batch indices . observ : Tensor of a batch of observations for all agents . Returns : Tuple of action batch tensor and summary tensor ."...
with tf . name_scope ( 'perform/' ) : observ = self . _observ_filter . transform ( observ ) if self . _last_state is None : state = None else : state = tools . nested . map ( lambda x : tf . gather ( x , agent_indices ) , self . _last_state ) with tf . device ( '/gpu:0' if self . _use_gp...
def needs_to_be_resolved ( parent_obj , attr_name ) : """This function determines , if a reference ( CrossReference ) needs to be resolved or not ( while creating the model , while resolving references ) . Args : parent _ obj : the object containing the attribute to be resolved . attr _ name : the attribute...
if hasattr ( get_model ( parent_obj ) , "_tx_reference_resolver" ) : return get_model ( parent_obj ) . _tx_reference_resolver . has_unresolved_crossrefs ( parent_obj , attr_name ) else : return False
def get_data ( context , id , keys ) : """get _ data ( context , id , keys ) Retrieve data field from a remoteci . > > > dcictl remoteci - get - data [ OPTIONS ] : param string id : ID of the remote CI to show [ required ] : param string id : Keys of the data field to retrieve [ optional ]"""
if keys : keys = keys . split ( ',' ) result = remoteci . get_data ( context , id = id , keys = keys ) utils . format_output ( result , context . format , keys )
def remove_menu ( self , menu ) : """Removes a sub - menu from the context menu . : param menu : Sub - menu to remove ."""
self . _menus . remove ( menu ) for action in menu . actions ( ) : self . removeAction ( action )
def unlockFile ( self , fileName , byteOffset , length , dokanFileInfo ) : """Unlock a file . : param fileName : name of file to unlock : type fileName : ctypes . c _ wchar _ p : param byteOffset : location to start unlock : type byteOffset : ctypes . c _ longlong : param length : number of bytes to unloc...
return self . operations ( 'unlockFile' , fileName , byteOffset , length )
def bridge_to_vlan ( br ) : '''Returns the VLAN ID of a bridge . Args : br : A string - bridge name Returns : VLAN ID of the bridge . The VLAN ID is 0 if the bridge is not a fake bridge . If the bridge does not exist , False is returned . CLI Example : . . code - block : : bash salt ' * ' openvswitc...
cmd = 'ovs-vsctl br-to-vlan {0}' . format ( br ) result = __salt__ [ 'cmd.run_all' ] ( cmd ) if result [ 'retcode' ] != 0 : return False return int ( result [ 'stdout' ] )
def seek ( self , offset , whence = os . SEEK_SET ) : """Seek to position in stream , see file . seek"""
pos = None if whence == os . SEEK_SET : pos = self . offset + offset elif whence == os . SEEK_CUR : pos = self . tell ( ) + offset elif whence == os . SEEK_END : pos = self . offset + self . len + offset else : raise ValueError ( "invalid whence {}" . format ( whence ) ) if pos > self . offset + self . ...
def clean ( self ) : '''This code prevents multiple individuals from substituting for the same class and class teacher . It also prevents an individual from substituting for a class in which they are a teacher .'''
super ( SubstituteReportingForm , self ) . clean ( ) occurrences = self . cleaned_data . get ( 'occurrences' , [ ] ) staffMember = self . cleaned_data . get ( 'staffMember' ) replacementFor = self . cleaned_data . get ( 'replacedStaffMember' , [ ] ) event = self . cleaned_data . get ( 'event' ) for occ in occurrences :...
def get_thread ( self , dwThreadId ) : """@ type dwThreadId : int @ param dwThreadId : Global ID of the thread to look for . @ rtype : L { Thread } @ return : Thread object with the given global ID ."""
self . __initialize_snapshot ( ) if dwThreadId not in self . __threadDict : msg = "Unknown thread ID: %d" % dwThreadId raise KeyError ( msg ) return self . __threadDict [ dwThreadId ]
def get_probability_no_exceedance ( self , poes ) : """Compute and return the probability that in the time span for which the rupture is defined , the rupture itself never generates a ground motion value higher than a given level at a given site . Such calculation is performed starting from the conditional pr...
if numpy . isnan ( self . occurrence_rate ) : # nonparametric rupture # Uses the formula # ∑ p ( k | T ) * p ( X < x | rup ) ^ k # where ` p ( k | T ) ` is the probability that the rupture occurs k times # in the time span ` T ` , ` p ( X < x | rup ) ` is the probability that a # rupture occurrence does not cause a gro...
def cpc ( self ) : """: class : ` ~ zhmcclient . Cpc ` : The : term : ` CPC ` to which this storage group is associated . The returned : class : ` ~ zhmcclient . Cpc ` has only a minimal set of properties populated ."""
# We do here some lazy loading . if not self . _cpc : cpc_uri = self . get_property ( 'cpc-uri' ) cpc_mgr = self . manager . console . manager . client . cpcs self . _cpc = cpc_mgr . resource_object ( cpc_uri ) return self . _cpc
def task_add ( self , subsystem , name , pid ) : """Add process ( with pid ) to a cgroup : param subsystem : the cgroup subsystem ( currently support ' memory ' , and ' cpuset ' ) : param name : name of the cgroup : param pid : PID to add"""
args = { 'subsystem' : subsystem , 'name' : name , 'pid' : pid , } self . _task_chk . check ( args ) return self . _client . json ( 'cgroup.task-add' , args )
def getWaveletData ( eda ) : '''This function computes the wavelet coefficients INPUT : data : DataFrame , index is a list of timestamps at 8Hz , columns include EDA , filtered _ eda OUTPUT : wave1Second : DateFrame , index is a list of timestamps at 1Hz , columns include OneSecond _ feature1 , OneSecond _ ...
# Create wavelet dataframes oneSecond = halfSecond = # Compute wavelets cA_n , cD_3 , cD_2 , cD_1 = pywt . wavedec ( eda , 'Haar' , level = 3 ) # 3 = 1Hz , 2 = 2Hz , 1 = 4Hz # Wavelet 1 second window N = int ( len ( eda ) / sampling_rate ) coeff1 = np . max ( abs ( np . reshape ( cD_1 [ 0 : 4 * N ] , ( N , 4 ) ) ) , ax...
def direct_to_template ( request , template , extra_context = None , mimetype = None , ** kwargs ) : """Render a given template with any extra URL parameters in the context as ` ` { { params } } ` ` ."""
if extra_context is None : extra_context = { } dictionary = { 'params' : kwargs } for key , value in extra_context . items ( ) : if callable ( value ) : dictionary [ key ] = value ( ) else : dictionary [ key ] = value t = loader . get_template ( template ) return HttpResponse ( t . render ( ...
def get ( self , * args , ** kw ) : """Load the configuration if necessary and forward the call to the parent ."""
if not self . _loaded : self . load_config ( ) return super ( FedmsgConfig , self ) . get ( * args , ** kw )
def dashrepl ( value ) : """Replace any non - word characters with a dash ."""
patt = re . compile ( r'\W' , re . UNICODE ) return re . sub ( patt , '-' , value )
def stencil ( ** kwargs ) : """Applying genotype calls to multi - way alignment incidence matrix : param alnfile : alignment incidence file ( h5 ) , : param gtypefile : genotype calls by GBRS ( tsv ) , : param grpfile : gene ID to isoform ID mapping info ( tsv ) : return : genotyped version of alignment inc...
alnfile = kwargs . get ( 'alnfile' ) gtypefile = kwargs . get ( 'gtypefile' ) grpfile = kwargs . get ( 'grpfile' ) if grpfile is None : grpfile2chk = os . path . join ( DATA_DIR , 'ref.gene2transcripts.tsv' ) if os . path . exists ( grpfile2chk ) : grpfile = grpfile2chk else : print >> sys ....
def space_set_acl ( args ) : """Assign an ACL role to list of users for a workspace"""
acl_updates = [ { "email" : user , "accessLevel" : args . role } for user in args . users ] r = fapi . update_workspace_acl ( args . project , args . workspace , acl_updates ) fapi . _check_response_code ( r , 200 ) errors = r . json ( ) [ 'usersNotFound' ] if len ( errors ) : eprint ( "Unable to assign role for un...
def _connect_signal ( self , index ) : """Create signals for building indexes ."""
post_save_signal = ElasticSignal ( index , 'build' ) post_save_signal . connect ( post_save , sender = index . object_type ) self . signals . append ( post_save_signal ) post_delete_signal = ElasticSignal ( index , 'remove_object' ) post_delete_signal . connect ( post_delete , sender = index . object_type ) self . sign...
def get_length ( self , n1 , n2 , bond_type = BOND_SINGLE ) : """Return the length of a bond between n1 and n2 of type bond _ type Arguments : | ` ` n1 ` ` - - the atom number of the first atom in the bond | ` ` n2 ` ` - - the atom number of the second atom the bond Optional argument : | ` ` bond _ type `...
dataset = self . lengths . get ( bond_type ) if dataset == None : return None return dataset . get ( frozenset ( [ n1 , n2 ] ) )
def _get_sizes_checksums ( checksums_path ) : """Returns { URL : ( size , checksum ) } s stored within file ."""
checksums = { } for line in _read_file ( checksums_path ) . split ( '\n' ) : if not line : continue # URL might have spaces inside , but size and checksum will not . url , size , checksum = line . rsplit ( ' ' , 2 ) checksums [ url ] = ( int ( size ) , checksum ) return checksums
def take_snapshot ( self , entity_id , lt = None , lte = None ) : """Takes a snapshot of the entity as it existed after the most recent event , optionally less than , or less than or equal to , a particular position ."""
snapshot = None if self . _snapshot_strategy : # Get the latest event ( optionally until a particular position ) . latest_event = self . event_store . get_most_recent_event ( entity_id , lt = lt , lte = lte ) # If there is something to snapshot , then look for a snapshot # taken before or at the entity vers...
def content ( self ) : """Return the entire section content ."""
return _bfd . section_get_content ( self . bfd , self . _ptr , 0 , self . size )
def derivLogCdfNormal ( z ) : """Robust implementations of derivative of the log cdf of a standard normal . @ see [ [ https : / / github . com / mseeger / apbsint / blob / master / src / eptools / potentials / SpecfunServices . h original implementation ] ] in C from Matthias Seeger ."""
if ( abs ( z ) < ERF_CODY_LIMIT1 ) : # Phi ( z ) approx ( 1 + y R _ 3 ( y ^ 2 ) ) / 2 , y = z / sqrt ( 2) return 2.0 * np . exp ( logPdfNormal ( z ) ) / ( 1.0 + ( z / M_SQRT2 ) * _erfRationalHelperR3 ( 0.5 * z * z ) ) elif ( z < 0.0 ) : # Phi ( z ) approx N ( z ) Q ( - z ) / ( - z ) , z < 0 return - z / _erfRat...
def set_geometry ( self , geom ) : """A convenience function to set the geometry variables . Args : geom : A tuple containing ( thet0 , thet , phi0 , phi , alpha , beta ) . See the Scatterer class documentation for a description of these angles ."""
( self . thet0 , self . thet , self . phi0 , self . phi , self . alpha , self . beta ) = geom
def getOrCreateForeignKey ( self , model_class , field_name ) : """Return related random object to set as ForeignKey ."""
# Getting related object type # Eg : < django . db . models . fields . related . ForeignKey : test _ ForeignKey > instance = getattr ( model_class , field_name ) . field # Getting the model name by instance to find / create first id / pk . # Eg : < class ' django . contrib . auth . models . User ' > related_model = ins...
def validator ( node , value ) : '''Colander validator that checks whether a given value is a valid is company number . For our purposes , we expect a firm number that is composed of nine or ten characters like 2028445291. Sometimes a company number is formatted with separation marks like 0.400.378.485. T...
if not re . match ( r'^[0-9]{9,10}$' , value ) : raise colander . Invalid ( node , 'Dit is geen correct ondernemingsnummer.' )
def step ( h , logy = None , axes = None , ** kwargs ) : """Make a matplotlib step plot from a ROOT histogram . Parameters h : Hist A rootpy Hist logy : bool , optional ( default = None ) If True then clip the y range between 1E - 300 and 1E300. If None ( the default ) then automatically determine if th...
if axes is None : axes = plt . gca ( ) if logy is None : logy = axes . get_yscale ( ) == 'log' _set_defaults ( h , kwargs , [ 'common' , 'line' ] ) if kwargs . get ( 'color' ) is None : kwargs [ 'color' ] = h . GetLineColor ( 'mpl' ) y = np . array ( list ( h . y ( ) ) + [ 0. ] ) if logy : np . clip ( y...
def blit_rect ( self , console : tcod . console . Console , x : int , y : int , width : int , height : int , bg_blend : int , ) -> None : """Blit onto a Console without scaling or rotation . Args : console ( Console ) : Blit destination Console . x ( int ) : Console tile X position starting from the left at 0...
lib . TCOD_image_blit_rect ( self . image_c , _console ( console ) , x , y , width , height , bg_blend )
def divs ( x , y ) : """safe division"""
tmp = np . ones ( x . shape ) nonzero_y = y != 0 tmp [ nonzero_y ] = x [ nonzero_y ] / y [ nonzero_y ] return tmp
def addColumn ( self , col , index = None ) : 'Insert column at given index or after all columns .'
if col : if index is None : index = len ( self . columns ) col . sheet = self self . columns . insert ( index , col ) return col
def get_raw ( self ) : """: rtype : bytearray"""
buff = bytearray ( ) buff += self . get_obj ( ) for i in self . list : buff += i . get_raw ( ) return buff
def get ( self , sid ) : """Constructs a ModelBuildContext : param sid : The unique string that identifies the resource : returns : twilio . rest . autopilot . v1 . assistant . model _ build . ModelBuildContext : rtype : twilio . rest . autopilot . v1 . assistant . model _ build . ModelBuildContext"""
return ModelBuildContext ( self . _version , assistant_sid = self . _solution [ 'assistant_sid' ] , sid = sid , )
def _gst_available ( ) : """Determine whether Gstreamer and the Python GObject bindings are installed ."""
try : import gi except ImportError : return False try : gi . require_version ( 'Gst' , '1.0' ) except ( ValueError , AttributeError ) : return False try : from gi . repository import Gst # noqa except ImportError : return False return True
def get_file_from_iso_fp ( self , outfp , ** kwargs ) : # type : ( BinaryIO , Any ) - > None '''A method to fetch a single file from the ISO and write it out to the file object . Parameters : outfp - The file object to write data to . blocksize - The number of bytes in each transfer . iso _ path - The abs...
if not self . _initialized : raise pycdlibexception . PyCdlibInvalidInput ( 'This object is not yet initialized; call either open() or new() to create an ISO' ) blocksize = 8192 joliet_path = None iso_path = None rr_path = None udf_path = None num_paths = 0 for key in kwargs : if key == 'blocksize' : bl...
def clean_data ( freqs , data , chunk , avg_bin ) : """Extract time - varying ( wandering ) lines from strain data . Parameters freqs : list List containing the frequencies of the wandering lines . data : pycbc . types . TimeSeries Strain data to extract the wandering lines from . chunk : float Durati...
if avg_bin >= chunk : raise ValueError ( 'The bin size for averaging the inner product ' 'must be less than the chunk size.' ) if chunk >= data . duration : raise ValueError ( 'The chunk size must be less than the ' 'data duration.' ) steps = numpy . arange ( 0 , int ( data . duration / chunk ) - 0.5 , 0.5 ) se...
def bind ( cls ) : """Bind the buttons to adapter ' s event handler ."""
super ( cls , cls ) . bind ( ) cls . search_btn_el . bind ( "click" , cls . start ) cls . input_el . bind ( "keypress" , func_on_enter ( cls . start ) )
def _update_record ( self , identifier = None , rtype = None , name = None , content = None ) : """Update a record from the hosted zone ."""
return self . _change_record_sets ( 'UPSERT' , rtype , name , content )
def write_segment ( buff , segment , ver , ver_range , eci = False ) : """Writes a segment . : param buff : The byte buffer . : param _ Segment segment : The segment to serialize . : param ver : ` ` None ` ` if a QR Code is written , " M1 " , " M2 " , " M3 " , or " M4 " if a Micro QR Code is written . : p...
mode = segment . mode append_bits = buff . append_bits # Write ECI header if requested if eci and mode == consts . MODE_BYTE and segment . encoding != consts . DEFAULT_BYTE_ENCODING : append_bits ( consts . MODE_ECI , 4 ) append_bits ( get_eci_assignment_number ( segment . encoding ) , 8 ) if ver is None : # QR...
def update_hit_count_ajax ( request , * args , ** kwargs ) : """Deprecated in 1.2 . Use hitcount . views . HitCountJSONView instead ."""
warnings . warn ( "hitcount.views.update_hit_count_ajax is deprecated. " "Use hitcount.views.HitCountJSONView instead." , RemovedInHitCount13Warning ) view = HitCountJSONView . as_view ( ) return view ( request , * args , ** kwargs )
def export_obo ( path_to_file , connection = None ) : """export database to obo file : param path _ to _ file : path to export file : param connection : connection string ( optional ) : return :"""
db = DbManager ( connection ) db . export_obo ( path_to_export_file = path_to_file ) db . session . close ( )
def httpretty_callback ( request , uri , headers ) : """httpretty request handler . converts a call intercepted by httpretty to the stack - in - a - box infrastructure : param request : request object : param uri : the uri of the request : param headers : headers for the response : returns : tuple - ( i...
method = request . method response_headers = CaseInsensitiveDict ( ) response_headers . update ( headers ) request_headers = CaseInsensitiveDict ( ) request_headers . update ( request . headers ) request . headers = request_headers return StackInABox . call_into ( method , request , uri , response_headers )
def is_initialised ( self ) : """Check whether the simulation has been initialised . Args : None Returns : None"""
if not self . lattice : raise AttributeError ( 'Running a simulation needs the lattice to be initialised' ) if not self . atoms : raise AttributeError ( 'Running a simulation needs the atoms to be initialised' ) if not self . number_of_jumps and not self . for_time : raise AttributeError ( 'Running a simula...
async def _throttled_request ( self , request ) : '''Process a single request , respecting the concurrency limit .'''
disconnect = False try : timeout = self . processing_timeout async with timeout_after ( timeout ) : async with self . _incoming_concurrency : if self . is_closing ( ) : return if self . _cost_fraction : await sleep ( self . _cost_fraction * self . ...
def main ( self , * args , ** kwargs ) : """Catch all exceptions ."""
try : result = super ( ) . main ( * args , ** kwargs ) return result except Exception : if HAS_SENTRY : self . _handle_sentry ( ) if not ( sys . stdin . isatty ( ) and sys . stdout . isatty ( ) ) : raise self . _handle_github ( )
def _FillEventSourceHeap ( self , storage_writer , event_source_heap , start_with_first = False ) : """Fills the event source heap with the available written event sources . Args : storage _ writer ( StorageWriter ) : storage writer for a session storage . event _ source _ heap ( _ EventSourceHeap ) : event s...
if self . _processing_profiler : self . _processing_profiler . StartTiming ( 'fill_event_source_heap' ) if self . _processing_profiler : self . _processing_profiler . StartTiming ( 'get_event_source' ) if start_with_first : event_source = storage_writer . GetFirstWrittenEventSource ( ) else : event_sour...
def add_binding ( self , node , value , report_redef = True ) : """Called when a binding is altered . - ` node ` is the statement responsible for the change - ` value ` is the optional new value , a Binding instance , associated with the binding ; if None , the binding is deleted if it exists . - if ` repor...
redefinedWhileUnused = False if not isinstance ( self . scope , ClassScope ) : for scope in self . scope_stack [ : : - 1 ] : existing = scope . get ( value . name ) if ( isinstance ( existing , Importation ) and not existing . used and ( not isinstance ( value , Importation ) or value . fullName == ...
def ones_comp_sum16 ( num1 : int , num2 : int ) -> int : """Calculates the 1 ' s complement sum for 16 - bit numbers . Args : num1 : 16 - bit number . num2 : 16 - bit number . Returns : The calculated result ."""
carry = 1 << 16 result = num1 + num2 return result if result < carry else result + 1 - carry
def get_indicator ( self , resource ) : """Return the modification time and size of a ` Resource ` ."""
path = resource . real_path # on dos , mtime does not change for a folder when files are added if os . name != 'posix' and os . path . isdir ( path ) : return ( os . path . getmtime ( path ) , len ( os . listdir ( path ) ) , os . path . getsize ( path ) ) return ( os . path . getmtime ( path ) , os . path . getsize...
def _generate_squashed_layer_path_id ( self ) : """This function generates the id used to name the directory to store the squashed layer content in the archive . This mimics what Docker does here : https : / / github . com / docker / docker / blob / v1.10.0 - rc1 / image / v1 / imagev1 . go # L42 To make it s...
# Using OrderedDict , because order of JSON elements is important v1_metadata = OrderedDict ( self . old_image_config ) # Update image creation date v1_metadata [ 'created' ] = self . date # Remove unnecessary elements # Do not fail if key is not found for key in 'history' , 'rootfs' , 'container' : v1_metadata . p...
def _process_deprecated ( attrib , deprecated_attrib , kwargs ) : """Processes optional deprecate arguments"""
if deprecated_attrib not in DEPRECATIONS : raise ValueError ( '{0} not included in deprecations list' . format ( deprecated_attrib ) ) if deprecated_attrib in kwargs : warnings . warn ( "'{0}' is DEPRECATED use '{1}' instead" . format ( deprecated_attrib , DEPRECATIONS [ deprecated_attrib ] ) , DeprecationWarni...
def WriteToFD ( self , fd ) : """Write out the updated configuration to the fd ."""
if self . writeback : self . writeback . SaveDataToFD ( self . writeback_data , fd ) else : raise RuntimeError ( "Attempting to write a configuration without a " "writeback location." )
def _html_to_img_tuples ( html : str , format : str = 'jpg' , n_images : int = 10 ) -> list : "Parse the google images html to img tuples containining ` ( fname , url ) `"
bs = BeautifulSoup ( html , 'html.parser' ) img_tags = bs . find_all ( 'div' , { 'class' : 'rg_meta' } ) metadata_dicts = ( json . loads ( e . text ) for e in img_tags ) img_tuples = ( ( _img_fname ( d [ 'ou' ] ) , d [ 'ou' ] ) for d in metadata_dicts if d [ 'ity' ] == format ) return list ( itertools . islice ( img_tu...
def _load_webgl_backend ( ipython ) : """Load the webgl backend for the IPython notebook"""
from . . import app app_instance = app . use_app ( "ipynb_webgl" ) if app_instance . backend_name == "ipynb_webgl" : ipython . write ( "Vispy IPython module has loaded successfully" ) else : # TODO : Improve this error message ipython . write_err ( "Unable to load webgl backend of Vispy" )
def posterior_predictive_to_xarray ( self ) : """Convert posterior _ predictive samples to xarray ."""
data = self . posterior_predictive if not isinstance ( data , dict ) : raise TypeError ( "DictConverter.posterior_predictive is not a dictionary" ) return dict_to_dataset ( data , library = None , coords = self . coords , dims = self . dims )
def public_key_to_address ( public_key : Union [ PublicKey , bytes ] ) -> ChecksumAddress : """Converts a public key to an Ethereum address ."""
if isinstance ( public_key , PublicKey ) : public_key = public_key . format ( compressed = False ) assert isinstance ( public_key , bytes ) return to_checksum_address ( sha3 ( public_key [ 1 : ] ) [ - 20 : ] )
async def parse_get_schema_response ( get_schema_response : str ) -> ( str , str ) : """Parse a GET _ SCHEMA response to get Schema in the format compatible with Anoncreds API : param get _ schema _ response : response of GET _ SCHEMA request . : return : Schema Id and Schema json . id : identifier of schema ...
logger = logging . getLogger ( __name__ ) logger . debug ( "parse_get_schema_response: >>> get_schema_response: %r" , get_schema_response ) if not hasattr ( parse_get_schema_response , "cb" ) : logger . debug ( "parse_get_schema_response: Creating callback" ) parse_get_schema_response . cb = create_cb ( CFUNCTY...
def list_bucket ( self , bucket ) : """Create several files and paginate through them . Production apps should set page _ size to a practical value . Args : bucket : bucket ."""
self . response . write ( 'Listbucket result:\n' ) page_size = 1 stats = gcs . listbucket ( bucket + '/foo' , max_keys = page_size ) while True : count = 0 for stat in stats : count += 1 self . response . write ( repr ( stat ) ) self . response . write ( '\n' ) if count != page_size ...
def _fit_full ( self , pairs , y ) : """Learn full metric using MMC . Parameters X : ( n x d ) data matrix each row corresponds to a single instance constraints : 4 - tuple of arrays ( a , b , c , d ) indices into X , with ( a , b ) specifying similar and ( c , d ) dissimilar pairs"""
num_dim = pairs . shape [ 2 ] error1 = error2 = 1e10 eps = 0.01 # error - bound of iterative projection on C1 and C2 A = self . A_ pos_pairs , neg_pairs = pairs [ y == 1 ] , pairs [ y == - 1 ] # Create weight vector from similar samples pos_diff = pos_pairs [ : , 0 , : ] - pos_pairs [ : , 1 , : ] w = np . einsum ( 'ij,...
def igft ( self , s_hat ) : r"""Compute the inverse graph Fourier transform . The inverse graph Fourier transform of a Fourier domain signal : math : ` \ hat { s } ` is defined as . . math : : s = U \ hat { s } , where : math : ` U ` is the Fourier basis : attr : ` U ` . Parameters s _ hat : array _ lik...
s_hat = self . _check_signal ( s_hat ) return np . tensordot ( self . U , s_hat , ( [ 1 ] , [ 0 ] ) )
def build_specfile_sections ( spec ) : """Builds the sections of a rpm specfile ."""
str = "" mandatory_sections = { 'DESCRIPTION' : '\n%%description\n%s\n\n' , } str = str + SimpleTagCompiler ( mandatory_sections ) . compile ( spec ) optional_sections = { 'DESCRIPTION_' : '%%description -l %s\n%s\n\n' , 'CHANGELOG' : '%%changelog\n%s\n\n' , 'X_RPM_PREINSTALL' : '%%pre\n%s\n\n' , 'X_RPM_POSTINSTALL' : ...
def save_trailer ( self , tocpos ) : """Save the trailer to disk . CArchives can be opened from the end - the trailer points back to the start ."""
totallen = tocpos + self . toclen + self . TRLLEN pyvers = sys . version_info [ 0 ] * 10 + sys . version_info [ 1 ] trl = struct . pack ( self . TRLSTRUCT , self . MAGIC , totallen , tocpos , self . toclen , pyvers ) self . lib . write ( trl )
def undo ( self ) : """Undo the last command by adding its inverse action to the stack . This method automatically takes care of applying the correct inverse action when it is called consecutively ( ie . without a calling ` ` push ` ` in between ) . The ` ` qtesigSavedState ` ` signal is triggered whenever ...
# If it is the first call to this method after a ` ` push ` ` then # reset ` ` qteIndex ` ` to the last element , otherwise just # decrease it . if not self . _wasUndo : self . _qteIndex = len ( self . _qteStack ) else : self . _qteIndex -= 1 # Flag that the last action was an ` undo ` operation . self . _wasUn...
def lengths ( self , sr , polylines , lengthUnit , calculationType ) : """The lengths operation is performed on a geometry service resource . This operation calculates the 2D Euclidean or geodesic lengths of each polyline specified in the input array . Inputs : polylines - array of polylines whose lengths a...
allowedCalcTypes = [ 'planar' , 'geodesic' , 'preserveShape' ] if calculationType not in allowedCalcTypes : raise AttributeError ( "Invalid calculation Type" ) url = self . _url + "/lengths" params = { "f" : "json" , "sr" : sr , "polylines" : self . __geomToStringArray ( geometries = polylines , returnType = "list"...
def parse_exposure ( self , node ) : """Parses < Exposure > @ param node : Node containing the < Exposure > element @ type node : xml . etree . Element @ raise ParseError : Raised when the exposure name is not being defined in the context of a component type ."""
if self . current_component_type == None : self . raise_error ( 'Exposures must be defined in a component type' ) try : name = node . lattrib [ 'name' ] except : self . raise_error ( '<Exposure> must specify a name' ) try : dimension = node . lattrib [ 'dimension' ] except : self . raise_error ( "Ex...
def new ( self , name , summary = None , description = None , protected = None , restricted = None , download_restricted = None , contains_phi = None , tags = None , properties = None , bill_to = None , ** kwargs ) : """: param name : The name of the project : type name : string : param summary : If provided , ...
input_hash = { } input_hash [ "name" ] = name if summary is not None : input_hash [ "summary" ] = summary if description is not None : input_hash [ "description" ] = description if protected is not None : input_hash [ "protected" ] = protected if restricted is not None : input_hash [ "restricted" ] = re...
def get ( self , request ) : """Forwards to CAS login URL or verifies CAS ticket : param request : : return :"""
next_page = request . GET . get ( 'next' ) required = request . GET . get ( 'required' , False ) service_url = get_service_url ( request , next_page ) client = get_cas_client ( service_url = service_url , request = request ) if not next_page and settings . CAS_STORE_NEXT and 'CASNEXT' in request . session : next_pa...
def choose_boundary ( ) : """Generate a multipart boundry . : returns : A boundary string"""
global BOUNDARY_PREFIX if BOUNDARY_PREFIX is None : BOUNDARY_PREFIX = "urlfetch" try : uid = repr ( os . getuid ( ) ) BOUNDARY_PREFIX += "." + uid except AttributeError : pass try : pid = repr ( os . getpid ( ) ) BOUNDARY_PREFIX += "." + pid except AttributeEr...
def get_argument ( # noqa : F811 self , name : str , default : Union [ None , str , _ArgDefaultMarker ] = _ARG_DEFAULT , strip : bool = True , ) -> Optional [ str ] : """Returns the value of the argument with the given name . If default is not provided , the argument is considered to be required , and we raise ...
return self . _get_argument ( name , default , self . request . arguments , strip )
def add_collection ( self , property_name , use_context = True ) : """Add collection property to schema : param property _ name : str , property name : param property _ name : str , property name : return : shiftschema . property . CollectionProperty"""
if self . has_property ( property_name ) : err = 'Property "{}" already exists' raise PropertyExists ( err . format ( property_name ) ) prop = CollectionProperty ( use_context = bool ( use_context ) ) self . collections [ property_name ] = prop return prop
def update_firmware ( self , hardware_id , ipmi = True , raid_controller = True , bios = True , hard_drive = True ) : """Update hardware firmware . This will cause the server to be unavailable for ~ 20 minutes . : param int hardware _ id : The ID of the hardware to have its firmware updated . : param bool i...
return self . hardware . createFirmwareUpdateTransaction ( bool ( ipmi ) , bool ( raid_controller ) , bool ( bios ) , bool ( hard_drive ) , id = hardware_id )
def is_valid ( self , context ) : """Checks through the previous _ actions iterable if required actions have been executed"""
if self . requires : for r in self . requires : if not r in context . executed_actions : raise RequirementMissingError ( "Action '%s' requires '%s'" % ( self . name , r ) ) return True
def create_group ( value ) : """Create the group wrapper node ."""
node = etree . Element ( 'div' , attrib = { 'class' : 'group-by' } ) span = etree . Element ( 'span' , attrib = { 'class' : 'group-label' } ) span . text = value node . append ( span ) return node
def write_bits ( self , stream , raw_bits , padded , left_right , endian ) : """Write the bits . Once the size of the written bits is equal to the number of the reserved bits , flush it to the stream"""
if padded : if left_right : self . _write_bits += raw_bits else : self . _write_bits = raw_bits + self . _write_bits if len ( self . _write_bits ) == self . reserved_bits : bits = self . _endian_transform ( self . _write_bits , endian ) # if it ' s padded , and all of the bit...
def writeCell ( self , row , col , value ) : '''write a cell'''
if self . __sheet is None : self . openSheet ( super ( ExcelWrite , self ) . DEFAULT_SHEET ) self . __sheet . write ( row , col , value )
def patch ( self , ** kw ) : """Update the environment for the duration of a context ."""
old_environ = self . _environ self . _environ = self . _environ . copy ( ) self . _environ . update ( kw ) yield self . _environ = old_environ
def get_joke ( ) : """Return a Ron Swanson quote . Returns None if unable to retrieve a quote ."""
page = requests . get ( "http://ron-swanson-quotes.herokuapp.com/v2/quotes" ) if page . status_code == 200 : jokes = [ ] jokes = json . loads ( page . content . decode ( page . encoding ) ) return '"' + jokes [ 0 ] + '" - Ron Swanson' return None
def key_to_metric ( self , key ) : """Replace all non - letter characters with underscores"""
return '' . join ( l if l in string . letters else '_' for l in key )
def is_eighth_sponsor ( self ) : """Determine whether the given user is associated with an . : class : ` intranet . apps . eighth . models . EighthSponsor ` and , therefore , should view activity sponsoring information ."""
# FIXME : remove recursive dep from . . eighth . models import EighthSponsor return EighthSponsor . objects . filter ( user = self ) . exists ( )
def _build_str_from_time_items ( items ) : """根据解析出的时间字符串关键字计算标准时间表示格式的字符串 : return : 标准时间格式字符串表示形式"""
if not items : return None items = [ int ( item ) for item in items if item ] items = items + [ 0 for _ in xrange ( 6 - len ( items ) ) ] return '%d-%02d-%02d %02d:%02d:%02d' % ( items [ 0 ] , items [ 1 ] , items [ 2 ] , items [ 3 ] , items [ 4 ] , items [ 5 ] )
def nlmsg_for_each_attr ( nlh , hdrlen , rem ) : """Iterate over a stream of attributes in a message . https : / / github . com / thom311 / libnl / blob / libnl3_2_25 / include / netlink / msg . h # L123 Positional arguments : nlh - - Netlink message header ( nlmsghdr class instance ) . hdrlen - - length of...
return nla_for_each_attr ( nlmsg_attrdata ( nlh , hdrlen ) , nlmsg_attrlen ( nlh , hdrlen ) , rem )
def destroy ( self , scriptid , params = None ) : '''/ v1 / startupscript / destroy POST - account Remove a startup script Link : https : / / www . vultr . com / api / # startupscript _ destroy'''
params = update_params ( params , { 'SCRIPTID' : scriptid } ) return self . request ( '/v1/startupscript/destroy' , params , 'POST' )
def is_dicteq ( dict1_ , dict2_ , almosteq_ok = True , verbose_err = True ) : """Checks to see if dicts are the same . Performs recursion . Handles numpy"""
import utool as ut assert len ( dict1_ ) == len ( dict2_ ) , 'dicts are not of same length' try : for ( key1 , val1 ) , ( key2 , val2 ) in zip ( dict1_ . items ( ) , dict2_ . items ( ) ) : assert key1 == key2 , 'key mismatch' assert type ( val1 ) == type ( val2 ) , 'vals are not same type' i...
def p_fromitem_list ( self , t ) : """fromitem _ list : fromitem _ list ' , ' fromitem | fromitem"""
if len ( t ) == 2 : t [ 0 ] = [ t [ 1 ] ] elif len ( t ) == 4 : t [ 0 ] = t [ 1 ] + [ t [ 3 ] ] else : raise NotImplementedError ( 'unk_len' , len ( t ) ) # pragma : no cover
def loadJSON ( self , jdata ) : """Loads the given JSON information for this column . : param jdata : < dict >"""
super ( ReferenceColumn , self ) . loadJSON ( jdata ) # load additional information self . __reference = jdata . get ( 'reference' ) or self . __reference self . __removeAction = jdata . get ( 'removeAction' ) or self . __removeAction
def _mock_request ( self , ** kwargs ) : """A mocked out make _ request call that bypasses all network calls and simply returns any mocked responses defined ."""
model = kwargs . get ( 'model' ) service = model . service_model . endpoint_prefix operation = model . name LOG . debug ( '_make_request: %s.%s' , service , operation ) return self . load_response ( service , operation )
def has_update ( self ) : """Depending on the interval : returns True if its time for an update , returns False if its not yet time for an update"""
_time = time if _time ( ) > self . next_update : self . update_data ( ) self . next_update = _time ( ) + self . interval return True return False
def _compare_expected ( expected , output , sess , onnx , decimal = 5 , onnx_shape = None , ** kwargs ) : """Compares the expected output against the runtime outputs . This is specific to * onnxruntime * due to variable * sess * of type * onnxruntime . InferenceSession * ."""
tested = 0 if isinstance ( expected , list ) : if isinstance ( output , list ) : onnx_shapes = [ _ . shape for _ in sess . get_outputs ( ) ] if 'Out0' in kwargs : expected = expected [ : 1 ] output = output [ : 1 ] del kwargs [ 'Out0' ] if 'Reshape' in kwa...
def absSymPath ( path ) : """like os . path . abspath except it doesn ' t dereference symlinks"""
curr_path = os . getcwd ( ) return os . path . normpath ( os . path . join ( curr_path , path ) )
def delete_user_rating ( self , item_type , item_id ) : """Deletes from the list of rating of the current user , the rating provided for the specified element type . : param item _ type : One of : series , episode , banner . : param item _ id : The TheTVDB Id of the item . : return : a python dictionary with ...
raw_response = requests_util . run_request ( 'delete' , self . API_BASE_URL + '/user/ratings/%s/%d' % ( item_type , item_id ) , headers = self . __get_header_with_auth ( ) ) return self . parse_raw_response ( raw_response )
def stream_events ( signals : Sequence [ Signal ] , filter : Callable [ [ T_Event ] , bool ] = None , * , max_queue_size : int = 0 ) -> AsyncIterator [ T_Event ] : """Return an async generator that yields events from the given signals . Only events that pass the filter callable ( if one has been given ) are retur...
@ async_generator async def streamer ( ) : try : while True : event = await queue . get ( ) if filter is None or filter ( event ) : await yield_ ( event ) finally : cleanup ( ) def cleanup ( ) : nonlocal queue if queue is not None : for sig...
def create_repository_configuration ( repository , no_sync = False ) : """Create a new RepositoryConfiguration . If the provided repository URL is for external repository , it is cloned into internal one . : return BPM Task ID of the new RepositoryConfiguration creation"""
repo = create_repository_configuration_raw ( repository , no_sync ) if repo : return utils . format_json ( repo )
def likelihood ( x , m = None , Cinv = None , sigma = 1 , detC = None ) : """return likelihood of x for the normal density N ( m , sigma * * 2 * Cinv * * - 1)"""
# testing : MC integrate must be one : mean ( p ( x _ i ) ) * volume ( where x _ i are uniformely sampled ) # for i in xrange ( 3 ) : print mean ( [ cma . likelihood ( 20 * r - 10 , dim * [ 0 ] , None , 3 ) for r in rand ( 10000 , dim ) ] ) * 20 * * dim if m is None : dx = x else : dx = x - m # array ( x ) ...