signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def add_transform_columns ( self ) : """add transformed values to the Pst . parameter _ data attribute"""
for col in [ "parval1" , "parlbnd" , "parubnd" , "increment" ] : if col not in self . parameter_data . columns : continue self . parameter_data . loc [ : , col + "_trans" ] = ( self . parameter_data . loc [ : , col ] * self . parameter_data . scale ) + self . parameter_data . offset # isnotfixed = s...
def get_wellseries ( self , matrix ) : """Returns the grid as a WellSeries of WellSeries"""
res = OrderedDict ( ) for col , cells in matrix . items ( ) : if col not in res : res [ col ] = OrderedDict ( ) for row , cell in cells . items ( ) : res [ col ] [ row ] = self . children_by_name [ '' . join ( cell ) ] res [ col ] = WellSeries ( res [ col ] , name = col ) return WellSeries (...
def setZValue ( self , zValue ) : """Sets the z - value for this layer to the inputed value . : param zValue | < int > : return < bool > changed"""
if zValue == self . _zValue : return False self . _zValue = zValue self . sync ( ) return True
def to_pycbc ( self , copy = True ) : """Convert this ` TimeSeries ` into a PyCBC ` ~ pycbc . types . timeseries . TimeSeries ` Parameters copy : ` bool ` , optional , default : ` True ` if ` True ` , copy these data to a new array Returns timeseries : ` ~ pycbc . types . timeseries . TimeSeries ` a P...
from pycbc import types return types . TimeSeries ( self . value , delta_t = self . dt . to ( 's' ) . value , epoch = self . epoch . gps , copy = copy )
def _multi_deref ( tensors : List [ tf . Tensor ] , index : tf . Tensor ) -> List [ tf . Tensor ] : """Equivalent to ` [ t [ index , . . . ] for t in tensors ] ` . See ` _ deref ` for more details ."""
assert tensors assert tensors [ 0 ] . shape [ 0 ] > 0 return _deref_helper ( lambda i : [ tensor [ i , ... ] for tensor in tensors ] , index , 0 , tensors [ 0 ] . shape [ 0 ] - 1 )
def _translate_pattern ( self , pattern , anchor = True , prefix = None , is_regex = False ) : """Translate a shell - like wildcard pattern to a compiled regular expression . Return the compiled regex . If ' is _ regex ' true , then ' pattern ' is directly compiled to a regex ( if it ' s a string ) or just ...
if is_regex : if isinstance ( pattern , str ) : return re . compile ( pattern ) else : return pattern if _PYTHON_VERSION > ( 3 , 2 ) : # ditch start and end characters start , _ , end = self . _glob_to_re ( '_' ) . partition ( '_' ) if pattern : pattern_re = self . _glob_to_re ( pattern ...
def tagged ( * tags : Tags ) -> Callable : global GREENSIM_TAG_ATTRIBUTE """Decorator for adding a label to the process . These labels are applied to any child Processes produced by event"""
def hook ( event : Callable ) : def wrapper ( * args , ** kwargs ) : event ( * args , ** kwargs ) setattr ( wrapper , GREENSIM_TAG_ATTRIBUTE , tags ) return wrapper return hook
def printImportedNames ( self ) : """Produce a report of imported names ."""
for module in self . listModules ( ) : print ( "%s:" % module . modname ) print ( " %s" % "\n " . join ( imp . name for imp in module . imported_names ) )
def parse_match ( match ) : """Accept an re match object resulting from an ` ` UPLOAD _ RE ` ` match and return a two - tuple where the first element is the corresponding ` ` FileUpload ` ` and the second is a dictionary of the key = value options . If there is no ` ` FileUpload ` ` object corresponding to ...
try : upload = FileUpload . objects . get ( slug = match . group ( 1 ) ) except FileUpload . DoesNotExist : upload = None options = parse_options ( match . group ( 2 ) ) return ( upload , options )
def merge_requests ( self , ** kwargs ) : """List the merge requests related to this milestone . Args : all ( bool ) : If True , return all the items , without pagination per _ page ( int ) : Number of items to retrieve per request page ( int ) : ID of the page to return ( starts with page 1) as _ list ( ...
path = '%s/%s/merge_requests' % ( self . manager . path , self . get_id ( ) ) data_list = self . manager . gitlab . http_list ( path , as_list = False , ** kwargs ) manager = ProjectMergeRequestManager ( self . manager . gitlab , parent = self . manager . _parent ) # FIXME ( gpocentek ) : the computed manager path is n...
def add ( self , addon , dev = False , interactive = True ) : """Add a new dependency and install it ."""
dependencies = self . get_dependency_manager ( dev = dev ) other_dependencies = self . get_dependency_manager ( dev = not dev ) existing = dependencies . get ( addon ) self . stdout . write ( style . format_command ( 'Adding' , addon ) ) dependencies . add ( addon ) try : # try running the build self . build ( ) ...
def ID_from_data ( self , ID_field = '$SRC' ) : '''Returns the well ID from the src keyword in the FCS file . ( e . g . , A2) This keyword may not appear in FCS files generated by other machines , in which case this function will raise an exception .'''
try : return self . get_meta_fields ( ID_field ) [ ID_field ] except KeyError : msg = "The keyword '{}' does not exist in the following FCS file: {}" msg = msg . format ( ID_field , self . datafile ) raise Exception ( msg )
def process ( self , key , val ) : """Try to look for ` key ` in all required and optional fields . If found , set the ` val ` ."""
for field in self . fields : if field . check ( key , val ) : return for field in self . optional : if field . check ( key , val ) : return
def winning_abbr ( self ) : """Returns a ` ` string ` ` of the winning team ' s abbreviation , such as ' ALABAMA ' for the Alabama Crimson Tide ."""
if self . winner == HOME : if 'cfb/schools' not in str ( self . _home_name ) : return self . _home_name . text ( ) return utils . _parse_abbreviation ( self . _home_name ) if 'cfb/schools' not in str ( self . _away_name ) : return self . _away_name . text ( ) return utils . _parse_abbreviation ( sel...
def extract_numeric_values_from_string ( str_contains_values ) : # type : ( AnyStr ) - > Optional [ List [ Union [ int , float ] ] ] """Find numeric values from string , e . g . , 1 , . 7 , 1.2 , 4e2 , 3e - 3 , - 9 , etc . Reference : ` how - to - extract - a - floating - number - from - a - string - in - python ...
numeric_const_pattern = r'[-+]?(?:(?:\d*\.\d+)|(?:\d+\.?))(?:[Ee][+-]?\d+)?' rx = re . compile ( numeric_const_pattern , re . VERBOSE ) value_strs = rx . findall ( str_contains_values ) if len ( value_strs ) == 0 : return None else : return [ int ( float ( v ) ) if float ( v ) % 1. == 0 else float ( v ) for v i...
def get_callable_fq_for_code ( code , locals_dict = None ) : """Determines the function belonging to a given code object in a fully qualified fashion . Returns a tuple consisting of - the callable - a list of classes and inner classes , locating the callable ( like a fully qualified name ) - a boolean indic...
if code in _code_callable_dict : res = _code_callable_dict [ code ] if not res [ 0 ] is None or locals_dict is None : return res md = getmodule ( code ) if not md is None : nesting = [ ] res , slf = _get_callable_fq_for_code ( code , md , md , False , nesting , set ( ) ) if res is None and n...
def recommend_get ( self , adgroup_id , ** kwargs ) : '''xxxxx . xxxxx . keywords . recommend . get 取得一个推广组的推荐关键词列表'''
request = TOPRequest ( 'xxxxx.xxxxx.keywords.recommend.get' ) request [ 'adgroup_id' ] = adgroup_id for k , v in kwargs . iteritems ( ) : if k not in ( 'nick' , 'order_by' , 'search' , 'pertinence' , 'page_size' , 'page_no' ) and v == None : continue request [ k ] = v self . create ( self . execute ( re...
def addElement ( self , etype = 'hex8' , corners = [ - 1.0 , - 1.0 , - 1.0 , 1. , - 1.0 , - 1.0 , 1.0 , 1.0 , - 1.0 , - 1.0 , 1.0 , - 1.0 , - 1.0 , - 1.0 , 1.0 , 1.0 , - 1.0 , 1.0 , 1.0 , 1.0 , 1.0 , - 1.0 , 1.0 , 1.0 ] , name = 'new_elem' ) : '''corners - list of nodal coordinates properly ordered for element type...
lastelm = self . elements [ - 1 ] [ 1 ] lastnode = self . nodes [ - 1 ] [ 0 ] elm = [ etype , lastelm + 1 ] for i in range ( old_div ( len ( corners ) , 3 ) ) : elm . append ( lastnode + 1 + i ) self . elements . append ( elm ) self . elsets [ 'e' + name ] = { } self . elsets [ 'e' + name ] [ int ( elm [ 1 ] ) ] = ...
def _print_value ( self ) : """Generates the table values ."""
for line in range ( self . Lines_num ) : for col , length in zip ( self . Table , self . AttributesLength ) : vals = list ( col . values ( ) ) [ 0 ] val = vals [ line ] if len ( vals ) != 0 and line < len ( vals ) else '' self . StrTable += "| " self . StrTable += self . _pad_string ...
def join_room ( self , room_name ) : """Connects to a given room If it does not exist it is created"""
logging . debug ( 'Joining room {ro}' . format ( ro = room_name ) ) for room in self . rooms : if room . name == room_name : room . add_user ( self ) self . _rooms [ room_name ] = room room . welcome ( self ) break else : room = Room ( room_name ) self . rooms . append ( room...
def add_line ( self , window , text , row = None , col = None , attr = None ) : """Unicode aware version of curses ' s built - in addnstr method . Safely draws a line of text on the window starting at position ( row , col ) . Checks the boundaries of the window and cuts off the text if it exceeds the length o...
# The following arg combos must be supported to conform with addnstr # ( window , text ) # ( window , text , attr ) # ( window , text , row , col ) # ( window , text , row , col , attr ) cursor_row , cursor_col = window . getyx ( ) row = row if row is not None else cursor_row col = col if col is not None else cursor_co...
def get_system_config_dir ( ) : """Returns system config location . E . g . / etc / dvc . conf . Returns : str : path to the system config directory ."""
from appdirs import site_config_dir return site_config_dir ( appname = Config . APPNAME , appauthor = Config . APPAUTHOR )
def anchor ( parser , token ) : """Parses a tag that ' s supposed to be in this format : { % anchor field title % }"""
bits = [ b . strip ( '"\'' ) for b in token . split_contents ( ) ] if len ( bits ) < 2 : raise TemplateSyntaxError , "anchor tag takes at least 1 argument" try : title = bits [ 2 ] except IndexError : title = bits [ 1 ] . capitalize ( ) return SortAnchorNode ( bits [ 1 ] . strip ( ) , title . strip ( ) )
def build_job_configs ( self , args ) : """Hook to build job configurations"""
job_configs = { } ttype = args [ 'ttype' ] ( sim_targets_yaml , sim ) = NAME_FACTORY . resolve_targetfile ( args ) targets = load_yaml ( sim_targets_yaml ) base_config = dict ( ttype = ttype , roi_baseline = args [ 'roi_baseline' ] , extracopy = args [ 'extracopy' ] , sim = sim ) for target_name in targets . keys ( ) :...
def get_meta_attribute ( self , param ) : """Retrieves django - meta attributes from apphook config instance : param param : django - meta attribute passed as key"""
return self . _get_meta_value ( param , getattr ( self . app_config , param ) ) or ''
def buffered_read ( fh , lock , offsets , bytecounts , buffersize = None ) : """Return iterator over segments read from file ."""
if buffersize is None : buffersize = 2 ** 26 length = len ( offsets ) i = 0 while i < length : data = [ ] with lock : size = 0 while size < buffersize and i < length : fh . seek ( offsets [ i ] ) bytecount = bytecounts [ i ] data . append ( fh . read ( byt...
def _apply_cached_indexes ( self , cached_indexes , persist = False ) : """Reassign various resampler index attributes ."""
# cacheable _ dict = { } for elt in [ 'valid_input_index' , 'valid_output_index' , 'index_array' , 'distance_array' ] : val = cached_indexes [ elt ] if isinstance ( val , tuple ) : val = cached_indexes [ elt ] [ 0 ] elif isinstance ( val , np . ndarray ) : val = da . from_array ( val , chunk...
def step ( self , actions ) : """Takes a step in all environments . Subclasses should override _ step to do the actual reset if something other than the default implementation is desired . Args : actions : Batch of actions . Returns : ( preprocessed _ observations , processed _ rewards , dones , infos )...
observations , raw_rewards , dones , infos = self . _step ( actions ) # Process rewards . raw_rewards = raw_rewards . astype ( np . float32 ) processed_rewards = self . process_rewards ( raw_rewards ) # Process observations . processed_observations = self . process_observations ( observations ) # Record history . self ...
def add_property_orders ( query_proto , * orders ) : """Add ordering constraint for the given datastore . Query proto message . Args : query _ proto : datastore . Query proto message . orders : list of propertype name string , default to ascending order and set descending if prefixed by ' - ' . Usage : ...
for order in orders : proto = query_proto . order . add ( ) if order [ 0 ] == '-' : order = order [ 1 : ] proto . direction = query_pb2 . PropertyOrder . DESCENDING else : proto . direction = query_pb2 . PropertyOrder . ASCENDING proto . property . name = order
def delete ( path , regex = None , recurse = False , test = False ) : """Deletes the file or directory at ` path ` . If ` path ` is a directory and ` regex ` is provided , matching files will be deleted ; ` recurse ` controls whether subdirectories are recursed . A list of deleted items is returned . If ` tes...
deleted = [ ] if op . isfile ( path ) : if not test : os . remove ( path ) else : return [ path ] return [ ] if op . exists ( path ) else [ path ] elif op . isdir ( path ) : if regex : for r , ds , fs in os . walk ( path ) : for i in fs : if _is_match ...
def detect_HouseDetector ( dat_orig , s_freq , time , opts ) : """House arousal detection . Parameters dat _ orig : ndarray ( dtype = ' float ' ) vector with the data for one channel s _ freq : float sampling frequency time : ndarray ( dtype = ' float ' ) vector with the time points for each sample ...
nperseg = int ( opts . spectrogram [ 'dur' ] * s_freq ) overlap = opts . spectrogram [ 'overlap' ] noverlap = int ( overlap * nperseg ) detrend = opts . spectrogram [ 'detrend' ] min_interval = int ( opts . min_interval * s_freq ) sf , t , dat_det = spectrogram ( dat_orig , fs = s_freq , nperseg = nperseg , noverlap = ...
def get_by_ip_hostname ( self , ip_hostname ) : """Retrieve a storage system by its IP . Works only with API version < = 300. Args : ip _ hostname : Storage system IP or hostname . Returns : dict"""
resources = self . _client . get_all ( ) resources_filtered = [ x for x in resources if x [ 'credentials' ] [ 'ip_hostname' ] == ip_hostname ] if resources_filtered : return resources_filtered [ 0 ] else : return None
def cmdloop ( self ) : """Start the main loop of the interactive shell . The preloop ( ) and postloop ( ) methods are always run before and after the main loop , respectively . Returns : ' root ' : Inform the parent shell to to keep exiting until the root shell is reached . ' all ' : Exit all the way ba...
self . print_debug ( "Enter subshell '{}'" . format ( self . prompt ) ) # Save the completer function , the history buffer , and the # completer _ delims . old_completer = readline . get_completer ( ) old_delims = readline . get_completer_delims ( ) new_delims = '' . join ( list ( set ( old_delims ) - set ( _ShellBase ...
def _as_rescale ( self , get , targetbitdepth ) : """Helper used by : meth : ` asRGB8 ` and : meth : ` asRGBA8 ` ."""
width , height , pixels , meta = get ( ) maxval = 2 ** meta [ 'bitdepth' ] - 1 targetmaxval = 2 ** targetbitdepth - 1 factor = float ( targetmaxval ) / float ( maxval ) meta [ 'bitdepth' ] = targetbitdepth def iterscale ( rows ) : for row in rows : yield array ( 'BH' [ targetbitdepth > 8 ] , [ int ( round (...
def del_store ( source , store , saltenv = 'base' ) : '''Delete the given cert into the given Certificate Store source The source certificate file this can be in the form salt : / / path / to / file store The certificate store to delete the certificate from saltenv The salt environment to use this is ...
cert_file = __salt__ [ 'cp.cache_file' ] ( source , saltenv ) serial = get_cert_serial ( cert_file ) cmd = "certutil.exe -delstore {0} {1}" . format ( store , serial ) return __salt__ [ 'cmd.run' ] ( cmd )
def get_pourbaix_domains ( pourbaix_entries , limits = None ) : """Returns a set of pourbaix stable domains ( i . e . polygons ) in pH - V space from a list of pourbaix _ entries This function works by using scipy ' s HalfspaceIntersection function to construct all of the 2 - D polygons that form the bounda...
if limits is None : limits = [ [ - 2 , 16 ] , [ - 4 , 4 ] ] # Get hyperplanes hyperplanes = [ np . array ( [ - PREFAC * entry . npH , - entry . nPhi , 0 , - entry . energy ] ) * entry . normalization_factor for entry in pourbaix_entries ] hyperplanes = np . array ( hyperplanes ) hyperplanes [ : , 2 ] = 1 max_contri...
def replace_namespaced_config_map ( self , name , namespace , body , ** kwargs ) : # noqa : E501 """replace _ namespaced _ config _ map # noqa : E501 replace the specified ConfigMap # noqa : E501 This method makes a synchronous HTTP request by default . To make an asynchronous HTTP request , please pass async...
kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'async_req' ) : return self . replace_namespaced_config_map_with_http_info ( name , namespace , body , ** kwargs ) # noqa : E501 else : ( data ) = self . replace_namespaced_config_map_with_http_info ( name , namespace , body , ** kwargs ) # no...
def add_key_path ( key_proto , * path_elements ) : """Add path elements to the given datastore . Key proto message . Args : key _ proto : datastore . Key proto message . * path _ elements : list of ancestors to add to the key . ( kind1 , id1 / name1 , . . . , kindN , idN / nameN ) , the last 2 elements re...
for i in range ( 0 , len ( path_elements ) , 2 ) : pair = path_elements [ i : i + 2 ] elem = key_proto . path . add ( ) elem . kind = pair [ 0 ] if len ( pair ) == 1 : return # incomplete key id_or_name = pair [ 1 ] if isinstance ( id_or_name , ( int , long ) ) : elem . i...
def build_pub_dates ( article , pub_dates ) : "convert pub _ dates into ArticleDate objects and add them to article"
for pub_date in pub_dates : # always want a date type , take it from pub - type if must if pub_date . get ( 'date-type' ) : date_instance = ea . ArticleDate ( pub_date . get ( 'date-type' ) , pub_date . get ( 'date' ) ) elif pub_date . get ( 'pub-type' ) : date_instance = ea . ArticleDate ( pub_...
def terminate ( self , nodes = None ) : """Destroy one or many nodes . : param nodes : Nodes to be destroyed . : type nodes : ` ` list ` ` : return : List of nodes which failed to terminate . : rtype : ` ` list ` `"""
if not self . is_connected ( ) : return None nodes = nodes or self . nodes failed_kill = [ ] result = self . gce . ex_destroy_multiple_nodes ( nodes , poll_interval = 1 , ignore_errors = False ) # Verify whether all instances have been terminated . for i , success in enumerate ( result ) : if success : ...
def get_name ( self ) : """@ rtype : str @ return : Module name , as used in labels . @ warning : Names are B { NOT } guaranteed to be unique . If you need unique identification for a loaded module , use the base address instead . @ see : L { get _ label }"""
pathname = self . get_filename ( ) if pathname : modName = self . __filename_to_modname ( pathname ) if isinstance ( modName , compat . unicode ) : try : modName = modName . encode ( 'cp1252' ) except UnicodeEncodeError : e = sys . exc_info ( ) [ 1 ] warnings ...
def _get_message ( self , key , since = None ) : """Return the MdMessage object for the key . The object is either returned from the cache in the store or made , cached and then returned . If ' since ' is passed in the modification time of the file is checked and the message is only returned if the mtime is...
stored = self . store [ key ] if isinstance ( stored , dict ) : filename = stored [ "path" ] folder = stored [ "folder" ] if since and since > 0.0 : st = stat ( filename ) if st . st_mtime < since : return None stored = MdMessage ( key , filename = filename , folder = folder ...
def match_tracks ( self , set_a , set_b , closest_matches = False ) : """Find the optimal set of matching assignments between set a and set b . This function supports optimal 1:1 matching using the Munkres method and matching from every object in set a to the closest object in set b . In this situation set b ac...
costs = self . track_cost_matrix ( set_a , set_b ) * 100 min_row_costs = costs . min ( axis = 1 ) min_col_costs = costs . min ( axis = 0 ) good_rows = np . where ( min_row_costs < 100 ) [ 0 ] good_cols = np . where ( min_col_costs < 100 ) [ 0 ] assignments = [ ] if len ( good_rows ) > 0 and len ( good_cols ) > 0 : ...
def process_agreement_events_publisher ( publisher_account , agreement_id , did , service_agreement , price , consumer_address , condition_ids ) : """Process the agreement events during the register of the service agreement for the publisher side : param publisher _ account : Account instance of the publisher :...
conditions_dict = service_agreement . condition_by_name events_manager = EventsManager . get_instance ( Keeper . get_instance ( ) ) events_manager . watch_lock_reward_event ( agreement_id , access_secret_store_condition . fulfillAccessSecretStoreCondition , None , ( agreement_id , did , service_agreement , consumer_add...
def child_task ( self ) : '''child process - this holds all the GUI elements'''
self . parent_pipe_send . close ( ) self . parent_pipe_recv . close ( ) from MAVProxy . modules . lib import wx_processguard from MAVProxy . modules . lib . wx_loader import wx from MAVProxy . modules . lib . wxconsole_ui import ConsoleFrame app = wx . App ( False ) app . frame = ConsoleFrame ( state = self , title = s...
def bld_rafter_deflection ( length = - 9 , force = - 9 , E_mod_elasticity = - 9 , I_moment_of_intertia = - 9 ) : """calculate rafter deflections - see test _ calc _ building _ design . py for Sample values for equations below from Structures II course"""
if length == - 9 : length = float ( input ( 'enter rafter length : ' ) ) if force == - 9 : force = float ( input ( 'enter Force or weight applied to roof : ' ) ) if E_mod_elasticity == - 9 : E_mod_elasticity = float ( input ( 'enter modulus of elasticity x10**5 (Steel beam example=2.1) : ' ) ) if I_moment_o...
def subscribe ( user_id , to_all = False , campaign_ids = None , on_error = None , on_success = None ) : """Resubscribe a user to some or all campaigns . : param str | number user _ id : the id you use to identify a user . this should be static for the lifetime of a user . : param bool to _ all True to reubsc...
__subscription ( user_id , unsubscribe = False , all_campaigns = to_all , campaign_ids = campaign_ids , on_error = on_error , on_success = on_success , )
def utf8 ( value ) : """Converts a string argument to a byte string . If the argument is already a byte string or None , it is returned unchanged . Otherwise it must be a unicode string and is encoded as utf8."""
if isinstance ( value , _UTF8_TYPES ) : return value if not isinstance ( value , unicode_type ) : raise TypeError ( "Expected bytes, unicode, or None; got %r" % type ( value ) ) return value . encode ( "utf-8" )
def create_signature ( key_dict , data ) : """< Purpose > Return a signature dictionary of the form : { ' keyid ' : ' f30a0870d026980100c0573bd557394f8c1bbd6 . . . ' , ' sig ' : ' . . . ' } . The signing process will use the private key in key _ dict [ ' keyval ' ] [ ' private ' ] and ' data ' to generate...
# Does ' key _ dict ' have the correct format ? # This check will ensure ' key _ dict ' has the appropriate number of objects # and object types , and that all dict keys are properly named . # Raise ' securesystemslib . exceptions . FormatError ' if the check fails . # The key type of ' key _ dict ' must be either ' rs...
async def storm ( self , text , opts = None , user = None ) : '''Evaluate a storm query and yield ( node , path ) tuples . Yields : ( Node , Path ) tuples'''
if user is None : user = self . auth . getUserByName ( 'root' ) await self . boss . promote ( 'storm' , user = user , info = { 'query' : text } ) async with await self . snap ( user = user ) as snap : async for mesg in snap . storm ( text , opts = opts , user = user ) : yield mesg
def prob_lnm ( m1 , m2 , s1z , s2z , ** kwargs ) : '''Return probability density for uniform in log Parameters m1 : array Component masses 1 m2 : array Component masses 2 s1z : array Aligned spin 1 ( Not in use currently ) s2z : Aligned spin 2 ( Not in use currently ) * * kwargs : string Keywo...
min_mass = kwargs . get ( 'min_mass' , 5. ) max_mass = kwargs . get ( 'max_mass' , 95. ) max_mtotal = min_mass + max_mass m1 , m2 = np . array ( m1 ) , np . array ( m2 ) C_lnm = integrate . quad ( lambda x : ( log ( max_mtotal - x ) - log ( min_mass ) ) / x , min_mass , max_mass ) [ 0 ] xx = np . minimum ( m1 , m2 ) m1...
def get_ast_dict ( belstr , component_type : str = "" ) : """Convert BEL string to AST dictionary Args : belstr : BEL string component _ type : Empty string or ' subject ' or ' object ' to indicate that we are parsing the subject or object field input"""
errors = [ ] parsed = { } bels = list ( belstr ) char_locs , errors = parse_chars ( bels , errors ) parsed , errors = parse_functions ( belstr , char_locs , parsed , errors ) parsed , errors = parse_args ( bels , char_locs , parsed , errors ) parsed , errors = arg_types ( parsed , errors ) parsed , errors = parse_relat...
def register ( linter ) : '''Required method to auto register this checker'''
linter . register_checker ( ResourceLeakageChecker ( linter ) ) linter . register_checker ( BlacklistedImportsChecker ( linter ) ) linter . register_checker ( MovedTestCaseClassChecker ( linter ) ) linter . register_checker ( BlacklistedLoaderModulesUsageChecker ( linter ) ) linter . register_checker ( BlacklistedFunct...
def timestamps ( self ) : '''Get all timestamps from all series in the group .'''
timestamps = set ( ) for series in self . groups . itervalues ( ) : timestamps |= set ( series . timestamps ) return sorted ( list ( timestamps ) )
def density ( self ) : """Gives emprical PDF , like np . histogram ( . . . . , density = True )"""
h = self . histogram . astype ( np . float ) bindifs = np . array ( np . diff ( self . bin_edges ) , float ) return h / ( bindifs * self . n )
def draw ( self ) : """Draws the Plot to screen . If there is a continuous datatype for the nodes , it will be reflected in self . sm being constructed ( in ` compute _ node _ colors ` ) . It will then automatically add in a colorbar to the plot and scale the plot axes accordingly ."""
self . draw_nodes ( ) self . draw_edges ( ) # note that self . groups only exists on condition # that group _ label _ position was given ! if hasattr ( self , "groups" ) and self . groups : self . draw_group_labels ( ) logging . debug ( "DRAW: {0}" . format ( self . sm ) ) if self . sm : self . figure . subplot...
def set_privkey_compressed ( privkey , compressed = True ) : """Make sure the private key given is compressed or not compressed"""
if len ( privkey ) != 64 and len ( privkey ) != 66 : raise ValueError ( "expected 32-byte private key as a hex string" ) # compressed ? if compressed and len ( privkey ) == 64 : privkey += '01' if not compressed and len ( privkey ) == 66 : if privkey [ - 2 : ] != '01' : raise ValueError ( "private k...
def parse ( self , fileobj , name_hint = '' , parser = None ) : """Fill from a file - like object ."""
self . current_block = None # Reset current block parser = parser or Parser ( ) for line in parser . parse ( fileobj , name_hint = name_hint ) : self . handle_line ( line )
def reset_namespace ( self , namespace = None , params = None ) : """Will delete and recreate specified namespace args : namespace ( str ) : Namespace to reset params ( dict ) : params used to reset the namespace"""
namespace = pick ( namespace , self . namespace ) params = pick ( params , self . namespace_params ) log . warning ( " Reseting namespace '%s' at host: %s" , namespace , self . url ) try : self . delete_namespace ( namespace ) except KeyError : pass self . create_namespace ( namespace , params )
def get_midi_data ( self ) : """Collect and return the raw , binary MIDI data from the tracks ."""
tracks = [ t . get_midi_data ( ) for t in self . tracks if t . track_data != '' ] return self . header ( ) + '' . join ( tracks )
def is_connected ( self ) : """Returns * True * if the SMTP connection is initialized and connected . Otherwise returns * False *"""
try : self . _conn . noop ( ) except ( AttributeError , smtplib . SMTPServerDisconnected ) : return False else : return True
def add_source ( self , label , source_type , ** kwargs ) : """Add a source to the spec . Sources should have a unique label . This will help tracing where your configurations are coming from if you turn up the log - level . The keyword arguments are significant . Different sources require different keyword...
self . _sources [ label ] = get_source ( label , source_type , ** kwargs )
def timesince ( dt , default = 'just now' ) : '''Returns string representing ' time since ' e . g . 3 days ago , 5 hours ago etc . > > > now = datetime . datetime . now ( ) > > > timesince ( now ) ' just now ' > > > timesince ( now - datetime . timedelta ( seconds = 1 ) ) '1 second ago ' > > > timesin...
if isinstance ( dt , datetime . timedelta ) : diff = dt else : now = datetime . datetime . now ( ) diff = abs ( now - dt ) periods = ( ( diff . days / 365 , 'year' , 'years' ) , ( diff . days % 365 / 30 , 'month' , 'months' ) , ( diff . days % 30 / 7 , 'week' , 'weeks' ) , ( diff . days % 7 , 'day' , 'days'...
def generate_binary ( outputfname , format_ , progname = '' , binary_files = None , headless_binary_files = None ) : """Outputs the memory binary to the output filename using one of the given formats : tap , tzx or bin"""
global AUTORUN_ADDR org , binary = MEMORY . dump ( ) if gl . has_errors : return if binary_files is None : binary_files = [ ] if headless_binary_files is None : headless_binary_files = [ ] bin_blocks = [ ] for fname in binary_files : with api . utils . open_file ( fname ) as f : bin_blocks . app...
def _read_packet ( self ) : """Reads next TDS packet from the underlying transport If timeout is happened during reading of packet ' s header will cancel current request . Can only be called when transport ' s read pointer is at the begining of the packet ."""
try : pos = 0 while pos < _header . size : received = self . _transport . recv_into ( self . _bufview [ pos : _header . size - pos ] ) if received == 0 : raise tds_base . ClosedConnectionError ( ) pos += received except tds_base . TimeoutError : self . _session . put_canc...
def pathpatch_2d_to_3d ( pathpatch , z = 0 , normal = 'z' ) : """Transforms a 2D Patch to a 3D patch using the given normal vector . The patch is projected into they XY plane , rotated about the origin and finally translated by z ."""
if type ( normal ) is str : # Translate strings to normal vectors index = "xyz" . index ( normal ) normal = np . roll ( ( 1.0 , 0 , 0 ) , index ) normal /= np . linalg . norm ( normal ) # Make sure the vector is normalised path = pathpatch . get_path ( ) # Get the path and the associated transform trans = pathp...
def closest_points ( S ) : """Closest pair of points : param S : list of points : requires : size of S at least 2 : modifies : changes the order in S : returns : pair of points p , q from S with minimum Euclidean distance : complexity : expected linear time"""
shuffle ( S ) assert len ( S ) >= 2 p = S [ 0 ] q = S [ 1 ] d = dist ( p , q ) while d > 0 : r = improve ( S , d ) if r : d , p , q = r else : break return p , q
def render_iconchoicefield ( field , attrs ) : """Render a ChoiceField with icon support ; where the value is split by a pipe ( | ) : first element being the value , last element is the icon ."""
choices = "" # Loop over every choice to manipulate for choice in field . field . _choices : value = choice [ 1 ] . split ( "|" ) # Value | Icon # Each choice is formatted with the choice value being split with # the " | " as the delimeter . First element is the value , the second # is the icon to b...
def distinct_seeds ( k ) : """returns k distinct seeds for random number generation"""
seeds = [ ] for _ in range ( k ) : while True : s = random . randint ( 2 ** 32 - 1 ) if s not in seeds : break seeds . append ( s ) return seeds
def verify_header_chain ( cls , path , chain = None ) : """Verify that a given chain of block headers has sufficient proof of work ."""
if chain is None : chain = SPVClient . load_header_chain ( path ) prev_header = chain [ 0 ] for i in xrange ( 1 , len ( chain ) ) : header = chain [ i ] height = header . get ( 'block_height' ) prev_hash = prev_header . get ( 'hash' ) if prev_hash != header . get ( 'prev_block_hash' ) : log ...
def list_ext ( self , collection , path , retrieve_all , ** _params ) : """Client extension hook for list ."""
return self . list ( collection , path , retrieve_all , ** _params )
def vectorize_inhibit ( audio : np . ndarray ) -> np . ndarray : """Returns an array of inputs generated from the wake word audio that shouldn ' t cause an activation"""
def samp ( x ) : return int ( pr . sample_rate * x ) inputs = [ ] for offset in range ( samp ( inhibit_t ) , samp ( inhibit_dist_t ) , samp ( inhibit_hop_t ) ) : if len ( audio ) - offset < samp ( pr . buffer_t / 2. ) : break inputs . append ( vectorize ( audio [ : - offset ] ) ) return np . array (...
def get_all_mfa_devices ( self , user_name , marker = None , max_items = None ) : """Get all MFA devices associated with an account . : type user _ name : string : param user _ name : The username of the user : type marker : string : param marker : Use this only when paginating results and only in follow ...
params = { 'UserName' : user_name } if marker : params [ 'Marker' ] = marker if max_items : params [ 'MaxItems' ] = max_items return self . get_response ( 'ListMFADevices' , params , list_marker = 'MFADevices' )
def save_plots ( self , directory , format = "png" , recommended_only = False ) : """Save images of dose - response curve - fits for each model . Parameters directory : str Directory where the PNG files will be saved . format : str , optional Image output format . Valid options include : png , pdf , svg ,...
for i , session in enumerate ( self ) : session . save_plots ( directory , prefix = str ( i ) , format = format , recommended_only = recommended_only )
def get_section_path ( section ) : """Return a list with keys to access the section from root : param section : A Section : type section : Section : returns : list of strings in the order to access the given section from root : raises : None"""
keys = [ ] p = section for i in range ( section . depth ) : keys . insert ( 0 , p . name ) p = p . parent return keys
def version_option ( f ) : """Largely a custom clone of click . version _ option - - almost identical , but prints our special output ."""
def callback ( ctx , param , value ) : # copied from click . decorators . version _ option # no idea what resilient _ parsing means , but . . . if not value or ctx . resilient_parsing : return print_version ( ) ctx . exit ( 0 ) return click . option ( "--version" , is_flag = True , expose_value = Fa...
def download_url ( url , destination , retries = None , retry_delay = None , runner = None ) : """Download the given URL with wget to the provided path . The command is run via Fabric on the current remote machine . Therefore , the destination path should be for the remote machine . : param str url : URL to d...
runner = runner if runner is not None else FabRunner ( ) return try_repeatedly ( lambda : runner . run ( "wget --quiet --output-document '{0}' '{1}'" . format ( destination , url ) ) , max_retries = retries , delay = retry_delay )
def delete_idx_status ( self , rdf_class ) : """Removes all of the index status triples from the datastore Args : rdf _ class : The class of items to remove the status from"""
sparql_template = """ DELETE {{ ?s kds:esIndexTime ?esTime . ?s kds:esIndexError ?esError . }} WHERE {{ VALUES ?rdftypes {{\n\t\t{} }} . ?s a ?rdftypes . OPTIONAL {{ ...
def decompose ( df , period = 365 , lo_frac = 0.6 , lo_delta = 0.01 ) : """Create a seasonal - trend ( with Loess , aka " STL " ) decomposition of observed time series data . This implementation is modeled after the ` ` statsmodels . tsa . seasonal _ decompose ` ` method but substitutes a Lowess regression for ...
# use some existing pieces of statsmodels lowess = sm . nonparametric . lowess _pandas_wrapper , _ = _maybe_get_pandas_wrapper_freq ( df ) # get plain np array observed = np . asanyarray ( df ) . squeeze ( ) # calc trend , remove from observation trend = lowess ( observed , [ x for x in range ( len ( observed ) ) ] , f...
def p_lconcatlist ( self , p ) : 'lconcatlist : lconcatlist COMMA lconcat _ one'
p [ 0 ] = p [ 1 ] + ( p [ 3 ] , ) p . set_lineno ( 0 , p . lineno ( 1 ) )
def exit_standby ( name , instance_ids , should_decrement_desired_capacity = False , region = None , key = None , keyid = None , profile = None ) : '''Exit desired instances from StandBy mode . . versionadded : : 2016.11.0 CLI example : : salt - call boto _ asg . exit _ standby my _ autoscale _ group _ name '...
conn = _get_conn_autoscaling_boto3 ( region = region , key = key , keyid = keyid , profile = profile ) try : response = conn . exit_standby ( InstanceIds = instance_ids , AutoScalingGroupName = name ) except ClientError as e : err = __utils__ [ 'boto3.get_error' ] ( e ) if e . response . get ( 'Error' , { }...
def rsr ( self ) : """A getter for the relative spectral response ( rsr ) curve"""
arr = np . array ( [ self . wave . value , self . throughput ] ) . swapaxes ( 0 , 1 ) return arr
def update_copyright ( path , year ) : """Update a file ' s copyright statement to include the given year"""
with open ( path , "r" ) as fobj : text = fobj . read ( ) . rstrip ( ) match = COPYRIGHT_REGEX . search ( text ) x = match . start ( "years" ) y = match . end ( "years" ) if text [ y - 1 ] == " " : # don ' t strip trailing whitespace y -= 1 yearstr = match . group ( "years" ) years = set ( _parse_years ( yearst...
def state_size ( self ) : """Tuple of ` tf . TensorShape ` s indicating the size of state tensors ."""
hidden_size = tf . TensorShape ( self . _input_shape [ : - 1 ] + ( self . _output_channels , ) ) return ( hidden_size , hidden_size )
def get_all ( ) : '''Return a list of all available services CLI Example : . . code - block : : bash salt ' * ' service . get _ all'''
if not os . path . isdir ( _GRAINMAP . get ( __grains__ . get ( 'os' ) , '/etc/init.d' ) ) : return [ ] return sorted ( os . listdir ( _GRAINMAP . get ( __grains__ . get ( 'os' ) , '/etc/init.d' ) ) )
def _set_history ( self , v , load = False ) : """Setter method for history , mapped from YANG variable / cpu _ state / history ( container ) If this variable is read - only ( config : false ) in the source YANG file , then _ set _ history is considered as a private method . Backends looking to populate this ...
if hasattr ( v , "_utype" ) : v = v . _utype ( v ) try : t = YANGDynClass ( v , base = history . history , is_container = 'container' , presence = False , yang_name = "history" , rest_name = "history" , parent = self , path_helper = self . _path_helper , extmethods = self . _extmethods , register_paths = True ,...
def collection ( self , path ) : """To return all items generated by get collection ."""
data = [ ] for item in self . get_collection ( path ) : data . append ( item ) return data
def fetch ( self , query_string = "" , common_query_options = None , limit_since = False ) : """Backend for the actual gerrit query . query _ string : basic query terms , e . g . , ' status : abandoned ' common _ query _ options : [ optional ] rest of the query string ; if omitted , the default one is use...
work_list = [ ] log . info ( u"Searching for changes by {0}" . format ( self . user ) ) log . debug ( 'query_string = {0}, common_query_options = {1}' . format ( query_string , common_query_options ) ) self . since_date = self . get_gerrit_date ( self . options . since ) if common_query_options is None : # Calculate ag...
def fetch_options ( self , ) : """Set and return the options for possible files to load , replace etc . The stored element will determine the options . The refobjinterface and typinterface are responsible for providing the options : returns : the options : rtype : : class : ` jukeboxcore . gui . treemodel ....
self . _options , self . _taskfileinfo_options = self . get_refobjinter ( ) . fetch_options ( self . get_typ ( ) , self . get_element ( ) ) return self . _options
def _flatten_plus_safe ( tmp_dir , rollback_files ) : """Flatten names of files and create temporary file names ."""
tx_fpaths , orig_files = [ ] , [ ] for fnames in rollback_files : if isinstance ( fnames , six . string_types ) : fnames = [ fnames ] for fname in fnames : tx_file = fname + '.tx' tx_fpath = join ( tmp_dir , tx_file ) if tmp_dir else tx_file tx_fpaths . append ( tx_fpath ) ...
def init ( script = sys . argv [ 0 ] , base = 'lib' , append = True , ignore = [ '/' , '/usr' ] , realpath = False , pythonpath = False , throw = False ) : """Parameters : * ` script ` : Path to script file . Default is currently running script file * ` base ` : Name of base module directory to add to sys . pat...
if type ( ignore ) is str : ignore = [ ignore ] script = os . path . realpath ( script ) if realpath else os . path . abspath ( script ) path = os . path . dirname ( script ) while os . path . dirname ( path ) != path and ( path in ignore or not os . path . isdir ( os . path . join ( path , base ) ) ) : path = ...
def post_process ( self , tagnum2name ) : """Map the tag name instead of tag number to the tag value ."""
for tag , value in self . raw_ifd . items ( ) : try : tag_name = tagnum2name [ tag ] except KeyError : # Ok , we don ' t recognize this tag . Just use the numeric id . msg = 'Unrecognized Exif tag ({tag}).' . format ( tag = tag ) warnings . warn ( msg , UserWarning ) tag_name = t...
def x_build_targets_target ( self , node ) : '''Process the target dependency DAG into an ancestry tree so we can look up which top - level library and test targets specific build actions correspond to .'''
target_node = node name = self . get_child_data ( target_node , tag = 'name' , strip = True ) path = self . get_child_data ( target_node , tag = 'path' , strip = True ) jam_target = self . get_child_data ( target_node , tag = 'jam-target' , strip = True ) # ~ Map for jam targets to virtual targets . self . target [ jam...
def natural_sorted ( iterable ) : """Return human sorted list of strings . E . g . for sorting file names . > > > natural _ sorted ( [ ' f1 ' , ' f2 ' , ' f10 ' ] ) [ ' f1 ' , ' f2 ' , ' f10 ' ]"""
def sortkey ( x ) : return [ ( int ( c ) if c . isdigit ( ) else c ) for c in re . split ( numbers , x ) ] numbers = re . compile ( r'(\d+)' ) return sorted ( iterable , key = sortkey )
def checkFuelPosition ( obs , agent_host ) : '''Make sure our coal , if we have any , is in slot 0.'''
# ( We need to do this because the furnace crafting commands - cooking the potato and the rabbit - # take the first available item of fuel in the inventory . If this isn ' t the coal , it could end up burning the wood # that we need for making the bowl . ) for i in range ( 1 , 39 ) : key = 'InventorySlot_' + str ( ...
def _run_wes ( args ) : """Run CWL using a Workflow Execution Service ( WES ) endpoint"""
main_file , json_file , project_name = _get_main_and_json ( args . directory ) main_file = _pack_cwl ( main_file ) if args . host and "stratus" in args . host : _run_wes_stratus ( args , main_file , json_file ) else : opts = [ "--no-wait" ] if args . host : opts += [ "--host" , args . host ] if ...
def get_all_tables ( self , dataset_id , project_id = None ) : """Retrieve a list of tables for the dataset . Parameters dataset _ id : str The dataset to retrieve table data for . project _ id : str Unique ` ` str ` ` identifying the BigQuery project contains the dataset Returns A ` ` list ` ` with a...
tables_data = self . _get_all_tables_for_dataset ( dataset_id , project_id ) tables = [ ] for table in tables_data . get ( 'tables' , [ ] ) : table_name = table . get ( 'tableReference' , { } ) . get ( 'tableId' ) if table_name : tables . append ( table_name ) return tables
def write_sources_file ( ) : """Write a sources . yaml file to current working dir ."""
file_content = ( 'schemes: ' 'https://github.com/chriskempson/base16-schemes-source.git\n' 'templates: ' 'https://github.com/chriskempson/base16-templates-source.git' ) file_path = rel_to_cwd ( 'sources.yaml' ) with open ( file_path , 'w' ) as file_ : file_ . write ( file_content )
def get_config_dict ( config ) : '''获取配置数据字典 对传入的配置包进行格式化处理 , 生成一个字典对象 : param object config : 配置模块 : return : 配置数据字典 : rtype : dict'''
dst = { } tmp = config . __dict__ key_list = dir ( config ) key_list . remove ( 'os' ) for k , v in tmp . items ( ) : if k in key_list and not k . startswith ( '_' ) : dst [ k ] = v return dst
def dispatch ( argdict ) : '''Call the command - specific function , depending on the command .'''
cmd = argdict [ 'command' ] ftc = getattr ( THIS_MODULE , 'do_' + cmd ) ftc ( argdict )