signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def _proc_pax ( self , tarfile ) : """Process an extended or global header as described in POSIX . 1-2008."""
# Read the header information . buf = tarfile . fileobj . read ( self . _block ( self . size ) ) # A pax header stores supplemental information for either # the following file ( extended ) or all following files # ( global ) . if self . type == XGLTYPE : pax_headers = tarfile . pax_headers else : pax_headers = ...
def Read ( self ) : """See base class ."""
raw_in = os . read ( self . dev , self . GetInReportDataLength ( ) ) decoded_in = list ( bytearray ( raw_in ) ) return decoded_in
def _make_rewritten_pyc ( state , fn , pyc , co ) : """Try to dump rewritten code to * pyc * ."""
if sys . platform . startswith ( "win" ) : # Windows grants exclusive access to open files and doesn ' t have atomic # rename , so just write into the final file . _write_pyc ( state , co , fn , pyc ) else : # When not on windows , assume rename is atomic . Dump the code object # into a file specific to this proces...
def make_assess_status_func ( * args , ** kwargs ) : """Creates an assess _ status _ func ( ) suitable for handing to pause _ unit ( ) and resume _ unit ( ) . This uses the _ determine _ os _ workload _ status ( . . . ) function to determine what the workload _ status should be for the unit . If the unit is ...
def _assess_status_func ( ) : state , message = _determine_os_workload_status ( * args , ** kwargs ) status_set ( state , message ) if state not in [ 'maintenance' , 'active' ] : return message return None return _assess_status_func
def clean ( self , string , n_cols = None ) : """Required reading ! http : / / nedbatchelder . com / text / unipain . html Python 2 input string will be a unicode type ( unicode code points ) . Curses will accept unicode if all of the points are in the ascii range . However , if any of the code points are n...
if n_cols is not None and n_cols <= 0 : return '' if isinstance ( string , six . text_type ) : string = unescape ( string ) if self . config [ 'ascii' ] : if isinstance ( string , six . binary_type ) : string = string . decode ( 'utf-8' ) string = string . encode ( 'ascii' , 'replace' ) retu...
def draw ( self ) : """Draws cell background to context"""
self . context . set_source_rgb ( * self . _get_background_color ( ) ) self . context . rectangle ( * self . rect ) self . context . fill ( ) # If show frozen is active , show frozen pattern if self . view_frozen and self . cell_attributes [ self . key ] [ "frozen" ] : self . _draw_frozen_pattern ( )
def _validate_and_parse ( self , batch_object ) : """Performs validation on the batch object to make sure it is in the proper format . Parameters : * batch _ object : The data provided to a POST . The expected format is the following : " username " : " username " , " course _ key " : " course - key " , " ...
if not waffle . waffle ( ) . is_enabled ( waffle . ENABLE_COMPLETION_TRACKING ) : raise ValidationError ( _ ( "BlockCompletion.objects.submit_batch_completion should not be called when the feature is disabled." ) ) for key in self . REQUIRED_KEYS : if key not in batch_object : raise ValidationError ( _ ...
def delete_datastore ( self ) : # type : ( ) - > None """Delete a resource from the HDX datastore Returns : None"""
success , result = self . _read_from_hdx ( 'datastore' , self . data [ 'id' ] , 'resource_id' , self . actions ( ) [ 'datastore_delete' ] , force = True ) if not success : logger . debug ( result )
def gen_rupture_getters ( dstore , slc = slice ( None ) , concurrent_tasks = 1 , hdf5cache = None ) : """: yields : RuptureGetters"""
if dstore . parent : dstore = dstore . parent csm_info = dstore [ 'csm_info' ] trt_by_grp = csm_info . grp_by ( "trt" ) samples = csm_info . get_samples_by_grp ( ) rlzs_by_gsim = csm_info . get_rlzs_by_gsim_grp ( ) rup_array = dstore [ 'ruptures' ] [ slc ] maxweight = numpy . ceil ( len ( rup_array ) / ( concurrent...
def get_prtflds_default ( self ) : """Get default fields ."""
return self . _fldsdefprt [ : - 1 ] + [ "p_{M}" . format ( M = m . fieldname ) for m in self . method_flds ] + [ self . _fldsdefprt [ - 1 ] ]
def ovsdb_server_port ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) ovsdb_server = ET . SubElement ( config , "ovsdb-server" , xmlns = "urn:brocade.com:mgmt:brocade-tunnels" ) name_key = ET . SubElement ( ovsdb_server , "name" ) name_key . text = kwargs . pop ( 'name' ) port = ET . SubElement ( ovsdb_server , "port" ) port . text = kwargs . pop ( 'por...
def mils_fl ( T , P , f , g , c , d , h , M ) : """mils _ fl : facility location formulation for the multi - item lot - sizing problem Requires more variables , but gives a better solution because LB is better than the standard formulation . It can be used as a heuristic method that is sometimes better than r...
Ts = range ( 1 , T + 1 ) model = Model ( "multi-item lotsizing -- facility location formulation" ) y , X = { } , { } for p in P : for t in Ts : y [ t , p ] = model . addVar ( vtype = "B" , name = "y(%s,%s)" % ( t , p ) ) for s in range ( 1 , t + 1 ) : X [ s , t , p ] = model . addVar ( n...
def get_csig ( self ) : """Generate a node ' s content signature , the digested signature of its content . node - the node cache - alternate node to use for the signature cache returns - the content signature"""
try : return self . ninfo . csig except AttributeError : pass contents = self . get_contents ( ) csig = SCons . Util . MD5signature ( contents ) self . get_ninfo ( ) . csig = csig return csig
def qtransform ( self , delta_t = None , delta_f = None , logfsteps = None , frange = None , qrange = ( 4 , 64 ) , mismatch = 0.2 , return_complex = False ) : """Return the interpolated 2d qtransform of this data Parameters delta _ t : { self . delta _ t , float } The time resolution to interpolate to delta...
from pycbc . filter . qtransform import qtiling , qplane from scipy . interpolate import interp2d if frange is None : frange = ( 30 , int ( self . sample_rate / 2 * 8 ) ) q_base = qtiling ( self , qrange , frange , mismatch ) _ , times , freqs , q_plane = qplane ( q_base , self . to_frequencyseries ( ) , return_com...
def is_valid_shape ( value ) : """must be a positive integer or a tuple / list of positive integers"""
if is_int_positive ( value ) : return True , value elif isinstance ( value , tuple ) or isinstance ( value , list ) : for v in value : if not is_int_positive ( v ) : return False , value return True , value else : return False , value
def expand_paths ( paths , marker = '*' ) : """: param paths : A glob path pattern string or pathlib . Path object holding such path , or a list consists of path strings or glob path pattern strings or pathlib . Path object holding such ones , or file objects : param marker : Glob marker character or string...
if is_path ( paths ) and marker in paths : return sglob ( paths ) if is_path_obj ( paths ) and marker in paths . as_posix ( ) : # TBD : Is it better to return [ p : : pathlib . Path ] instead ? return [ normpath ( p ) for p in sglob ( paths . as_posix ( ) ) ] return list ( _expand_paths_itr ( paths , marker = m...
def plot ( self , figsize = None , rotation = 45 ) : """Plot the confusion matrix . Args : figsize : tuple ( x , y ) of ints . Sets the size of the figure rotation : the rotation angle of the labels on the x - axis ."""
fig , ax = plt . subplots ( figsize = figsize ) plt . imshow ( self . _cm , interpolation = 'nearest' , cmap = plt . cm . Blues , aspect = 'auto' ) plt . title ( 'Confusion matrix' ) plt . colorbar ( ) tick_marks = np . arange ( len ( self . _labels ) ) plt . xticks ( tick_marks , self . _labels , rotation = rotation )...
def boolify ( value , nullable = False , return_string = False ) : """Convert a number , string , or sequence type into a pure boolean . Args : value ( number , string , sequence ) : pretty much anything Returns : bool : boolean representation of the given value Examples : > > > [ boolify ( x ) for x in...
# cast number types naturally if isinstance ( value , BOOL_COERCEABLE_TYPES ) : return bool ( value ) # try to coerce string into number val = text_type ( value ) . strip ( ) . lower ( ) . replace ( '.' , '' , 1 ) if val . isnumeric ( ) : return bool ( float ( val ) ) elif val in BOOLISH_TRUE : return True ...
def clear ( self , shape = None ) : """Empties grid and sets shape to shape Clears all attributes , row heights , column withs and frozen states . Empties undo / redo list and caches . Empties globals . Properties shape : 3 - tuple of Integer , defaults to None \t Target shape of grid after clearing all c...
# Without setting this explicitly , the cursor is set too late self . grid . actions . cursor = 0 , 0 , 0 self . grid . current_table = 0 post_command_event ( self . main_window . grid , self . GotoCellMsg , key = ( 0 , 0 , 0 ) ) # Clear cells self . code_array . dict_grid . clear ( ) # Clear attributes del self . code...
def filter_by_analysis_period ( self , analysis_period ) : """Filter the Data Collection based on an analysis period . Args : analysis period : A Ladybug analysis period Return : A new Data Collection with filtered data"""
self . _check_analysis_period ( analysis_period ) analysis_period = self . _get_analysis_period_subset ( analysis_period ) if analysis_period . st_hour == 0 and analysis_period . end_hour == 23 : # We can still return an Hourly Continuous Data Collection t_s = 60 / analysis_period . timestep st_ind = int ( ( an...
def _store_variable ( self , j , key , m , value ) : """Store a copy of the variable in the history"""
if hasattr ( value , 'copy' ) : v = value . copy ( ) else : v = value self . history [ j ] [ key ] [ m ] . append ( v )
def set_size ( self , position , size , padding ) : """Row size setter . The size correspond to the row height , since the row width is constraint to the surface width the associated keyboard belongs . Once size is settled , the size for each child keys is associated . : param position : Position of this ro...
self . height = size self . position = position x = position [ 0 ] for key in self . keys : key . set_size ( size ) key . position = ( x , position [ 1 ] ) x += padding + key . size [ 0 ]
def rtl_assert ( w , exp , block = None ) : """Add hardware assertions to be checked on the RTL design . : param w : should be a WireVector : param Exception exp : Exception to throw when assertion fails : param Block block : block to which the assertion should be added ( default to working block ) : return...
block = working_block ( block ) if not isinstance ( w , WireVector ) : raise PyrtlError ( 'Only WireVectors can be asserted with rtl_assert' ) if len ( w ) != 1 : raise PyrtlError ( 'rtl_assert checks only a WireVector of bitwidth 1' ) if not isinstance ( exp , Exception ) : raise PyrtlError ( 'the second a...
def paragraph ( self , nb_sentences = 3 , variable_nb_sentences = True , ext_word_list = None ) : """: returns : A single paragraph . For example : ' Sapiente sunt omnis . Ut pariatur ad autem ducimus et . Voluptas rem voluptas sint modi dolorem amet . ' Keyword arguments : : param nb _ sentences : around how...
if nb_sentences <= 0 : return '' if variable_nb_sentences : nb_sentences = self . randomize_nb_elements ( nb_sentences , min = 1 ) para = self . word_connector . join ( self . sentences ( nb_sentences , ext_word_list = ext_word_list , ) ) return para
def widget_from_abbrev ( cls , abbrev , default = empty ) : """Build a ValueWidget instance given an abbreviation or Widget ."""
if isinstance ( abbrev , ValueWidget ) or isinstance ( abbrev , fixed ) : return abbrev if isinstance ( abbrev , tuple ) : widget = cls . widget_from_tuple ( abbrev ) if default is not empty : try : widget . value = default except Exception : # ignore failure to set default ...
def main ( input_bed , output_file , output_features = False , genome = None , only_canonical = False , short = False , extended = False , high_confidence = False , ambiguities_method = False , coding_only = False , collapse_exons = False , work_dir = False , is_debug = False ) : """Annotating BED file based on ref...
logger . init ( is_debug_ = is_debug ) if not genome : raise click . BadParameter ( 'Error: please, specify genome build name with -g (e.g. `-g hg19`)' , param = 'genome' ) if short : if extended : raise click . BadParameter ( '--short and --extended can\'t be set both' , param = 'extended' ) if out...
def is_valid_mimetype ( response ) : """Return ` ` True ` ` if the mimetype is not blacklisted . : rtype : bool"""
blacklist = [ 'image/' , ] mimetype = response . get ( 'mimeType' ) if not mimetype : return True for bw in blacklist : if bw in mimetype : return False return True
def distance_between ( self , place_1 , place_2 , unit = 'km' ) : """Return the great - circle distance between * place _ 1 * and * place _ 2 * , in the * unit * specified . The default unit is ` ` ' km ' ` ` , but ` ` ' m ' ` ` , ` ` ' mi ' ` ` , and ` ` ' ft ' ` ` can also be specified ."""
pickled_place_1 = self . _pickle ( place_1 ) pickled_place_2 = self . _pickle ( place_2 ) try : return self . redis . geodist ( self . key , pickled_place_1 , pickled_place_2 , unit = unit ) except TypeError : return None
def lsmod ( ) : '''Return a dict containing information about currently loaded modules CLI Example : . . code - block : : bash salt ' * ' kmod . lsmod'''
ret = [ ] for line in __salt__ [ 'cmd.run' ] ( 'kldstat' ) . splitlines ( ) : comps = line . split ( ) if not len ( comps ) > 2 : continue if comps [ 0 ] == 'Id' : continue if comps [ 4 ] == 'kernel' : continue ret . append ( { 'module' : comps [ 4 ] [ : - 3 ] , 'size' : comp...
def auth ( name , nodes , pcsuser = 'hacluster' , pcspasswd = 'hacluster' , extra_args = None ) : '''Ensure all nodes are authorized to the cluster name Irrelevant , not used ( recommended : pcs _ auth _ _ auth ) nodes a list of nodes which should be authorized to the cluster pcsuser user for communicat...
ret = { 'name' : name , 'result' : True , 'comment' : '' , 'changes' : { } } auth_required = False authorized = __salt__ [ 'pcs.is_auth' ] ( nodes = nodes ) log . trace ( 'Output of pcs.is_auth: %s' , authorized ) authorized_dict = { } for line in authorized [ 'stdout' ] . splitlines ( ) : node = line . split ( ':'...
def find ( self , keys , _index = 0 ) : """: param keys : key path . ` ` ' a . b ' ` ` is equivalent to ` ` [ ' a ' , ' b ' ] ` ` : type keys : : class : ` str ` or : class : ` list ` Find a nested : class : ` Component ` by a " ` . ` " separated list of names . for example : : > > > motor . find ( ' bearin...
if isinstance ( keys , six . string_types ) : keys = re . split ( r'[\.-]+' , keys ) if _index >= len ( keys ) : return self key = keys [ _index ] if key in self . components : component = self . components [ key ] if isinstance ( component , Assembly ) : return component . find ( keys , _index ...
def bezier_curve_approx_len ( P = [ ( 0.0 , 0.0 ) ] ) : '''Return approximate length of a bezier curve defined by control points P . Segment curve into N lines where N is the order of the curve , and accumulate the length of the segments .'''
assert isinstance ( P , list ) assert len ( P ) > 0 for p in P : assert isinstance ( p , tuple ) for i in p : assert len ( p ) > 1 assert isinstance ( i , float ) n_seg = len ( P ) - 1 pts = pts_on_bezier_curve ( P , n_seg ) return sum ( [ distance_between_pts ( pts [ i ] , pts [ i + 1 ] ) for i...
def combine ( self , blocks , copy = True ) : """return a new manager with the blocks"""
if len ( blocks ) == 0 : return self . make_empty ( ) # FIXME : optimization potential indexer = np . sort ( np . concatenate ( [ b . mgr_locs . as_array for b in blocks ] ) ) inv_indexer = lib . get_reverse_indexer ( indexer , self . shape [ 0 ] ) new_blocks = [ ] for b in blocks : b = b . copy ( deep = copy )...
def _ensure_sequence ( self , mutable = False ) : """This method can be called by methods that need a sequence . If ` mutable ` is true , it will also ensure that the response sequence is a standard Python list . . . versionadded : : 0.6"""
if self . is_sequence : # if we need a mutable object , we ensure it ' s a list . if mutable and not isinstance ( self . response , list ) : self . response = list ( self . response ) return if self . direct_passthrough : raise RuntimeError ( 'Attempted implicit sequence conversion ' 'but the respon...
def _write ( self ) : """Writes data from backup _ dict property in serialized and compressed form to backup file pointed in json _ file property ."""
self . json_file . seek ( 0 ) self . json_file . truncate ( ) dump = json . dumps ( self . backup_dict ) dump_c = zlib . compress ( dump . encode ( 'utf-8' ) ) self . json_file . write ( dump_c )
def get_all ( cls , parent = None , ** params ) : if parent is not None : route = copy ( parent . route ) else : route = { } if cls . ID_NAME is not None : # Empty string triggers " get all resources " route [ cls . ID_NAME ] = "" base_obj = cls ( key = parent . key , route = rou...
start = datetime . now ( ) r = requests . get ( base_obj . _url ( ) , auth = ( base_obj . key , "" ) , params = params ) cls . _delay_for_ratelimits ( start ) if r . status_code not in cls . TRUTHY_CODES : return base_obj . _handle_request_exception ( r ) response = r . json ( ) objects_data = response . get ( base...
def flush_profile_data ( self ) : """Push the logged profiling data to the global control store ."""
with self . lock : events = self . events self . events = [ ] if self . worker . mode == ray . WORKER_MODE : component_type = "worker" else : component_type = "driver" self . worker . raylet_client . push_profile_events ( component_type , ray . UniqueID ( self . worker . worker_id ) , self . worker . no...
def ListClientsForKeywords ( self , keywords , start_time = None , cursor = None ) : """Lists the clients associated with keywords ."""
keywords = set ( keywords ) hash_to_kw = { mysql_utils . Hash ( kw ) : kw for kw in keywords } result = { kw : [ ] for kw in keywords } query = """ SELECT keyword_hash, client_id FROM client_keywords FORCE INDEX (client_index_by_keyword_hash) WHERE keyword_hash IN ({}) """ . format ( ", " . ...
def adapter_add_nio_binding ( self , adapter_number , nio ) : """Adds an adapter NIO binding . : param adapter _ number : adapter number : param nio : NIO instance to add to the slot / port"""
try : adapter = self . _ethernet_adapters [ adapter_number ] except IndexError : raise VMwareError ( "Adapter {adapter_number} doesn't exist on VMware VM '{name}'" . format ( name = self . name , adapter_number = adapter_number ) ) self . _read_vmx_file ( ) # check if trying to connect to a nat , bridged or hos...
def fill_traversals ( traversals , edges , edges_hash = None ) : """Convert a traversal of a list of edges into a sequence of traversals where every pair of consecutive node indexes is an edge in a passed edge list Parameters traversals : sequence of ( m , ) int Node indexes of traversals of a graph edg...
# make sure edges are correct type edges = np . asanyarray ( edges , dtype = np . int64 ) # make sure edges are sorted edges . sort ( axis = 1 ) # if there are no traversals just return edges if len ( traversals ) == 0 : return edges . copy ( ) # hash edges for contains checks if edges_hash is None : edges_hash...
def decompose_dateint ( dateint ) : """Decomposes the given dateint into its year , month and day components . Arguments dateint : int An integer object decipting a specific calendaric day ; e . g . 20161225. Returns year : int The year component of the given dateint . month : int The month componen...
year = int ( dateint / 10000 ) leftover = dateint - year * 10000 month = int ( leftover / 100 ) day = leftover - month * 100 return year , month , day
def getConfig ( self ) : """Return the configuration of the city . : return : configuration of the city . : rtype : dict ."""
config = { } config [ "name" ] = self . city config [ "intervals" ] = self . __intervals config [ "last_date" ] = self . __lastDay config [ "excludedUsers" ] = [ ] config [ "excludedLocations" ] = [ ] for e in self . __excludedUsers : config [ "excludedUsers" ] . append ( e ) for e in self . __excludedLocations : ...
def check_user_password ( self , user , password = None , form = None ) : """Checks if the password matches the one of the user . If no password is provided , the current form will be used"""
pwcol = self . options [ 'password_column' ] if password is None : if not form and "form" in current_context . data and request . method == "POST" : form = current_context . data . form if form : password = form [ pwcol ] . data else : raise OptionMissingError ( "Missing 'password' o...
def SplitBuffer ( buff , index = 0 , length = None ) : """Parses the buffer as a prototypes . Args : buff : The buffer to parse . index : The position to start parsing . length : Optional length to parse until . Yields : Splits the buffer into tuples of strings : ( encoded _ tag , encoded _ length , w...
buffer_len = length or len ( buff ) while index < buffer_len : # data _ index is the index where the data begins ( i . e . after the tag ) . encoded_tag , data_index = ReadTag ( buff , index ) tag_type = ORD_MAP [ encoded_tag [ 0 ] ] & TAG_TYPE_MASK if tag_type == WIRETYPE_VARINT : # new _ index is the inde...
def map_df ( self , df ) : """Map values from a dataframe . Returns dataframe"""
if ( len ( df ) == 0 ) or ( len ( self ) == 0 ) : return df # Each scale maps the columns it understands for sc in self : df = sc . map_df ( df ) return df
def parse ( filename ) : """parses a . ase file and returns a list of colors and color groups ` swatch . parse ` reads in an ase file and converts it to a list of colors and palettes . colors are simple dicts of the form ` ` ` json ' name ' : u ' color name ' , ' type ' : u ' Process ' , ' data ' : { ...
with open ( filename , "rb" ) as data : header , v_major , v_minor , chunk_count = struct . unpack ( "!4sHHI" , data . read ( 12 ) ) assert header == b"ASEF" assert ( v_major , v_minor ) == ( 1 , 0 ) return [ c for c in parser . parse_chunk ( data ) ]
def combine_express_output ( fnL , column = 'eff_counts' , names = None , tg = None , define_sample_name = None , debug = False ) : """Combine eXpress output files Parameters : fnL : list of strs of filenames List of paths to results . xprs files . column : string Column name of eXpress output to combine ...
if names is not None : assert len ( names ) == len ( fnL ) if define_sample_name is None : define_sample_name = lambda x : x transcriptL = [ ] for i , fn in enumerate ( fnL ) : if names is not None : bn = names [ i ] else : bn = define_sample_name ( fn ) tDF = pd . read_table ( fn , ...
def set_datastore_policy ( self , func ) : """Set the context datastore policy function . Args : func : A function that accepts a Key instance as argument and returns a bool indicating if it should use the datastore . May be None ."""
if func is None : func = self . default_datastore_policy elif isinstance ( func , bool ) : func = lambda unused_key , flag = func : flag self . _datastore_policy = func
def disconnect ( self , cback ) : "See signal"
return self . signal . disconnect ( cback , subscribers = self . subscribers , instance = self . instance )
def Ry_matrix ( theta ) : """Rotation matrix around the Y axis"""
return np . array ( [ [ np . cos ( theta ) , 0 , np . sin ( theta ) ] , [ 0 , 1 , 0 ] , [ - np . sin ( theta ) , 0 , np . cos ( theta ) ] ] )
def plot_welch_peaks ( f , S , peak_loc = None , title = '' ) : '''Plot welch PSD with peaks as scatter points Args f : ndarray Array of frequencies produced with PSD S : ndarray Array of powers produced with PSD peak _ loc : ndarray Indices of peak locations in signal title : str Main title for p...
plt . plot ( f , S , linewidth = _linewidth ) plt . title ( title ) plt . xlabel ( 'Fequency (Hz)' ) plt . ylabel ( '"Power" (g**2 Hz**−1)' ) if peak_loc is not None : plt . scatter ( f [ peak_loc ] , S [ peak_loc ] , label = 'peaks' ) plt . legend ( loc = 'upper right' ) plt . show ( ) return None
def save_dictionary ( data , filename ) : """Save dictionary in a single file . spydata file"""
filename = osp . abspath ( filename ) old_cwd = getcwd ( ) os . chdir ( osp . dirname ( filename ) ) error_message = None skipped_keys = [ ] data_copy = { } try : # Copy dictionary before modifying it to fix # 6689 for obj_name , obj_value in data . items ( ) : # Skip modules , since they can ' t be pickled , users...
def returnToMatches ( allowed_return_to_urls , return_to ) : """Is the return _ to URL under one of the supplied allowed return _ to URLs ? @ since : 2.1.0"""
for allowed_return_to in allowed_return_to_urls : # A return _ to pattern works the same as a realm , except that # it ' s not allowed to use a wildcard . We ' ll model this by # parsing it as a realm , and not trying to match it if it has # a wildcard . return_realm = TrustRoot . parse ( allowed_return_to ) if...
def spawn ( self , options , port , background = False , prefix = "" ) : "Spawn a daemon instance ."
self . spawncmd = None # Look for gpsd in GPSD _ HOME env variable if os . environ . get ( 'GPSD_HOME' ) : for path in os . environ [ 'GPSD_HOME' ] . split ( ':' ) : _spawncmd = "%s/gpsd" % path if os . path . isfile ( _spawncmd ) and os . access ( _spawncmd , os . X_OK ) : self . spawnc...
def group_add_user_action ( model , request ) : """Add user to group ."""
user_id = request . params . get ( 'id' ) if not user_id : user_ids = request . params . getall ( 'id[]' ) else : user_ids = [ user_id ] try : group = model . model validate_add_users_to_groups ( model , user_ids , [ group . id ] ) for user_id in user_ids : group . add ( user_id ) group ...
def BGPNeighborPrefixExceeded_neighborPrefixLimit ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) BGPNeighborPrefixExceeded = ET . SubElement ( config , "BGPNeighborPrefixExceeded" , xmlns = "http://brocade.com/ns/brocade-notification-stream" ) neighborPrefixLimit = ET . SubElement ( BGPNeighborPrefixExceeded , "neighborPrefixLimit" ) neighborPrefixLimit . text = kwargs . pop ( 'n...
def setColorSet ( self , colorSet ) : """Sets the colors for this console to the inputed collection . : param colors | < XLoggerColorSet >"""
self . _colorSet = colorSet # update the palette information palette = self . palette ( ) palette . setColor ( palette . Text , colorSet . color ( 'Standard' ) ) palette . setColor ( palette . Base , colorSet . color ( 'Background' ) ) self . setPalette ( palette )
def json_2_routing_area ( json_obj ) : """transform JSON obj coming from Ariane to ariane _ clip3 object : param json _ obj : the JSON obj coming from Ariane : return : ariane _ clip3 RoutingArea object"""
LOGGER . debug ( "RoutingArea.json_2_routing_area" ) return RoutingArea ( raid = json_obj [ 'routingAreaID' ] , name = json_obj [ 'routingAreaName' ] , description = json_obj [ 'routingAreaDescription' ] , ra_type = json_obj [ 'routingAreaType' ] , multicast = json_obj [ 'routingAreaMulticast' ] , routing_area_loc_ids ...
def _insert_part_map ( self , part_map , index = - 1 ) : """add a part map to self . _ my _ map [ ' assessmentParts ' ]"""
if index == - 1 : self . _my_map [ 'assessmentParts' ] . append ( part_map ) else : self . _my_map [ 'assessmentParts' ] . insert ( index , part_map )
def set_meta ( self , meta , name = None , index = None ) : """Add metadata columns as pd . Series , list or value ( int / float / str ) Parameters meta : pd . Series , list , int , float or str column to be added to metadata ( by ` [ ' model ' , ' scenario ' ] ` index if possible ) name : str , optional ...
# check that name is valid and doesn ' t conflict with data columns if ( name or ( hasattr ( meta , 'name' ) and meta . name ) ) in [ None , False ] : raise ValueError ( 'Must pass a name or use a named pd.Series' ) name = name or meta . name if name in self . data . columns : raise ValueError ( '`{}` already e...
def translate_state ( self , s ) : """Translate the given state string"""
if not isinstance ( s , basestring ) : return s s = s . capitalize ( ) . replace ( "_" , " " ) return t ( _ ( s ) )
def autoconfig_url_from_preferences ( ) : """Get the PAC ` ` AutoConfigURL ` ` value from the macOS System Preferences . This setting is visible as the " URL " field in System Preferences > Network > Advanced . . . > Proxies > Automatic Proxy Configuration . : return : The value from the registry , or None if...
if not ON_DARWIN : raise NotDarwinError ( ) try : config = SystemConfiguration . SCDynamicStoreCopyProxies ( None ) except AttributeError : return # Key or value not found . if all ( ( 'ProxyAutoConfigEnable' in config , 'ProxyAutoConfigURLString' in config , not config . get ( 'ProxyAutoDiscoveryEnable' , ...
def _init_report ( self ) : """create the report directory and return the directory name"""
self . sections = [ ] self . section_names = [ ] # if the directory already exists , print a warning try : if os . path . isdir ( self . directory ) is False : if self . verbose : print ( "Created directory {}" . format ( self . directory ) ) os . mkdir ( self . directory ) # list of...
def decode_data_with_length ( reader ) -> bytes : """Read data from a reader . Data is prefixed with 2 bytes length : param reader : Stream reader : return : bytes read from stream ( without length )"""
length_bytes = yield from read_or_raise ( reader , 2 ) bytes_length = unpack ( "!H" , length_bytes ) data = yield from read_or_raise ( reader , bytes_length [ 0 ] ) return data
def calculate_localised_cost ( self , d1 , d2 , neighbours , motions ) : """Calculates assignment cost between two cells taking into account the movement of cells neighbours . : param CellFeatures d1 : detection in first frame : param CellFeatures d2 : detection in second frame"""
my_nbrs_with_motion = [ n for n in neighbours [ d1 ] if n in motions ] my_motion = ( d1 . center [ 0 ] - d2 . center [ 0 ] , d1 . center [ 1 ] - d2 . center [ 1 ] ) if my_nbrs_with_motion == [ ] : distance = euclidean_dist ( d1 . center , d2 . center ) / self . scale else : # it is not in motions if there is no tra...
def _project_to_part_level ( hist : Hist , outliers_removal_axis : OutliersRemovalAxis ) -> Hist : """Project the input histogram to the particle level axis . Args : hist : Histogram to check for outliers . outliers _ removal _ axis : Axis along which outliers removal will be performed . Usually the particl...
# Setup the projector import ROOT if isinstance ( hist , ( ROOT . TH2 , ROOT . TH3 ) ) : projection_information : Dict [ str , Any ] = { } output_object = _OutputObject ( None ) projector = projectors . HistProjector ( observable_to_project_from = hist , output_observable = output_object , output_attribute_...
def _lower ( string ) : """Custom lower string function . Examples : FooBar - > foo _ bar"""
if not string : return "" new_string = [ string [ 0 ] . lower ( ) ] for char in string [ 1 : ] : if char . isupper ( ) : new_string . append ( "_" ) new_string . append ( char . lower ( ) ) return "" . join ( new_string )
def add_global ( self , globalvalue ) : """Add a new global value ."""
assert globalvalue . name not in self . globals self . globals [ globalvalue . name ] = globalvalue
def read ( self , count = 1024 ) : # By default we choose a rather small chunk size , because reading # big amounts of input at once , causes the event loop to process # all these key bindings also at once without going back to the # loop . This will make the application feel unresponsive . """Read the input and re...
if self . closed : return b'' # Note : the following works better than wrapping ` self . stdin ` like # ` codecs . getreader ( ' utf - 8 ' ) ( stdin ) ` and doing ` read ( 1 ) ` . # Somehow that causes some latency when the escape # character is pressed . ( Especially on combination with the ` select ` . ) try : ...
def register_all_models ( self , module_instance , exclude_name_list = [ ] ) : """: param module _ instance : the module instance that containing models . Model inherited classes , mostly the models module : param exclude _ name _ list : class does not need to register or is already registered : return : N / ...
for class_instance in class_enumerator ( module_instance , exclude_name_list ) : if is_inherit_from_model ( class_instance ) : self . register ( class_instance )
def pyramid_analysis ( Gs , f , ** kwargs ) : r"""Compute the graph pyramid transform coefficients . Parameters Gs : list of graphs A multiresolution sequence of graph structures . f : ndarray Graph signal to analyze . h _ filters : list A list of filter that will be used for the analysis and sythesis...
if np . shape ( f ) [ 0 ] != Gs [ 0 ] . N : raise ValueError ( "PYRAMID ANALYSIS: The signal to analyze should have the same dimension as the first graph." ) levels = len ( Gs ) - 1 # check if the type of filters is right . h_filters = kwargs . pop ( 'h_filters' , lambda x : 1. / ( 2 * x + 1 ) ) if not isinstance (...
def write_cache ( entries , stream , extension_data = None , ShaStreamCls = IndexFileSHA1Writer ) : """Write the cache represented by entries to a stream : param entries : * * sorted * * list of entries : param stream : stream to wrap into the AdapterStreamCls - it is used for final output . : param ShaStre...
# wrap the stream into a compatible writer stream = ShaStreamCls ( stream ) tell = stream . tell write = stream . write # header version = 2 write ( b"DIRC" ) write ( pack ( ">LL" , version , len ( entries ) ) ) # body for entry in entries : beginoffset = tell ( ) write ( entry [ 4 ] ) # ctime write ( e...
def api_auth ( func ) : """If the user is not logged in , this decorator looks for basic HTTP auth data in the request header ."""
@ wraps ( func ) def _decorator ( request , * args , ** kwargs ) : authentication = APIAuthentication ( request ) if authentication . authenticate ( ) : return func ( request , * args , ** kwargs ) raise Http404 return _decorator
def set_send_enable ( self , setting ) : """Set the send enable setting on the watch"""
self . _pebble . send_packet ( DataLogging ( data = DataLoggingSetSendEnable ( enabled = setting ) ) )
def ls_files ( client , names , authors , include , exclude , format ) : """List files in dataset ."""
records = _filter ( client , names = names , authors = authors , include = include , exclude = exclude ) DATASET_FILES_FORMATS [ format ] ( client , records )
def base_url ( self ) : """Like : attr : ` url ` but without the querystring See also : : attr : ` trusted _ hosts ` ."""
return get_current_url ( self . environ , strip_querystring = True , trusted_hosts = self . trusted_hosts )
def get_namespace ( self , namespace : str , lowercase : bool = True , trim_namespace : bool = True , ) -> Dict [ str , Any ] : """Return a dictionary of keys within a namespace . A namespace is considered to be a key prefix , for example the keys ` ` FOO _ A , FOO _ BAR , FOO _ B ` ` are all within the ` ` FOO...
config = { } for key , value in self . items ( ) : if key . startswith ( namespace ) : if trim_namespace : new_key = key [ len ( namespace ) : ] else : new_key = key if lowercase : new_key = new_key . lower ( ) config [ new_key ] = value return con...
def _job_sorting_key ( self , job ) : """Get the sorting key of a VFGJob instance . : param VFGJob job : the VFGJob object . : return : An integer that determines the order of this job in the queue . : rtype : int"""
MAX_BLOCKS_PER_FUNCTION = 1000000 task_functions = list ( reversed ( list ( task . function_address for task in self . _task_stack if isinstance ( task , FunctionAnalysis ) ) ) ) try : function_pos = task_functions . index ( job . func_addr ) except ValueError : # not in the list # it might be because we followed t...
def xadd ( self , name , fields , id = '*' , maxlen = None , approximate = True ) : """Add to a stream . name : name of the stream fields : dict of field / value pairs to insert into the stream id : Location to insert this record . By default it is appended . maxlen : truncate old stream members beyond this...
pieces = [ ] if maxlen is not None : if not isinstance ( maxlen , ( int , long ) ) or maxlen < 1 : raise DataError ( 'XADD maxlen must be a positive integer' ) pieces . append ( Token . get_token ( 'MAXLEN' ) ) if approximate : pieces . append ( Token . get_token ( '~' ) ) pieces . appen...
def _connect ( self ) : """Connect to the statsd server"""
if not statsd : return if hasattr ( statsd , 'StatsClient' ) : self . connection = statsd . StatsClient ( host = self . host , port = self . port ) . pipeline ( ) else : # Create socket self . connection = statsd . Connection ( host = self . host , port = self . port , sample_rate = 1.0 )
def kwargs_warn_until ( kwargs , version , category = DeprecationWarning , stacklevel = None , _version_info_ = None , _dont_call_warnings = False ) : '''Helper function to raise a warning ( by default , a ` ` DeprecationWarning ` ` ) when unhandled keyword arguments are passed to function , until the provided ...
if not isinstance ( version , ( tuple , six . string_types , salt . version . SaltStackVersion ) ) : raise RuntimeError ( 'The \'version\' argument should be passed as a tuple, string or ' 'an instance of \'salt.version.SaltStackVersion\'.' ) elif isinstance ( version , tuple ) : version = salt . version . Salt...
def has_api_scope_with_prefix ( self , prefix ) : """Test if there is an API scope with the given prefix . : rtype : bool | None"""
if self . _authorized_api_scopes is None : return None return any ( x == prefix or x . startswith ( prefix + '.' ) for x in self . _authorized_api_scopes )
def get_git_refs ( repopath ) : """Return Git active branch , state , branches ( plus tags ) ."""
tags = [ ] branches = [ ] branch = '' files_modifed = [ ] if os . path . isfile ( repopath ) : repopath = os . path . dirname ( repopath ) try : git = programs . find_program ( 'git' ) # Files modified out , err = programs . run_program ( git , [ 'status' , '-s' ] , cwd = repopath , ) . communicate ( ) ...
def split_window ( self , fpath , vertical = False , size = None , bufopts = None ) : """Open file in a new split window . Args : fpath ( str ) : Path of the file to open . If ` ` None ` ` , a new empty split is created . vertical ( bool ) : Whether to open a vertical split . size ( Optional [ int ] ) : T...
command = 'split {}' . format ( fpath ) if fpath else 'new' if vertical : command = 'v' + command if size : command = str ( size ) + command self . _vim . command ( command ) if bufopts : self . set_buffer_options ( bufopts )
def _strip_trailing_zeros ( value ) : """Strip trailing zeros from a list of ints . : param value : the value to be stripped : type value : list of str : returns : list with trailing zeros stripped : rtype : list of int"""
return list ( reversed ( list ( itertools . dropwhile ( lambda x : x == 0 , reversed ( value ) ) ) ) )
def parse_eprocess ( self , eprocess_data ) : """Parse the EProcess object we get from some rekall output"""
Name = eprocess_data [ '_EPROCESS' ] [ 'Cybox' ] [ 'Name' ] PID = eprocess_data [ '_EPROCESS' ] [ 'Cybox' ] [ 'PID' ] PPID = eprocess_data [ '_EPROCESS' ] [ 'Cybox' ] [ 'Parent_PID' ] return { 'Name' : Name , 'PID' : PID , 'PPID' : PPID }
def reduce_to_unit ( divider ) : """Reduce a repeating divider to the smallest repeating unit possible . Note : this function is used by make - div : param divider : the divider : return : smallest repeating unit possible : rtype : str : Example : ' XxXxXxX ' - > ' Xx '"""
for unit_size in range ( 1 , len ( divider ) // 2 + 1 ) : length = len ( divider ) unit = divider [ : unit_size ] # Ignores mismatches in final characters : divider_item = divider [ : unit_size * ( length // unit_size ) ] if unit * ( length // unit_size ) == divider_item : return unit return...
def _adjust_count_if_required ( start_int , count_int , total_int ) : """Adjust requested object count down if there are not enough objects visible to the active subjects to cover the requested slice start and count . Preconditions : start is verified to be lower than the number of visible objects , making it...
if start_int + count_int > total_int : count_int = total_int - start_int count_int = min ( count_int , django . conf . settings . MAX_SLICE_ITEMS ) return count_int
def init ( cls , path ) : """Set up an SPV client . If the locally - stored headers do not exist , then create a stub headers file with the genesis block information ."""
if not os . path . exists ( path ) : block_header_serializer = BlockHeaderSerializer ( ) genesis_block_header = BlockHeader ( ) if USE_MAINNET : # we know the mainnet block header # but we don ' t know the testnet / regtest block header genesis_block_header . version = 1 genesis_block_he...
def split ( self , new_index ) : """Create a new event which is a copy of this one but with a new index ."""
new_event = Event ( new_index , self . user_data ) new_event . time = self . time new_event . step_size = self . step_size return new_event
def extract_one ( self , L , P , R ) : """Given left context ` L ` , punctuation mark ` P ` , and right context R ` , extract features . Probability distributions for any quantile - based features will not be modified ."""
yield "*bias*" # L feature ( s ) if match ( QUOTE , L ) : L = QUOTE_TOKEN elif isnumberlike ( L ) : L = NUMBER_TOKEN else : yield "len(L)={}" . format ( min ( len ( L ) , CLIP ) ) if "." in L : yield "L:*period*" if not self . nocase : cf = case_feature ( R ) if cf : ...
def findSynonymsArray ( self , word , num ) : """Find " num " number of words closest in similarity to " word " . word can be a string or vector representation . Returns an array with two fields word and similarity ( which gives the cosine similarity ) ."""
if not isinstance ( word , basestring ) : word = _convert_to_vector ( word ) tuples = self . _java_obj . findSynonymsArray ( word , num ) return list ( map ( lambda st : ( st . _1 ( ) , st . _2 ( ) ) , list ( tuples ) ) )
def _fix_example_namespace ( self ) : """Attempts to resolve issues where our samples use ' http : / / example . com / ' for our example namespace but python - stix uses ' http : / / example . com ' by removing the former ."""
example_prefix = 'example' # Example ns prefix idgen_prefix = idgen . get_id_namespace_prefix ( ) # If the ID namespace alias doesn ' t match the example alias , return . if idgen_prefix != example_prefix : return # If the example namespace prefix isn ' t in the parsed namespace # prefixes , return . if example_pre...
def subtract_and_intersect_circle ( self , center , radius ) : '''Will throw a VennRegionException if the circle to be subtracted is completely inside and not touching the given region .'''
# Check whether the target circle intersects us center = np . asarray ( center , float ) d = np . linalg . norm ( center - self . center ) if d > ( radius + self . radius - tol ) : return [ self , VennEmptyRegion ( ) ] # The circle does not intersect us elif d < tol : if radius > self . radius - tol : # We ...
def execute ( self , write_concern = None ) : """Execute all provided operations . : Parameters : - write _ concern ( optional ) : the write concern for this bulk execution ."""
if write_concern is not None : write_concern = WriteConcern ( ** write_concern ) return self . __bulk . execute ( write_concern , session = None )
def _compiler_bridge_cache_dir ( self ) : """A directory where we can store compiled copies of the ` compiler - bridge ` . The compiler - bridge is specific to each scala version . Currently we compile the ` compiler - bridge ` only once , while bootstrapping . Then , we store it in the working directory unde...
hasher = sha1 ( ) for cp_entry in [ self . zinc , self . compiler_interface , self . compiler_bridge ] : hasher . update ( os . path . relpath ( cp_entry , self . _workdir ( ) ) . encode ( 'utf-8' ) ) key = hasher . hexdigest ( ) [ : 12 ] return os . path . join ( self . _workdir ( ) , 'zinc' , 'compiler-bridge' , ...
def get_folder_list ( folder = '.' ) : """Get list of sub - folders contained in input folder : param folder : input folder to list sub - folders . Default is ` ` ' . ' ` ` : type folder : str : return : list of sub - folders : rtype : list ( str )"""
dir_list = get_content_list ( folder ) return [ f for f in dir_list if not os . path . isfile ( os . path . join ( folder , f ) ) ]
def GetReportDescriptor ( cls ) : """Returns plugins ' metadata in ApiReportDescriptor ."""
if cls . TYPE is None : raise ValueError ( "%s.TYPE is unintialized." % cls ) if cls . TITLE is None : raise ValueError ( "%s.TITLE is unintialized." % cls ) if cls . SUMMARY is None : raise ValueError ( "%s.SUMMARY is unintialized." % cls ) return rdf_report_plugins . ApiReportDescriptor ( type = cls . TYP...
def data ( self ) : """Parameters passed to the API containing the details to create a new alert . : return : parameters to create new alert . : rtype : dict"""
data = { } data [ "name" ] = self . name data [ "query" ] = self . queryd data [ "languages" ] = self . languages data [ "countries" ] = self . countries if self . countries else "" data [ "sources" ] = self . sources if self . sources else "" data [ "blocked_sites" ] = self . blocked_sites if self . blocked_sites else...
def send_mail ( subject , message , from_email , recipient_list , html_message = '' , scheduled_time = None , headers = None , priority = PRIORITY . medium ) : """Add a new message to the mail queue . This is a replacement for Django ' s ` ` send _ mail ` ` core email method ."""
subject = force_text ( subject ) status = None if priority == PRIORITY . now else STATUS . queued emails = [ ] for address in recipient_list : emails . append ( Email . objects . create ( from_email = from_email , to = address , subject = subject , message = message , html_message = html_message , status = status ,...