signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def _with_context ( self , * args , ** kwargs ) : """As the ` with _ context ` class method but for recordset ."""
context = dict ( args [ 0 ] if args else self . env . context , ** kwargs ) return self . with_env ( self . env ( context = context ) )
def _convert_weekday_pattern ( p_weekday ) : """Converts a weekday name to an absolute date . When today ' s day of the week is entered , it will return next week ' s date ."""
day_value = { 'mo' : 0 , 'tu' : 1 , 'we' : 2 , 'th' : 3 , 'fr' : 4 , 'sa' : 5 , 'su' : 6 } target_day_string = p_weekday [ : 2 ] . lower ( ) target_day = day_value [ target_day_string ] day = date . today ( ) . weekday ( ) shift = 7 - ( day - target_day ) % 7 return date . today ( ) + timedelta ( shift )
def do_export ( self , subcmd , opts , * args ) : """Create an unversioned copy of a tree . usage : 1 . export [ - r REV ] URL [ PATH ] 2 . export [ - r REV ] PATH1 [ PATH2] 1 . Exports a clean directory tree from the repository specified by URL , at revision REV if it is given , otherwise at HEAD , into ...
print "'svn %s' opts: %s" % ( subcmd , opts ) print "'svn %s' args: %s" % ( subcmd , args )
def _parse_udf_descriptors ( self ) : # type : ( ) - > None '''An internal method to parse the UDF descriptors on the ISO . This should only be called if it the ISO has a valid UDF Volume Recognition Sequence at the beginning of the ISO . Parameters : None . Returns : Nothing .'''
block_size = self . pvd . logical_block_size ( ) # Parse the anchors anchor_locations = [ ( 256 * block_size , os . SEEK_SET ) , ( - 2048 , os . SEEK_END ) ] for loc , whence in anchor_locations : self . _cdfp . seek ( loc , whence ) extent = self . _cdfp . tell ( ) // 2048 anchor_data = self . _cdfp . read...
def can_edit ( self , user ) : """Return whether or not ` user ` can make changes to the class ."""
return user . is_admin or not self . is_locked and self in user . admin_for
def avail_locations ( call = None ) : '''Return available Linode datacenter locations . CLI Example : . . code - block : : bash salt - cloud - - list - locations my - linode - config salt - cloud - f avail _ locations my - linode - config'''
if call == 'action' : raise SaltCloudException ( 'The avail_locations function must be called with -f or --function.' ) response = _query ( 'avail' , 'datacenters' ) ret = { } for item in response [ 'DATA' ] : name = item [ 'LOCATION' ] ret [ name ] = item return ret
def _create_dictionary_of_ned_d ( self ) : """create a list of dictionaries containing all the rows in the ned _ d catalogue * * Return : * * - ` ` dictList ` ` - a list of dictionaries containing all the rows in the ned _ d catalogue . . todo : : - update key arguments values and definitions with defaults ...
self . log . debug ( 'starting the ``_create_dictionary_of_ned_d`` method' ) count = 0 with open ( self . pathToDataFile , 'rb' ) as csvFile : csvReader = csv . reader ( csvFile , dialect = 'excel' , delimiter = ',' , quotechar = '"' ) totalRows = sum ( 1 for row in csvReader ) csvFile . close ( ) totalCount = ...
def from_config ( cls , name , config ) : """Returns a Configurable instance with the given name and config . By default this is a simple matter of calling the constructor , but subclasses that are also ` Pluggable ` instances override this in order to check that the plugin is installed correctly first ."""
cls . validate_config ( config ) instance = cls ( ) if not instance . name : instance . name = config . get ( "name" , name ) instance . apply_config ( config ) return instance
def _make_path ( * parts ) : """Create a URL string from parts , omit all ` None ` values and empty strings . Convert lists and tuples to comma separated values ."""
# TODO : maybe only allow some parts to be lists / tuples ? return "/" + "/" . join ( # preserve ' , ' and ' * ' in url for nicer URLs in logs quote_plus ( _escape ( p ) , b",*" ) for p in parts if p not in SKIP_IN_PATH )
def offset_gaussian ( data ) : """Fit a gaussian model to ` data ` and return its center"""
nbins = 2 * int ( np . ceil ( np . sqrt ( data . size ) ) ) mind , maxd = data . min ( ) , data . max ( ) drange = ( mind - ( maxd - mind ) / 2 , maxd + ( maxd - mind ) / 2 ) histo = np . histogram ( data , nbins , density = True , range = drange ) dx = abs ( histo [ 1 ] [ 1 ] - histo [ 1 ] [ 2 ] ) / 2 hx = histo [ 1 ]...
def _update_dprx ( self ) : """Update ` dprx ` ."""
super ( ExpCM_fitprefs , self ) . _update_dprx ( ) j = 0 if 'zeta' in self . freeparams : self . dprx [ 'zeta' ] . fill ( 0 ) for r in range ( self . nsites ) : for i in range ( N_AA - 1 ) : zetari = self . zeta [ j ] for a in range ( i , N_AA ) : delta_aAx = ( CO...
def create ( gandi , name , datacenter , subnet , gateway , background ) : """Create a new vlan"""
try : gandi . datacenter . is_opened ( datacenter , 'iaas' ) except DatacenterLimited as exc : gandi . echo ( '/!\ Datacenter %s will be closed on %s, ' 'please consider using another datacenter.' % ( datacenter , exc . date ) ) result = gandi . vlan . create ( name , datacenter , subnet , gateway , background ...
def vcard ( self , qs ) : """VCARD format ."""
try : import vobject except ImportError : print ( self . style . ERROR ( "Please install vobject to use the vcard export format." ) ) sys . exit ( 1 ) out = sys . stdout for ent in qs : card = vobject . vCard ( ) card . add ( 'fn' ) . value = full_name ( ** ent ) if not ent [ 'last_name' ] and n...
def create_aws_lambda ( ctx , bucket , region_name , aws_access_key_id , aws_secret_access_key ) : """Creates an AWS Chalice project for deployment to AWS Lambda ."""
from canari . commands . create_aws_lambda import create_aws_lambda create_aws_lambda ( ctx . project , bucket , region_name , aws_access_key_id , aws_secret_access_key )
def slackpkg_update ( self ) : """This replace slackpkg ChangeLog . txt file with new from Slackware official mirrors after update distribution ."""
NEW_ChangeLog_txt = URL ( mirrors ( "ChangeLog.txt" , "" ) ) . reading ( ) if os . path . isfile ( self . meta . slackpkg_lib_path + "ChangeLog.txt.old" ) : os . remove ( self . meta . slackpkg_lib_path + "ChangeLog.txt.old" ) if os . path . isfile ( self . meta . slackpkg_lib_path + "ChangeLog.txt" ) : shutil ...
def push ( self ) : """Returns a callable that can be used to transmit a message in a push - pull fashion . Note that the sender function has a ` ` print ` ` like signature , with an infinite number of arguments . Each one being a part of the complete message . : rtype : function"""
sock = self . __sock ( zmq . PUSH ) return self . __send_function ( sock )
def add_libravatar ( generator , metadata ) : """Article generator connector for the Libravatar plugin"""
missing = generator . settings . get ( 'LIBRAVATAR_MISSING' ) size = generator . settings . get ( 'LIBRAVATAR_SIZE' ) # # Check the presence of the Email header if 'email' not in metadata . keys ( ) : try : metadata [ 'email' ] = generator . settings . get ( 'AUTHOR_EMAIL' ) except : pass # # Ad...
def inventory ( self , modules_inventory = False ) : """Get chassis inventory . : param modules _ inventory : True - read modules inventory , false - don ' t read ."""
self . c_info = self . get_attributes ( ) for m_index , m_portcounts in enumerate ( self . c_info [ 'c_portcounts' ] . split ( ) ) : if int ( m_portcounts ) : module = XenaModule ( parent = self , index = m_index ) if modules_inventory : module . inventory ( )
def get_key_words ( s , max_words = 50 , weighted = False ) : """Determines key words in Chinese text * s * . The key words are returned in a list . If * weighted * is ` ` True ` ` , then each list item is a tuple : ` ` ( word , weight ) ` ` , where * weight * is a float . If it ' s * False * , then each list...
s = _decode ( s ) logger . debug ( "Searching for up to {}{} key words in: {}." . format ( max_words , ' weighted' if weighted else '' , s ) ) result = nlpir . GetKeyWords ( _encode ( s ) , max_words , weighted ) result = _decode ( result ) logger . debug ( "Finished key word search: {}." . format ( result ) ) logger ....
def transform ( self ) : """Return a new transformed matrix . : return : Returns a new transformed Matrix : rtype : Matrix"""
t_matrix = Matrix ( self . _rows , self . _columns ) for col_i , col in enumerate ( self . matrix ) : for row_i , entry in enumerate ( col ) : t_matrix . set_value ( row_i , col_i , entry ) return t_matrix
def _pdf ( self , xloc , left , right , cache ) : """Probability density function . Example : > > > print ( chaospy . Uniform ( ) . pdf ( [ - 0.5 , 0.5 , 1.5 , 2.5 ] ) ) [0 . 1 . 0 . 0 . ] > > > print ( Mul ( chaospy . Uniform ( ) , 2 ) . pdf ( [ - 0.5 , 0.5 , 1.5 , 2.5 ] ) ) [0 . 0.5 0.5 0 . ] > > > pr...
left = evaluation . get_forward_cache ( left , cache ) right = evaluation . get_forward_cache ( right , cache ) if isinstance ( left , Dist ) : if isinstance ( right , Dist ) : raise evaluation . DependencyError ( "under-defined distribution {} or {}" . format ( left , right ) ) elif not isinstance ( right ...
def get_volumes ( self ) : """Gets a list of all volumes in this disk , including volumes that are contained in other volumes ."""
volumes = [ ] for v in self . volumes : volumes . extend ( v . get_volumes ( ) ) return volumes
def user_line ( self , frame , breakpoint_hits = None ) : """This function is called when we stop or break at this line ."""
if not breakpoint_hits : self . interaction ( frame , None ) else : commands_result = self . bp_commands ( frame , breakpoint_hits ) if not commands_result : self . interaction ( frame , None ) else : doprompt , silent = commands_result if not silent : self . print_st...
def tee_output_python ( ) : """Duplicate sys . stdout and sys . stderr to new StringIO ."""
buffer = StringIO ( ) out = CapturedStdout ( buffer ) orig_stdout , orig_stderr = sys . stdout , sys . stderr flush ( ) sys . stdout = TeeingStreamProxy ( sys . stdout , buffer ) sys . stderr = TeeingStreamProxy ( sys . stderr , buffer ) try : yield out finally : flush ( ) out . finalize ( ) sys . stdou...
def compile_initial_state ( self , batch_size : Optional [ int ] = None ) -> Sequence [ tf . Tensor ] : '''Returns a tuple of tensors representing the initial state fluents . Args : batch _ size ( Optional [ int ] ) : The batch size . Returns : Sequence [ tf . Tensor ] : A tuple of tensors .'''
with self . graph . as_default ( ) : with tf . name_scope ( 'initial_state' ) : self . _initialize_initial_state_fluents ( ) if batch_size is None : return self . initial_state_fluents return self . _compile_batch_fluents ( self . initial_state_fluents , batch_size )
def interfaces ( self ) : """Get the list of network on compute"""
if not self . _interfaces_cache : response = yield from self . get ( "/network/interfaces" ) self . _interfaces_cache = response . json return self . _interfaces_cache
def get_example_from_prop_spec ( self , prop_spec , from_allof = False ) : """Return an example value from a property specification . Args : prop _ spec : the specification of the property . from _ allof : whether these properties are part of an allOf section Returns : An example value"""
# Read example directly from ( X - ) Example or Default value easy_keys = [ 'example' , 'x-example' , 'default' ] for key in easy_keys : if key in prop_spec . keys ( ) and self . use_example : return prop_spec [ key ] # Enum if 'enum' in prop_spec . keys ( ) : return prop_spec [ 'enum' ] [ 0 ] # From de...
def creep_data ( data_set = 'creep_rupture' ) : """Brun and Yoshida ' s metal creep rupture data ."""
if not data_available ( data_set ) : download_data ( data_set ) path = os . path . join ( data_path , data_set ) tar_file = os . path . join ( path , 'creeprupt.tar' ) tar = tarfile . open ( tar_file ) print ( 'Extracting file.' ) tar . extractall ( path = path ) tar . close ( ) all_data = n...
def validate ( value ) : """checks if given value is a valid country codes @ param string value @ return bool"""
if not helpers . has_len ( value ) : return False return COUNTRIES . has_key ( str ( value ) . lower ( ) )
def save_to ( self , image ) : """Save this image to another DockerImage : param image : DockerImage : return :"""
if not isinstance ( image , self . __class__ ) : raise ConuException ( "Invalid target image type" , type ( image ) ) self . copy ( image . name , image . tag , target_transport = image . transport , target_path = image . path , logs = False )
def get ( self , sid ) : """Constructs a TaskQueueContext : param sid : The sid : returns : twilio . rest . taskrouter . v1 . workspace . task _ queue . TaskQueueContext : rtype : twilio . rest . taskrouter . v1 . workspace . task _ queue . TaskQueueContext"""
return TaskQueueContext ( self . _version , workspace_sid = self . _solution [ 'workspace_sid' ] , sid = sid , )
def calculate ( self , msg : array . array ) -> array . array : """Get the checksum for a WSP message . There are three hashes possible : 1 ) 4 Bit Checksum - For Switch Telegram ( RORG = 5 or 6 and STATUS = 0x20 or 0x30) 2 ) 8 Bit Checksum : STATUS bit 2 ^ 7 = 0 3 ) 8 Bit CRC : STATUS bit 2 ^ 7 = 1 : param...
try : if self . mode == self . ChecksumMode . auto : if msg [ 0 : 4 ] == util . hex2bit ( "5" ) or msg [ 0 : 4 ] == util . hex2bit ( "6" ) : # Switch telegram return self . checksum4 ( msg ) status = msg [ - 16 : - 8 ] if status [ 0 ] : return self . crc8 ( msg [ : - ...
def number ( self ) : """Return a multidigit int or float number ."""
number = '' while self . char is not None and self . char . isdigit ( ) : number += self . char self . advance ( ) if self . char == '.' : number += self . char self . advance ( ) while self . char is not None and self . char . isdigit ( ) : number += self . char self . advance ( ) ...
def override_operation ( self , operation , reason ) : """Re - Classify entry pair ."""
prev_class = ( self . local_classification , self . remote_classification ) prev_op = self . operation assert operation != prev_op assert operation in PAIR_OPERATIONS if self . any_entry . target . synchronizer . verbose > 3 : write ( "override_operation({}, {}) -> {} ({})" . format ( prev_class , prev_op , operati...
def get_child_type_choices ( self , request , action ) : """Override choice labels with ` ` verbose _ name ` ` from plugins and sort ."""
# Get choices from the super class to check permissions . choices = super ( ChildModelPluginPolymorphicParentModelAdmin , self ) . get_child_type_choices ( request , action ) # Update label with verbose name from plugins . plugins = self . child_model_plugin_class . get_plugins ( ) labels = { } sort_priorities = { } if...
def asluav_status_encode ( self , LED_status , SATCOM_status , Servo_status , Motor_rpm ) : '''Extended state information for ASLUAVs LED _ status : Status of the position - indicator LEDs ( uint8 _ t ) SATCOM _ status : Status of the IRIDIUM satellite communication system ( uint8 _ t ) Servo _ status : Statu...
return MAVLink_asluav_status_message ( LED_status , SATCOM_status , Servo_status , Motor_rpm )
def write_byte ( self , cmd , value ) : """Writes an 8 - bit byte to the specified command register"""
self . bus . write_byte_data ( self . address , cmd , value ) self . log . debug ( "write_byte: Wrote 0x%02X to command register 0x%02X" % ( value , cmd ) )
def click ( self , target = None , modifiers = "" ) : """Moves the cursor to the target location and clicks the default mouse button ."""
if target is None : target = self . _lastMatch or self # Whichever one is not None target_location = None if isinstance ( target , Pattern ) : target_location = self . find ( target ) . getTarget ( ) elif isinstance ( target , basestring ) : target_location = self . find ( target ) . getTarget ( ) elif isin...
def add_edge ( self , u , v , weight = None ) : """Add an edge between u and v . The nodes u and v will be automatically added if they are not already in the graph . Parameters u , v : nodes Nodes can be any hashable Python object . weight : int , float ( default = None ) The weight of the edge . Ex...
super ( UndirectedGraph , self ) . add_edge ( u , v , weight = weight )
def iswhat ( o ) : """Returns a dictionary of all possible identity checks available to : mod : ` inspect ` applied to ` o ` . Returns : dict : keys are ` inspect . is * ` function names ; values are ` bool ` results returned by each of the methods ."""
import inspect isfs = { n : f for n , f in inspect . getmembers ( inspect ) if n [ 0 : 2 ] == "is" } return { n : f ( o ) for n , f in isfs . items ( ) }
def from_string ( cls , model_id , default_project = None ) : """Construct a model reference from model ID string . Args : model _ id ( str ) : A model ID in standard SQL format . If ` ` default _ project ` ` is not specified , this must included a project ID , dataset ID , and model ID , each separated b...
proj , dset , model = _helpers . _parse_3_part_id ( model_id , default_project = default_project , property_name = "model_id" ) return cls . from_api_repr ( { "projectId" : proj , "datasetId" : dset , "modelId" : model } )
def _operator_symbol_handler ( c , ctx ) : """Handles operator symbol values within s - expressions ."""
assert c in _OPERATORS ctx . set_unicode ( ) val = ctx . value val . append ( c ) c , self = yield trans = ctx . immediate_transition ( self ) while c in _OPERATORS : val . append ( c ) c , _ = yield trans yield ctx . event_transition ( IonEvent , IonEventType . SCALAR , IonType . SYMBOL , val . as_symbol ( ) )
def create_free_shipping_coupon ( cls , free_shipping_coupon , ** kwargs ) : """Create FreeShippingCoupon Create a new FreeShippingCoupon This method makes a synchronous HTTP request by default . To make an asynchronous HTTP request , please pass async = True > > > thread = api . create _ free _ shipping _ ...
kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'async' ) : return cls . _create_free_shipping_coupon_with_http_info ( free_shipping_coupon , ** kwargs ) else : ( data ) = cls . _create_free_shipping_coupon_with_http_info ( free_shipping_coupon , ** kwargs ) return data
def repositories ( self ) : """Get dependencies by repositories"""
if self . repo == "sbo" : self . sbo_case_insensitive ( ) self . find_pkg = sbo_search_pkg ( self . name ) if self . find_pkg : self . dependencies_list = Requires ( self . flag ) . sbo ( self . name ) else : PACKAGES_TXT = Utils ( ) . read_file ( self . meta . lib_path + "{0}_repo/PACKAGES.TXT"...
def on_message ( self , message_id_service , contact_id_service , content ) : """To use as callback in message service backend"""
try : live_chat = Chat . live . get ( Q ( agent__id_service = contact_id_service ) | Q ( asker__id_service = contact_id_service ) ) except ObjectDoesNotExist : self . _new_chat_processing ( message_id_service , contact_id_service , content ) else : live_chat . handle_message ( message_id_service , contact_i...
def symmetric_rescaling ( A , copy = True ) : """Scale the matrix symmetrically . A = D ^ { - 1/2 } A D ^ { - 1/2} where D = diag ( A ) . The left multiplication is accomplished through scale _ rows and the right multiplication is done through scale columns . Parameters A : sparse matrix Sparse matrix...
if isspmatrix_csr ( A ) or isspmatrix_csc ( A ) or isspmatrix_bsr ( A ) : if A . shape [ 0 ] != A . shape [ 1 ] : raise ValueError ( 'expected square matrix' ) D = diag_sparse ( A ) mask = ( D != 0 ) if A . dtype != complex : D_sqrt = np . sqrt ( abs ( D ) ) else : # We can take squa...
def check_installation ( cur_file ) : """Warn user if running cleverhans from a different directory than tutorial ."""
cur_dir = os . path . split ( os . path . dirname ( os . path . abspath ( cur_file ) ) ) [ 0 ] ch_dir = os . path . split ( cleverhans . __path__ [ 0 ] ) [ 0 ] if cur_dir != ch_dir : warnings . warn ( "It appears that you have at least two versions of " "cleverhans installed, one at %s and one at" " %s. You are run...
def run_simulations ( self , parameter_list , data_folder ) : """This function runs multiple simulations in parallel ."""
# Open up a session s = drmaa . Session ( ) s . initialize ( ) # Create a job template for each parameter combination jobs = { } for parameter in parameter_list : # Initialize result current_result = { 'params' : { } , 'meta' : { } } current_result [ 'params' ] . update ( parameter ) command = " " . join ( ...
def astype ( self , type_name ) : """Convert AstroImage object to some other kind of object ."""
if type_name == 'nddata' : return self . as_nddata ( ) if type_name == 'hdu' : return self . as_hdu ( ) raise ValueError ( "Unrecognized conversion type '%s'" % ( type_name ) )
def fetch ( ** kwargs ) : '''. . versionadded : : 2016.3.4 freebsd - update fetch wrapper . Based on the currently installed world and the configuration options set , fetch all available binary updates . kwargs : Parameters of freebsd - update command .'''
# fetch continues when no controlling terminal is present pre = '' post = '' run_args = { } if float ( __grains__ [ 'osrelease' ] ) >= 10.2 : post += '--not-running-from-cron' else : pre += ' env PAGER=cat' run_args [ 'python_shell' ] = True return _wrapper ( 'fetch' , pre = pre , post = post , run_args = r...
def device_measurement ( device , ts = None , part = None , result = None , code = None , ** kwargs ) : """Returns a JSON MeasurementPayload ready to be send through a transport . If ` ts ` is not given , the current time is used . ` part ` is an optional ` Part ` object , and ` result ` and ` code ` are the ...
if ts is None : ts = local_now ( ) payload = MeasurementPayload ( device = device , part = part ) m = Measurement ( ts , result , code , list ( kwargs ) ) payload . measurements . append ( m ) m . add_sample ( ts , ** kwargs ) return dumps ( payload )
def get_item ( self , identifier , item_metadata = None , request_kwargs = None ) : """A method for creating : class : ` internetarchive . Item < Item > ` and : class : ` internetarchive . Collection < Collection > ` objects . : type identifier : str : param identifier : A globally unique Archive . org identi...
request_kwargs = { } if not request_kwargs else request_kwargs if not item_metadata : logger . debug ( 'no metadata provided for "{0}", ' 'retrieving now.' . format ( identifier ) ) item_metadata = self . get_metadata ( identifier , request_kwargs ) mediatype = item_metadata . get ( 'metadata' , { } ) . get ( '...
def get_reqv ( self ) : """: returns : an instance of class : ` RjbEquivalent ` if reqv _ hdf5 is set"""
if 'reqv' not in self . inputs : return return { key : valid . RjbEquivalent ( value ) for key , value in self . inputs [ 'reqv' ] . items ( ) }
def find_time_base ( self , gps , first_ms_stamp ) : '''work out time basis for the log - new style'''
t = self . _gpsTimeToTime ( gps . Week , gps . TimeMS ) self . set_timebase ( t - gps . T * 0.001 ) self . timestamp = self . timebase + first_ms_stamp * 0.001
def _update_control_section ( self ) : """private method to synchronize the control section counters with the various parts of the control file . This is usually called during the Pst . write ( ) method ."""
self . control_data . npar = self . npar self . control_data . nobs = self . nobs self . control_data . npargp = self . parameter_groups . shape [ 0 ] self . control_data . nobsgp = self . observation_data . obgnme . value_counts ( ) . shape [ 0 ] + self . prior_information . obgnme . value_counts ( ) . shape [ 0 ] sel...
def answer_callback_query ( self , callback_query_id , text = None , show_alert = None , url = None , cache_time = None ) : """Use this method to send answers to callback queries sent from inline keyboards . The answer will be displayed to the user as a notification at the top of the chat screen or as an alert . ...
return apihelper . answer_callback_query ( self . token , callback_query_id , text , show_alert , url , cache_time )
def broadcast ( cls , message ) : """broadcast message to all connected clients"""
clients = cls . get_clients ( ) # loop over every client and send message for id , client in clients . iteritems ( ) : client . send_message ( message )
def add_drop_down ( self , col_number , col_label ) : """Add a correctly formatted drop - down - menu for given col _ label , if required or suggested . Otherwise do nothing . Parameters col _ number : int grid position at which to add a drop down menu col _ label : str column name"""
if col_label . endswith ( '**' ) or col_label . endswith ( '^^' ) : col_label = col_label [ : - 2 ] # add drop - down for experiments if col_label == "experiments" : if 'measurements' in self . contribution . tables : meas_table = self . contribution . tables [ 'measurements' ] . df if 'experime...
def kill_process ( process ) : """Kill the process group associated with the given process . ( posix )"""
logger = logging . getLogger ( 'xenon' ) logger . info ( 'Terminating Xenon-GRPC server.' ) os . kill ( process . pid , signal . SIGINT ) process . wait ( )
def send_lockedtransfer ( transfer_description : TransferDescriptionWithSecretState , channel_state : NettingChannelState , message_identifier : MessageID , block_number : BlockNumber , ) -> SendLockedTransfer : """Create a mediated transfer using channel ."""
assert channel_state . token_network_identifier == transfer_description . token_network_identifier lock_expiration = get_initial_lock_expiration ( block_number , channel_state . reveal_timeout , ) # The payment amount and the fee amount must be included in the locked # amount , as a guarantee to the mediator that the f...
def add_link ( self , link_id = None , dump = True ) : """Create a link . By default the link is empty : param dump : Dump topology to disk"""
if link_id and link_id in self . _links : return self . _links [ link_id ] link = UDPLink ( self , link_id = link_id ) self . _links [ link . id ] = link if dump : self . dump ( ) return link
def update_filter ( self , * args , ** kwargs ) : """Update the filter : returns : None : rtype : None : raises : NotImplementedError"""
forbidden_statuses = [ ] if not self . loaded_checkb . isChecked ( ) : forbidden_statuses . append ( reftrack . Reftrack . LOADED ) if not self . unloaded_checkb . isChecked ( ) : forbidden_statuses . append ( reftrack . Reftrack . UNLOADED ) if not self . imported_checkb . isChecked ( ) : forbidden_statuse...
def update_node ( availability = str , node_name = str , role = str , node_id = str , version = int ) : '''Updates docker swarm nodes / needs to target a manager node / minion availability Drain or Active node _ name minion / node role role of manager or worker node _ id The Id and that can be obtai...
client = docker . APIClient ( base_url = 'unix://var/run/docker.sock' ) try : salt_return = { } node_spec = { 'Availability' : availability , 'Name' : node_name , 'Role' : role } client . update_node ( node_id = node_id , version = version , node_spec = node_spec ) salt_return . update ( { 'Node Informa...
def parse ( self ) : """Parse command line arguments and options . Returns : Dictionary containing all given command line arguments and options ."""
( options , args ) = self . parser . parse_args ( ) self . _set_attributes ( args , options ) return self . _create_dictionary ( )
def ParseFileObject ( self , parser_mediator , file_object ) : """Parses an ASL file - like object . Args : parser _ mediator ( ParserMediator ) : mediates interactions between parsers and other components , such as storage and dfvfs . file _ object ( dfvfs . FileIO ) : file - like object . Raises : Una...
file_header_map = self . _GetDataTypeMap ( 'asl_file_header' ) try : file_header , _ = self . _ReadStructureFromFileObject ( file_object , 0 , file_header_map ) except ( ValueError , errors . ParseError ) as exception : raise errors . UnableToParseFile ( 'Unable to parse file header with error: {0!s}' . format ...
def _fetch_rrd_meta ( self , connection , rrd_path_root , whitelist , field_names , tags ) : '''Fetch metadata about each RRD in this Cacti DB , returning a list of tuples of ( hostname , device _ name , rrd _ path )'''
def _in_whitelist ( rrd ) : path = rrd . replace ( '<path_rra>/' , '' ) for p in whitelist : if fnmatch ( path , p ) : return True return False c = connection . cursor ( ) and_parameters = " OR " . join ( [ "hsc.field_name = '%s'" % field_name for field_name in field_names ] ) # Check fo...
def set_rtscts ( self , enable ) : '''enable / disable RTS / CTS if applicable'''
try : self . port . setRtsCts ( enable ) except Exception : self . port . rtscts = enable self . rtscts = enable
def output ( f ) : """This decorator allows to choose to return an output as text or to save it to a file ."""
def wrapper ( self , * args , ** kwargs ) : try : text = kwargs . get ( 'text' ) or args [ 0 ] except IndexError : text = True _ = f ( self , * args , ** kwargs ) if text : return _ elif _ is not None and isinstance ( _ , string_types ) : filename = "{}.{}" . format (...
def _to_user_defined ( pif_obj ) : """Read the systems in the PIF to populate the user - defined portion"""
res = { } # make a read view to flatten the hierarchy rv = ReadView ( pif_obj ) # Iterate over the keys in the read view for k in rv . keys ( ) : name , value = _extract_key_value ( rv [ k ] . raw ) # add any objects that can be extracted if name and value is not None : res [ name ] = value # Grab i...
def replace_node_status ( self , name , body , ** kwargs ) : """replace status of the specified Node This method makes a synchronous HTTP request by default . To make an asynchronous HTTP request , please pass async _ req = True > > > thread = api . replace _ node _ status ( name , body , async _ req = True )...
kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'async_req' ) : return self . replace_node_status_with_http_info ( name , body , ** kwargs ) else : ( data ) = self . replace_node_status_with_http_info ( name , body , ** kwargs ) return data
def get_thumbnail_name ( self , thumbnail_options , transparent = False , high_resolution = False ) : """A version of ` ` Thumbnailer . get _ thumbnail _ name ` ` that returns the original filename to resize ."""
path , filename = os . path . split ( self . name ) basedir = self . thumbnail_basedir subdir = self . thumbnail_subdir return os . path . join ( basedir , path , subdir , filename )
def from_parmed ( cls , path , * args , ** kwargs ) : """Try to load a file automatically with ParmEd . Not guaranteed to work , but might be useful if it succeeds . Arguments path : str Path to file that ParmEd can load"""
st = parmed . load_file ( path , structure = True , * args , ** kwargs ) box = kwargs . pop ( 'box' , getattr ( st , 'box' , None ) ) velocities = kwargs . pop ( 'velocities' , getattr ( st , 'velocities' , None ) ) positions = kwargs . pop ( 'positions' , getattr ( st , 'positions' , None ) ) return cls ( master = st ...
def get_library_instance ( self , library_path , library_name ) : """Generate a Library instance from within libraries dictionary tree ."""
if self . is_library_in_libraries ( library_path , library_name ) : from rafcon . core . states . library_state import LibraryState return LibraryState ( library_path , library_name , "0.1" ) else : logger . warning ( "Library manager will not create a library instance which is not in the mounted libraries....
def extend ( self , * bindings ) : """Append the given bindings to this keymap . Arguments : * bindings ( Binding ) : Bindings to be added . Returns : Keymap : self"""
self . _bindings . extend ( self . _preprocess ( bindings ) ) return self
def _parse_volume_descriptors ( self ) : # type : ( ) - > None '''An internal method to parse the volume descriptors on an ISO . Parameters : None . Returns : Nothing .'''
# Ecma - 119 says that the Volume Descriptor set is a sequence of volume # descriptors recorded in consecutively numbered Logical Sectors # starting with Logical Sector Number 16 . Since sectors are 2048 bytes # in length , we start at sector 16 * 2048 # Ecma - 119 , 6.2.1 says that the Volume Space is divided into a S...
def open ( self ) : """Open an existing database"""
if self . _table_exists ( ) : self . mode = "open" # get table info self . _get_table_info ( ) return self else : # table not found raise IOError , "Table %s doesn't exist" % self . name
def get_definition ( self ) : """Add Definition to XMLBIF Return dict : dict of type { variable : definition tag } Examples > > > writer = XMLBIFWriter ( model ) > > > writer . get _ definition ( ) { ' hear - bark ' : < Element DEFINITION at 0x7f1d48977408 > , ' family - out ' : < Element DEFINITION a...
cpds = self . model . get_cpds ( ) cpds . sort ( key = lambda x : x . variable ) definition_tag = { } for cpd in cpds : definition_tag [ cpd . variable ] = etree . SubElement ( self . network , "DEFINITION" ) etree . SubElement ( definition_tag [ cpd . variable ] , "FOR" ) . text = cpd . variable for child ...
def _sector_erase_program_double_buffer ( self , progress_cb = _stub_progress ) : """! @ brief Double - buffered program by performing sector erases ."""
actual_sector_erase_count = 0 actual_sector_erase_weight = 0 progress = 0 progress_cb ( 0.0 ) # Fill in same flag for all pages . This is done up front so we ' re not trying # to read from flash while simultaneously programming it . progress = self . _scan_pages_for_same ( progress_cb ) # Erase all sectors up front . s...
def get_orders ( self , address , chain_name = 'NEO' , contract_version = 'V2' , pair = None , from_epoch_time = None , order_status = None , before_id = None , limit = 50 ) : """Function to fetch the order history of the given address . Execution of this function is as follows : : get _ orders ( address = neo ...
api_params = { "address" : address , "contract_hash" : self . get_contracts ( ) [ chain_name . upper ( ) ] [ contract_version . upper ( ) ] , "limit" : limit } if pair is not None : api_params [ 'pair' ] = pair if from_epoch_time is not None : api_params [ 'from_epoch_time' ] = from_epoch_time if order_status i...
def _printedby_data ( self , ws ) : """Returns a dict that represents the user who prints the ws Keys : username , fullname , email"""
data = { } member = self . context . portal_membership . getAuthenticatedMember ( ) if member : username = member . getUserName ( ) data [ 'username' ] = username data [ 'fullname' ] = to_utf8 ( self . user_fullname ( username ) ) data [ 'email' ] = to_utf8 ( self . user_email ( username ) ) c = [ x...
def get_document ( self , doc_url , force_download = False ) : """Retrieve the data for the given document from the server : type doc _ url : String or Document : param doc _ url : the URL of the document , or a Document object : type force _ download : Boolean : param force _ download : True to download fr...
doc_url = str ( doc_url ) if ( self . use_cache and not force_download and self . cache . has_document ( doc_url ) ) : doc_data = self . cache . get_document ( doc_url ) else : doc_data = self . api_request ( doc_url , raw = True ) if self . update_cache : self . cache . add_document ( doc_url , doc...
def addStampAnnot ( self , rect , stamp = 0 ) : """Add a ' rubber stamp ' in a rectangle ."""
CheckParent ( self ) val = _fitz . Page_addStampAnnot ( self , rect , stamp ) if not val : return val . thisown = True val . parent = weakref . proxy ( self ) self . _annot_refs [ id ( val ) ] = val return val
def sendline ( self , text ) : """Sends an input line to the running program , including os . linesep . Args : text ( str ) : The input text to be send . Raises : TerminationException : The program terminated before / while / after sending the input . NestedException : An internal problem occured while wa...
logger . debug ( "Sending input '{0}' to '{1}'" . format ( text , self . name ) ) try : return self . _spawn . sendline ( text ) except pexpect . exceptions . EOF as e : logger . debug ( "Raising termination exception." ) raise TerminationException ( instance = self , real_exception = e , output = self . ge...
def fit ( self , data , debug = False ) : """Fit each of the models in the group . Parameters data : pandas . DataFrame Must have a column with the same name as ` segmentation _ col ` . debug : bool If set to true ( default false ) will pass the debug parameter to model estimation . Returns fits : d...
with log_start_finish ( 'fitting models in group {}' . format ( self . name ) , logger ) : return { name : self . models [ name ] . fit ( df , debug = debug ) for name , df in self . _iter_groups ( data ) }
def _get_available ( recommended = False , restart = False ) : '''Utility function to get all available update packages . Sample return date : { ' updatename ' : ' 1.2.3-45 ' , . . . }'''
cmd = [ 'softwareupdate' , '--list' ] out = salt . utils . mac_utils . execute_return_result ( cmd ) # rexp parses lines that look like the following : # * Safari6.1.2MountainLion - 6.1.2 # Safari ( 6.1.2 ) , 51679K [ recommended ] # - iCal - 1.0.2 # iCal , 1.0.2 , 6520K rexp = re . compile ( '(?m)^ [*|-] ' r'([^ ].*...
def get_distributed_seismicity_source_nodes ( source ) : """Returns list of nodes of attributes common to all distributed seismicity source classes : param source : Seismic source as instance of : class : ` openquake . hazardlib . source . area . AreaSource ` or : class : ` openquake . hazardlib . source ...
source_nodes = [ ] # parse msr source_nodes . append ( Node ( "magScaleRel" , text = source . magnitude_scaling_relationship . __class__ . __name__ ) ) # Parse aspect ratio source_nodes . append ( Node ( "ruptAspectRatio" , text = source . rupture_aspect_ratio ) ) # Parse MFD source_nodes . append ( obj_to_node ( sourc...
def loop_through_agency ( self ) : """Loop through an agency to grab the definitions for its tables ."""
agency = self . agency with open ( agency + '.txt' ) as f : data = eval ( f . read ( ) ) for table in data : for column in data [ table ] : value_link = data [ table ] [ column ] data [ table ] [ column ] = self . grab_definition ( value_link ) data = json . dumps ( data ) with open ( agency + '...
def patched_packing_env ( env ) : """Monkey patch packaging . markers . default _ environment"""
old_env = pkg_resources . packaging . markers . default_environment new_env = lambda : env pkg_resources . _vendor . packaging . markers . default_environment = new_env try : yield finally : pkg_resources . _vendor . packaging . markers . default_environment = old_env
def override_level_names ( self , mapping ) : """Rename level names . : param mapping : Mapping level names to new ones : type mapping : dict"""
if not isinstance ( mapping , dict ) : return for key , val in mapping . items ( ) : if key in self . _level_names : self . _level_names [ key ] = val
def create ( self , name , * args , ** kwargs ) : """Standard task creation , but first check for the existence of the containers , and raise an exception if they don ' t exist ."""
cont = kwargs . get ( "cont" ) if cont : # Verify that it exists . If it doesn ' t , a NoSuchContainer exception # will be raised . api = self . api rgn = api . region_name cf = api . identity . object_store [ rgn ] . client cf . get_container ( cont ) return super ( ImageTasksManager , self ) . create ...
def create_package ( self , dirpath ) : """Set up a package directory ."""
dirpath = fixpath ( dirpath ) filepath = os . path . join ( dirpath , "__coconut__.py" ) with openfile ( filepath , "w" ) as opened : writefile ( opened , self . comp . getheader ( "__coconut__" ) )
def sbessely ( x , N ) : """Returns a vector of spherical bessel functions yn : x : The argument . N : values of n will run from 0 to N - 1."""
out = np . zeros ( N , dtype = np . float64 ) out [ 0 ] = - np . cos ( x ) / x out [ 1 ] = - np . cos ( x ) / ( x ** 2 ) - np . sin ( x ) / x for n in xrange ( 2 , N ) : out [ n ] = ( ( 2.0 * n - 1.0 ) / x ) * out [ n - 1 ] - out [ n - 2 ] return out
def _stream ( self ) : """Returns a generator of lines instead of a list of lines ."""
if self . _exception : raise self . _exception try : if self . _content : yield self . _content else : args = self . create_args ( ) with self . ctx . connect ( * args , env = self . create_env ( ) , timeout = self . timeout ) as s : yield s except StopIteration : rai...
def _ibis_sqlite_regex_extract ( string , pattern , index ) : """Extract match of regular expression ` pattern ` from ` string ` at ` index ` . Parameters string : str pattern : str index : int Returns result : str or None"""
result = re . search ( pattern , string ) if result is not None and 0 <= index <= ( result . lastindex or - 1 ) : return result . group ( index ) return None
def transaction ( self , session = None ) : """Start a new transaction based on the passed session object . If session is not passed , then create one and make sure of closing it finally ."""
local_session = None if session is None : local_session = session = self . create_scoped_session ( ) try : yield session finally : # Since ` ` local _ session ` ` was created locally , close it here itself if local_session is not None : # but wait ! # http : / / groups . google . com / group / sqlalchem...
def restore_package_version_from_recycle_bin ( self , package_version_details , feed , group_id , artifact_id , version ) : """RestorePackageVersionFromRecycleBin . [ Preview API ] Restore a package version from the recycle bin to its associated feed . : param : class : ` < MavenRecycleBinPackageVersionDetails ...
route_values = { } if feed is not None : route_values [ 'feed' ] = self . _serialize . url ( 'feed' , feed , 'str' ) if group_id is not None : route_values [ 'groupId' ] = self . _serialize . url ( 'group_id' , group_id , 'str' ) if artifact_id is not None : route_values [ 'artifactId' ] = self . _serialize...
def reset_api_secret ( context , id , etag ) : """reset _ api _ secret ( context , id , etag ) Reset a Feeder api _ secret . > > > dcictl feeder - reset - api - secret [ OPTIONS ] : param string id : ID of the feeder [ required ] : param string etag : Entity tag of the feeder resource [ required ]"""
result = feeder . reset_api_secret ( context , id = id , etag = etag ) utils . format_output ( result , context . format , headers = [ 'id' , 'api_secret' , 'etag' ] )
def get_modified_files ( ) : """Returns a list of all modified files ."""
c = subprocess . Popen ( [ "git" , "diff-index" , "--cached" , "--name-only" , "HEAD" ] , stdout = subprocess . PIPE ) return c . communicate ( ) [ 0 ] . splitlines ( )
def _initialize_random_state ( self , seed = None , shared = True , name = None ) : """Initialization method to be called in the constructor of subclasses to initialize the random state correctly . If seed is None , there is no control over the random stream ( no reproducibility of the stream ) . If shared ...
if seed is None : # Equivalent to an uncontrolled seed . seed = random . Random ( ) . randint ( 0 , 1000000 ) suffix = '' else : suffix = str ( seed ) # If time _ dependent , independent state required : otherwise # time - dependent seeding ( via hash ) will affect shared # state . Note that if all objects ...
def connect ( self , callback , weak = False ) : """Connects a new callback to this signal . : param callback : The callback to connect . : param weak : If ` True ` , only holds a weak reference to the specified callback . ` callback ` will be called whenever ` emit ` gets called on the ` Signal ` instanc...
if weak : callback = ref ( callback , self . _disconnect ) with self . _write_lock : with self . _read_lock : self . _callbacks . append ( callback )