signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def rsync ( src_dir , dst_dir , mirror , dry_run , print_func , recursed , sync_hidden ) : """Synchronizes 2 directory trees ."""
# This test is a hack to avoid errors when accessing / flash . When the # cache synchronisation issue is solved it should be removed if not isinstance ( src_dir , str ) or not len ( src_dir ) : return sstat = auto ( get_stat , src_dir ) smode = stat_mode ( sstat ) if mode_isfile ( smode ) : print_err ( 'Source ...
def _zoom_rows ( self , zoom ) : """Zooms grid rows"""
self . grid . SetDefaultRowSize ( self . grid . std_row_size * zoom , resizeExistingRows = True ) self . grid . SetRowLabelSize ( self . grid . row_label_size * zoom ) for row , tab in self . code_array . row_heights : if tab == self . grid . current_table and row < self . grid . code_array . shape [ 0 ] : ...
def exists ( self , path , mtime = None ) : """Return ` True ` if file or directory at ` path ` exist , False otherwise . Additional check on modified time when mtime is passed in . Return False if the file ' s modified time is older mtime ."""
self . _connect ( ) if self . sftp : exists = self . _sftp_exists ( path , mtime ) else : exists = self . _ftp_exists ( path , mtime ) self . _close ( ) return exists
def _create_placeholders ( self , n_features ) : """Create the TensorFlow placeholders for the model . : param n _ features : number of features : return : self"""
self . input_data = tf . placeholder ( tf . float32 , [ None , n_features ] , name = 'x-input' ) self . hrand = tf . placeholder ( tf . float32 , [ None , self . num_hidden ] , name = 'hrand' ) self . vrand = tf . placeholder ( tf . float32 , [ None , n_features ] , name = 'vrand' ) # not used in this model , created j...
def find_natural_neighbors ( tri , grid_points ) : r"""Return the natural neighbor triangles for each given grid cell . These are determined by the properties of the given delaunay triangulation . A triangle is a natural neighbor of a grid cell if that triangles circumcenter is within the circumradius of the ...
tree = cKDTree ( grid_points ) in_triangulation = tri . find_simplex ( tree . data ) >= 0 triangle_info = { } members = { key : [ ] for key in range ( len ( tree . data ) ) } for i , simplices in enumerate ( tri . simplices ) : ps = tri . points [ simplices ] cc = circumcenter ( * ps ) r = circumcircle_radi...
def put_item ( self , tablename , item , expected = None , returns = NONE , return_capacity = None , expect_or = False , ** kwargs ) : """Store an item , overwriting existing data This uses the older version of the DynamoDB API . See also : : meth : ` ~ . put _ item2 ` . Parameters tablename : str Name of...
keywords = { } if kwargs : keywords [ 'Expected' ] = encode_query_kwargs ( self . dynamizer , kwargs ) if len ( keywords [ 'Expected' ] ) > 1 : keywords [ 'ConditionalOperator' ] = 'OR' if expect_or else 'AND' elif expected is not None : keywords [ 'Expected' ] = build_expected ( self . dynamizer , ...
def getNodeRefs ( self ) : '''Return a list of ( prop , ( form , valu ) ) refs out for the node .'''
retn = [ ] for name , valu in self . props . items ( ) : pobj = self . form . props . get ( name ) if isinstance ( pobj . type , s_types . Ndef ) : retn . append ( ( name , valu ) ) continue if self . snap . model . forms . get ( pobj . type . name ) is None : continue ndef = ( p...
def TakeIf ( self : dict , f ) : """' self ' : [ 1 , 2 , 3 ] , ' f ' : lambda e : e % 2, ' assert ' : lambda ret : list ( ret ) = = [ 1 , 3]"""
if is_to_destruct ( f ) : f = destruct_func ( f ) return ( e for e in self . items ( ) if f ( e ) )
def strip ( self , inplace = False ) : """Sets all edge lengths to None"""
if not inplace : t = self . copy ( ) else : t = self for e in t . _tree . preorder_edge_iter ( ) : e . length = None t . _dirty = True return t
def pull ( handle , enumerate = False ) : """Pulls next message for handle . Args : handle : A : class : ` . stream . Handle ` or GroupHandle . enumerate ( bool ) : boolean to indicate whether a tuple ` ` ( idx , msg ) ` ` should be returned , not unlike Python ' s enumerate ( ) . Returns : A : class : ...
assert isinstance ( handle , Handle ) , handle return Pull ( handle , enumerate )
def jtype ( c ) : """Return the a string with the data type of a value , for JSON data"""
ct = c [ 'type' ] return ct if ct != 'literal' else '{}, {}' . format ( ct , c . get ( 'xml:lang' ) )
def get_pk_descriptors ( cls ) : """Return tuple of tuples with attribute name and descriptor on the ` cls ` that is defined as the primary keys ."""
pk_fields = { name : descriptor for name , descriptor in vars_class ( cls ) . items ( ) if isinstance ( descriptor , ObjectField ) and is_pk_descriptor ( descriptor ) } alt_pk_fields = defaultdict ( list ) for name , descriptor in vars_class ( cls ) . items ( ) : if isinstance ( descriptor , ObjectField ) : ...
def changed ( self , * fields ) : """Test if one or more fields have changed . A field is considered to have changed if it has been marked as changed , or if any of its parent , or child , fields have been marked as changed ."""
S = super ( Value , self ) . changed for fld in fields or ( None , ) : # no args tests for any change if S ( fld ) : return True return False
def get_non_compulsory_fields ( layer_purpose , layer_subcategory = None ) : """Get non compulsory field based on layer _ purpose and layer _ subcategory . Used for get field in InaSAFE Fields step in wizard . : param layer _ purpose : The layer purpose . : type layer _ purpose : str : param layer _ subcate...
all_fields = get_fields ( layer_purpose , layer_subcategory , replace_null = False ) compulsory_field = get_compulsory_fields ( layer_purpose , layer_subcategory ) if compulsory_field in all_fields : all_fields . remove ( compulsory_field ) return all_fields
def calc_constitutive_matrix ( self ) : """Calculates the laminate constitutive matrix This is the commonly called ` ` ABD ` ` matrix with ` ` shape = ( 6 , 6 ) ` ` when the classical laminated plate theory is used , or the ` ` ABDE ` ` matrix when the first - order shear deformation theory is used , containi...
self . A_general = np . zeros ( [ 5 , 5 ] , dtype = np . float64 ) self . B_general = np . zeros ( [ 5 , 5 ] , dtype = np . float64 ) self . D_general = np . zeros ( [ 5 , 5 ] , dtype = np . float64 ) lam_thick = sum ( [ ply . h for ply in self . plies ] ) self . h = lam_thick h0 = - lam_thick / 2 + self . offset for p...
def detect_mdn ( self ) : """Function checks if the received raw message is an AS2 MDN or not . : raises MDNNotFound : If the received payload is not an MDN then this exception is raised . : return : A two element tuple containing ( message _ id , message _ recipient ) . The message _ id is the original A...
mdn_message = None if self . payload . get_content_type ( ) == 'multipart/report' : mdn_message = self . payload elif self . payload . get_content_type ( ) == 'multipart/signed' : for part in self . payload . walk ( ) : if part . get_content_type ( ) == 'multipart/report' : mdn_message = sel...
def multi_buffering ( layer , radii , callback = None ) : """Buffer a vector layer using many buffers ( for volcanoes or rivers ) . This processing algorithm will keep the original attribute table and will add a new one for the hazard class name according to safe . definitions . fields . hazard _ value _ fiel...
# Layer output output_layer_name = buffer_steps [ 'output_layer_name' ] processing_step = buffer_steps [ 'step_name' ] input_crs = layer . crs ( ) feature_count = layer . featureCount ( ) fields = layer . fields ( ) # Set the new hazard class field . new_field = create_field_from_definition ( hazard_class_field ) field...
def atlas_node_add_callback ( atlas_state , callback_name , callback ) : """Add a callback to the initialized atlas state"""
if callback_name == 'store_zonefile' : atlas_state [ 'zonefile_crawler' ] . set_store_zonefile_callback ( callback ) else : raise ValueError ( "Unrecognized callback {}" . format ( callback_name ) )
def getpLvlPcvd ( self ) : '''Finds the representative agent ' s ( average ) perceived productivity level for each Markov state , as well as the distribution of the representative agent ' s perception of the Markov state . Parameters None Returns pLvlPcvd : np . array Array with average perception of ...
StateCount = self . MrkvArray . shape [ 0 ] t = self . t_cycle [ 0 ] i = self . MrkvNow [ 0 ] dont_mass = self . MrkvPcvd * ( 1. - self . UpdatePrb ) # pmf of non - updaters update_mass = np . zeros ( StateCount ) update_mass [ i ] = self . UpdatePrb # pmf of updaters dont_pLvlPcvd = self . pLvlNow * self . PermGroFac ...
def fetch_access_token ( self ) : """Fetch access token"""
return self . _fetch_access_token ( url = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken' , params = { 'corpid' : self . corp_id , 'corpsecret' : self . secret } )
def make_sngl_ifo ( workflow , sngl_file , bank_file , trigger_id , out_dir , ifo , tags = None , rank = None ) : """Setup a job to create sngl detector sngl ifo html summary snippet ."""
tags = [ ] if tags is None else tags makedir ( out_dir ) name = 'page_snglinfo' files = FileList ( [ ] ) node = PlotExecutable ( workflow . cp , name , ifos = [ ifo ] , out_dir = out_dir , tags = tags ) . create_node ( ) node . add_input_opt ( '--single-trigger-file' , sngl_file ) node . add_input_opt ( '--bank-file' ,...
def options ( self ) : """Engine options discover HTTP entry point"""
# configure engine with an empty dict to ensure default selection / options self . engine . configure ( { } ) conf = self . engine . as_dict ( ) conf [ "returns" ] = [ oname for oname in six . iterkeys ( self . _outputs ) ] # Note : we overide args to only list the ones that are declared in this view conf [ "args" ] = ...
def update_mp_firware_version ( self , timeout = - 1 ) : """Updates the iLO firmware on a physical server to a minimum ILO firmware version required by OneView to manage the server . Args : timeout : Timeout in seconds . Wait for task completion by default . The timeout does not abort the operation in One...
uri = "{}/mpFirmwareVersion" . format ( self . data [ "uri" ] ) return self . _helper . do_put ( uri , None , timeout , None )
def list_affinity_groups ( kwargs = None , conn = None , call = None ) : '''. . versionadded : : 2015.8.0 List input endpoints associated with the deployment CLI Example : . . code - block : : bash salt - cloud - f list _ affinity _ groups my - azure'''
if call != 'function' : raise SaltCloudSystemExit ( 'The list_affinity_groups function must be called with -f or --function.' ) if not conn : conn = get_conn ( ) data = conn . list_affinity_groups ( ) ret = { } for item in data . affinity_groups : ret [ item . name ] = object_to_dict ( item ) return ret
def _compile_list ( self , data , indent_level ) : """Correctly write possibly nested list ."""
if len ( data ) == 0 : return '--' elif not any ( isinstance ( i , ( dict , list ) ) for i in data ) : return ', ' . join ( self . _compile_literal ( value ) for value in data ) else : # ' ere be dragons , # granted there are fewer dragons than the parser , # but dragons nonetheless buffer = '' i = 0 ...
def print_block_bit_list ( block_bit_list , display_block_count = 8 , no_repr = False ) : """> > > bit _ list = ( . . . [ 0,0,1,1,0,0,1,0 ] , # L . . . [ 1,0,0,1,0,0,1,0 ] , # I > > > print _ block _ bit _ list ( bit _ list ) . . . # doctest : + NORMALIZE _ WHITESPACE 2 - 00110010 10010010 0x4c ' L ' 0x...
def print_line ( no , line , line_info ) : print "%4s - %s" % ( no , line ) if no_repr : return line = [ ] for codepoint in line_info : r = repr ( chr ( codepoint ) ) if "\\x" in r : # FIXME txt = "%s" % hex ( codepoint ) else : txt = "%s %s" % ( h...
def Tags ( self ) : """Return all tags found in the value stream . Returns : A ` { tagType : [ ' list ' , ' of ' , ' tags ' ] } ` dictionary ."""
return { IMAGES : self . images . Keys ( ) , AUDIO : self . audios . Keys ( ) , HISTOGRAMS : self . histograms . Keys ( ) , SCALARS : self . scalars . Keys ( ) , COMPRESSED_HISTOGRAMS : self . compressed_histograms . Keys ( ) , TENSORS : self . tensors . Keys ( ) , # Use a heuristic : if the metagraph is available , bu...
def tickUpdate ( self , tick ) : '''consume ticks'''
LOG . debug ( "tickUpdate %s with tick %s, price %s" % ( self . __symbol , tick . time , tick . close ) ) self . __priceZscore ( tick . close ) self . __volumeZscore ( tick . volume ) # get zscore priceZscore = self . __priceZscore . getLastValue ( ) volumeZscore = self . __volumeZscore . getLastValue ( ) # if haven ' ...
def get_entry_url ( entry , blog_page , root_page ) : """Get the entry url given and entry page a blog page instances . It will use an url or another depending if blog _ page is the root page ."""
if root_page == blog_page : return reverse ( 'entry_page_serve' , kwargs = { 'year' : entry . date . strftime ( '%Y' ) , 'month' : entry . date . strftime ( '%m' ) , 'day' : entry . date . strftime ( '%d' ) , 'slug' : entry . slug } ) else : # The method get _ url _ parts provides a tuple with a custom URL routing ...
def normalize_ranking ( ranking_tuples ) : """Normalize rankings by reducing them to the simplest order . E . g . : If the rankings for 2 choices are - 244 and 4, this function will normalize them to 0 and 1, respectively . Parameters : ranking _ tuples should be an iterable of tuples of form ( choice ,...
ranking_tuples = sorted ( ranking_tuples , key = lambda x : x [ 1 ] ) normalized = [ ( ranking_tuples . pop ( 0 ) [ 0 ] , 0 ) ] while ranking_tuples : current = ranking_tuples . pop ( 0 ) normalized . append ( ( current [ 0 ] , normalized [ - 1 ] [ 1 ] if current [ 1 ] == normalized [ - 1 ] [ 1 ] else normalize...
def check_params ( num_rows , num_cols , padding ) : """Validation and typcasting"""
num_rows = check_int ( num_rows , 'num_rows' , min_value = 1 ) num_cols = check_int ( num_cols , 'num_cols' , min_value = 1 ) padding = check_int ( padding , 'padding' , min_value = 0 ) return num_rows , num_cols , padding
def sorted ( self , fsort ) : '''Allows to add one or more sort on specific fields . Each sort can be reversed as well . The sort is defined on a per field level , with special field name for _ score to sort by score .'''
if not self . params : self . params = dict ( ) self . params [ 'sort' ] = fsort return self
def CreateExtensionSetting ( client , feed_items , campaign_feed , feed_item_ids , platform_restrictions = None ) : """Creates the extension setting for a list of Feed Items . Args : client : an AdWordsClient instance . feed _ items : the list of all Feed Items . campaign _ feed : the original Campaign Feed...
campaign_extension_setting_service = client . GetService ( 'CampaignExtensionSettingService' , 'v201809' ) extension_feed_items = [ { CreateSitelinkFeedItem ( feed_items , feed_item_id ) } for feed_item_id in feed_item_ids ] extension_setting = { 'extensions' : extension_feed_items } if platform_restrictions : exte...
def atomic_batch_mutate ( self , mutation_map , consistency_level ) : """Atomically mutate many columns or super columns for many row keys . See also : Mutation . mutation _ map maps key to column family to a list of Mutation objects to take place at that scope . Parameters : - mutation _ map - consistency ...
self . _seqid += 1 d = self . _reqs [ self . _seqid ] = defer . Deferred ( ) self . send_atomic_batch_mutate ( mutation_map , consistency_level ) return d
def _CopyFromDateTimeValues ( self , date_time_values ) : """Copies time elements from date and time values . Args : date _ time _ values ( dict [ str , int ] ) : date and time values , such as year , month , day of month , hours , minutes , seconds , microseconds ."""
year = date_time_values . get ( 'year' , 0 ) month = date_time_values . get ( 'month' , 0 ) day_of_month = date_time_values . get ( 'day_of_month' , 0 ) hours = date_time_values . get ( 'hours' , 0 ) minutes = date_time_values . get ( 'minutes' , 0 ) seconds = date_time_values . get ( 'seconds' , 0 ) self . _normalized...
def ang2pix ( nside , theta , phi , nest = False , lonlat = False ) : """Drop - in replacement for healpy ` ~ healpy . pixelfunc . ang2pix ` ."""
lon , lat = _healpy_to_lonlat ( theta , phi , lonlat = lonlat ) return lonlat_to_healpix ( lon , lat , nside , order = 'nested' if nest else 'ring' )
def _print_base64 ( self , base64_data ) : """Pipe the binary directly to the label printer . Works under Linux without requiring PySerial . This is not typically something you should call directly , unless you have special needs . @ type base64 _ data : L { str } @ param base64 _ data : The base64 encoded ...
label_file = open ( self . device , "w" ) label_file . write ( base64_data ) label_file . close ( )
def _nan_argminmax_object ( func , fill_value , value , axis = None , ** kwargs ) : """In house nanargmin , nanargmax for object arrays . Always return integer type"""
valid_count = count ( value , axis = axis ) value = fillna ( value , fill_value ) data = _dask_or_eager_func ( func ) ( value , axis = axis , ** kwargs ) # TODO This will evaluate dask arrays and might be costly . if ( valid_count == 0 ) . any ( ) : raise ValueError ( 'All-NaN slice encountered' ) return data
def prepare_state_m_for_insert_as ( state_m_to_insert , previous_state_size ) : """Prepares and scales the meta data to fit into actual size of the state ."""
# TODO check how much code is duplicated or could be reused for library fit functionality meta data helper # TODO DO REFACTORING ! ! ! and move maybe the hole method to meta data and rename it if isinstance ( state_m_to_insert , AbstractStateModel ) and not gui_helper_meta_data . model_has_empty_meta ( state_m_to_inser...
def removeClass ( self , className ) : '''removeClass - remove a class name if present . Returns the class name if removed , otherwise None . @ param className < str > - The name of the class to remove @ return < str > - The class name removed if one was removed , otherwise None if # className wasn ' t present'...
className = stripWordsOnly ( className ) if not className : return None if ' ' in className : # Multiple class names passed , do one at a time for oneClassName in className . split ( ' ' ) : self . removeClass ( oneClassName ) return myClassNames = self . _classNames # If not present , this is a no ...
def get_illuminant_xyz ( self , observer = None , illuminant = None ) : """: param str observer : Get the XYZ values for another observer angle . Must be either ' 2 ' or ' 10 ' . : param str illuminant : Get the XYZ values for another illuminant . : returns : the color ' s illuminant ' s XYZ values ."""
try : if observer is None : observer = self . observer illums_observer = color_constants . ILLUMINANTS [ observer ] except KeyError : raise InvalidObserverError ( self ) try : if illuminant is None : illuminant = self . illuminant illum_xyz = illums_observer [ illuminant ] except ( K...
def make_canonical_urlargd ( urlargd , default_urlargd ) : """Build up the query part of an URL from the arguments passed in the ' urlargd ' dictionary . ' default _ urlargd ' is a secondary dictionary which contains tuples of the form ( type , default value ) for the query arguments ( this is the same dictio...
canonical = drop_default_urlargd ( urlargd , default_urlargd ) if canonical : return '?' + urlencode ( canonical , doseq = True ) # FIXME double escaping of ' & ' ? . replace ( ' & ' , ' & amp ; ' ) return ''
def _compile_wildcard ( self , pattern , pathname = False ) : """Compile or format the wildcard inclusion / exclusion pattern ."""
patterns = None flags = self . flags if pathname : flags |= _wcparse . PATHNAME if pattern : patterns = _wcparse . WcSplit ( pattern , flags = flags ) . split ( ) return _wcparse . compile ( patterns , flags ) if patterns else patterns
def draw ( self , filename , color = True ) : '''Render a plot of the graph via pygraphviz . Args : filename ( str ) : Path to save the generated image to . color ( bool ) : If True , will color graph nodes based on their type , otherwise will draw a black - and - white graph .'''
verify_dependencies ( [ 'pgv' ] ) if not hasattr ( self , '_results' ) : raise RuntimeError ( "Graph cannot be drawn before it is executed. " "Try calling run() first." ) g = pgv . AGraph ( directed = True ) g . node_attr [ 'colorscheme' ] = 'set312' for elem in self . _results : if not hasattr ( elem , 'histor...
def _validate_max_staleness ( max_staleness ) : """Validate max _ staleness ."""
if max_staleness == - 1 : return - 1 if not isinstance ( max_staleness , integer_types ) : raise TypeError ( _invalid_max_staleness_msg ( max_staleness ) ) if max_staleness <= 0 : raise ValueError ( _invalid_max_staleness_msg ( max_staleness ) ) return max_staleness
def show_taghistory ( ) : """Show history of all known repo / tags for image"""
if not nav : sys . exit ( 1 ) ecode = 0 try : result = nav . get_taghistory ( ) if result : anchore_utils . print_result ( config , result ) except : anchore_print_err ( "operation failed" ) ecode = 1 contexts [ 'anchore_allimages' ] . clear ( ) sys . exit ( ecode )
def get_code_indices ( s : Union [ str , 'ChainedBase' ] ) -> Dict [ int , str ] : """Retrieve a dict of { index : escape _ code } for a given string . If no escape codes are found , an empty dict is returned ."""
indices = { } i = 0 codes = get_codes ( s ) for code in codes : codeindex = s . index ( code ) realindex = i + codeindex indices [ realindex ] = code codelen = len ( code ) i = realindex + codelen s = s [ codeindex + codelen : ] return indices
def pretty_print ( x , numchars ) : """Given an object ` x ` , call ` str ( x ) ` and format the returned string so that it is numchars long , padding with trailing spaces or truncating with ellipses as necessary"""
s = maybe_truncate ( x , numchars ) return s + ' ' * max ( numchars - len ( s ) , 0 )
def as_scipy_operator ( op ) : """Wrap ` ` op ` ` as a ` ` scipy . sparse . linalg . LinearOperator ` ` . This is intended to be used with the scipy sparse linear solvers . Parameters op : ` Operator ` A linear operator that should be wrapped Returns ` ` scipy . sparse . linalg . LinearOperator ` ` : li...
# Lazy import to improve ` import odl ` time import scipy . sparse if not op . is_linear : raise ValueError ( '`op` needs to be linear' ) dtype = op . domain . dtype if op . range . dtype != dtype : raise ValueError ( 'dtypes of ``op.domain`` and ``op.range`` needs to ' 'match' ) shape = ( native ( op . range ....
def clear ( self ) : """Clear current state ."""
self . exposures = [ ] self . exposure_labels = [ ] self . exposure_combo_boxes = [ ] self . exposure_edit_buttons = [ ] self . mode = CHOOSE_MODE self . layer_purpose = None self . layer_mode = None self . special_case_index = None self . value_maps = { } self . thresholds = { } # Temporary attributes self . threshold...
def couchdb ( user , passwd , ** kwargs ) : """Provides a context manager to create a CouchDB session and provide access to databases , docs etc . : param str user : Username used to connect to CouchDB . : param str passwd : Passcode used to connect to CouchDB . : param str url : URL for CouchDB server . ...
couchdb_session = CouchDB ( user , passwd , ** kwargs ) couchdb_session . connect ( ) yield couchdb_session couchdb_session . disconnect ( )
def count ( self , v ) : """Count occurrences of value v in the entire history . Note that the subclass must implement the _ _ reversed _ _ method , otherwise an exception will be thrown . : param object v : The value to look for : return : The number of occurrences : rtype : int"""
ctr = 0 for item in reversed ( self ) : if item == v : ctr += 1 return ctr
def normalized_table_calc ( classes , table ) : """Return normalized confusion matrix . : param classes : classes list : type classes : list : param table : table : type table : dict : return : normalized table as dict"""
map_dict = { k : 0 for k in classes } new_table = { k : map_dict . copy ( ) for k in classes } for key in classes : div = sum ( table [ key ] . values ( ) ) if div == 0 : div = 1 for item in classes : new_table [ key ] [ item ] = numpy . around ( table [ key ] [ item ] / div , 5 ) return new...
def set_countriesdata ( cls , countries ) : # type : ( str ) - > None """Set up countries data from data in form provided by UNStats and World Bank Args : countries ( str ) : Countries data in HTML format provided by UNStats Returns : None"""
cls . _countriesdata = dict ( ) cls . _countriesdata [ 'countries' ] = dict ( ) cls . _countriesdata [ 'iso2iso3' ] = dict ( ) cls . _countriesdata [ 'm49iso3' ] = dict ( ) cls . _countriesdata [ 'countrynames2iso3' ] = dict ( ) cls . _countriesdata [ 'regioncodes2countries' ] = dict ( ) cls . _countriesdata [ 'regionc...
def insert_chunk ( self , id_ ) : """Insert a new chunk at the end of the IFF file"""
assert_valid_chunk_id ( id_ ) self . __fileobj . seek ( self . __next_offset ) self . __fileobj . write ( pack ( '>4si' , id_ . ljust ( 4 ) . encode ( 'ascii' ) , 0 ) ) self . __fileobj . seek ( self . __next_offset ) chunk = IFFChunk ( self . __fileobj , self [ u'FORM' ] ) self [ u'FORM' ] . _update_size ( self [ u'FO...
def challenge ( self ) : """Override challenge to raise an exception that will trigger regular error handling ."""
response = super ( ConfigBasicAuth , self ) . challenge ( ) raise with_headers ( Unauthorized ( ) , response . headers )
def _do_create ( di ) : """Function that interprets a dictionary and creates objects"""
track = di [ 'track' ] . strip ( ) artists = di [ 'artist' ] if isinstance ( artists , StringType ) : artists = [ artists ] # todo : handle case where different artists have a song with the same title tracks = Track . objects . filter ( title = track , state = 'published' ) if tracks : track = tracks [ 0 ] ...
def high_cli ( repo_name , login , with_blog , as_list , role ) : """Extract mails from stargazers , collaborators and people involved with issues of given repository ."""
passw = getpass . getpass ( ) github = gh_login ( login , passw ) repo = github . repository ( login , repo_name ) role = [ ROLES [ k ] for k in role ] users = fetch_logins ( role , repo ) mails , blogs = contacts ( github , users ) if 'issue' in role : mails |= extract_mail ( repo . issues ( state = 'all' ) ) # Pr...
def apply ( cls , text , mode ) : """Apply mode for text : param text : : param mode : : return :"""
if mode == cls . SCREAMING_SNAKE_CASE : return cls . _screaming_snake_case ( text ) elif mode == cls . snake_case : return cls . _snake_case ( text ) elif mode == cls . lowercase : return cls . _snake_case ( text ) . replace ( '_' , '' ) elif mode == cls . lowerCamelCase : return cls . _camel_case ( tex...
def container_rename_folder ( object_id , input_params = { } , always_retry = False , ** kwargs ) : """Invokes the / container - xxxx / renameFolder API method . For more info , see : https : / / wiki . dnanexus . com / API - Specification - v1.0.0 / Folders - and - Deletion # API - method % 3A - % 2Fclass - xxxx...
return DXHTTPRequest ( '/%s/renameFolder' % object_id , input_params , always_retry = always_retry , ** kwargs )
def start_connect ( self ) : """Start the timeout clock , used during a connect ( ) attempt : raises urllib3 . exceptions . TimeoutStateError : if you attempt to start a timer that has been started already ."""
if self . _start_connect is not None : raise TimeoutStateError ( "Timeout timer has already been started." ) self . _start_connect = current_time ( ) return self . _start_connect
def url_to_text ( self , url ) : '''Download PDF file and transform its document to string . Args : url : PDF url . Returns : string .'''
path , headers = urllib . request . urlretrieve ( url ) return self . path_to_text ( path )
def _read_hdf_columns ( path_or_buf , columns , num_splits , kwargs ) : # pragma : no cover """Use a Ray task to read columns from HDF5 into a Pandas DataFrame . Note : Ray functions are not detected by codecov ( thus pragma : no cover ) Args : path _ or _ buf : The path of the HDF5 file . columns : The lis...
df = pandas . read_hdf ( path_or_buf , columns = columns , ** kwargs ) # Append the length of the index here to build it externally return _split_result_for_readers ( 0 , num_splits , df ) + [ len ( df . index ) ]
def getTCPportConnCount ( self , ipv4 = True , ipv6 = True , resolve_ports = False , ** kwargs ) : """Returns TCP connection counts for each local port . @ param ipv4 : Include IPv4 ports in output if True . @ param ipv6 : Include IPv6 ports in output if True . @ param resolve _ ports : Resolve numeric ports ...
port_dict = { } result = self . getStats ( tcp = True , udp = False , include_listen = False , ipv4 = ipv4 , ipv6 = ipv6 , resolve_ports = resolve_ports , ** kwargs ) stats = result [ 'stats' ] for stat in stats : if stat [ 8 ] == 'ESTABLISHED' : port_dict [ stat [ 5 ] ] = port_dict . get ( 5 , 0 ) + 1 retu...
def check_cursor_location ( self ) : """Check whether the data location of the last known position of the cursor has changed . If so , issue a callback ."""
# Check whether cursor data position has changed relative # to previous value data_x , data_y = self . get_data_xy ( self . last_win_x , self . last_win_y ) if ( data_x != self . last_data_x or data_y != self . last_data_y ) : self . last_data_x , self . last_data_y = data_x , data_y self . logger . debug ( "cu...
def on_message ( self ) : # type : ( ) - > Callable """Decorator . Decorator to handle all messages that have been subscribed and that are not handled via the ` on _ message ` decorator . * * Note : * * Unlike as written in the paho mqtt documentation this callback will not be called if there exists an topi...
def decorator ( handler ) : # type : ( Callable ) - > Callable self . client . on_message = handler return handler return decorator
def rebuild_auth ( self , prepared_request , response ) : """When being redirected we may want to strip authentication from the request to avoid leaking credentials . This method intelligently removes and reapplies authentication where possible to avoid credential loss ."""
headers = prepared_request . headers url = prepared_request . url if 'Authorization' in headers and self . should_strip_auth ( response . request . url , url ) : # If we get redirected to a new host , we should strip out any # authentication headers . del headers [ 'Authorization' ] # . netrc might have more auth f...
def record_date ( self , value ) : """The date on which the corporate action takes effect : param value : : return :"""
if value : self . _record_date = parse ( value ) . date ( ) if isinstance ( value , type_check ) else value
def jira_role ( name , rawtext , text , lineno , inliner , options = None , content = None , oxford_comma = True ) : """Sphinx role for referencing a JIRA ticket . Examples : : : jira : ` DM - 6181 ` - > DM - 6181 : jira : ` DM - 6181 , DM - 6181 ` - > DM - 6180 and DM - 6181 : jira : ` DM - 6181 , DM - 618...
options = options or { } content = content or [ ] config = inliner . document . settings . env . app . config ticket_ids = [ each . strip ( ) for each in utils . unescape ( text ) . split ( ',' ) ] n_tickets = len ( ticket_ids ) if oxford_comma : sep_factory = _oxford_comma_separator else : sep_factory = _comma...
def run_hook ( self , app : FlaskUnchained , bundles : List [ Bundle ] , _config_overrides : Optional [ Dict [ str , Any ] ] = None , ) -> None : """For each bundle in ` ` unchained _ config . BUNDLES ` ` , iterate through that bundle ' s class hierarchy , starting from the base - most bundle . For each bundle ...
self . apply_default_config ( app , bundles and bundles [ - 1 ] or None ) BundleConfig . _set_current_app ( app ) for bundle_ in bundles : for bundle in bundle_ . _iter_class_hierarchy ( ) : app . config . from_mapping ( self . get_bundle_config ( bundle , app . env ) ) if _config_overrides and isinstance (...
def _CaptureException ( f , * args , ** kwargs ) : """Decorator implementation for capturing exceptions ."""
from ambry . dbexceptions import LoggedException b = args [ 0 ] # The ' self ' argument try : return f ( * args , ** kwargs ) except Exception as e : raise try : b . set_error_state ( ) b . commit ( ) except Exception as e2 : b . log ( 'Failed to set bundle error state: {}' . for...
def search_element ( elements_list , target_element ) : """Function to perform binary search on a list to find a target element . Function returns boolean value depending on whether target element exists in the list or not . Example : search _ element ( [ 1 , 2 , 3 , 5 , 8 ] , 6) Output : False search _...
left_index = 0 right_index = len ( elements_list ) - 1 element_found = False while ( left_index <= right_index ) and ( not element_found ) : mid_index = ( left_index + right_index ) // 2 if elements_list [ mid_index ] == target_element : element_found = True elif target_element < elements_list [ mid...
def da_spdhg ( x , f , g , A , tau , sigma_tilde , niter , mu , ** kwargs ) : r"""Computes a saddle point with a PDHG and dual acceleration . It therefore requires the functionals f * _ i to be mu [ i ] strongly convex . Parameters x : primal variable This variable is both input and output of the method . ...
# Callback object callback = kwargs . pop ( 'callback' , None ) if callback is not None and not callable ( callback ) : raise TypeError ( '`callback` {} is not callable' '' . format ( callback ) ) # Probabilities prob = kwargs . pop ( 'prob' , None ) if prob is None : prob = [ 1 / len ( A ) ] * len ( A ) # Sele...
def copy ( src , dst ) : """Copies a source file to a destination file or directory . Equivalent to " shutil . copy " . Source and destination can also be binary opened file - like objects . Args : src ( path - like object or file - like object ) : Source file . dst ( path - like object or file - like obj...
# Handles path - like objects and checks if storage src , src_is_storage = format_and_is_storage ( src ) dst , dst_is_storage = format_and_is_storage ( dst ) # Local files : Redirects to " shutil . copy " if not src_is_storage and not dst_is_storage : return shutil_copy ( src , dst ) with handle_os_exceptions ( ) :...
def get_drive_rotational_speed_rpm ( system_obj ) : """Gets the set of rotational speed rpms of the disks . : param system _ obj : The HPESystem object . : returns the set of rotational speed rpms of the HDD devices ."""
speed = set ( ) smart_resource = _get_attribute_value_of ( system_obj , 'smart_storage' ) if smart_resource is not None : speed . update ( _get_attribute_value_of ( smart_resource , 'drive_rotational_speed_rpm' , default = set ( ) ) ) storage_resource = _get_attribute_value_of ( system_obj , 'storages' ) if storage...
def _imm_trans_delattr ( self , name ) : '''A transient immutable ' s delattr allows the object ' s value - caches to be invalidated ; a var that is deleted returns to its default - value in a transient immutable , otherwise raises an exception .'''
( params , values ) = ( _imm_param_data ( self ) , _imm_value_data ( self ) ) if name in params : dflt = params [ name ] [ 0 ] if dflt is None : raise TypeError ( 'Attempt to reset required parameter \'%s\' of immutable' % name ) setattr ( self , name , dflt [ 0 ] ) elif name in values : dd = ob...
def parse_annotations ( self , annotation_file , genes , db_sel = 'UniProtKB' , select_evidence = None , exclude_evidence = None , exclude_ref = None , strip_species = False , ignore_case = False ) : """Parse a GO annotation file ( in GAF 2.0 format ) . GO annotation files can be downloaded from the ` UniProt -...
assert isinstance ( annotation_file , str ) assert isinstance ( genes , ( list , tuple ) ) if not self . terms : raise ValueError ( 'You need to first parse an OBO file!' ) if select_evidence is None : select_evidence = [ ] if exclude_evidence is None : exclude_evidence = [ ] if exclude_ref is None : ex...
def image_list ( self , name = None ) : '''List server images'''
nt_ks = self . compute_conn ret = { } for image in nt_ks . images . list ( ) : links = { } for link in image . links : links [ link [ 'rel' ] ] = link [ 'href' ] ret [ image . name ] = { 'name' : image . name , 'id' : image . id , 'status' : image . status , 'progress' : image . progress , 'created'...
def handle_profile_delete ( self , sender , instance , ** kwargs ) : """Custom handler for user profile delete"""
try : self . handle_save ( instance . user . __class__ , instance . user ) # we call save just as well except ( get_profile_model ( ) . DoesNotExist ) : pass
def add_server ( self , name , ip , port ) : """Add a new server to the list ."""
new_server = { 'key' : name , # Zeroconf name with both hostname and port 'name' : name . split ( ':' ) [ 0 ] , # Short name 'ip' : ip , # IP address seen by the client 'port' : port , # TCP port 'username' : 'glances' , # Default username 'password' : '' , # Default password 'status' : 'UNKNOWN' , # Server status : ' ...
def extract_domain ( host ) : """Domain name extractor . Turns host names into domain names , ported from pwdhash javascript code"""
host = re . sub ( 'https?://' , '' , host ) host = re . match ( '([^/]+)' , host ) . groups ( ) [ 0 ] domain = '.' . join ( host . split ( '.' ) [ - 2 : ] ) if domain in _domains : domain = '.' . join ( host . split ( '.' ) [ - 3 : ] ) return domain
def ReadHuntFlowsStatesAndTimestamps ( self , hunt_id , cursor = None ) : """Reads hunt flows states and timestamps ."""
query = """ SELECT flow_state, UNIX_TIMESTAMP(timestamp), UNIX_TIMESTAMP(last_update) FROM flows FORCE INDEX(flows_by_hunt) WHERE parent_hunt_id = %s AND parent_flow_id IS NULL """ cursor . execute ( query , [ db_utils . HuntIDToInt ( hunt_id ) ] ) result = [ ] for fs , ct , lup in c...
def set_data ( self , value ) : """Sets a new string as response . The value set must either by a unicode or bytestring . If a unicode string is set it ' s encoded automatically to the charset of the response ( utf - 8 by default ) . . . versionadded : : 0.9"""
# if an unicode string is set , it ' s encoded directly so that we # can set the content length if isinstance ( value , text_type ) : value = value . encode ( self . charset ) else : value = bytes ( value ) self . response = [ value ] if self . automatically_set_content_length : self . headers [ 'Content-Le...
def negative_label_inference ( self , label ) : '''Return a generator of inferred negative label relationships . Construct ad - hoc negative labels between ` ` label . content _ id1 ` ` and the positive connected component of ` ` label . content _ id2 ` ` , and ` ` label . content _ id2 ` ` to the connected c...
assert label . value == CorefValue . Negative yield label cid2_comp = self . connected_component ( label . content_id2 ) for comp_label in cid2_comp : comp_cids = ( comp_label . content_id1 , comp_label . content_id2 ) for comp_cid in comp_cids : if not comp_cid == label . content_id2 : yiel...
def base62_decode ( cls , string ) : """Decode a Base X encoded string into the number . Arguments : - ` string ` : The encoded string - ` alphabet ` : The alphabet to use for encoding Stolen from : http : / / stackoverflow . com / a / 1119769/1144479"""
alphabet = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" base = len ( alphabet ) strlen = len ( string ) num = 0 idx = 0 for char in string : power = ( strlen - ( idx + 1 ) ) try : num += alphabet . index ( char ) * ( base ** power ) except ValueError : raise Base62DecodeE...
def load_env ( ) : """Analyse enviroment variables and update conf accordingly"""
# environment variables take precedence over conf file for key , envvar in [ [ 'cache_dir' , 'INTAKE_CACHE_DIR' ] , [ 'catalog_path' , 'INTAKE_PATH' ] , [ 'persist_path' , 'INTAKE_PERSIST_PATH' ] ] : if envvar in os . environ : conf [ key ] = make_path_posix ( os . environ [ envvar ] ) conf [ 'catalog_path'...
def end_of_day ( self ) -> datetime : """End of day"""
self . value = datetime ( self . value . year , self . value . month , self . value . day , 23 , 59 , 59 ) return self . value
def __do_query_level ( self ) : """Helper to perform the actual query the current dimmer level of the output . For pure on / off loads the result is either 0.0 or 100.0."""
self . _lutron . send ( Lutron . OP_QUERY , Output . _CMD_TYPE , self . _integration_id , Output . _ACTION_ZONE_LEVEL )
def login ( self , url = None , api_key = None , login = None , pwd = None , api_version = None , timeout = None , verify = True , alt_filepath = None , domain = None , ** kwargs ) : """Login to SMC API and retrieve a valid session . Sessions use a pool connection manager to provide dynamic scalability during t...
params = { } if not url or ( not api_key and not ( login and pwd ) ) : try : # First try load from file params = load_from_file ( alt_filepath ) if alt_filepath is not None else load_from_file ( ) logger . debug ( 'Read config data from file: %s' , params ) except ConfigLoadError : # Last ditch ...
def compute_panel ( cls , data , scales , ** params ) : """Calculate the stats of all the groups and return the results in a single dataframe . This is a default function that can be overriden by individual stats Parameters data : dataframe data for the computing scales : types . SimpleNamespace x (...
if not len ( data ) : return type ( data ) ( ) stats = [ ] for _ , old in data . groupby ( 'group' ) : new = cls . compute_group ( old , scales , ** params ) unique = uniquecols ( old ) missing = unique . columns . difference ( new . columns ) u = unique . loc [ [ 0 ] * len ( new ) , missing ] . res...
def cal_p ( self , v , temp ) : """calculate total pressure at given volume and temperature : param v : unit - cell volume in A ^ 3 : param temp : temperature in K : return : pressure in GPa"""
return self . cal_pst ( v ) + self . cal_pth ( v , temp )
def parse_file ( self , filename , encoding = None , debug = False ) : """Parse a file and return the syntax tree ."""
stream = codecs . open ( filename , "r" , encoding ) try : return self . parse_stream ( stream , debug ) finally : stream . close ( )
def read_file ( path ) : """Read a UTF - 8 file from the package . Takes a list of strings to join to make the path"""
file_path = os . path . join ( here , * path ) with open ( file_path , encoding = "utf-8" ) as f : return f . read ( )
def chunk ( self , chunks = None , name_prefix = 'xarray-' , token = None , lock = False ) : """Coerce all arrays in this dataset into dask arrays with the given chunks . Non - dask arrays in this dataset will be converted to dask arrays . Dask arrays will be rechunked to the given chunk sizes . If neither ...
try : from dask . base import tokenize except ImportError : # raise the usual error if dask is entirely missing import dask # noqa raise ImportError ( 'xarray requires dask version 0.9 or newer' ) if isinstance ( chunks , Number ) : chunks = dict . fromkeys ( self . dims , chunks ) if chunks is not ...
def minor_min_width ( G ) : """Computes a lower bound for the treewidth of graph G . Parameters G : NetworkX graph The graph on which to compute a lower bound on the treewidth . Returns lb : int A lower bound on the treewidth . Examples This example computes a lower bound for the treewidth of the : ...
# we need only deal with the adjacency structure of G . We will also # be manipulating it directly so let ' s go ahead and make a new one adj = { v : set ( G [ v ] ) for v in G } lb = 0 # lower bound on treewidth while len ( adj ) > 1 : # get the node with the smallest degree v = min ( adj , key = lambda v : len ( ...
def convert_pad ( node , ** kwargs ) : """Map MXNet ' s pad operator attributes to onnx ' s Pad operator and return the created node ."""
name , input_nodes , attrs = get_inputs ( node , kwargs ) mxnet_pad_width = convert_string_to_list ( attrs . get ( "pad_width" ) ) onnx_pad_width = transform_padding ( mxnet_pad_width ) pad_mode = attrs . get ( "mode" ) if pad_mode == "constant" : pad_value = float ( attrs . get ( "constant_value" ) ) if "constant_...
def _collect_colored_outputs ( unspent_outputs , asset_id , asset_quantity ) : """Returns a list of colored outputs for the specified quantity . : param list [ SpendableOutput ] unspent _ outputs : The list of available outputs . : param bytes asset _ id : The ID of the asset to collect . : param int asset _ ...
total_amount = 0 result = [ ] for output in unspent_outputs : if output . output . asset_id == asset_id : result . append ( output ) total_amount += output . output . asset_quantity if total_amount >= asset_quantity : return result , total_amount raise InsufficientAssetQuantityError
def get_body_size ( params , boundary ) : """Returns the number of bytes that the multipart / form - data encoding of ` ` params ` ` will be ."""
size = sum ( p . get_size ( boundary ) for p in MultipartParam . from_params ( params ) ) return size + len ( boundary ) + 6
def rpc_name ( rpc_id ) : """Map an RPC id to a string name . This function looks the RPC up in a map of all globally declared RPCs , and returns a nice name string . if the RPC is not found in the global name map , returns a generic name string such as ' rpc 0x % 04X ' . Args : rpc _ id ( int ) : The id ...
name = _RPC_NAME_MAP . get ( rpc_id ) if name is None : name = 'RPC 0x%04X' % rpc_id return name
def _legacy_request ( self , * args , ** kwargs ) : """Makes sure token has been set , then calls parent to create a new : class : ` pysnow . LegacyRequest ` object : param args : args to pass along to _ legacy _ request ( ) : param kwargs : kwargs to pass along to _ legacy _ request ( ) : return : - : clas...
if isinstance ( self . token , dict ) : self . session = self . _get_oauth_session ( ) return super ( OAuthClient , self ) . _legacy_request ( * args , ** kwargs ) raise MissingToken ( "You must set_token() before creating a legacy request with OAuthClient" )