signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def close ( self ) : """Close the sockets"""
self . _socket . close ( ) if self . _async_socket_cache : self . _async_socket_cache . close ( ) self . _async_socket_cache = None
def header ( self ) : """Wea header ."""
return "place %s\n" % self . location . city + "latitude %.2f\n" % self . location . latitude + "longitude %.2f\n" % - self . location . longitude + "time_zone %d\n" % ( - self . location . time_zone * 15 ) + "site_elevation %.1f\n" % self . location . elevation + "weather_data_file_units 1\n"
def search_task_views ( self , user , search_string ) : """invokes TouchWorksMagicConstants . ACTION _ GET _ ENCOUNTER _ LIST _ FOR _ PATIENT action : return : JSON response"""
magic = self . _magic_json ( action = TouchWorksMagicConstants . ACTION_SEARCH_TASK_VIEWS , parameter1 = user , parameter2 = search_string ) response = self . _http_request ( TouchWorksEndPoints . MAGIC_JSON , data = magic ) result = self . _get_results_or_raise_if_magic_invalid ( magic , response , TouchWorksMagicCons...
def _countDigits ( self , text ) : """Count digits at start of text"""
index = 0 while index < len ( text ) : if not text [ index ] . isdigit ( ) : break index += 1 return index
def _plt_pydot ( self , fout_img ) : """Plot using the pydot graphics engine ."""
dag = self . _get_pydot_graph ( ) img_fmt = os . path . splitext ( fout_img ) [ 1 ] [ 1 : ] dag . write ( fout_img , format = img_fmt ) self . log . write ( " {GO_USR:>3} usr {GO_ALL:>3} GOs WROTE: {F}\n" . format ( F = fout_img , GO_USR = len ( self . godag . go_sources ) , GO_ALL = len ( self . godag . go2obj ) ) )
def update_time_reset_passwd ( user_name , the_time ) : '''Update the time when user reset passwd .'''
entry = TabMember . update ( time_reset_passwd = the_time , ) . where ( TabMember . user_name == user_name ) try : entry . execute ( ) return True except : return False
def skip ( self , content ) : """Get whether to skip this I { content } . Should be skipped when the content is optional and value is either None or an empty list . @ param content : Content to skip . @ type content : L { Object } @ return : True if content is to be skipped . @ rtype : bool"""
if self . optional ( content ) : v = content . value if v is None : return True if isinstance ( v , ( list , tuple ) ) and not v : return True return False
def compute_control_digit ( clabe : str ) -> str : """Compute CLABE control digit according to https : / / es . wikipedia . org / wiki / CLABE # D . C3 . ADgito _ control"""
clabe = [ int ( i ) for i in clabe ] weighted = [ c * w % 10 for c , w in zip ( clabe [ : CLABE_LENGTH - 1 ] , CLABE_WEIGHTS ) ] summed = sum ( weighted ) % 10 control_digit = ( 10 - summed ) % 10 return str ( control_digit )
def cors ( origins , methods = [ 'HEAD' , 'OPTIONS' , 'GET' , 'POST' , 'PUT' , 'PATCH' , 'DELETE' ] , headers = [ 'Accept' , 'Accept-Language' , 'Content-Language' , 'Content-Type' , 'X-Requested-With' ] , max_age = None ) : """Adds CORS headers to the decorated view function . : param origins : Allowed origins (...
def inner ( f ) : @ wraps ( f ) def wrapper ( * args , ** kwargs ) : origin = request . headers . get ( 'Origin' ) if request . method not in methods : abort ( 405 ) if origins == '*' : pass elif is_collection ( origins ) and origin in origins : ...
def return_dat ( self , chan , begsam , endsam ) : """Return the data as 2D numpy . ndarray . Parameters chan : list indices of the channels to read begsam : int index of the first sample endsam : int index of the last sample Returns numpy . ndarray A 2d matrix , with dimension chan X samples ...
assert begsam < endsam data = empty ( ( len ( chan ) , endsam - begsam ) ) data . fill ( NaN ) chan = asarray ( chan ) # we assume there are only two signals signals_to_read = [ ] if ( chan < self . _nchan_signal1 ) . any ( ) : signals_to_read . append ( 0 ) if ( chan >= self . _nchan_signal1 ) . any ( ) : sign...
def _find_paths ( self , current_dir , patterns ) : """Recursively generates absolute paths whose components underneath current _ dir match the corresponding pattern in patterns"""
pattern = patterns [ 0 ] patterns = patterns [ 1 : ] has_wildcard = is_pattern ( pattern ) using_globstar = pattern == "**" # This avoids os . listdir ( ) for performance if has_wildcard : entries = [ x . name for x in scandir ( current_dir ) ] else : entries = [ pattern ] if using_globstar : matching_subdi...
def description ( self ) : """This read - only attribute is a sequence of 7 - item sequences . Each of these sequences contains information describing one result column : - name - type _ code - display _ size ( None in current implementation ) - internal _ size ( None in current implementation ) - preci...
# Sleep until we ' re done or we got the columns if self . _columns is None : return [ ] return [ # name , type _ code , display _ size , internal _ size , precision , scale , null _ ok ( col [ 0 ] , col [ 1 ] , None , None , None , None , True ) for col in self . _columns ]
def find_interface_by_mac ( self , ** kwargs ) : """Find the interface through which a MAC can be reached . Args : mac _ address ( str ) : A MAC address in ' xx : xx : xx : xx : xx : xx ' format . Returns : list [ dict ] : a list of mac table data . Raises : KeyError : if ` mac _ address ` is not specif...
mac = kwargs . pop ( 'mac_address' ) results = [ x for x in self . mac_table if x [ 'mac_address' ] == mac ] return results
def get_defaults_str ( raw = None , after = 'Defaults::' ) : """Get the string YAML representation of configuration defaults ."""
if raw is None : raw = __doc__ return unicode ( textwrap . dedent ( raw . split ( after ) [ - 1 ] ) . strip ( ) )
def CMFR ( t , C_initial , C_influent ) : """Calculate the effluent concentration of a conversative ( non - reacting ) material with continuous input to a completely mixed flow reactor . Note : time t = 0 is the time at which the material starts to flow into the reactor . : param C _ initial : The concentra...
return C_influent * ( 1 - np . exp ( - t ) ) + C_initial * np . exp ( - t )
def make_directory_if_needed ( directory_path ) : """Make the directory path , if needed ."""
if os . path . exists ( directory_path ) : if not os . path . isdir ( directory_path ) : raise OSError ( "Path is not a directory:" , directory_path ) else : os . makedirs ( directory_path )
def _create_clock ( self ) : """If the clock property is not set , then create one based on frequency ."""
trading_o_and_c = self . trading_calendar . schedule . ix [ self . sim_params . sessions ] market_closes = trading_o_and_c [ 'market_close' ] minutely_emission = False if self . sim_params . data_frequency == 'minute' : market_opens = trading_o_and_c [ 'market_open' ] minutely_emission = self . sim_params . emi...
def new ( cls , starting_domino = None , starting_player = 0 ) : ''': param Domino starting _ domino : the domino that should be played to start the game . The player with this domino in their hand will play first . : param int starting _ player : the player that should play first . This value is ignored ...
board = dominoes . Board ( ) hands = _randomized_hands ( ) moves = [ ] result = None if starting_domino is None : _validate_player ( starting_player ) valid_moves = tuple ( ( d , True ) for d in hands [ starting_player ] ) game = cls ( board , hands , moves , starting_player , valid_moves , starting_player ...
def v_center_cell_text ( cell ) : """Vertically center the text within the cell ' s grid . Like this : : | foobar | | | | | - - > | foobar | Parameters cell : dashtable . data2rst . Cell Returns cell : dashtable . data2rst . Cell"""
lines = cell . text . split ( '\n' ) cell_width = len ( lines [ 0 ] ) - 2 truncated_lines = [ ] for i in range ( 1 , len ( lines ) - 1 ) : truncated = lines [ i ] [ 1 : len ( lines [ i ] ) - 1 ] truncated_lines . append ( truncated ) total_height = len ( truncated_lines ) empty_lines_above = 0 for i in range ( ...
def fetch ( destination ) : """Fetch TLE from internet and save it to ` destination ` ."""
with io . open ( destination , mode = "w" , encoding = "utf-8" ) as dest : for url in TLE_URLS : response = urlopen ( url ) dest . write ( response . read ( ) . decode ( "utf-8" ) )
def check_connection_state ( self ) : """Check the state of the connection using connection state request . This sends a CONNECTION _ STATE _ REQUEST . This method will only return True , if the connection is established and no error code is returned from the KNX / IP gateway"""
if not self . connected : self . connection_state = - 1 return False frame = KNXIPFrame ( KNXIPFrame . CONNECTIONSTATE_REQUEST ) frame . body = self . hpai_body ( ) # Send maximum 3 connection state requests with a 10 second timeout res = False self . connection_state = 0 maximum_retry = 3 for retry_counter in ...
def set_iscsi_info ( self , target_name , lun , ip_address , port = '3260' , auth_method = None , username = None , password = None ) : """Set iscsi details of the system in uefi boot mode . The initiator system is set with the target details like IQN , LUN , IP , Port etc . : param target _ name : Target Nam...
raise exception . IloCommandNotSupportedError ( ERRMSG )
def get_serializer_class ( self ) : """gets the class type of the serializer : return : ` rest _ framework . Serializer `"""
klass = None lookup_url_kwarg = self . lookup_url_kwarg or self . lookup_field if lookup_url_kwarg in self . kwargs : # Looks like this is a detail . . . klass = self . get_object ( ) . __class__ elif "doctype" in self . request . REQUEST : base = self . model . get_base_class ( ) doctypes = indexable_regis...
def ensure_parent_dir ( filename ) : """< Purpose > To ensure existence of the parent directory of ' filename ' . If the parent directory of ' name ' does not exist , create it . Example : If ' filename ' is ' / a / b / c / d . txt ' , and only the directory ' / a / b / ' exists , then directory ' / a / b /...
# Ensure ' filename ' corresponds to ' PATH _ SCHEMA ' . # Raise ' securesystemslib . exceptions . FormatError ' on a mismatch . securesystemslib . formats . PATH_SCHEMA . check_match ( filename ) # Split ' filename ' into head and tail , check if head exists . directory = os . path . split ( filename ) [ 0 ] if direct...
def _dict_compare ( d1 , d2 ) : """We care if one of two things happens : * d2 has added a new key * a ( value for the same key ) in d2 has a different value than d1 We don ' t care if this stuff happens : * A key is deleted from the dict Should return a list of keys that either have been added or have a ...
keys_added = set ( d2 . keys ( ) ) - set ( d1 . keys ( ) ) keys_changed = [ k for k in d1 . keys ( ) if k in d2 . keys ( ) and d1 [ k ] != d2 [ k ] ] return list ( keys_added ) + keys_changed
def ClearCallHistory ( self , Username = 'ALL' , Type = chsAllCalls ) : """Clears the call history . : Parameters : Username : str Skypename of the user . A special value of ' ALL ' means that entries of all users should be removed . Type : ` enums ` . clt * Call type ."""
cmd = 'CLEAR CALLHISTORY %s %s' % ( str ( Type ) , Username ) self . _DoCommand ( cmd , cmd )
def quantized ( values , steps , input_min = 0 , input_max = 1 ) : """Returns * values * quantized to * steps * increments . All items in * values * are assumed to be between * input _ min * and * input _ max * ( which default to 0 and 1 respectively ) , and the output will be in the same range . For example ...
values = _normalize ( values ) if steps < 1 : raise ValueError ( "steps must be 1 or larger" ) if input_min >= input_max : raise ValueError ( 'input_min must be smaller than input_max' ) input_size = input_max - input_min for v in scaled ( values , 0 , 1 , input_min , input_max ) : yield ( ( int ( v * steps...
def new_window ( self , type_hint = None ) : """Switches to a new top - level browsing context . The type hint can be one of " tab " or " window " . If not specified the browser will automatically select it . : Usage : driver . switch _ to . new _ window ( ' tab ' )"""
value = self . _driver . execute ( Command . NEW_WINDOW , { 'type' : type_hint } ) [ 'value' ] self . _w3c_window ( value [ 'handle' ] )
def _get_module_via_sys_modules ( self , fullname ) : """Attempt to fetch source code via sys . modules . This is specifically to support _ _ main _ _ , but it may catch a few more cases ."""
module = sys . modules . get ( fullname ) LOG . debug ( '_get_module_via_sys_modules(%r) -> %r' , fullname , module ) if not isinstance ( module , types . ModuleType ) : LOG . debug ( 'sys.modules[%r] absent or not a regular module' , fullname ) return path = self . _py_filename ( getattr ( module , '__file__' ...
def reshuffle_batches ( self , indices , rng ) : """Permutes global batches : param indices : torch . tensor with batch indices : param rng : instance of torch . Generator"""
indices = indices . view ( - 1 , self . global_batch_size ) num_batches = indices . shape [ 0 ] order = torch . randperm ( num_batches , generator = rng ) indices = indices [ order , : ] indices = indices . view ( - 1 ) return indices
def save ( self , filePath ) : """save the CSV to a file"""
self . filename = filePath f = open ( filePath , 'w' ) f . write ( self . toStr ( ) ) f . flush ( ) f . close ( )
def add_badge_roles ( app ) : """Add ` ` badge ` ` role to your sphinx documents . It can create a colorful badge inline ."""
from docutils . nodes import inline , make_id from docutils . parsers . rst . roles import set_classes def create_badge_role ( color = None ) : def badge_role ( name , rawtext , text , lineno , inliner , options = None , content = None ) : options = options or { } set_classes ( options ) cla...
def scopes ( self ) : """Gets the Scopes API client . Returns : Scopes :"""
if not self . __scopes : self . __scopes = Scopes ( self . __connection ) return self . __scopes
def mavlink_packet ( self , msg ) : '''handle an incoming mavlink packet'''
# check for any closed graphs for i in range ( len ( self . graphs ) - 1 , - 1 , - 1 ) : if not self . graphs [ i ] . is_alive ( ) : self . graphs [ i ] . close ( ) self . graphs . pop ( i ) # add data to the rest for g in self . graphs : g . add_mavlink_packet ( msg )
def Nu_cylinder_Perkins_Leppert_1964 ( Re , Pr , mu = None , muw = None ) : r'''Calculates Nusselt number for crossflow across a single tube as shown in [ 1 ] _ at a specified ` Re ` and ` Pr ` , both evaluated at the free stream temperature . Recommends a viscosity exponent correction of 0.25 , which is appl...
Nu = ( 0.31 * Re ** 0.5 + 0.11 * Re ** 0.67 ) * Pr ** 0.4 if mu and muw : Nu *= ( mu / muw ) ** 0.25 return Nu
def DEFINE_multichoice ( self , name , default , choices , help , constant = False ) : """Choose multiple options from a list ."""
self . AddOption ( type_info . MultiChoice ( name = name , default = default , choices = choices , description = help ) , constant = constant )
def directory ( self , key ) : '''Retrieves directory entries for given key .'''
if key . name != 'directory' : key = key . instance ( 'directory' ) return self . get ( key ) or [ ]
def get_result ( self , decorated_function , * args , ** kwargs ) : """Get result from storage for specified function . Will raise an exception ( : class : ` . WCacheStorage . CacheMissedException ` ) if there is no cached result . : param decorated _ function : called function ( original ) : param args : arg...
cache_entry = self . get_cache ( decorated_function , * args , ** kwargs ) if cache_entry . has_value is False : raise WCacheStorage . CacheMissedException ( 'No cache record found' ) return cache_entry . cached_value
def build ( self , limit_states , discretization , steps_per_interval ) : """: param limit _ states : a sequence of limit states : param discretization : continouos fragility discretization parameter : param steps _ per _ interval : steps _ per _ interval parameter : returns : a populated FragilityFunctionLis...
new = copy . copy ( self ) add_zero = ( self . format == 'discrete' and self . nodamage and self . nodamage <= self . imls [ 0 ] ) new . imls = build_imls ( new , discretization ) if steps_per_interval > 1 : new . interp_imls = build_imls ( # passed to classical _ damage new , discretization , steps_per_interva...
def start ( self ) : """Starts the event dispatcher . Initiates executor and start polling events . Raises : IllegalStateError : Can ' t start a dispatcher again when it ' s already running ."""
if not self . started : self . started = True self . executor = ThreadPoolExecutor ( max_workers = 32 ) self . poller = self . executor . submit ( self . poll_events ) else : raise IllegalStateError ( "Dispatcher is already started." )
def stats_view ( request , activity_id = None ) : """If a the GET parameter ` year ` is set , it uses stats from given year with the following caveats : - If it ' s the current year and start _ date is set , start _ date is ignored - If it ' s the current year , stats will only show up to today - they won ' t...
if not ( request . user . is_eighth_admin or request . user . is_teacher ) : return render ( request , "error/403.html" , { "reason" : "You do not have permission to view statistics for this activity." } , status = 403 ) activity = get_object_or_404 ( EighthActivity , id = activity_id ) if request . GET . get ( "pr...
def os_walk_pre_35 ( top , topdown = True , onerror = None , followlinks = False ) : """Pre Python 3.5 implementation of os . walk ( ) that doesn ' t use scandir ."""
islink , join , isdir = os . path . islink , os . path . join , os . path . isdir try : names = os . listdir ( top ) except OSError as err : if onerror is not None : onerror ( err ) return dirs , nondirs = [ ] , [ ] for name in names : if isdir ( join ( top , name ) ) : dirs . append ( n...
def calculate_statistics ( self ) : "Jam some data through to generate statistics"
rev_ids = range ( 0 , 100 , 1 ) feature_values = zip ( rev_ids , [ 0 ] * 100 ) scores = [ self . score ( f ) for f in feature_values ] labels = [ s [ 'prediction' ] for s in scores ] statistics = Classification ( labels , threshold_ndigits = 1 , decision_key = 'probability' ) score_labels = list ( zip ( scores , labels...
def _get_mounts ( fs_type = None ) : '''List mounted filesystems .'''
mounts = { } with salt . utils . files . fopen ( '/proc/mounts' ) as fhr : for line in fhr . readlines ( ) : line = salt . utils . stringutils . to_unicode ( line ) device , mntpnt , fstype , options , fs_freq , fs_passno = line . strip ( ) . split ( " " ) if fs_type and fstype != fs_type : ...
def get_composition_admin_session_for_repository ( self , repository_id = None ) : """Gets a composiiton administrative session for the given repository . arg : repository _ id ( osid . id . Id ) : the Id of the repository return : ( osid . repository . CompositionAdminSession ) - a CompositionAdminSession ...
if repository_id is None : raise NullArgument ( ) if not self . supports_composition_admin ( ) or not self . supports_visible_federation ( ) : raise Unimplemented ( ) try : from . import sessions except ImportError : raise # OperationFailed ( ) try : session = sessions . CompositionSearchSession...
def indicate_last ( items ) : """iterate through list and indicate which item is the last , intended to assist tree displays of hierarchical content . : return : yielding ( < bool > , < item > ) where bool is True only on last entry : rtype : generator"""
last_index = len ( items ) - 1 for ( i , item ) in enumerate ( items ) : yield ( i == last_index , item )
def match_owner ( self , url ) : """Finds the first entity , with keys in the key jar , with an identifier that matches the given URL . The match is a leading substring match . : param url : A URL : return : An issue entity ID that exists in the Key jar"""
for owner in self . issuer_keys . keys ( ) : if owner . startswith ( url ) : return owner raise KeyError ( "No keys for '{}' in this keyjar" . format ( url ) )
def get_relationships ( manager , handle_id1 , handle_id2 , rel_type = None , legacy = True ) : """Takes a start and an end node with an optional relationship type . Returns the relationships between the nodes or an empty list ."""
if rel_type : q = """ MATCH (a:Node {{handle_id: {{handle_id1}}}})-[r:{rel_type}]-(b:Node {{handle_id: {{handle_id2}}}}) RETURN collect(r) as relationships """ . format ( rel_type = rel_type ) else : q = """ MATCH (a:Node {handle_id: {handle_id1}})-[r]-(b:Node {handle_id: {ha...
async def get_clan ( self , * tags ) : '''Get a clan object using tag ( s )'''
url = '{0.BASE}/clan/{1}' . format ( self , ',' . join ( tags ) ) data = await self . request ( url ) if isinstance ( data , list ) : return [ Clan ( self , c ) for c in data ] else : return Clan ( self , data )
def restoreDefaultWCS ( imageObjectList , output_wcs ) : """Restore WCS information to default values , and update imageObject accordingly ."""
if not isinstance ( imageObjectList , list ) : imageObjectList = [ imageObjectList ] output_wcs . restoreWCS ( ) updateImageWCS ( imageObjectList , output_wcs )
def getLogs ( self , CorpNum , MgtKey ) : """문서이력 조회 args CorpNum : 팝빌회원 사업자번호 MgtKey : 문서관리번호 return 문서 이력 목록 as List raise PopbillException"""
if MgtKey == None or MgtKey == "" : raise PopbillException ( - 99999999 , "관리번호가 입력되지 않았습니다." ) return self . _httpget ( '/Cashbill/' + MgtKey + '/Logs' , CorpNum )
def fit ( self , data , debug = False ) : """Fit each segment . Segments that have not already been explicitly added will be automatically added with default model and ytransform . Parameters data : pandas . DataFrame Must have a column with the same name as ` segmentation _ col ` . debug : bool If set ...
data = util . apply_filter_query ( data , self . fit_filters ) unique = data [ self . segmentation_col ] . unique ( ) value_counts = data [ self . segmentation_col ] . value_counts ( ) # Remove any existing segments that may no longer have counterparts # in the data . This can happen when loading a saved model and then...
def p_throttling ( p ) : """throttling : THROTTLING COLON NONE | THROTTLING COLON TAIL _ DROP OPEN _ BRACKET NUMBER CLOSE _ BRACKET"""
throttling = NoThrottlingSettings ( ) if len ( p ) == 7 : throttling = TailDropSettings ( int ( p [ 5 ] ) ) p [ 0 ] = { "throttling" : throttling }
def export_image ( self , bbox , zoomlevel , imagepath ) : """Writes to ` ` imagepath ` ` the tiles for the specified bounding box and zoomlevel ."""
assert has_pil , _ ( "Cannot export image without python PIL" ) grid = self . grid_tiles ( bbox , zoomlevel ) width = len ( grid [ 0 ] ) height = len ( grid ) widthpix = width * self . tile_size heightpix = height * self . tile_size result = Image . new ( "RGBA" , ( widthpix , heightpix ) ) offset = ( 0 , 0 ) for i , r...
def eval_option_value ( self , option ) : """Evaluates an option : param option : a string : return : an object of type str , bool , int , float or list"""
try : value = eval ( option , { } , { } ) except ( SyntaxError , NameError , TypeError ) : return option if type ( value ) in ( str , bool , int , float ) : return value elif type ( value ) in ( list , tuple ) : for v in value : if type ( v ) not in ( str , bool , int , float ) : sel...
def parse_band_log ( self , message ) : """Process incoming logging messages from the service ."""
if "payload" in message and hasattr ( message [ "payload" ] , "name" ) : record = message [ "payload" ] for k in dir ( record ) : if k . startswith ( "workflows_exc_" ) : setattr ( record , k [ 14 : ] , getattr ( record , k ) ) delattr ( record , k ) for k , v in self . get_s...
def sepconv_relu_sepconv ( inputs , filter_size , output_size , first_kernel_size = ( 1 , 1 ) , second_kernel_size = ( 1 , 1 ) , padding = "LEFT" , nonpadding_mask = None , dropout = 0.0 , name = None ) : """Hidden layer with RELU activation followed by linear projection ."""
with tf . variable_scope ( name , "sepconv_relu_sepconv" , [ inputs ] ) : inputs = maybe_zero_out_padding ( inputs , first_kernel_size , nonpadding_mask ) if inputs . get_shape ( ) . ndims == 3 : is_3d = True inputs = tf . expand_dims ( inputs , 2 ) else : is_3d = False h = separ...
def hicpro_pairing_chart ( self ) : """Generate Pairing chart"""
# Specify the order of the different possible categories keys = OrderedDict ( ) keys [ 'Unique_paired_alignments' ] = { 'color' : '#005ce6' , 'name' : 'Uniquely Aligned' } keys [ 'Low_qual_pairs' ] = { 'color' : '#b97b35' , 'name' : 'Low Quality' } keys [ 'Pairs_with_singleton' ] = { 'color' : '#ff9933' , 'name' : 'Sin...
def _compute_distance_term ( self , C , mag , dists ) : """Computes the distance scaling term , as contained within equation ( 1b )"""
return ( ( C [ 'theta2' ] + C [ 'theta14' ] + C [ 'theta3' ] * ( mag - 7.8 ) ) * np . log ( dists . rhypo + self . CONSTS [ 'c4' ] * np . exp ( ( mag - 6. ) * self . CONSTS [ 'theta9' ] ) ) + ( C [ 'theta6' ] * dists . rhypo ) ) + C [ "theta10" ]
def close_other_windows ( self ) : """Closes all not current windows . Useful for tests - after each test you can automatically close all windows ."""
main_window_handle = self . current_window_handle for window_handle in self . window_handles : if window_handle == main_window_handle : continue self . switch_to_window ( window_handle ) self . close ( ) self . switch_to_window ( main_window_handle )
def export_process_template ( self , id , ** kwargs ) : """ExportProcessTemplate . [ Preview API ] Returns requested process template . : param str id : The ID of the process : rtype : object"""
route_values = { } if id is not None : route_values [ 'id' ] = self . _serialize . url ( 'id' , id , 'str' ) route_values [ 'action' ] = 'Export' response = self . _send ( http_method = 'GET' , location_id = '29e1f38d-9e9c-4358-86a5-cdf9896a5759' , version = '5.0-preview.1' , route_values = route_values , accept_me...
def fallback_move ( fobj , dest , src , count , BUFFER_SIZE = 2 ** 16 ) : """Moves data around using read ( ) / write ( ) . Args : fileobj ( fileobj ) dest ( int ) : The destination offset src ( int ) : The source offset count ( int ) The amount of data to move Raises : IOError : In case an operation ...
if dest < 0 or src < 0 or count < 0 : raise ValueError fobj . seek ( 0 , 2 ) filesize = fobj . tell ( ) if max ( dest , src ) + count > filesize : raise ValueError ( "area outside of file" ) if src > dest : moved = 0 while count - moved : this_move = min ( BUFFER_SIZE , count - moved ) f...
def upsert_multi ( db , collection , object , match_params = None ) : """Wrapper for pymongo . insert _ many ( ) and update _ many ( ) : param db : db connection : param collection : collection to update : param object : the modifications to apply : param match _ params : a query that matches the documents ...
if isinstance ( object , list ) and len ( object ) > 0 : return str ( db [ collection ] . insert_many ( object ) . inserted_ids ) elif isinstance ( object , dict ) : return str ( db [ collection ] . update_many ( match_params , { "$set" : object } , upsert = False ) . upserted_id )
def get_cached_zone_variable ( self , zone_id , variable , default = None ) : """Retrieve the current value of a zone variable from the cache or return the default value if the variable is not present ."""
try : return self . _retrieve_cached_zone_variable ( zone_id , variable ) except UncachedVariable : return default
def _timestep_cull ( self , timestep ) : """Cull out values that do not fit a timestep ."""
new_values = [ ] new_datetimes = [ ] mins_per_step = int ( 60 / timestep ) for i , date_t in enumerate ( self . datetimes ) : if date_t . moy % mins_per_step == 0 : new_datetimes . append ( date_t ) new_values . append ( self . values [ i ] ) a_per = self . header . analysis_period new_ap = Analysis...
def getServiceEndpoints ( self , yadis_url , service_element ) : """Generate all endpoint objects for all of the subfilters of this filter and return their concatenation ."""
endpoints = [ ] for subfilter in self . subfilters : endpoints . extend ( subfilter . getServiceEndpoints ( yadis_url , service_element ) ) return endpoints
def path ( self , name ) : """Look for files in subdirectory of MEDIA _ ROOT using the tenant ' s domain _ url value as the specifier ."""
if name is None : name = '' try : location = safe_join ( self . location , connection . tenant . domain_url ) except AttributeError : location = self . location try : path = safe_join ( location , name ) except ValueError : raise SuspiciousOperation ( "Attempted access to '%s' denied." % name ) retu...
def set_row_heights ( self ) : """the row height is defined by following factors : * how many facts are there in the day * does the fact have description / tags This func creates a list of row start positions to be able to quickly determine what to display"""
if not self . height : return y , pos , heights = 0 , [ ] , [ ] for date , facts in self . days : height = 0 for fact in facts : fact_height = self . fact_row . height ( fact ) fact . y = y + height fact . height = fact_height height += fact . height height += self . day_...
def qt_at_least ( needed_version , test_version = None ) : """Check if the installed Qt version is greater than the requested : param needed _ version : minimally needed Qt version in format like 4.8.4 : type needed _ version : str : param test _ version : Qt version as returned from Qt . QT _ VERSION . As in...
major , minor , patch = needed_version . split ( '.' ) needed_version = '0x0%s0%s0%s' % ( major , minor , patch ) needed_version = int ( needed_version , 0 ) installed_version = Qt . QT_VERSION if test_version is not None : installed_version = test_version if needed_version <= installed_version : return True el...
def workgroup ( name ) : '''. . versionadded : : 2019.2.0 Manage the workgroup of the computer name The workgroup to set Example : . . code - block : : yaml set workgroup : system . workgroup : - name : local'''
ret = { 'name' : name . upper ( ) , 'result' : False , 'changes' : { } , 'comment' : '' } # Grab the current domain / workgroup out = __salt__ [ 'system.get_domain_workgroup' ] ( ) current_workgroup = out [ 'Domain' ] if 'Domain' in out else out [ 'Workgroup' ] if 'Workgroup' in out else '' # Notify the user if the req...
def remove_input_data_port ( self , data_port_id , force = False , destroy = True ) : """Remove an input data port from the state : param int data _ port _ id : the id or the output data port to remove : param bool force : if the removal should be forced without checking constraints : raises exceptions . Attr...
if data_port_id in self . _input_data_ports : if destroy : self . remove_data_flows_with_data_port_id ( data_port_id ) self . _input_data_ports [ data_port_id ] . parent = None return self . _input_data_ports . pop ( data_port_id ) else : raise AttributeError ( "input data port with name %s does...
def dispatch_strict ( self , stream , * args , ** kwargs ) : """Dispatch to function held internally depending upon the value of stream . Matching on directories is strict . This means dictionaries will match if they are exactly the same ."""
for f , pat in self . functions : matched , matched_stream = self . _match ( stream , pat , { 'strict' : True } , { } ) if matched : return f ( matched_stream , * args , ** kwargs ) raise DispatchFailed ( )
def get_datasets ( catalog , filter_in = None , filter_out = None , meta_field = None , exclude_meta_fields = None , only_time_series = False ) : """Devuelve una lista de datasets del catálogo o de uno de sus metadatos . Args : catalog ( dict , str or DataJson ) : Representación externa / interna de un cata...
filter_in = filter_in or { } filter_out = filter_out or { } catalog = read_catalog_obj ( catalog ) if filter_in or filter_out : filtered_datasets = [ dataset for dataset in catalog [ "dataset" ] if _filter_dictionary ( dataset , filter_in . get ( "dataset" ) , filter_out . get ( "dataset" ) ) ] else : filtered_...
def chunk_string ( string , length ) : """Splits a string into fixed - length chunks . This function returns a generator , using a generator comprehension . The generator returns the string sliced , from 0 + a multiple of the length of the chunks , to the length of the chunks + a multiple of the length of t...
return ( string [ 0 + i : length + i ] for i in range ( 0 , len ( string ) , length ) )
def stop ( ) : '''Stops lazarus , regardless of which mode it was started in . For example : > > > import lazarus > > > lazarus . default ( ) > > > lazarus . stop ( )'''
global _active if not _active : msg = 'lazarus is not active' raise RuntimeWarning ( msg ) _observer . stop ( ) _observer . join ( ) _deactivate ( )
def undo_nested_group ( self ) : """Performs the last group opened , or the top group on the undo stack . Creates a redo group with the same name ."""
if self . _undoing or self . _redoing : raise RuntimeError if self . _open : group = self . _open . pop ( ) elif self . _undo : group = self . _undo . pop ( ) else : return self . _undoing = True self . begin_grouping ( ) group . perform ( ) self . set_action_name ( group . name ) self . end_grouping ( ...
def start ( self , any_zone ) : """Start the event listener listening on the local machine at port 1400 ( default ) Make sure that your firewall allows connections to this port Args : any _ zone ( SoCo ) : Any Sonos device on the network . It does not matter which device . It is used only to find a local ...
# Find our local network IP address which is accessible to the # Sonos net , see http : / / stackoverflow . com / q / 166506 with self . _start_lock : if not self . is_running : # Use configured IP address if there is one , else detect # automatically . if config . EVENT_LISTENER_IP : ip_add...
def wait_for_capture ( self , timeout = None ) : """See base class documentation"""
if self . _process is None : raise sniffer . InvalidOperationError ( "Trying to wait on a non-started process" ) try : utils . wait_for_standing_subprocess ( self . _process , timeout ) self . _post_process ( ) except subprocess . TimeoutExpired : self . stop_capture ( )
def get_drive ( self , drive_id ) : """Returns a Drive instance : param drive _ id : the drive _ id to be retrieved : return : Drive for the id : rtype : Drive"""
if not drive_id : return None url = self . build_url ( self . _endpoints . get ( 'get_drive' ) . format ( id = drive_id ) ) response = self . con . get ( url ) if not response : return None drive = response . json ( ) # Everything received from cloud must be passed as self . _ cloud _ data _ key return self . d...
def get_vpnv4fs_table ( self ) : """Returns global VPNv4 Flow Specification table . Creates the table if it does not exist ."""
vpnv4fs_table = self . _global_tables . get ( RF_VPNv4_FLOWSPEC ) # Lazy initialization of the table . if not vpnv4fs_table : vpnv4fs_table = VPNv4FlowSpecTable ( self . _core_service , self . _signal_bus ) self . _global_tables [ RF_VPNv4_FLOWSPEC ] = vpnv4fs_table self . _tables [ ( None , RF_VPNv4_FLOWSP...
def clause_indices ( self ) : """The list of clause indices in ` ` words ` ` layer . The indices are unique only in the boundary of a single sentence ."""
if not self . is_tagged ( CLAUSE_ANNOTATION ) : self . tag_clause_annotations ( ) return [ word . get ( CLAUSE_IDX , None ) for word in self [ WORDS ] ]
def get_preview_name ( self ) : """Returns . SAFE name of full resolution L1C preview : return : name of preview file : rtype : str"""
if self . safe_type == EsaSafeType . OLD_TYPE : name = _edit_name ( self . tile_id , AwsConstants . PVI , delete_end = True ) else : name = '_' . join ( [ self . tile_id . split ( '_' ) [ 1 ] , self . get_datatake_time ( ) , AwsConstants . PVI ] ) return '{}.jp2' . format ( name )
def build_collision_table ( aliases , levels = COLLISION_CHECK_LEVEL_DEPTH ) : """Build the collision table according to the alias configuration file against the entire command table . self . collided _ alias is structured as : ' collided _ alias ' : [ the command level at which collision happens ] For exampl...
collided_alias = defaultdict ( list ) for alias in aliases : # Only care about the first word in the alias because alias # cannot have spaces ( unless they have positional arguments ) word = alias . split ( ) [ 0 ] for level in range ( 1 , levels + 1 ) : collision_regex = r'^{}{}($|\s)' . format ( r'([a...
def pylint_raw ( options ) : """Use check _ output to run pylint . Because pylint changes the exit code based on the code score , we have to wrap it in a try / except block . : param options : : return :"""
command = [ 'pylint' ] command . extend ( options ) proc = subprocess . Popen ( command , stdout = subprocess . PIPE , stderr = subprocess . PIPE ) outs , __ = proc . communicate ( ) return outs . decode ( )
def _get_converter_type ( identifier ) : """Return the converter type for ` identifier ` ."""
if isinstance ( identifier , str ) : return ConverterType [ identifier ] if isinstance ( identifier , ConverterType ) : return identifier return ConverterType ( identifier )
def update_task_db ( self , row ) : '''更新数据库中的任务信息'''
sql = '''UPDATE tasks SET currsize=?, state=?, statename=?, humansize=?, percent=? WHERE fsid=? ''' self . cursor . execute ( sql , [ row [ CURRSIZE_COL ] , row [ STATE_COL ] , row [ STATENAME_COL ] , row [ HUMANSIZE_COL ] , row [ PERCENT_COL ] , row [ FSID_COL ] ] ) self . check_commit ( )
def get_proficiency_search_session_for_objective_bank ( self , objective_bank_id , proxy ) : """Gets the ` ` OsidSession ` ` associated with the proficiency search service for the given objective bank . : param objective _ bank _ id : the ` ` Id ` ` of the ` ` ObjectiveBank ` ` : type objective _ bank _ id : ` ...
if not objective_bank_id : raise NullArgument if not self . supports_proficiency_search ( ) : raise Unimplemented ( ) try : from . import sessions except ImportError : raise OperationFailed ( ) proxy = self . _convert_proxy ( proxy ) try : session = sessions . ProficiencySearchSession ( objective_ba...
def _format_data ( data ) : # type : ( Union [ str , IO ] ) - > Union [ Tuple [ None , str ] , Tuple [ Optional [ str ] , IO , str ] ] """Format field data according to whether it is a stream or a string for a form - data request . : param data : The request field data . : type data : str or file - like objec...
if hasattr ( data , 'read' ) : data = cast ( IO , data ) data_name = None try : if data . name [ 0 ] != '<' and data . name [ - 1 ] != '>' : data_name = os . path . basename ( data . name ) except ( AttributeError , TypeError ) : pass return ( data_name , data , "applicat...
def _density_par_approx_higherorder ( self , Oparb , lowbindx , _return_array = False , gaussxpolyInt = None ) : """Contribution from non - linear spline terms"""
spline_order = self . _kick_interpdOpar_raw . _eval_args [ 2 ] if spline_order == 1 : return 0. # Form all Gaussian - like integrals necessary ll = ( numpy . roll ( Oparb , - 1 ) [ : - 1 ] - self . _kick_interpdOpar_poly . c [ - 1 ] - self . _meandO - self . _kick_interpdOpar_poly . c [ - 2 ] * self . _timpact * ( ...
def reset ( self ) : """Reset all resolver configuration to the defaults ."""
self . domain = dns . name . Name ( dns . name . from_text ( socket . gethostname ( ) ) [ 1 : ] ) if len ( self . domain ) == 0 : self . domain = dns . name . root self . nameservers = [ ] self . localhosts = set ( [ 'localhost' , 'loopback' , '127.0.0.1' , '0.0.0.0' , '::1' , 'ip6-localhost' , 'ip6-loopback' , ] )...
def create ( self , session ) : """caches the session and caches an entry to associate the cached session with the subject"""
sessionid = super ( ) . create ( session ) # calls _ do _ create and verify self . _cache ( session , sessionid ) return sessionid
def check_connection ( self ) : """Open a telnet connection and try to login . Expected login label is " login : " , expected password label is " Password : " ."""
self . url_connection = telnetlib . Telnet ( timeout = self . aggregate . config [ "timeout" ] ) if log . is_debug ( LOG_CHECK ) : self . url_connection . set_debuglevel ( 1 ) self . url_connection . open ( self . host , self . port ) if self . user : self . url_connection . read_until ( "login: " , 10 ) se...
def check_bot ( task_type = SYSTEM_TASK ) : """wxpy bot 健康检查任务"""
if glb . wxbot . bot . alive : msg = generate_run_info ( ) message = Message ( content = msg , receivers = 'status' ) glb . wxbot . send_msg ( message ) _logger . info ( '{0} Send status message {1} at {2:%Y-%m-%d %H:%M:%S}' . format ( task_type , msg , datetime . datetime . now ( ) ) ) else : # todo ...
def fs_cache ( app_name = '' , cache_type = '' , idx = 1 , expires = DEFAULT_EXPIRES , cache_dir = '' , helper_class = _FSCacher ) : """A decorator to cache results of functions returning pd . DataFrame or pd . Series objects under : < cache _ dir > / < app _ name > / < cache _ type > / < func _ name > . < para...
def decorator ( func ) : return helper_class ( func , cache_dir , app_name , cache_type , idx , expires ) return decorator
def satisfy_custom_matcher ( self , args , kwargs ) : """Return a boolean indicating if the args satisfy the stub : return : Whether or not the stub accepts the provided arguments . : rtype : bool"""
if not self . _custom_matcher : return False try : return self . _custom_matcher ( * args , ** kwargs ) except Exception : return False
def _setBatchSystemEnvVars ( self ) : """Sets the environment variables required by the job store and those passed on command line ."""
for envDict in ( self . _jobStore . getEnv ( ) , self . config . environment ) : for k , v in iteritems ( envDict ) : self . _batchSystem . setEnv ( k , v )
def remove_override ( self , key ) : """Remove a setting override , if one exists ."""
keys = key . split ( '.' ) if len ( keys ) > 1 : raise NotImplementedError elif key in self . overrides : del self . overrides [ key ] self . _uncache ( key )
def animate ( self , duration = None , easing = None , on_complete = None , on_update = None , round = False , ** kwargs ) : """Request parent Scene to Interpolate attributes using the internal tweener . Specify sprite ' s attributes that need changing . ` duration ` defaults to 0.4 seconds and ` easing ` to cu...
scene = self . get_scene ( ) if scene : return scene . animate ( self , duration , easing , on_complete , on_update , round , ** kwargs ) else : for key , val in kwargs . items ( ) : setattr ( self , key , val ) return None
def return_features_numpy ( self , names = 'all' ) : """Returns a 2d numpy array of extracted features Parameters names : list of strings , a list of feature names which are to be retrieved from the database , if equal to ' all ' , all features will be returned , default value : ' all ' Returns A numpy ar...
if self . _prepopulated is False : raise errors . EmptyDatabase ( self . dbpath ) else : return return_features_numpy_base ( self . dbpath , self . _set_object , self . points_amt , names )
def bulkCmd ( snmpDispatcher , authData , transportTarget , nonRepeaters , maxRepetitions , * varBinds , ** options ) : """Creates a generator to perform one or more SNMP GETBULK queries . On each iteration , new SNMP GETBULK request is send ( : RFC : ` 1905 # section - 4.2.3 ` ) . The iterator blocks waiting f...
def cbFun ( * args , ** kwargs ) : response [ : ] = args + ( kwargs . get ( 'nextVarBinds' , ( ) ) , ) options [ 'cbFun' ] = cbFun lexicographicMode = options . pop ( 'lexicographicMode' , True ) maxRows = options . pop ( 'maxRows' , 0 ) maxCalls = options . pop ( 'maxCalls' , 0 ) initialVarBinds = VB_PROCESSOR . m...