signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def slices_overlap ( slice_a , slice_b ) : """Test if the ranges covered by a pair of slices overlap ."""
assert slice_a . step is None assert slice_b . step is None return max ( slice_a . start , slice_b . start ) < min ( slice_a . stop , slice_b . stop )
def from_api ( cls , ** kwargs ) : """Create a new instance from API arguments . This will switch camelCase keys into snake _ case for instantiation . It will also identify any ` ` Instance ` ` or ` ` List ` ` properties , and instantiate the proper objects using the values . The end result being a fully Ob...
vals = cls . get_non_empty_vals ( { cls . _to_snake_case ( k ) : v for k , v in kwargs . items ( ) } ) remove = [ ] for attr , val in vals . items ( ) : try : vals [ attr ] = cls . _parse_property ( attr , val ) except HelpScoutValidationException : remove . append ( attr ) logger . info...
def parse_value ( cls , itype , value ) : """Parse the input value ."""
parsed = None if itype == "date" : m = RE_DATE . match ( value ) if m : year = int ( m . group ( 'year' ) , 10 ) month = int ( m . group ( 'month' ) , 10 ) day = int ( m . group ( 'day' ) , 10 ) if cls . validate_year ( year ) and cls . validate_month ( month ) and cls . validate...
def enabled_scanner_ids ( self ) : """Retrieves a list of currently enabled scanners ."""
enabled_scanners = [ ] scanners = self . zap . ascan . scanners ( ) for scanner in scanners : if scanner [ 'enabled' ] == 'true' : enabled_scanners . append ( scanner [ 'id' ] ) return enabled_scanners
def enable_servicegroup_host_checks ( self , servicegroup ) : """Enable host checks for a servicegroup Format of the line that triggers function call : : ENABLE _ SERVICEGROUP _ HOST _ CHECKS ; < servicegroup _ name > : param servicegroup : servicegroup to enable : type servicegroup : alignak . objects . se...
for service_id in servicegroup . get_services ( ) : if service_id in self . daemon . services : host_id = self . daemon . services [ service_id ] . host self . enable_host_check ( self . daemon . hosts [ host_id ] )
def make_at_least_n_items_valid ( flag_list , n ) : """tries to make at least min ( len ( flag _ list , n ) items True in flag _ list Args : flag _ list ( list ) : list of booleans n ( int ) : number of items to ensure are True CommandLine : python - m utool . util _ dev - - test - make _ at _ least _ n _...
flag_list = np . array ( flag_list ) num_valid = flag_list . sum ( ) # Find how many places we need to make true num_extra = min ( len ( flag_list ) - num_valid , n - num_valid ) # make _ at _ least _ n _ items _ valid # Add in some extra daids to show if there are not enough for index in range ( len ( flag_list ) ) : ...
def stop ( self , msg = 'Thread stopped' ) : """Stop send thread and flush points for a safe exit ."""
with self . _lock : if not self . _thread_running : return self . _thread_running = False self . _queue . put ( _BaseSignalFxIngestClient . _QUEUE_STOP ) self . _send_thread . join ( ) _logger . debug ( msg )
def parse_pdb ( self ) : """Extracts additional information from PDB files . I . When reading in a PDB file , OpenBabel numbers ATOMS and HETATOMS continously . In PDB files , TER records are also counted , leading to a different numbering system . This functions reads in a PDB file and provides a mapping as ...
if self . as_string : fil = self . pdbpath . rstrip ( '\n' ) . split ( '\n' ) # Removing trailing newline character else : f = read ( self . pdbpath ) fil = f . readlines ( ) f . close ( ) corrected_lines = [ ] i , j = 0 , 0 # idx and PDB numbering d = { } modres = set ( ) covalent = [ ] alt = [ ] p...
def locate_files ( pattern , root_dir = os . curdir ) : """Locate all files matching fiven filename pattern in and below supplied root directory ."""
for dirpath , dirnames , filenames in os . walk ( os . path . abspath ( root_dir ) ) : for filename in fnmatch . filter ( filenames , pattern ) : yield os . path . join ( dirpath , filename )
def analysis_add_tags ( object_id , input_params = { } , always_retry = True , ** kwargs ) : """Invokes the / analysis - xxxx / addTags API method . For more info , see : https : / / wiki . dnanexus . com / API - Specification - v1.0.0 / Workflows - and - Analyses # API - method % 3A - % 2Fanalysis - xxxx % 2Fadd...
return DXHTTPRequest ( '/%s/addTags' % object_id , input_params , always_retry = always_retry , ** kwargs )
def dre_drho0 ( self , pars ) : r"""Compute partial derivative of real parts with respect to : math : ` \ rho _ 0 ` : math : ` \ frac { \ partial \ hat { \ rho ' } ( \ omega ) } { \ partial \ rho _ 0 } = 1 - \ frac { m ( \ omega \ tau ) ^ c cos ( \ frac { c \ pi } { 2 } ) + ( \ omega \ tau ) ^ c } { 1 + 2 (...
self . _set_parameters ( pars ) numerator = self . m * self . otc * ( np . cos ( self . ang ) + self . otc ) term = numerator / self . denom specs = np . sum ( term , axis = 1 ) result = 1 - specs return result
def connected ( self , client ) : """Call this method when a client connected ."""
self . clients . add ( client ) self . _log_connected ( client ) self . _start_watching ( client ) self . send_msg ( client , WELCOME , ( self . pickle_protocol , __version__ ) , pickle_protocol = 0 ) profiler = self . profiler while True : try : profiler = profiler . profiler except AttributeError : ...
def get_for_objects ( self , queryset ) : """Get log entries for the objects in the specified queryset . : param queryset : The queryset to get the log entries for . : type queryset : QuerySet : return : The LogEntry objects for the objects in the given queryset . : rtype : QuerySet"""
if not isinstance ( queryset , QuerySet ) or queryset . count ( ) == 0 : return self . none ( ) content_type = ContentType . objects . get_for_model ( queryset . model ) primary_keys = list ( queryset . values_list ( queryset . model . _meta . pk . name , flat = True ) ) if isinstance ( primary_keys [ 0 ] , integer...
def get_msg_info ( yaml_info , topics , parse_header = True ) : '''Get info from all of the messages about what they contain and will be added to the dataframe'''
topic_info = yaml_info [ 'topics' ] msgs = { } classes = { } for topic in topics : base_key = get_key_name ( topic ) msg_paths = [ ] msg_types = { } for info in topic_info : if info [ 'topic' ] == topic : msg_class = get_message_class ( info [ 'type' ] ) if msg_class is N...
def blobs ( self , repository_ids = [ ] , reference_names = [ ] , commit_hashes = [ ] ) : """Retrieves the blobs of a list of repositories , reference names and commit hashes . So the result will be a DataFrame of all the blobs in the given commits that are in the given references that belong to the given repos...
if not isinstance ( repository_ids , list ) : raise Exception ( "repository_ids must be a list" ) if not isinstance ( reference_names , list ) : raise Exception ( "reference_names must be a list" ) if not isinstance ( commit_hashes , list ) : raise Exception ( "commit_hashes must be a list" ) return BlobsDa...
def mount ( name = None , ** kwargs ) : '''Mounts ZFS file systems name : string name of the filesystem , having this set to None will mount all filesystems . ( this is the default ) overlay : boolean perform an overlay mount . options : string optional comma - separated list of mount options to use tem...
# # Configure command # NOTE : initialize the defaults flags = [ ] opts = { } # NOTE : set extra config from kwargs if kwargs . get ( 'overlay' , False ) : flags . append ( '-O' ) if kwargs . get ( 'options' , False ) : opts [ '-o' ] = kwargs . get ( 'options' ) if name in [ None , '-a' ] : # NOTE : the new way...
def cluster_set_config_epoch ( self , config_epoch ) : """Set the configuration epoch in a new node ."""
fut = self . execute ( b'CLUSTER' , b'SET-CONFIG-EPOCH' , config_epoch ) return wait_ok ( fut )
def transform ( self , new_frame ) : """Change the frame of the orbit Args : new _ frame ( str ) Return : numpy . ndarray"""
steps = self . __class__ . steps ( new_frame ) orbit = self . orbit for _from , _to in steps : from_obj = _from ( self . date , orbit ) direct = "_to_%s" % _to if hasattr ( from_obj , direct ) : rotation , offset = getattr ( from_obj , direct ) ( ) else : to_obj = _to ( self . date , orb...
def _get_path ( dict_ , path ) : '''Get value at specific path in dictionary . Path is specified by slash - separated string , eg _ get _ path ( foo , ' bar / baz ' ) returns foo [ ' bar ' ] [ ' baz ' ]'''
cur = dict_ for part in path . split ( '/' ) : cur = cur [ part ] return cur
def _ConvertFloat ( value ) : """Convert an floating point number ."""
if value == 'nan' : raise ParseError ( 'Couldn\'t parse float "nan", use "NaN" instead.' ) try : # Assume Python compatible syntax . return float ( value ) except ValueError : # Check alternative spellings . if value == _NEG_INFINITY : return float ( '-inf' ) elif value == _INFINITY : re...
def event ( self , event ) : """Qt Override . Filter tab keys and process double tab keys ."""
if ( event . type ( ) == QEvent . KeyPress ) and ( event . key ( ) == Qt . Key_Tab ) : self . sig_tab_pressed . emit ( True ) self . numpress += 1 if self . numpress == 1 : self . presstimer = QTimer . singleShot ( 400 , self . handle_keypress ) return True return QComboBox . event ( self , even...
def sync_lists ( self ) : """Access the sync _ lists : returns : twilio . rest . sync . v1 . service . sync _ list . SyncListList : rtype : twilio . rest . sync . v1 . service . sync _ list . SyncListList"""
if self . _sync_lists is None : self . _sync_lists = SyncListList ( self . _version , service_sid = self . _solution [ 'sid' ] , ) return self . _sync_lists
def _x_axis ( self ) : """Make the x axis : labels and guides"""
if not self . _x_labels or not self . show_x_labels : return axis = self . svg . node ( self . nodes [ 'plot' ] , class_ = "axis x%s" % ( ' always_show' if self . show_x_guides else '' ) ) truncation = self . truncate_label if not truncation : if self . x_label_rotation or len ( self . _x_labels ) <= 1 : ...
def copy_folder_content ( src , dst ) : """Copy all content in src directory to dst directory . The src and dst must exist ."""
for file in os . listdir ( src ) : file_path = os . path . join ( src , file ) dst_file_path = os . path . join ( dst , file ) if os . path . isdir ( file_path ) : shutil . copytree ( file_path , dst_file_path ) else : shutil . copyfile ( file_path , dst_file_path )
def simulate ( self ) : """Simulates a stream of types ."""
# Simulates zero to 10 types return [ t . simulate ( ) for t in itertools . islice ( self , random . choice ( range ( 10 ) ) ) ]
def populate_tree ( self , master , parent , element , from_file = False ) : """Reads xml nodes and populates tree item"""
data = WidgetDescr ( None , None ) data . from_xml_node ( element ) cname = data . get_class ( ) uniqueid = self . get_unique_id ( cname , data . get_id ( ) ) data . set_property ( 'id' , uniqueid ) if cname in builder . CLASS_MAP : pwidget = self . _insert_item ( master , data , from_file = from_file ) xpath =...
def _add_genes_to_bed ( in_file , gene_file , fai_file , out_file , data , max_distance = 10000 ) : """Re - usable subcomponent that annotates BED file genes from another BED"""
try : input_rec = next ( iter ( pybedtools . BedTool ( in_file ) ) ) except StopIteration : # empty file utils . copy_plus ( in_file , out_file ) return # keep everything after standard chrom / start / end , 1 - based extra_fields = list ( range ( 4 , len ( input_rec . fields ) + 1 ) ) # keep the new gene a...
def list ( self , includes = None , doc_type = None , promulgated_only = False , sort = None , owner = None , series = None ) : '''List entities in the charmstore . @ param includes What metadata to return in results ( e . g . charm - config ) . @ param doc _ type Filter to this type : bundle or charm . @ par...
queries = self . _common_query_parameters ( doc_type , includes , owner , promulgated_only , series , sort ) if len ( queries ) : url = '{}/list?{}' . format ( self . url , urlencode ( queries ) ) else : url = '{}/list' . format ( self . url ) data = self . _get ( url ) return data . json ( ) [ 'Results' ]
def itemTypeWithSomeAttributes ( attributeTypes ) : """Create a new L { Item } subclass with L { numAttributes } integers in its schema ."""
class SomeItem ( Item ) : typeName = 'someitem_' + str ( typeNameCounter ( ) ) for i , attributeType in enumerate ( attributeTypes ) : locals ( ) [ 'attr_' + str ( i ) ] = attributeType ( ) return SomeItem
def run ( steps , iter_vars = None , data_out = None , out_interval = 1 , out_base_tables = None , out_run_tables = None , compress = False , out_base_local = True , out_run_local = True ) : """Run steps in series , optionally repeatedly over some sequence . The current iteration variable is set as a global injec...
iter_vars = iter_vars or [ None ] max_i = len ( iter_vars ) # get the tables to write out if out_base_tables is None or out_run_tables is None : step_tables = get_step_table_names ( steps ) if out_base_tables is None : out_base_tables = step_tables if out_run_tables is None : out_run_tables ...
def AddContract ( self , contract ) : """Add a contract to the wallet . Args : contract ( Contract ) : a contract of type neo . SmartContract . Contract . Raises : Exception : Invalid operation - public key mismatch ."""
if not contract . PublicKeyHash . ToBytes ( ) in self . _keys . keys ( ) : raise Exception ( 'Invalid operation - public key mismatch' ) self . _contracts [ contract . ScriptHash . ToBytes ( ) ] = contract if contract . ScriptHash in self . _watch_only : self . _watch_only . remove ( contract . ScriptHash )
def _set_default_format ( self , vmin , vmax ) : "Returns the default ticks spacing ."
if self . plot_obj . date_axis_info is None : self . plot_obj . date_axis_info = self . finder ( vmin , vmax , self . freq ) info = self . plot_obj . date_axis_info if self . isminor : format = np . compress ( info [ 'min' ] & np . logical_not ( info [ 'maj' ] ) , info ) else : format = np . compress ( info...
def point ( self , x , y , z = 0 , m = 0 ) : """Creates a point shape ."""
pointShape = _Shape ( self . shapeType ) pointShape . points . append ( [ x , y , z , m ] ) self . _shapes . append ( pointShape )
def _StartProcessStatusRPCServer ( self ) : """Starts the process status RPC server ."""
if self . _rpc_server : return self . _rpc_server = plaso_xmlrpc . XMLProcessStatusRPCServer ( self . _GetStatus ) hostname = 'localhost' # Try the PID as port number first otherwise pick something random # between 1024 and 60000. if self . _pid < 1024 or self . _pid > 60000 : port = random . randint ( 1024 , 6...
def commit ( self , partitions = None ) : """Commit stored offsets to Kafka via OffsetCommitRequest ( v0) Keyword Arguments : partitions ( list ) : list of partitions to commit , default is to commit all of them Returns : True on success , False on failure"""
# short circuit if nothing happened . This check is kept outside # to prevent un - necessarily acquiring a lock for checking the state if self . count_since_commit == 0 : return with self . commit_lock : # Do this check again , just in case the state has changed # during the lock acquiring timeout if self . cou...
def get_groups ( self , username ) : """Get a user ' s groups : param username : ' key ' attribute of the user : type username : string : rtype : list of groups"""
try : return self . users [ username ] [ 'groups' ] except Exception as e : raise UserDoesntExist ( username , self . backend_name )
def reviewboard ( client , channel , nick , message , matches ) : """Automatically responds to reviewboard urls if a user mentions a pattern like cr # # # # . Requires REVIEWBOARD _ URL to exist in settings with formattable substring ' { review } '"""
url_fmt = getattr ( settings , 'REVIEWBOARD_URL' , 'http://localhost/{review}' ) reviews = [ url_fmt . format ( review = cr ) for cr in matches ] return '{0} might be talking about codereview: {1}' . format ( nick , ', ' . join ( reviews ) )
def filter_generic ( self , content_object = None , ** kwargs ) : """Filter by a generic object . : param content _ object : the content object to filter on ."""
if content_object : kwargs [ 'content_type' ] = ContentType . objects . get_for_model ( content_object ) kwargs [ 'object_id' ] = content_object . id return self . filter ( ** kwargs )
def handle ( self ) : """Executes the command ."""
database = self . option ( "database" ) self . resolver . set_default_connection ( database ) repository = DatabaseMigrationRepository ( self . resolver , "migrations" ) migrator = Migrator ( repository , self . resolver ) if not migrator . repository_exists ( ) : return self . error ( "No migrations found" ) self ...
def _translate_port ( port ) : '''Look into services and return the port value using the service name as lookup value .'''
services = _get_services_mapping ( ) if port in services and services [ port ] [ 'port' ] : return services [ port ] [ 'port' ] [ 0 ] return port
def save ( self , filename = None , debug = False ) : """save a data file such that all processes know the game that is running"""
if not filename : filename = self . name with open ( filename , "w" ) as f : # save config data file f . write ( self . toJson ( self . attrs ) ) if self . debug or debug : print ( "saved configuration %s" % ( self . name ) ) for k , v in sorted ( iteritems ( self . attrs ) ) : print ( "%15s : %...
def fromJob ( cls , job , command , predecessorNumber ) : """Build a job node from a job object : param toil . job . Job job : the job object to be transformed into a job node : param str command : the JobNode ' s command : param int predecessorNumber : the number of predecessors that must finish successful...
return cls ( jobStoreID = None , requirements = job . _requirements , command = command , jobName = job . jobName , unitName = job . unitName , displayName = job . displayName , predecessorNumber = predecessorNumber )
def setup_logger ( log_level , log_file = None , logger_name = None ) : """setup logger @ param log _ level : debug / info / warning / error / critical @ param log _ file : log file path @ param logger _ name : the name of logger , default is ' root ' if not specify"""
applogger = AppLog ( logger_name ) level = getattr ( logging , log_level . upper ( ) , None ) if not level : color_print ( "Invalid log level: %s" % log_level , "RED" ) sys . exit ( 1 ) # hide traceback when log level is INFO / WARNING / ERROR / CRITICAL if level >= logging . INFO : sys . tracebacklimit = 0...
def getparam ( self , name , default = None , parents = False ) : '''A parameter in this : class : ` . Router `'''
value = getattr ( self , name , None ) if value is None : if parents and self . _parent : return self . _parent . getparam ( name , default , parents ) else : return default else : return value
def GetRootFileEntry ( self ) : """Retrieves the root file entry . Returns : TARFileEntry : file entry ."""
path_spec = tar_path_spec . TARPathSpec ( location = self . LOCATION_ROOT , parent = self . _path_spec . parent ) return self . GetFileEntryByPathSpec ( path_spec )
def visit_parenthesized ( self , node , parenthesized ) : """Treat a parenthesized subexpression as just its contents . Its position in the tree suffices to maintain its grouping semantics ."""
left_paren , _ , expression , right_paren , _ = parenthesized return expression
def make_isotropic_source ( name , Spectrum_Filename , spectrum ) : """Construct and return a ` fermipy . roi _ model . IsoSource ` object"""
data = dict ( Spectrum_Filename = Spectrum_Filename ) if spectrum is not None : data . update ( spectrum ) return roi_model . IsoSource ( name , data )
def set_logfile ( self , filename , max_bytes = 0 , backup_count = 0 ) : """Setup logging to a ( rotating ) logfile . Args : filename ( str ) : Logfile . If filename is None , disable file logging max _ bytes ( int ) : Maximum number of bytes per logfile . If used together with backup _ count , logfile will...
_logger = logging . getLogger ( "neo-python" ) if not filename and not self . rotating_filehandler : _logger . removeHandler ( self . rotating_filehandler ) else : self . rotating_filehandler = RotatingFileHandler ( filename , mode = 'a' , maxBytes = max_bytes , backupCount = backup_count , encoding = None ) ...
def get_facts ( self ) : """Return a set of facts from the devices ."""
# default values . vendor = u'Cisco' uptime = - 1 serial_number , fqdn , os_version , hostname , domain_name = ( 'Unknown' , ) * 5 # obtain output from device show_ver = self . _send_command ( 'show version' ) show_hosts = self . _send_command ( 'show hosts' ) show_ip_int_br = self . _send_command ( 'show ip interface ...
def __lists_to_str ( self ) : """There are some data lists that we collected across the dataset that need to be concatenated into a single string before writing to the text file . : return none :"""
# [ " archive _ type " , " sensor _ genus " , " sensor _ species " , " investigator " ] if self . lsts_tmp [ "archive" ] : self . noaa_data_sorted [ "Top" ] [ "Archive" ] = "," . join ( self . lsts_tmp [ "archive" ] ) if self . lsts_tmp [ "species" ] : self . noaa_data_sorted [ "Species" ] [ "Species_Name" ] = ...
def add_port_profile ( self , profile_name , vlan_id , device_id ) : """Adds a port profile and its vlan _ id to the table ."""
if not self . get_port_profile_for_vlan ( vlan_id , device_id ) : port_profile = ucsm_model . PortProfile ( profile_id = profile_name , vlan_id = vlan_id , device_id = device_id , created_on_ucs = False ) with self . session . begin ( subtransactions = True ) : self . session . add ( port_profile ) ...
def dnd_setSnooze ( self , * , num_minutes : int , ** kwargs ) -> SlackResponse : """Turns on Do Not Disturb mode for the current user , or changes its duration . Args : num _ minutes ( int ) : The snooze duration . e . g . 60"""
self . _validate_xoxp_token ( ) kwargs . update ( { "num_minutes" : num_minutes } ) return self . api_call ( "dnd.setSnooze" , http_verb = "GET" , params = kwargs )
def process_request ( self , request ) : """Discovers if a request is from a knwon spam bot and denies access ."""
if COOKIE_KEY in request . COOKIES and request . COOKIES [ COOKIE_KEY ] == COOKIE_SPAM : # Is a known spammer . response = HttpResponse ( "" ) # We do not reveal why it has been forbbiden : response . status_code = 404 if DJANGOSPAM_LOG : logger . log ( "SPAM REQUEST" , request . method , reques...
def _retrieve_binary ( self , file_name ) : """Retrieve a file in binary transfer mode ."""
with open ( file_name , 'wb' ) as f : return self . session . retrbinary ( 'RETR ' + file_name , f . write )
def getMaskIndices ( mask ) : """get lower and upper index of mask"""
return [ list ( mask ) . index ( True ) , len ( mask ) - 1 - list ( mask ) [ : : - 1 ] . index ( True ) ]
def indexes ( self ) : """Mapping of pandas . Index objects used for label based indexing"""
if self . _indexes is None : self . _indexes = default_indexes ( self . _coords , self . dims ) return Indexes ( self . _indexes )
def manipulateLattice ( self , beamline , type = 'quad' , irange = 'all' , property = 'k1' , opstr = '+0%' ) : """manipulate element with type , e . g . quad input parameters : : param beamline : beamline definition keyword : param type : element type , case insensitive : param irange : slice index , see ge...
# lattice _ list = self . getFullBeamline ( beamline , extend = True ) # orderedLattice _ list = self . orderLattice ( beamline ) opele_list = self . getElementByOrder ( beamline , type , irange ) opr = opstr [ 0 ] opn = float ( opstr [ 1 : ] . strip ( '%' ) ) if opstr [ - 1 ] == '%' : opn /= 100.0 opsdict = { ...
def create_attachment ( self , container , attachment_file , ** kw ) : """Create an Attachment object in the given container"""
filename = getattr ( attachment_file , "filename" , "Attachment" ) attachment = api . create ( container , "Attachment" , title = filename ) attachment . edit ( AttachmentFile = attachment_file , ** kw ) attachment . processForm ( ) attachment . reindexObject ( ) logger . info ( "Created new Attachment {} in {}" . form...
def hsetnx ( self , key , field , value ) : """Sets ` field ` in the hash stored at ` key ` only if it does not exist . Sets ` field ` in the hash stored at ` key ` only if ` field ` does not yet exist . If ` key ` does not exist , a new key holding a hash is created . If ` field ` already exists , this opera...
return self . _execute ( [ b'HSETNX' , key , field , value ] )
def _sumindex ( self , index = None ) : """Convert tuple index to 1 - D index into value"""
try : ndim = len ( index ) except TypeError : # turn index into a 1 - tuple index = ( index , ) ndim = 1 if len ( self . shape ) != ndim : raise ValueError ( "Index to %d-dimensional array %s has too %s dimensions" % ( len ( self . shape ) , self . name , [ "many" , "few" ] [ len ( self . shape ) > ndim...
def canGoBack ( self ) : """Returns whether or not this wizard can move forward . : return < bool >"""
try : backId = self . _navigation . index ( self . currentId ( ) ) - 1 if backId >= 0 : self . _navigation [ backId ] else : return False except StandardError : return False else : return True
def remove_file ( filename , verbose = True ) : """Attempt to delete filename . log is boolean . If true , removal is logged . Log a warning if file does not exist . Logging filenames are relative to config . BASE _ DIR to cut down on noise in output ."""
if verbose : LOG . info ( 'Deleting file %s' , os . path . relpath ( filename , config . BASE_DIR ) ) if not os . path . exists ( filename ) : LOG . warning ( "File does not exist: %s" , os . path . relpath ( filename , config . BASE_DIR ) ) else : os . remove ( filename )
def command ( cmd ) : """Playback command request ."""
message = create ( protobuf . SEND_COMMAND_MESSAGE ) send_command = message . inner ( ) send_command . command = cmd return message
def isel ( self , indexers = None , drop = False , ** indexers_kwargs ) : """Returns a new dataset with each array indexed along the specified dimension ( s ) . This method selects values from each array using its ` _ _ getitem _ _ ` method , except this method does not require knowing the order of each arr...
indexers = either_dict_or_kwargs ( indexers , indexers_kwargs , 'isel' ) indexers_list = self . _validate_indexers ( indexers ) variables = OrderedDict ( ) indexes = OrderedDict ( ) for name , var in self . variables . items ( ) : var_indexers = { k : v for k , v in indexers_list if k in var . dims } if drop an...
def fmt_sia ( sia , ces = True ) : """Format a | SystemIrreducibilityAnalysis | ."""
if ces : body = ( '{ces}' '{partitioned_ces}' . format ( ces = fmt_ces ( sia . ces , 'Cause-effect structure' ) , partitioned_ces = fmt_ces ( sia . partitioned_ces , 'Partitioned cause-effect structure' ) ) ) center_header = True else : body = '' center_header = False title = 'System irreducibility anal...
def rewind ( self , places ) : '''Rewinds the current buffer to a position . Needed for reading varints , because we might read bytes that belong to the stream after the varint .'''
log . debug ( "Rewinding pos %d with %d places" % ( self . pos , places ) ) self . pos -= places log . debug ( "Reset buffer to pos %d" % self . pos )
def _read_image_list ( self , skip_image_ids = None ) : """Reads list of dataset images from the datastore ."""
if skip_image_ids is None : skip_image_ids = [ ] images = self . _storage_client . list_blobs ( prefix = os . path . join ( 'dataset' , self . _dataset_name ) + '/' ) zip_files = [ i for i in images if i . endswith ( '.zip' ) ] if len ( zip_files ) == 1 : # we have a zip archive with images zip_name = zip_files...
def __authorize ( self , client_id , client_secret , credit_card_id , ** kwargs ) : """Call documentation : ` / credit _ card / authorize < https : / / www . wepay . com / developer / reference / credit _ card # authorize > ` _ , plus extra keyword parameter : : keyword bool batch _ mode : turn on / off the b...
params = { 'client_id' : client_id , 'client_secret' : client_secret , 'credit_card_id' : credit_card_id } return self . make_call ( self . __authorize , params , kwargs )
def _hash ( self , hash_name ) : """Returns a hash object for the file at the current path . ` hash _ name ` should be a hash algo name ( such as ` ` ' md5 ' ` ` or ` ` ' sha1 ' ` ` ) that ' s available in the : mod : ` hashlib ` module ."""
m = hashlib . new ( hash_name ) for chunk in self . chunks ( 8192 , mode = "rb" ) : m . update ( chunk ) return m
def save_plot ( code , elem ) : """Converts matplotlib plots to tikz code . If elem has either the plt attribute ( format : plt = width , height ) or the attributes width = width and / or height = height , the figurewidth and - height are set accordingly . If none are given , a height of 4cm and a width of 6c...
if 'plt' in elem . attributes : figurewidth , figureheight = elem . attributes [ 'plt' ] . split ( ',' ) else : try : figureheight = elem . attributes [ 'height' ] except KeyError : figureheight = '4cm' try : figurewidth = elem . attributes [ 'width' ] except KeyError : ...
def create_interface_connection ( interface_a , interface_b ) : '''. . versionadded : : 2019.2.0 Create an interface connection between 2 interfaces interface _ a Interface id for Side A interface _ b Interface id for Side B CLI Example : . . code - block : : bash salt myminion netbox . create _ int...
payload = { 'interface_a' : interface_a , 'interface_b' : interface_b } ret = _add ( 'dcim' , 'interface-connections' , payload ) if ret : return { 'dcim' : { 'interface-connections' : { ret [ 'id' ] : payload } } } else : return ret
def delete_payment_transaction_by_id ( cls , payment_transaction_id , ** kwargs ) : """Delete PaymentTransaction Delete an instance of PaymentTransaction by its ID . This method makes a synchronous HTTP request by default . To make an asynchronous HTTP request , please pass async = True > > > thread = api ....
kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'async' ) : return cls . _delete_payment_transaction_by_id_with_http_info ( payment_transaction_id , ** kwargs ) else : ( data ) = cls . _delete_payment_transaction_by_id_with_http_info ( payment_transaction_id , ** kwargs ) return data
def match_sound_mode ( self , sound_mode_raw ) : """Match the raw _ sound _ mode to its corresponding sound _ mode ."""
try : sound_mode = self . _sm_match_dict [ sound_mode_raw . upper ( ) ] return sound_mode except KeyError : smr_up = sound_mode_raw . upper ( ) self . _sound_mode_dict [ smr_up ] = [ smr_up ] self . _sm_match_dict = self . construct_sm_match_dict ( ) _LOGGER . warning ( "Not able to match sound ...
def virtual_host ( self ) : """Return request virtual host ( " Host " header value ) : return : None or str"""
if self . headers ( ) is not None : host_value = self . headers ( ) [ 'Host' ] return host_value [ 0 ] . lower ( ) if host_value is not None else None
def agp ( args ) : """% prog agp evidencefile contigs . fasta Convert SSPACE scaffold structure to AGP format ."""
p = OptionParser ( agp . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) evidencefile , contigs = args ef = EvidenceFile ( evidencefile , contigs ) agpfile = evidencefile . replace ( ".evidence" , ".agp" ) ef . write_agp ( agpfile )
def reverse_list_valued_dict ( dict_obj ) : """Reverse a list - valued dict , so each element in a list maps to its key . Parameters dict _ obj : dict A dict where each key maps to a list of unique values . Values are assumed to be unique across the entire dict , on not just per - list . Returns dict ...
new_dict = { } for key in dict_obj : for element in dict_obj [ key ] : new_dict [ element ] = key return new_dict
def rename_keys ( d , keymap = None , list_of_dicts = False , deepcopy = True ) : """rename keys in dict Parameters d : dict keymap : dict dictionary of key name mappings list _ of _ dicts : bool treat list of dicts as additional branches deepcopy : bool deepcopy values Examples > > > from pprin...
list_of_dicts = '__list__' if list_of_dicts else None keymap = { } if keymap is None else keymap flatd = flatten ( d , list_of_dicts = list_of_dicts ) flatd = { tuple ( [ keymap . get ( k , k ) for k in path ] ) : v for path , v in flatd . items ( ) } return unflatten ( flatd , list_of_dicts = list_of_dicts , deepcopy ...
def parse ( cls , s , ** kwargs ) : """Parse a bytes object and create a class object . : param bytes s : A bytes object . : return : A class object . : rtype : cls"""
pb2_obj = cls . _get_cmsg ( ) pb2_obj . ParseFromString ( s ) return cls . parse_from_cmessage ( pb2_obj , ** kwargs )
def _VarUInt64ByteSizeNoTag ( uint64 ) : """Returns the number of bytes required to serialize a single varint using boundary value comparisons . ( unrolled loop optimization - WPierce ) uint64 must be unsigned ."""
if uint64 <= 0x7f : return 1 if uint64 <= 0x3fff : return 2 if uint64 <= 0x1fffff : return 3 if uint64 <= 0xfffffff : return 4 if uint64 <= 0x7ffffffff : return 5 if uint64 <= 0x3ffffffffff : return 6 if uint64 <= 0x1ffffffffffff : return 7 if uint64 <= 0xffffffffffffff : return 8 if uin...
def _do_ned_namesearch_queries_and_add_resulting_metadata_to_database ( self , batchCount ) : """* Query NED via name searcha and add result metadata to database * * * Key Arguments : * * - ` ` batchCount ` ` - the index number of the batch sent to NED ( only needed for printing to STDOUT to give user idea of p...
self . log . debug ( 'starting the ``_do_ned_namesearch_queries_and_add_resulting_metadata_to_database`` method' ) # ASTROCALC UNIT CONVERTER OBJECT converter = unit_conversion ( log = self . log ) tableName = self . dbTableName # QUERY NED WITH BATCH totalCount = len ( self . theseIds ) print "requesting metadata from...
def call ( ) : """Execute command line helper ."""
args = get_arguments ( ) if args . debug : log_level = logging . DEBUG elif args . quiet : log_level = logging . WARN else : log_level = logging . INFO setup_logging ( log_level ) lupusec = None if not args . username or not args . password or not args . ip_address : raise Exception ( "Please supply a u...
def saveAs ( self , path ) : """save to file under given name"""
if not path : path = self . _dialogs . getSaveFileName ( filter = '*.csv' ) if path : self . _setPath ( path ) with open ( str ( self . _path ) , 'wb' ) as stream : writer = csv . writer ( stream ) table = self . table ( ) for row in table : writer . writerow ( row )
def make_transformer ( self , decompose = 'svd' , decompose_by = 50 , tsne_kwargs = { } ) : """Creates an internal transformer pipeline to project the data set into 2D space using TSNE , applying an pre - decomposition technique ahead of embedding if necessary . This method will reset the transformer on the c...
# TODO : detect decompose by inferring from sparse matrix or dense or # If number of features > 50 etc . decompositions = { 'svd' : TruncatedSVD , 'pca' : PCA , } if decompose and decompose . lower ( ) not in decompositions : raise YellowbrickValueError ( "'{}' is not a valid decomposition, use {}, or None" . forma...
def write ( self , * messages ) : """Push a list of messages in the inputs of this graph ' s inputs , matching the output of special node " BEGIN " in our graph ."""
for i in self . graph . outputs_of ( BEGIN ) : for message in messages : self [ i ] . write ( message )
def p_source_text ( self , p ) : 'source _ text : description'
p [ 0 ] = Source ( name = '' , description = p [ 1 ] , lineno = p . lineno ( 1 ) ) p . set_lineno ( 0 , p . lineno ( 1 ) )
def Expire ( self ) : """Expires old cache entries ."""
while len ( self . _age ) > self . _limit : node = self . _age . PopLeft ( ) self . _hash . pop ( node . key , None ) self . KillObject ( node . data )
def load_json ( json_file , ** kwargs ) : """Open and load data from a JSON file . . code : : python reusables . load _ json ( " example . json " ) # { u ' key _ 1 ' : u ' val _ 1 ' , u ' key _ for _ dict ' : { u ' sub _ dict _ key ' : 8 } } : param json _ file : Path to JSON file as string : param kwargs...
with open ( json_file ) as f : return json . load ( f , ** kwargs )
def _max ( self ) : """Getter for the maximum series value"""
return ( self . range [ 1 ] if ( self . range and self . range [ 1 ] is not None ) else ( max ( self . yvals ) if self . yvals else None ) )
def rawselect ( message : Text , choices : List [ Union [ Text , Choice , Dict [ Text , Any ] ] ] , default : Optional [ Text ] = None , qmark : Text = DEFAULT_QUESTION_PREFIX , style : Optional [ Style ] = None , ** kwargs : Any ) -> Question : """Ask the user to select one item from a list of choices using shortc...
return select . select ( message , choices , default , qmark , style , use_shortcuts = True , ** kwargs )
def asinh ( x ) : """Inverse hyperbolic sine"""
if isinstance ( x , UncertainFunction ) : mcpts = np . arcsinh ( x . _mcpts ) return UncertainFunction ( mcpts ) else : return np . arcsinh ( x )
def get_objective_bank_lookup_session ( self , proxy ) : """Gets the OsidSession associated with the objective bank lookup service . arg : proxy ( osid . proxy . Proxy ) : a proxy return : ( osid . learning . ObjectiveBankLookupSession ) - an ` ` ObjectiveBankLookupSession ` ` raise : NullArgument - ` ` pro...
if not self . supports_objective_bank_lookup ( ) : raise errors . Unimplemented ( ) # pylint : disable = no - member return sessions . ObjectiveBankLookupSession ( proxy = proxy , runtime = self . _runtime )
def logger_file ( self , value ) : """The logger file . If the logger _ file is None , then add stream handler and remove file handler . Otherwise , add file handler and remove stream handler . : param value : The logger _ file path . : type : str"""
self . __logger_file = value if self . __logger_file : # If set logging file , # then add file handler and remove stream handler . self . logger_file_handler = logging . FileHandler ( self . __logger_file ) self . logger_file_handler . setFormatter ( self . logger_formatter ) for _ , logger in six . iterite...
def boundedFunction ( x , minY , ax , ay ) : '''limit [ function ] to a minimum y value'''
y = function ( x , ax , ay ) return np . maximum ( np . nan_to_num ( y ) , minY )
def func_timeout ( timeout , func , args = ( ) , kwargs = None ) : '''func _ timeout - Runs the given function for up to # timeout # seconds . Raises any exceptions # func # would raise , returns what # func # would return ( unless timeout is exceeded ) , in which case it raises FunctionTimedOut @ param timeout...
if not kwargs : kwargs = { } if not args : args = ( ) ret = [ ] exception = [ ] isStopped = False def funcwrap ( args2 , kwargs2 ) : try : ret . append ( func ( * args2 , ** kwargs2 ) ) except FunctionTimedOut : # Don ' t print traceback to stderr if we time out pass except Exception...
def apply_T5 ( word ) : '''If a ( V ) VVV - sequence contains a VV - sequence that could be an / i / - final diphthong , there is a syllable boundary between it and the third vowel , e . g . , [ raa . ois . sa ] , [ huo . uim . me ] , [ la . eis . sa ] , [ sel . vi . äi . si ] , [ tai . an ] , [ säi . e ] ,...
WORD = _split_consonants_and_vowels ( word ) for k , v in WORD . iteritems ( ) : if len ( v ) >= 3 and is_vowel ( v [ 0 ] ) : vv = [ v . find ( i ) for i in i_DIPHTHONGS if v . find ( i ) > 0 ] if any ( vv ) : vv = vv [ 0 ] if vv == v [ 0 ] : WORD [ k ] = v [ ...
def termfinder ( self , pattern ) : """Search srt in project for cells matching term ."""
if Config . options . regex : flags = re . M | re . S | ( 0 if Config . options . case_sensitive else re . I ) self . project . set_search_regex ( pattern , flags = flags ) else : self . project . set_search_string ( pattern , ignore_case = not Config . options . case_sensitive ) matches = [ ] while True : ...
def is_pre_prepare_time_acceptable ( self , pp : PrePrepare , sender : str ) -> bool : """Returns True or False depending on the whether the time in PRE - PREPARE is acceptable . Can return True if time is not acceptable but sufficient PREPAREs are found to support the PRE - PREPARE : param pp : : return :"...
key = ( pp . viewNo , pp . ppSeqNo ) if key in self . requested_pre_prepares : # Special case for requested PrePrepares return True correct = self . is_pre_prepare_time_correct ( pp , sender ) if not correct : if key in self . pre_prepares_stashed_for_incorrect_time and self . pre_prepares_stashed_for_incorrect...
def make_copy ( self , copy_to ) : """Copy self attributes to the new object . : param CFGBase copy _ to : The target to copy to . : return : None"""
for attr , value in self . __dict__ . items ( ) : if attr . startswith ( '__' ) and attr . endswith ( '__' ) : continue setattr ( copy_to , attr , value )
def write_metadata ( self , handler ) : """set the meta data"""
if self . metadata is not None : handler . write_metadata ( self . cname , self . metadata )
def generate_execute_macro ( model , config , manifest , provider ) : """Internally , macros can be executed like nodes , with some restrictions : - they don ' t have have all values available that nodes do : - ' this ' , ' pre _ hooks ' , ' post _ hooks ' , and ' sql ' are missing - ' schema ' does not use a...
model_dict = model . serialize ( ) context = generate_base ( model , model_dict , config , manifest , None , provider ) return modify_generated_context ( context , model , model_dict , config , manifest )