signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def getstruct ( self , msgid , as_json = False , stream = sys . stdout ) : """Get and print the whole message . as _ json indicates whether to print the part list as JSON or not ."""
parts = [ part . get_content_type ( ) for hdr , part in self . _get ( msgid ) ] if as_json : print ( json . dumps ( parts ) , file = stream ) else : for c in parts : print ( c , file = stream )
def replace_ext ( filename , new_ext ) : """Replace the file extention ."""
filename_base = os . path . splitext ( filename ) [ 0 ] new_filename = '{}.{}' . format ( filename_base , new_ext ) return new_filename
def update ( self , parent = None ) : """Updates the resource . This will trigger an api PATCH request . : param parent ResourceBase : the parent of the resource - used for nesting the request url , optional : raises ResourceError : if the resource does not have an id ( does not exist yet ) : returns : the re...
if not self . id : raise self . ResourceError ( 'cannot update a resource without an ID' ) data = self . __class__ . _process_request ( connection . patch , parent = parent , id = self . id , payload = self . payload ( ) ) return self . _reload ( data )
def _sort_io_counters ( process , sortedby = 'io_counters' , sortedby_secondary = 'memory_percent' ) : """Specific case for io _ counters Sum of io _ r + io _ w"""
return process [ sortedby ] [ 0 ] - process [ sortedby ] [ 2 ] + process [ sortedby ] [ 1 ] - process [ sortedby ] [ 3 ]
def prepare_release ( ver = None ) : """Prepare release artifacts"""
write_changelog ( True ) if ver is None : ver = next_release ( ) print ( 'saving updates to ChangeLog' ) run ( 'git commit ChangeLog -m "[RELEASE] Update to version v{}"' . format ( ver ) , hide = True ) sha = run ( 'git log -1 --pretty=format:"%h"' , hide = True ) . stdout run ( 'git tag -a "{ver}" -m "version {ve...
def break_type_id ( self , break_type_id ) : """Sets the break _ type _ id of this ModelBreak . The ` BreakType ` this ` Break ` was templated on . : param break _ type _ id : The break _ type _ id of this ModelBreak . : type : str"""
if break_type_id is None : raise ValueError ( "Invalid value for `break_type_id`, must not be `None`" ) if len ( break_type_id ) < 1 : raise ValueError ( "Invalid value for `break_type_id`, length must be greater than or equal to `1`" ) self . _break_type_id = break_type_id
def reinit_nested_vars ( variables , indices = None ) : """Reset all variables in a nested tuple to zeros . Args : variables : Nested tuple or list of variables . indices : Batch indices to reset , defaults to all . Returns : Operation ."""
if isinstance ( variables , ( tuple , list ) ) : return tf . group ( * [ reinit_nested_vars ( variable , indices ) for variable in variables ] ) if indices is None : return variables . assign ( tf . zeros_like ( variables ) ) else : zeros = tf . zeros ( [ tf . shape ( indices ) [ 0 ] ] + variables . shape [...
def get_correlated_reports_page ( self , indicators , enclave_ids = None , is_enclave = True , page_size = None , page_number = None ) : """Retrieves a page of all TruSTAR reports that contain the searched indicators . : param indicators : A list of indicator values to retrieve correlated reports for . : param ...
if is_enclave : distribution_type = DistributionType . ENCLAVE else : distribution_type = DistributionType . COMMUNITY params = { 'indicators' : indicators , 'enclaveIds' : enclave_ids , 'distributionType' : distribution_type , 'pageNumber' : page_number , 'pageSize' : page_size } resp = self . _client . get ( ...
def hydra_parser ( in_file , options = None ) : """Parse hydra input file into namedtuple of values ."""
if options is None : options = { } BedPe = namedtuple ( 'BedPe' , [ "chrom1" , "start1" , "end1" , "chrom2" , "start2" , "end2" , "name" , "strand1" , "strand2" , "support" ] ) with open ( in_file ) as in_handle : reader = csv . reader ( in_handle , dialect = "excel-tab" ) for line in reader : cur =...
def handle_wcs ( self , pkt ) : """This part of the protocol is used by IRAF to bidirectionally communicate metadata about frames in the framebuffers . IIS WCS format : name - title \n a b c d tx ty z1 z2 zt \n region _ name sx sy snx sny dx dy dnx dny \n object _ ref where the new parameters are defi...
self . logger . debug ( "handle wcs" ) if pkt . tid & IIS_READ : self . logger . debug ( "iis read" ) # Return the WCS for the referenced frame . if ( pkt . x & 0o17777 ) and ( pkt . y & 0o17777 ) : # return IIS version number text = "version=" + str ( IIS_VERSION ) text = right_pad ( text ,...
def weekly ( date = datetime . date . today ( ) ) : """Weeks start are fixes at Monday for now ."""
return date - datetime . timedelta ( days = date . weekday ( ) )
async def losetup ( self , image , read_only = True , offset = None , size = None , no_part_scan = None ) : """Setup a loop device . : param str image : path of the image file : param bool read _ only : : param int offset : : param int size : : param bool no _ part _ scan : : returns : the device object...
try : device = self . udisks . find ( image ) except FileNotFoundError : pass else : self . _log . info ( _ ( 'not setting up {0}: already up' , device ) ) return device if not os . path . isfile ( image ) : self . _log . error ( _ ( 'not setting up {0}: not a file' , image ) ) return None self ...
def set_defaults ( self , default_values , recursive = False ) : """Set default values from specified Parameters and returns a new Parameters object . : param default _ values : Parameters with default parameter values . : param recursive : ( optional ) true to perform deep copy , and false for shallow copy . D...
result = Parameters ( ) if recursive : RecursiveObjectWriter . copy_properties ( result , default_values ) RecursiveObjectWriter . copy_properties ( result , self ) else : ObjectWriter . set_properties ( result , default_values ) ObjectWriter . set_properties ( result , self ) return result
def _summarize_translations ( cls , translations ) : """Summarize a collection of Translation objects into three values : 1 ) List of unique reads supporting underlying variant sequences 2 ) Set of unique transcript names for establishing reading frames of the translations . 3 ) Set of unique gene names for...
read_name_to_reads = { } gene_names = set ( [ ] ) transcript_ids = set ( [ ] ) for translation in translations : for read in translation . reads : read_name_to_reads [ read . name ] = read for transcript in translation . reference_context . transcripts : transcript_ids . add ( transcript . id ) ...
def unpause ( name , call = None , session = None ) : '''UnPause a vm . . code - block : : bash salt - cloud - a unpause xenvm01'''
if call == 'function' : raise SaltCloudException ( 'The show_instnce function must be called with -a or --action.' ) if session is None : session = _get_session ( ) log . info ( 'Unpausing VM %s' , name ) vm = _get_vm ( name , session ) task = session . xenapi . Async . VM . unpause ( vm ) _run_async_task ( tas...
def rolling_vwap ( bars , window = 200 , min_periods = None ) : """calculate vwap using moving window ( input can be pandas series or numpy array ) bars are usually mid [ ( h + l ) / 2 ] or typical [ ( h + l + c ) / 3 ]"""
min_periods = window if min_periods is None else min_periods typical = ( ( bars [ 'high' ] + bars [ 'low' ] + bars [ 'close' ] ) / 3 ) volume = bars [ 'volume' ] left = ( volume * typical ) . rolling ( window = window , min_periods = min_periods ) . sum ( ) right = volume . rolling ( window = window , min_periods = min...
def with_transaction ( self , callback , read_concern = None , write_concern = None , read_preference = None ) : """Execute a callback in a transaction . This method starts a transaction on this session , executes ` ` callback ` ` once , and then commits the transaction . For example : : def callback ( sessio...
start_time = monotonic . time ( ) while True : self . start_transaction ( read_concern , write_concern , read_preference ) try : ret = callback ( self ) except Exception as exc : if self . _in_transaction : self . abort_transaction ( ) if ( isinstance ( exc , PyMongoError...
def from_jabsorb ( request , seems_raw = False ) : """Transforms a jabsorb request into a more Python data model ( converts maps and lists ) : param request : Data coming from Jabsorb : param seems _ raw : Set it to True if the given data seems to already have been parsed ( no Java class hint ) . If True , ...
if isinstance ( request , ( tuple , set , frozenset ) ) : # Special case : JSON arrays ( Python lists ) return type ( request ) ( from_jabsorb ( element ) for element in request ) elif isinstance ( request , list ) : # Check if we were a list or a tuple if seems_raw : return list ( from_jabsorb ( elemen...
def encode_request ( name , uuid , callable , address ) : """Encode request into client _ message"""
client_message = ClientMessage ( payload_size = calculate_size ( name , uuid , callable , address ) ) client_message . set_message_type ( REQUEST_TYPE ) client_message . set_retryable ( RETRYABLE ) client_message . append_str ( name ) client_message . append_str ( uuid ) client_message . append_data ( callable ) Addres...
def init_instance ( self , key ) : """Create an empty instance if it doesn ' t exist . If the instance already exists , this is a noop ."""
with self . _mor_lock : if key not in self . _mor : self . _mor [ key ] = { }
def RgbToGreyscale ( r , g , b ) : '''Convert the color from RGB to its greyscale equivalent Parameters : The Red component value [ 0 . . . 1] The Green component value [ 0 . . . 1] The Blue component value [ 0 . . . 1] Returns : The color as an ( r , g , b ) tuple in the range : the range : r [ 0 ....
v = ( r + g + b ) / 3.0 return ( v , v , v )
def check_csrf_token ( ) : """Check token"""
from uliweb import request , settings token = ( request . params . get ( settings . CSRF . form_token_name , None ) or request . headers . get ( "X-Xsrftoken" ) or request . headers . get ( "X-Csrftoken" ) ) if not token : raise Forbidden ( "CSRF token missing." ) if csrf_token ( ) != token : raise Forbidden ( ...
def save ( self , fname ) : """Save figure to a file"""
out = etree . tostring ( self . root , xml_declaration = True , standalone = True , pretty_print = True ) with open ( fname , 'wb' ) as fid : fid . write ( out )
def cmap_from_text ( filename , norm = False , transparency = False , hex = False ) : '''cmap _ from _ text takes as input a file that contains a colormap in text format composed by lines with 3 values in the range [ 0,255 ] or [ 00 , FF ] and returns a tuple of integers . If the parameters cat and tot are give...
lines = [ line . rstrip ( '\n' ) for line in open ( filename ) ] _colors = [ ] _tot = len ( lines ) _index = 1 for i in lines : if transparency : _colors . append ( _text_to_rgb ( i , norm = norm , cat = _index , tot = _tot , hex = hex ) ) else : _colors . append ( _text_to_rgb ( i , norm = norm...
def post ( self , request , * args , ** kwargs ) : """Handles POST requests ."""
return self . approve ( request , * args , ** kwargs )
def print_topics ( self , Nwords = 10 ) : """Print the top ` ` Nwords ` ` words for each topic ."""
print ( 'Topic\tTop %i words' % Nwords ) for k , words in self . list_topics ( Nwords ) : print ( unicode ( k ) . ljust ( 3 ) + '\t' + ' ' . join ( list ( zip ( * words ) ) [ 0 ] ) )
def get_ssh_key ( host , username , password , protocol = None , port = None , certificate_verify = False ) : '''Retrieve the authorized _ keys entry for root . This function only works for ESXi , not vCenter . : param host : The location of the ESXi Host : param username : Username to connect as : param pa...
if protocol is None : protocol = 'https' if port is None : port = 443 url = '{0}://{1}:{2}/host/ssh_root_authorized_keys' . format ( protocol , host , port ) ret = { } try : result = salt . utils . http . query ( url , status = True , text = True , method = 'GET' , username = username , password = password ...
def parse_map_bump ( self ) : """Bump map"""
Kd = os . path . join ( self . dir , " " . join ( self . values [ 1 : ] ) ) self . this_material . set_texture_bump ( Kd )
def differing_constants ( block_a , block_b ) : """Compares two basic blocks and finds all the constants that differ from the first block to the second . : param block _ a : The first block to compare . : param block _ b : The second block to compare . : returns : Returns a list of differing constants in the ...
statements_a = [ s for s in block_a . vex . statements if s . tag != "Ist_IMark" ] + [ block_a . vex . next ] statements_b = [ s for s in block_b . vex . statements if s . tag != "Ist_IMark" ] + [ block_b . vex . next ] if len ( statements_a ) != len ( statements_b ) : raise UnmatchedStatementsException ( "Blocks h...
def copy_mode ( pymux , variables ) : """Enter copy mode ."""
go_up = variables [ '-u' ] # Go in copy mode and page - up directly . # TODO : handle ' - u ' pane = pymux . arrangement . get_active_pane ( ) pane . enter_copy_mode ( )
def do_renegotiate ( self ) -> None : """Initiate an SSL renegotiation ."""
if not self . _is_handshake_completed : raise IOError ( 'SSL Handshake was not completed; cannot renegotiate.' ) self . _ssl . renegotiate ( ) self . do_handshake ( )
def add_frequency ( self , name , value ) : """Add a frequency that will be displayed on the variant level Args : name ( str ) : The name of the frequency field"""
logger . debug ( "Adding frequency {0} with value {1} to variant {2}" . format ( name , value , self [ 'variant_id' ] ) ) self [ 'frequencies' ] . append ( { 'label' : name , 'value' : value } )
def connect ( self , host = HOST , port = GPSD_PORT ) : """Connect to a host on a given port . Arguments : host : default host = ' 127.0.0.1' port : default port = 2947"""
for alotta_stuff in socket . getaddrinfo ( host , port , 0 , socket . SOCK_STREAM ) : family , socktype , proto , _canonname , host_port = alotta_stuff try : self . streamSock = socket . socket ( family , socktype , proto ) self . streamSock . connect ( host_port ) self . streamSock . se...
def create_dummy_func ( func , dependency ) : """When a dependency of a function is not available , create a dummy function which throws ImportError when used . Args : func ( str ) : name of the function . dependency ( str or list [ str ] ) : name ( s ) of the dependency . Returns : function : a function ...
assert not building_rtfd ( ) if isinstance ( dependency , ( list , tuple ) ) : dependency = ',' . join ( dependency ) def _dummy ( * args , ** kwargs ) : raise ImportError ( "Cannot import '{}', therefore '{}' is not available" . format ( dependency , func ) ) return _dummy
def build ( cls , path , tag = None , dockerfile = None ) : """Build the image from the provided dockerfile in path : param path : str , path to the directory containing the Dockerfile : param tag : str , A tag to add to the final image : param dockerfile : str , path within the build context to the Dockerfil...
if not path : raise ConuException ( 'Please specify path to the directory containing the Dockerfile' ) client = get_client ( ) response = [ line for line in client . build ( path , rm = True , tag = tag , dockerfile = dockerfile , quiet = True ) ] if not response : raise ConuException ( 'Failed to get ID of ima...
def get_95_percentile_bleak ( games_nr , n_back = 500 ) : """Gets the 95th percentile of bleakest _ eval from bigtable"""
end_game = int ( games_nr . latest_game_number ) start_game = end_game - n_back if end_game >= n_back else 0 moves = games_nr . bleakest_moves ( start_game , end_game ) evals = np . array ( [ m [ 2 ] for m in moves ] ) return np . percentile ( evals , 5 )
def legacy ( ** kwargs ) : """Compute options for using the PHOEBE 1.0 legacy backend ( must be installed ) . Generally , this will be used as an input to the kind argument in : meth : ` phoebe . frontend . bundle . Bundle . add _ compute ` Please see : func : ` phoebe . backend . backends . legacy ` for a ...
params = [ ] params += [ BoolParameter ( qualifier = 'enabled' , copy_for = { 'context' : 'dataset' , 'kind' : [ 'lc' , 'rv' , 'mesh' ] , 'dataset' : '*' } , dataset = '_default' , value = kwargs . get ( 'enabled' , True ) , description = 'Whether to create synthetics in compute/fitting run' ) ] # TODO : the kwargs nee...
def _pindel_options ( items , config , out_file , region , tmp_path ) : """parse pindel options . Add region to cmd . : param items : ( dict ) information from yaml : param config : ( dict ) information from yaml ( items [ 0 ] [ ' config ' ] ) : param region : ( str or tupple ) region to analyze : param tmp...
variant_regions = utils . get_in ( config , ( "algorithm" , "variant_regions" ) ) target = subset_variant_regions ( variant_regions , region , out_file , items ) opts = "" if target : if isinstance ( target , six . string_types ) and os . path . isfile ( target ) : target_bed = target else : tar...
def has_custom_image ( user_context , app_id ) : """Returns True if there exists a custom image for app _ id ."""
possible_paths = _valid_custom_image_paths ( user_context , app_id ) return any ( map ( os . path . exists , possible_paths ) )
def delete_address_by_id ( cls , address_id , ** kwargs ) : """Delete Address Delete an instance of Address by its ID . This method makes a synchronous HTTP request by default . To make an asynchronous HTTP request , please pass async = True > > > thread = api . delete _ address _ by _ id ( address _ id , a...
kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'async' ) : return cls . _delete_address_by_id_with_http_info ( address_id , ** kwargs ) else : ( data ) = cls . _delete_address_by_id_with_http_info ( address_id , ** kwargs ) return data
def check_units ( * units_by_pos , ** units_by_name ) : """Create a decorator to check units of function arguments ."""
try : from inspect import signature def dec ( func ) : # Match the signature of the function to the arguments given to the decorator sig = signature ( func ) bound_units = sig . bind_partial ( * units_by_pos , ** units_by_name ) # Convert our specified dimensionality ( e . g . " [ pressu...
def create ( self , client = None ) : """API call : create the metric via a PUT request See https : / / cloud . google . com / logging / docs / reference / v2 / rest / v2 / projects . metrics / create : type client : : class : ` ~ google . cloud . logging . client . Client ` or ` ` NoneType ` ` : param cl...
client = self . _require_client ( client ) client . metrics_api . metric_create ( self . project , self . name , self . filter_ , self . description )
def _parse_options ( opts , delim ) : """Helper method for split _ options which creates the options dict . Also handles the creation of a list for the URI tag _ sets / readpreferencetags portion and the use of the tlsInsecure option ."""
options = _CaseInsensitiveDictionary ( ) for uriopt in opts . split ( delim ) : key , value = uriopt . split ( "=" ) if key . lower ( ) == 'readpreferencetags' : options . setdefault ( key , [ ] ) . append ( value ) else : if key in options : warnings . warn ( "Duplicate URI opti...
def add_types ( self , types , ** kwargs ) : """: param types : Types to add to the object : type types : list of strings : raises : : class : ` ~ dxpy . exceptions . DXAPIError ` if the object is not in the " open " state Adds each of the specified types to the remote object . Takes no action for types tha...
self . _add_types ( self . _dxid , { "types" : types } , ** kwargs )
def copy ( self , repodir ) : """Copies the static files and folders specified in these settings into the locally - cloned repository directory . : arg repodir : the full path to the directory with the locally - cloned version of the pull request being unit tested ."""
# Instead of using the built - in shell copy , we make shell calls to rsync . # This allows us to copy only changes across between runs of pull - requests . from os import system , path vms ( "Running static file copy locally." , 2 ) for file in self . files : fullpath = path . expanduser ( file [ "source" ] ) ...
def get_element ( source , path , separator = r'[/.]' ) : """Given a dict and path ' / ' or ' . ' separated . Digs into de dict to retrieve the specified element . Args : source ( dict ) : set of nested objects in which the data will be searched path ( string ) : ' / ' or ' . ' string with attribute names""...
return _get_element_by_names ( source , re . split ( separator , path ) )
def main ( self , c ) : """: type c : Complex : return : abs ( gain corrected ) angle ( in 1 to - 1 range )"""
phase = Sfix ( 0.0 , 0 , - 17 ) abs , _ , angle = self . core . main ( c . real , c . imag , phase ) # get rid of CORDIC gain and extra bits self . y_abs = abs * ( 1.0 / 1.646760 ) self . y_angle = angle return self . y_abs , self . y_angle
def check_threat ( self ) : """function to check input filetype against threat extensions list"""
is_high_threat = False for val in THREAT_EXTENSIONS . values ( ) : if type ( val ) == list : for el in val : if self . optionmenu . get ( ) == el : is_high_threat = True break else : if self . optionmenu . get ( ) == val : is_high_threat = ...
def addFixedEffect ( self , F = None , A = None , index = None ) : """set sample and trait designs F : NxK sample design A : LxP sample design fast _ computations : False deactivates the fast computations for any and common effects ( for debugging )"""
if F is None : F = np . ones ( ( self . N , 1 ) ) else : assert F . shape [ 0 ] == self . N , "F dimension mismatch" if ( ( A is None ) or ( ( A . shape == ( self . P , self . P ) ) and ( A == np . eye ( self . P ) ) . all ( ) ) ) : # case any effect self . F_any = np . hstack ( ( self . F_any , F ) ) elif ...
def update ( self ) : '''Update the encoder and the decoder to minimize the reconstruction error of the inputs . Returns : ` np . ndarray ` of the reconstruction errors .'''
observed_arr = self . noise_sampler . generate ( ) inferenced_arr = self . inference ( observed_arr ) error_arr = self . __encoder_decoder_controller . computable_loss . compute_loss ( observed_arr , inferenced_arr ) delta_arr = self . __encoder_decoder_controller . computable_loss . compute_delta ( observed_arr , infe...
def asfreq_actual ( series , freq , method = 'ffill' , how = 'end' , normalize = False ) : """Similar to pandas ' asfreq but keeps the actual dates . For example , if last data point in Jan is on the 29th , that date will be used instead of the 31st ."""
orig = series is_series = False if isinstance ( series , pd . Series ) : is_series = True name = series . name if series . name else 'data' orig = pd . DataFrame ( { name : series } ) # add date column t = pd . concat ( [ orig , pd . DataFrame ( { 'dt' : orig . index . values } , index = orig . index . valu...
def extract ( obj , pointer , bypass_ref = False ) : """Extract member or element of obj according to pointer . : param obj : the object source : param pointer : the pointer : type pointer : Pointer , str : param bypass _ ref : bypass JSON Reference event : type bypass _ ref : boolean"""
return Pointer ( pointer ) . extract ( obj , bypass_ref )
def thai_to_eng ( text : str ) -> str : """Correct text in one language that is incorrectly - typed with a keyboard layout in another language . ( type Thai with English keyboard ) : param str text : Incorrect input ( type English with Thai keyboard ) : return : English text"""
return "" . join ( [ TH_EN_KEYB_PAIRS [ ch ] if ( ch in TH_EN_KEYB_PAIRS ) else ch for ch in text ] )
def get_ad_info ( self ) : """Polls for basic AD information ( needed for determine password usage characteristics ! )"""
logger . debug ( 'Polling AD for basic info' ) ldap_filter = r'(distinguishedName=%s)' % self . _tree attributes = MSADInfo . ATTRS for entry in self . pagedsearch ( ldap_filter , attributes ) : self . _ldapinfo = MSADInfo . from_ldap ( entry ) return self . _ldapinfo logger . debug ( 'Poll finished!' )
def copy_templates ( entry_point , py_entry_point , auto_write , output_dir ) : '''Copy formatted templates from scrim / bin to output directory Attributes : entry _ point : Name of shell script py _ entry _ point : Name of python console script auto _ write : Sets SCRIM _ AUTO _ WRITE to True output _ di...
if not os . path . exists ( output_dir ) : os . makedirs ( output_dir ) scripts = [ ] for f in os . listdir ( bin_path ( ) ) : ext = os . path . splitext ( f ) [ - 1 ] newline = NEWLINE_MAP . get ( ext , '\n' ) template = bin_path ( f ) destination = output_dir + '/' + entry_point + ext scripts ...
def scale_rows_by_largest_entry ( S ) : """Scale each row in S by it ' s largest in magnitude entry . Parameters S : csr _ matrix Returns S : csr _ matrix Each row has been scaled by it ' s largest in magnitude entry Examples > > > from pyamg . gallery import poisson > > > from pyamg . util . utils ...
if not isspmatrix_csr ( S ) : raise TypeError ( 'expected csr_matrix' ) # Scale S by the largest magnitude entry in each row largest_row_entry = np . zeros ( ( S . shape [ 0 ] , ) , dtype = S . dtype ) pyamg . amg_core . maximum_row_value ( S . shape [ 0 ] , largest_row_entry , S . indptr , S . indices , S . data )...
def get_max_bond_distance ( self , el1_sym , el2_sym ) : """Use Jmol algorithm to determine bond length from atomic parameters Args : el1 _ sym : ( str ) symbol of atom 1 el2 _ sym : ( str ) symbol of atom 2 Returns : ( float ) max bond length"""
return sqrt ( ( self . el_radius [ el1_sym ] + self . el_radius [ el2_sym ] + self . tol ) ** 2 )
def delete_all_thumbnails ( path , recursive = True ) : """Delete all files within a path which match the thumbnails pattern . By default , matching files from all sub - directories are also removed . To only remove from the path directory , set recursive = False ."""
total = 0 for thumbs in all_thumbnails ( path , recursive = recursive ) . values ( ) : total += _delete_using_thumbs_list ( thumbs ) return total
def to_2d ( self ) : """Generates the real 2D polygon of the 3D polygon . This method performs a change of reference system obtaining the same polygon but with the new z = 0 plane containing the polygon . This library mostly uses the z = 0 projection to perform operations with the polygons . For this reason...
# New reference system a = self [ 1 ] - self [ 0 ] a = a / np . linalg . norm ( a ) # arbitrary first axis n = np . cross ( a , self [ - 1 ] - self [ 0 ] ) n = n / np . linalg . norm ( n ) # normal axis b = - np . cross ( a , n ) # Orthogonal to the others # Reference system change R_inv = np . linalg . inv ( np . arra...
def disassociate_elastic_ips ( self ) : """For each attached Elastic IP , disassociate it : return : None : raises AWSAPIError"""
log = logging . getLogger ( self . cls_logger + '.disassociate_elastic_ips' ) try : address_info = self . get_elastic_ips ( ) except AWSAPIError : _ , ex , trace = sys . exc_info ( ) msg = 'Unable to determine Elastic IPs on this EC2 instance' log . error ( msg ) raise AWSAPIError , msg , trace # Re...
def make_levels_set ( levels ) : '''make set efficient will convert all lists of items in levels to a set to speed up operations'''
for level_key , level_filters in levels . items ( ) : levels [ level_key ] = make_level_set ( level_filters ) return levels
def _collect_fields ( self ) : """Iterate over all Field objects within , including multi fields ."""
for f in itervalues ( self . properties . to_dict ( ) ) : yield f # multi fields if hasattr ( f , 'fields' ) : for inner_f in itervalues ( f . fields . to_dict ( ) ) : yield inner_f # nested and inner objects if hasattr ( f , '_collect_fields' ) : for inner_f in f . _coll...
def assert_header_parsing ( headers ) : """Asserts whether all headers have been successfully parsed . Extracts encountered errors from the result of parsing headers . Only works on Python 3. : param headers : Headers to verify . : type headers : ` httplib . HTTPMessage ` . : raises urllib3 . exceptions ....
# This will fail silently if we pass in the wrong kind of parameter . # To make debugging easier add an explicit check . if not isinstance ( headers , httplib . HTTPMessage ) : raise TypeError ( 'expected httplib.Message, got {0}.' . format ( type ( headers ) ) ) defects = getattr ( headers , 'defects' , None ) get...
def read_full ( data , size ) : """read _ full reads exactly ` size ` bytes from reader . returns ` size ` bytes . : param data : Input stream to read from . : param size : Number of bytes to read from ` data ` . : return : Returns : bytes : ` part _ data `"""
default_read_size = 32768 # 32KiB per read operation . chunk = io . BytesIO ( ) chunk_size = 0 while chunk_size < size : read_size = default_read_size if ( size - chunk_size ) < default_read_size : read_size = size - chunk_size current_data = data . read ( read_size ) if not current_data or len ...
def multi_future ( children : Union [ List [ _Yieldable ] , Dict [ Any , _Yieldable ] ] , quiet_exceptions : "Union[Type[Exception], Tuple[Type[Exception], ...]]" = ( ) , ) -> "Union[Future[List], Future[Dict]]" : """Wait for multiple asynchronous futures in parallel . Since Tornado 6.0 , this function is exactly...
if isinstance ( children , dict ) : keys = list ( children . keys ( ) ) # type : Optional [ List ] children_seq = children . values ( ) # type : Iterable else : keys = None children_seq = children children_futs = list ( map ( convert_yielded , children_seq ) ) assert all ( is_future ( i ) or isi...
def create_table ( self ) : """Create the DynamoDB table used by this ObjectStore , only if it does not already exists ."""
all_tables = self . aws_conn . list_tables ( ) [ 'TableNames' ] if self . table_name in all_tables : log . info ( "Table %s already exists" % self . table_name ) else : log . info ( "Table %s does not exist: creating it" % self . table_name ) self . table = Table . create ( self . table_name , schema = [ Ha...
def prepare_for_optimization ( self ) : """Create tensorflow op for running one step of descent ."""
if self . params [ 'eig_type' ] == 'TF' : self . eig_vec_estimate = self . get_min_eig_vec_proxy ( ) elif self . params [ 'eig_type' ] == 'LZS' : self . eig_vec_estimate = self . dual_object . m_min_vec else : self . eig_vec_estimate = tf . placeholder ( tf . float32 , shape = ( self . dual_object . matrix_...
def func_args ( func ) : '''Basic function which returns a tuple of arguments of a function or method .'''
try : return tuple ( inspect . signature ( func ) . parameters ) except : return tuple ( inspect . getargspec ( func ) . args )
def integrations ( self , ** kwargs ) : """Retrieve all this services integrations ."""
ids = [ ref [ 'id' ] for ref in self [ 'integrations' ] ] return [ Integration . fetch ( id , service = self , query_params = kwargs ) for id in ids ]
def to_string ( cls , error_code ) : """Returns the string message for the given ` ` error _ code ` ` . Args : cls ( JLinkReadErrors ) : the ` ` JLinkReadErrors ` ` class error _ code ( int ) : error code to convert Returns : An error string corresponding to the error code . Raises : ValueError : if t...
if error_code == cls . ZONE_NOT_FOUND_ERROR : return 'Zone not found' return super ( JLinkReadErrors , cls ) . to_string ( error_code )
def _hash_cookies ( self ) : '''Returns the hash of a list of hashes from sorted repr ( ) of every cookie in jar as LWPCookieJar does not change it ' s hash when cookies change .'''
return hash ( frozenset ( [ hash ( c ) for c in sorted ( [ repr ( c ) for c in self . session . cookies ] ) ] ) )
def choose_directory ( self , line_edit , title ) : """Show a directory selection dialog . This function will show the dialog then set line _ edit widget text with output from the dialog . : param line _ edit : Widget whose text should be updated . : type line _ edit : QLineEdit : param title : title of d...
path = line_edit . text ( ) # noinspection PyCallByClass , PyTypeChecker new_path = QFileDialog . getExistingDirectory ( self , title , path , QFileDialog . ShowDirsOnly ) if new_path is not None and os . path . exists ( new_path ) : line_edit . setText ( new_path )
def doublewell_eigs ( n_grid , lag_time = 1 ) : """Analytic eigenvalues / eigenvectors for the doublwell system TODO : DOCUMENT ME"""
return _brownian_eigs ( n_grid , lag_time , DOUBLEWELL_GRAD_POTENTIAL , - np . pi , np . pi , reflect_bc = True )
def integer_fractional_parts ( number ) : """Returns a tuple of the integer and fractional parts of a number . Args : number ( iterable container ) : A number in the following form : ( . . . , " . " , int , int , int , . . . ) Returns : ( integer _ part , fractional _ part ) : tuple . Example : > > > ...
radix_point = number . index ( "." ) integer_part = number [ : radix_point ] fractional_part = number [ radix_point : ] return ( integer_part , fractional_part )
def stop_message_live_location ( self , chat_id = None , message_id = None , inline_message_id = None , reply_markup = None ) : """Use this method to stop updating a live location message sent by the bot or via the bot ( for inline bots ) before live _ period expires : param chat _ id : : param message _ id :...
return types . Message . de_json ( apihelper . stop_message_live_location ( self . token , chat_id , message_id , inline_message_id , reply_markup ) )
def predict ( self , prediction_index , temperature_data , with_disaggregated = False , with_design_matrix = False , ** kwargs ) : """Predict"""
return caltrack_usage_per_day_predict ( self . model_type , self . model_params , prediction_index , temperature_data , with_disaggregated = with_disaggregated , with_design_matrix = with_design_matrix , ** kwargs )
def load_waypoints ( self , filename ) : '''load waypoints from a file'''
self . wploader . target_system = self . target_system self . wploader . target_component = self . target_component try : self . wploader . load ( filename ) except Exception as msg : print ( "Unable to load %s - %s" % ( filename , msg ) ) return print ( "Loaded %u waypoints from %s" % ( self . wploader . c...
def read_text ( self , text ) : """Read a given text phrase . Parameters text : str The text to read . Typically a sentence or a paragraph ."""
logger . info ( 'Reading: "%s"' % text ) msg_id = 'RT000%s' % self . msg_counter kqml_perf = _get_perf ( text , msg_id ) self . reply_counter += 1 self . msg_counter += 1 self . send ( kqml_perf )
def virtual_interface_list ( provider , names , ** kwargs ) : '''List virtual interfaces on a server CLI Example : . . code - block : : bash salt minionname cloud . virtual _ interface _ list my - nova names = [ ' salt - master ' ]'''
client = _get_client ( ) return client . extra_action ( provider = provider , names = names , action = 'virtual_interface_list' , ** kwargs )
def check_if_release_is_current ( log ) : """Warns the user if their release is behind the latest PyPi _ _ version _ _ ."""
if __version__ == '0.0.0' : return client = xmlrpclib . ServerProxy ( 'https://pypi.python.org/pypi' ) latest_pypi_version = client . package_releases ( 'hca' ) latest_version_nums = [ int ( i ) for i in latest_pypi_version [ 0 ] . split ( '.' ) ] this_version_nums = [ int ( i ) for i in __version__ . split ( '.' )...
def export_json ( self , filename , orient = 'records' ) : """Writes an SFrame to a JSON file . Parameters filename : string The location to save the JSON file . orient : string , optional . Either " records " or " lines " If orient = " records " the file is saved as a single JSON array . If orient = " ...
if orient == "records" : self . pack_columns ( dtype = dict ) . export_csv ( filename , file_header = '[' , file_footer = ']' , header = False , double_quote = False , quote_level = csv . QUOTE_NONE , line_prefix = ',' , _no_prefix_on_first_value = True ) elif orient == "lines" : self . pack_columns ( dtype = d...
def imdecode ( image_path ) : """Return BGR image read by opencv"""
import os assert os . path . exists ( image_path ) , image_path + ' not found' im = cv2 . imread ( image_path ) return im
def launch ( exception = None , extraceback = None , signalnum = None , frame = None ) : """Launches an emergency console : param exception : unhandled exception value : param extraceback : unhandled exception traceback : param signalnum : interrupting signal number : param frame : interrupting signal frame...
print ( '\n' ) print ( 'Activating emergency console' ) print ( '----------------------------' ) print ( 'Caused by:' ) if signalnum : signals = dict ( ( k , v ) for v , k in signal . __dict__ . iteritems ( ) if v . startswith ( 'SIG' ) ) print ( 'Signal' , signals . get ( signalnum , 'unknown' ) ) elif excepti...
def run ( configobj = None , editpars = False ) : """Teal interface for running this code ."""
if configobj is None : configobj = teal . teal ( __taskname__ , loadOnly = ( not editpars ) ) update ( configobj [ 'input' ] , configobj [ 'refdir' ] , local = configobj [ 'local' ] , interactive = configobj [ 'interactive' ] , wcsupdate = configobj [ 'wcsupdate' ] )
def export ( self , swf , shape , ** export_opts ) : """Exports the specified shape of the SWF to SVG . @ param swf The SWF . @ param shape Which shape to export , either by characterId ( int ) or as a Tag object ."""
# If ` shape ` is given as int , find corresponding shape tag . if isinstance ( shape , Tag ) : shape_tag = shape else : shapes = [ x for x in swf . all_tags_of_type ( ( TagDefineShape , TagDefineSprite ) ) if x . characterId == shape ] if len ( shapes ) : shape_tag = shapes [ 0 ] else : ...
def pretty_format ( message ) : """Convert a message dictionary into a human - readable string . @ param message : Message to parse , as dictionary . @ return : Unicode string ."""
skip = { TIMESTAMP_FIELD , TASK_UUID_FIELD , TASK_LEVEL_FIELD , MESSAGE_TYPE_FIELD , ACTION_TYPE_FIELD , ACTION_STATUS_FIELD } def add_field ( previous , key , value ) : value = unicode ( pprint . pformat ( value , width = 40 ) ) . replace ( "\\n" , "\n " ) . replace ( "\\t" , "\t" ) # Reindent second line and ...
def set ( self , timestamp , status , value ) : """Set the current value of the sensor . Parameters timestamp : float in seconds The time at which the sensor value was determined . status : Sensor status constant Whether the value represents an error condition or not . value : object The value of the ...
reading = self . _current_reading = Reading ( timestamp , status , value ) self . notify ( reading )
def comment ( self , issue , body ) : """Comment on existing issue on Github . For JSON data returned by Github refer : https : / / developer . github . com / v3 / issues / comments / # create - a - comment : param issue : object of exisiting issue : param body : body of the comment : returns : dict of JS...
url = issue . comments_url data = { 'body' : body } response = self . session . post ( url , json . dumps ( data ) ) assert response . status_code == 201 return json . loads ( response . content )
def merge ( branch , fast_forward = False , commit = True , options = None ) : """Merge that branch into current branch fast _ forward and commit add the eponymous options to the command"""
more_options = [ fast_forward and '--ff' or '--no-ff' , commit and '--commit' or '--no-commit' , ] + ( options and options or [ ] ) option_string = ' ' . join ( more_options ) all_branches = branches ( ) assert branch in all_branches , 'Missing branch: %s' % branch command = 'merge %s %s' % ( option_string , branch ) r...
async def get_creds_by_id ( self , proof_req_json : str , cred_ids : set ) -> str : """Get creds structure from HolderProver wallet by credential identifiers . : param proof _ req _ json : proof request as per get _ creds ( ) above : param cred _ ids : set of credential identifiers of interest : return : json...
LOGGER . debug ( 'HolderProver.get_creds_by_id >>> proof_req_json: %s, cred_ids: %s' , proof_req_json , cred_ids ) creds_json = await anoncreds . prover_get_credentials_for_proof_req ( self . wallet . handle , proof_req_json ) # retain only creds of interest : find corresponding referents rv_json = prune_creds_json ( j...
def selectnotnone ( table , field , complement = False ) : """Select rows where the given field is not ` None ` ."""
return select ( table , field , lambda v : v is not None , complement = complement )
def save_species_count ( self , delimiter = ' ' , filename = 'speciation.csv' ) : """Log speciation throughout evolution ."""
with open ( filename , 'w' ) as f : w = csv . writer ( f , delimiter = delimiter ) for s in self . get_species_sizes ( ) : w . writerow ( s )
def update_group ( self , group_id , name ) : """修改分组名 。 : param group _ id : 分组 ID , 由微信分配 : param name : 分组名字 ( 30个字符以内 ) : return : 返回的 JSON 数据包"""
return self . post ( url = "https://api.weixin.qq.com/cgi-bin/groups/update" , data = { "group" : { "id" : int ( group_id ) , "name" : to_text ( name ) } } )
def map_request_to_vnics ( self , requests , vnics , existing_network , default_network , reserved_networks ) : """gets the requests for connecting netwoks and maps it the suitable vnic of specific is not specified : param reserved _ networks : array of reserved networks : param requests : : param vnics : :...
mapping = dict ( ) reserved_networks = reserved_networks if reserved_networks else [ ] vnics_to_network_mapping = self . _map_vnic_to_network ( vnics , existing_network , default_network , reserved_networks ) for request in requests : if request . vnic_name : if request . vnic_name not in vnics_to_network_m...
def _set_rp_address ( self , v , load = False ) : """Setter method for rp _ address , mapped from YANG variable / rbridge _ id / router / hide _ pim _ holder / pim / rp _ address ( list ) If this variable is read - only ( config : false ) in the source YANG file , then _ set _ rp _ address is considered as a pr...
if hasattr ( v , "_utype" ) : v = v . _utype ( v ) try : t = YANGDynClass ( v , base = YANGListType ( "rp_ip_addr" , rp_address . rp_address , yang_name = "rp-address" , rest_name = "rp-address" , parent = self , is_container = 'list' , user_ordered = False , path_helper = self . _path_helper , yang_keys = 'rp-...
def ilsr_pairwise ( n_items , data , alpha = 0.0 , initial_params = None , max_iter = 100 , tol = 1e-8 ) : """Compute the ML estimate of model parameters using I - LSR . This function computes the maximum - likelihood ( ML ) estimate of model parameters given pairwise - comparison data ( see : ref : ` data - pa...
fun = functools . partial ( lsr_pairwise , n_items = n_items , data = data , alpha = alpha ) return _ilsr ( fun , initial_params , max_iter , tol )
def calculate_size ( name , expected , updated ) : """Calculates the request payload size"""
data_size = 0 data_size += calculate_size_str ( name ) data_size += BOOLEAN_SIZE_IN_BYTES if expected is not None : data_size += calculate_size_data ( expected ) data_size += BOOLEAN_SIZE_IN_BYTES if updated is not None : data_size += calculate_size_data ( updated ) return data_size
def _get_filtered_stmts ( self , lookup_node , node , stmts , mystmt ) : """method used in filter _ stmts"""
if self is mystmt : if isinstance ( lookup_node , ( Const , Name ) ) : return [ lookup_node ] , True elif self . statement ( ) is mystmt : # original node ' s statement is the assignment , only keeps # current node ( gen exp , list comp ) return [ node ] , True return stmts , False
def get_goea_nts_all ( self , fldnames = None , ** kws ) : """Get namedtuples containing user - specified ( or default ) data from GOEA results . Reformats data from GOEnrichmentRecord objects into lists of namedtuples so the generic table writers may be used ."""
# kws : prt _ if indent itemid2name ( study _ items ) data_nts = [ ] # A list of namedtuples containing GOEA results if not self . goea_results : return data_nts keep_if = kws . get ( 'keep_if' , None ) rpt_fmt = kws . get ( 'rpt_fmt' , False ) indent = kws . get ( 'indent' , False ) # I . FIELD ( column ) NAMES no...
def to_frame ( self , index = True , name = None ) : """Create a DataFrame with the levels of the MultiIndex as columns . Column ordering is determined by the DataFrame constructor with data as a dict . . . versionadded : : 0.24.0 Parameters index : boolean , default True Set the index of the returned D...
from pandas import DataFrame if name is not None : if not is_list_like ( name ) : raise TypeError ( "'name' must be a list / sequence " "of column names." ) if len ( name ) != len ( self . levels ) : raise ValueError ( "'name' should have same length as " "number of levels on index." ) idx_n...