signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def prune_to_subset ( self , subset , inplace = False ) : """Prunes the Tree to just the taxon set given in ` subset `"""
if not subset . issubset ( self . labels ) : print ( '"subset" is not a subset' ) return if not inplace : t = self . copy ( ) else : t = self t . _tree . retain_taxa_with_labels ( subset ) t . _tree . encode_bipartitions ( ) t . _dirty = True return t
def is_session_storage_enabled ( self , subject = None ) : """Returns ` ` True ` ` if session storage is generally available ( as determined by the super class ' s global configuration property is _ session _ storage _ enabled and no request - specific override has turned off session storage , False otherwise...
if subject . get_session ( False ) : # then use what already exists return True if not self . session_storage_enabled : # honor global setting : return False # non - web subject instances can ' t be saved to web - only session managers : if ( not hasattr ( subject , 'web_registry' ) and self . session_manager a...
def _paint_icon ( self , iconic , painter , rect , mode , state , options ) : """Paint a single icon ."""
painter . save ( ) color = options [ 'color' ] char = options [ 'char' ] color_options = { QIcon . On : { QIcon . Normal : ( options [ 'color_on' ] , options [ 'on' ] ) , QIcon . Disabled : ( options [ 'color_on_disabled' ] , options [ 'on_disabled' ] ) , QIcon . Active : ( options [ 'color_on_active' ] , options [ 'on...
def loop_until_timeout_or_not_none ( timeout_s , function , sleep_s = 1 ) : # pylint : disable = invalid - name """Loops until the specified function returns non - None or until a timeout . Args : timeout _ s : The number of seconds to wait until a timeout condition is reached . As a convenience , this accept...
return loop_until_timeout_or_valid ( timeout_s , function , lambda x : x is not None , sleep_s )
def validate ( self , request , response ) : """refreshes a resource when a validation response is received : param request : : param response : : return :"""
element = self . search_response ( request ) if element is not None : element . cached_response . options = response . options element . freshness = True element . max_age = response . max_age element . creation_time = time . time ( ) element . uri = request . proxy_uri
def install ( ) : """Function executed when running the script with the - install switch"""
# Create Spyder start menu folder # Don ' t use CSIDL _ COMMON _ PROGRAMS because it requres admin rights # This is consistent with use of CSIDL _ DESKTOPDIRECTORY below # CSIDL _ COMMON _ PROGRAMS = # C : \ ProgramData \ Microsoft \ Windows \ Start Menu \ Programs # CSIDL _ PROGRAMS = # C : \ Users \ < username > \ Ap...
def available_readers ( as_dict = False ) : """Available readers based on current configuration . Args : as _ dict ( bool ) : Optionally return reader information as a dictionary . Default : False Returns : List of available reader names . If ` as _ dict ` is ` True ` then a list of dictionaries including...
readers = [ ] for reader_configs in configs_for_reader ( ) : try : reader_info = read_reader_config ( reader_configs ) except ( KeyError , IOError , yaml . YAMLError ) : LOG . warning ( "Could not import reader config from: %s" , reader_configs ) LOG . debug ( "Error loading YAML" , exc_...
def download ( directory , filename ) : """Download ( and unzip ) a file from the MNIST dataset if not already done ."""
filepath = os . path . join ( directory , filename ) if tf . gfile . Exists ( filepath ) : return filepath if not tf . gfile . Exists ( directory ) : tf . gfile . MakeDirs ( directory ) url = 'http://yann.lecun.com/exdb/mnist/' + filename + '.gz' _ , zipped_filepath = tempfile . mkstemp ( suffix = '.gz' ) print...
def is_optional ( self ) : """Returns whether the parameter is optional or required : return : Return True if optional , False if required"""
if ( ( 'optional' in self . attributes and bool ( self . attributes [ 'optional' ] . strip ( ) ) ) and ( 'minValue' in self . attributes and self . attributes [ 'minValue' ] == 0 ) ) : return True else : return False
def _GenerateChunk ( self , length ) : """Generates data for a single chunk ."""
while 1 : to_read = min ( length , self . RECV_BLOCK_SIZE ) if to_read == 0 : return data = self . rfile . read ( to_read ) if not data : return yield data length -= len ( data )
def functions_shadowed ( self ) : '''Return the list of functions shadowed Returns : list ( core . Function )'''
candidates = [ c . functions_not_inherited for c in self . contract . inheritance ] candidates = [ candidate for sublist in candidates for candidate in sublist ] return [ f for f in candidates if f . full_name == self . full_name ]
def _idle_register_view ( self , view ) : """Internal method that calls register _ view"""
assert ( self . view is None ) self . view = view if self . handlers == "class" : for name in dir ( self ) : when , _ , what = partition ( name , '_' ) widget , _ , signal = partition ( what , '__' ) if when == "on" : try : view [ widget ] . connect ( signal , get...
def _recon_lcs ( x , y ) : """Returns the Longest Subsequence between x and y . Source : http : / / www . algorithmist . com / index . php / Longest _ Common _ Subsequence : param x : sequence of words : param y : sequence of words : returns sequence : LCS of x and y"""
table = _lcs ( x , y ) def _recon ( i , j ) : if i == 0 or j == 0 : return [ ] elif x [ i - 1 ] == y [ j - 1 ] : return _recon ( i - 1 , j - 1 ) + [ ( x [ i - 1 ] , i ) ] elif table [ i - 1 , j ] > table [ i , j - 1 ] : return _recon ( i - 1 , j ) else : return _recon ( i...
def integrate_predefined ( rhs , jac , y0 , xout , atol , rtol , dx0 = 0.0 , dx_max = 0.0 , check_callable = False , check_indexing = False , ** kwargs ) : """Integrates a system of ordinary differential equations . Parameters rhs : callable Function with signature f ( t , y , fout ) which modifies fout * inp...
# Sanity checks to reduce risk of having a segfault : jac = _ensure_5args ( jac ) if check_callable : _check_callable ( rhs , jac , xout [ 0 ] , y0 ) if check_indexing : _check_indexing ( rhs , jac , xout [ 0 ] , y0 ) return predefined ( rhs , jac , np . asarray ( y0 , dtype = np . float64 ) , np . asarray ( xo...
def unpy2exe ( filename , python_version = None , output_dir = None ) : """Process input params and produce output pyc files ."""
if output_dir is None : output_dir = '.' elif not os . path . exists ( output_dir ) : os . makedirs ( output_dir ) pe = pefile . PE ( filename ) is_py2exe = check_py2exe_file ( pe ) if not is_py2exe : raise ValueError ( 'Not a py2exe executable.' ) code_objects = extract_code_objects ( pe ) for co in code_o...
def get_matching_text_in_strs ( a , b , match_min_size = 30 , ignore = '' , end_characters = '' ) : # type : ( str , str , int , str , str ) - > List [ str ] """Returns a list of matching blocks of text in a and b Args : a ( str ) : First string to match b ( str ) : Second string to match match _ min _ size...
compare = difflib . SequenceMatcher ( lambda x : x in ignore ) compare . set_seqs ( a = a , b = b ) matching_text = list ( ) for match in compare . get_matching_blocks ( ) : start = match . a text = a [ start : start + match . size ] if end_characters : prev_text = text while len ( text ) !=...
def compute_node_positions ( self ) : """Uses the get _ cartesian function to compute the positions of each node in the Circos plot ."""
xs = [ ] ys = [ ] node_r = self . nodeprops [ "radius" ] radius = circos_radius ( n_nodes = len ( self . graph . nodes ( ) ) , node_r = node_r ) self . plot_radius = radius self . nodeprops [ "linewidth" ] = radius * 0.01 for node in self . nodes : x , y = get_cartesian ( r = radius , theta = node_theta ( self . no...
def scale_and_crop ( im , size , crop = False , upscale = False , zoom = None , target = None , ** kwargs ) : """Handle scaling and cropping the source image . Images can be scaled / cropped against a single dimension by using zero as the placeholder in the size . For example , ` ` size = ( 100 , 0 ) ` ` will c...
source_x , source_y = [ float ( v ) for v in im . size ] target_x , target_y = [ int ( v ) for v in size ] if crop or not target_x or not target_y : scale = max ( target_x / source_x , target_y / source_y ) else : scale = min ( target_x / source_x , target_y / source_y ) # Handle one - dimensional targets . if ...
def write_file ( file , b ) : """Write ` ` b ` ` to file ` ` file ` ` . : arg file type : path - like or file - like object . : arg bytes b : The content ."""
if hasattr ( file , "write_bytes" ) : file . write_bytes ( b ) elif hasattr ( file , "write" ) : file . write ( b ) else : with open ( file , "wb" ) as f : f . write ( b )
def send ( self , load , tries = None , timeout = None , raw = False ) : # pylint : disable = unused - argument '''Emulate the channel send method , the tries and timeout are not used'''
if 'cmd' not in load : log . error ( 'Malformed request, no cmd: %s' , load ) return { } cmd = load [ 'cmd' ] . lstrip ( '_' ) if cmd in self . cmd_stub : return self . cmd_stub [ cmd ] if not hasattr ( self . fs , cmd ) : log . error ( 'Malformed request, invalid cmd: %s' , load ) return { } return...
def _add_new_route ( dcidr , router_ip , vpc_info , con , route_table_id ) : """Add a new route to the route table ."""
try : instance , eni = find_instance_and_eni_by_ip ( vpc_info , router_ip ) # Only set the route if the RT is associated with any of the subnets # used for the cluster . rt_subnets = set ( vpc_info [ 'rt_subnet_lookup' ] . get ( route_table_id , [ ] ) ) cluster_node_subnets = set ( vpc_info [ 'clust...
def __update_keywords ( uid , inkeywords ) : '''Update with keywords .'''
entry = TabPost . update ( keywords = inkeywords ) . where ( TabPost . uid == uid ) entry . execute ( )
def p_generate_items ( self , p ) : 'generate _ items : generate _ items generate _ item'
p [ 0 ] = p [ 1 ] + ( p [ 2 ] , ) p . set_lineno ( 0 , p . lineno ( 1 ) )
def tuple ( self ) : """Return values as a tuple ."""
return tuple ( getattr ( self , k ) for k in self . __class__ . defaults )
def serve_assets ( path ) : """Serve Nikola assets . This is meant to be used ONLY by the internal dev server . Please configure your web server to handle requests to this URL : : / assets / = > output / assets"""
res = os . path . join ( app . config [ 'NIKOLA_ROOT' ] , _site . config [ "OUTPUT_FOLDER" ] , 'assets' ) return send_from_directory ( res , path )
def ram_dp_rf ( clka , clkb , wea , web , addra , addrb , dia , dib , doa , dob ) : '''RAM : Dual - Port , Read - First'''
memL = [ Signal ( intbv ( 0 ) [ len ( dia ) : ] ) for _ in range ( 2 ** len ( addra ) ) ] @ always ( clka . posedge ) def writea ( ) : if wea : memL [ int ( addra ) ] . next = dia doa . next = memL [ int ( addra ) ] @ always ( clkb . posedge ) def writeb ( ) : if web : memL [ int ( addrb ) ]...
def _compute_faulting_style_term ( self , C , rake ) : """Compute and return fifth and sixth terms in equations ( 2a ) and ( 2b ) , pages 20."""
Fn = float ( rake > - 135.0 and rake < - 45.0 ) Fr = float ( rake > 45.0 and rake < 135.0 ) return C [ 'a8' ] * Fn + C [ 'a9' ] * Fr
def keys ( cls , fqdn , sort_by = None ) : """Display keys information about a domain ."""
meta = cls . get_fqdn_info ( fqdn ) url = meta [ 'domain_keys_href' ] return cls . json_get ( cls . get_sort_url ( url , sort_by ) )
def load ( ctx , variant_source , family_file , family_type , root ) : """Load a variant source into the database . If no database was found run puzzle init first . 1 . VCF : If a vcf file is used it can be loaded with a ped file 2 . GEMINI : Ped information will be retreived from the gemini db"""
root = root or ctx . obj . get ( 'root' ) or os . path . expanduser ( "~/.puzzle" ) if os . path . isfile ( root ) : logger . error ( "'root' can't be a file" ) ctx . abort ( ) logger . info ( "Root directory is: {}" . format ( root ) ) db_path = os . path . join ( root , 'puzzle_db.sqlite3' ) logger . info ( "...
def build_stoplist ( self , texts , basis = 'zou' , size = 100 , sort_words = True , inc_values = False , lower = True , remove_punctuation = True , remove_numbers = True , include = [ ] , exclude = [ ] ) : """: param texts : list of strings used as document collection for extracting stopwords : param basis : Def...
# Check ' texts ' type for string if isinstance ( texts , str ) : texts = [ texts ] # Move all of this preprocessing code outside ' build _ stoplist ' if lower : texts = [ text . lower ( ) for text in texts ] if remove_punctuation : texts = self . _remove_punctuation ( texts , self . punctuation ) if remove...
def part_lister ( mpupload , part_number_marker = None ) : """A generator function for listing parts of a multipart upload ."""
more_results = True part = None while more_results : parts = mpupload . get_all_parts ( None , part_number_marker ) for part in parts : yield part part_number_marker = mpupload . next_part_number_marker more_results = mpupload . is_truncated
def detect_volumes ( self , vstype = None , method = None , force = False ) : """Iterator for detecting volumes within this volume system . : param str vstype : The volume system type to use . If None , uses : attr : ` vstype ` : param str method : The detection method to use . If None , uses : attr : ` detecti...
if self . has_detected and not force : logger . warning ( "Detection already ran." ) return if vstype is None : vstype = self . vstype if method is None : method = self . volume_detector if method == 'auto' : method = VolumeSystem . _determine_auto_detection_method ( ) if method in ALL_VOLUME_SYSTEM...
def state_size ( self ) -> Sequence [ Shape ] : '''Returns the MDP state size .'''
return self . _sizes ( self . _compiler . rddl . state_size )
def show_help ( command_name : str = None , raw_args : str = '' ) -> Response : """Prints the basic command help to the console"""
response = Response ( ) cmds = fetch ( ) if command_name and command_name in cmds : parser , result = parse . get_parser ( cmds [ command_name ] , parse . explode_line ( raw_args ) , dict ( ) ) if parser is not None : out = parser . format_help ( ) return response . notify ( kind = 'INFO' , code...
def wrap_error ( self , data , renderer_context , keys_are_fields , issue_is_title ) : """Convert error native data to the JSON API Error format JSON API has a different format for errors , but Django REST Framework doesn ' t have a separate rendering path for errors . This results in some guesswork to determ...
response = renderer_context . get ( "response" , None ) status_code = str ( response and response . status_code ) errors = [ ] for field , issues in data . items ( ) : if isinstance ( issues , six . string_types ) : issues = [ issues ] for issue in issues : error = self . dict_class ( ) ...
def _add_spacer_to_menu ( self ) : """Create a spacer to the menu to separate action groups ."""
separator = QAction ( self . iface . mainWindow ( ) ) separator . setSeparator ( True ) self . iface . addPluginToMenu ( self . tr ( 'InaSAFE' ) , separator )
def get_weather_name ( self , ip ) : '''Get weather _ name'''
rec = self . get_all ( ip ) return rec and rec . weather_name
def apply_filters ( instance , html , field_name ) : """Run all filters for a given HTML snippet . Returns the results of the pre - filter and post - filter as tuple . This function can be called from the : meth : ` ~ django . db . models . Model . full _ clean ` method in the model . That function is called ...
try : html = apply_pre_filters ( instance , html ) # Perform post processing . This does not effect the original ' html ' html_final = apply_post_filters ( instance , html ) except ValidationError as e : if hasattr ( e , 'error_list' ) : # The filters can raise a " dump " ValidationError with a single e...
def initialize_request ( self , request , * args , ** kwargs ) : """Returns the initial request object ."""
parser_context = self . get_parser_context ( request ) return Request ( request , parsers = self . get_parsers ( ) , authenticators = self . get_authenticators ( ) , negotiator = self . get_content_negotiator ( ) , parser_context = parser_context )
def attributes ( self , full = 0 ) : """Return a dictionnary describing every global attribute attached to the SD interface . Args : : full true to get complete info about each attribute false to report only each attribute value Returns : : Empty dictionnary if no global attribute defined Otherwise , ...
# Get the number of global attributes . nsds , natts = self . info ( ) # Inquire each attribute res = { } for n in range ( natts ) : a = self . attr ( n ) name , aType , nVal = a . info ( ) if full : res [ name ] = ( a . get ( ) , a . index ( ) , aType , nVal ) else : res [ name ] = a . ...
def i_ll ( self ) : """Second moment of inertia around the length axis . : return :"""
d_values = [ ] for i in range ( self . n_pads_w ) : d_values . append ( self . pad_position_w ( i ) ) d_values = np . array ( d_values ) - self . width / 2 area_d_sqrd = sum ( self . pad_area * d_values ** 2 ) * self . n_pads_l i_second = self . pad_i_ll * self . n_pads return area_d_sqrd + i_second
def rmdir ( self , directory , missing_okay = False ) : """Forcefully remove the specified directory and all its children ."""
# Build a script to walk an entire directory structure and delete every # file and subfolder . This is tricky because MicroPython has no os . walk # or similar function to walk folders , so this code does it manually # with recursion and changing directories . For each directory it lists # the files and deletes everyth...
def reset_offsets_if_needed ( self , partitions ) : """Lookup and set offsets for any partitions which are awaiting an explicit reset . Arguments : partitions ( set of TopicPartitions ) : the partitions to reset"""
for tp in partitions : # TODO : If there are several offsets to reset , we could submit offset requests in parallel if self . _subscriptions . is_assigned ( tp ) and self . _subscriptions . is_offset_reset_needed ( tp ) : self . _reset_offset ( tp )
def line_width ( default_width = DEFAULT_LINE_WIDTH , max_width = MAX_LINE_WIDTH ) : """Return the ideal column width for the output from : func : ` see . see ` , taking the terminal width into account to avoid wrapping ."""
width = term_width ( ) if width : # pragma : no cover ( no terminal info in Travis CI ) return min ( width , max_width ) else : return default_width
def parse_docstring ( docstring ) : '''Given a docstring , parse it into a description and epilog part'''
if docstring is None : return '' , '' parts = _DOCSTRING_SPLIT . split ( docstring ) if len ( parts ) == 1 : return docstring , '' elif len ( parts ) == 2 : return parts [ 0 ] , parts [ 1 ] else : raise TooManySplitsError ( )
def __similarity ( s1 , s2 , ngrams_fn , n = 3 ) : """The fraction of n - grams matching between two sequences Args : s1 : a string s2 : another string n : an int for the n in n - gram Returns : float : the fraction of n - grams matching"""
ngrams1 , ngrams2 = set ( ngrams_fn ( s1 , n = n ) ) , set ( ngrams_fn ( s2 , n = n ) ) matches = ngrams1 . intersection ( ngrams2 ) return 2 * len ( matches ) / ( len ( ngrams1 ) + len ( ngrams2 ) )
def addend_ids ( self ) : """tuple of int ids of elements contributing to this subtotal . Any element id not present in the dimension or present but representing missing data is excluded ."""
return tuple ( arg for arg in self . _subtotal_dict . get ( "args" , [ ] ) if arg in self . valid_elements . element_ids )
def jboss_domain_server_log_dir ( broker ) : """Command : JBoss domain server log directory"""
ps = broker [ DefaultSpecs . ps_auxww ] . content results = [ ] findall = re . compile ( r"\-Djboss\.server\.log\.dir=(\S+)" ) . findall # JBoss domain server progress command content should contain jboss . server . log . dir for p in ps : if '-D[Server:' in p : found = findall ( p ) if found : # On...
def next ( self ) : """Return one of record in this batch in out - of - order . : raises : ` StopIteration ` when no more record is in this batch"""
if self . _records_iter >= len ( self . _records ) : raise StopIteration self . _records_iter += 1 return self . _records [ self . _records_iter - 1 ]
def cluster_2_json ( self ) : """transform this local object ot Ariane server JSON object : return : the JSON object"""
LOGGER . debug ( "Cluster.cluster_2_json" ) json_obj = { 'clusterID' : self . id , 'clusterName' : self . name , 'clusterContainersID' : self . containers_id } return json_obj
def _equalizeHistogram ( img ) : '''histogram equalisation not bounded to int ( ) or an image depth of 8 bit works also with negative numbers'''
# to float if int : intType = None if 'f' not in img . dtype . str : TO_FLOAT_TYPES = { np . dtype ( 'uint8' ) : np . float16 , np . dtype ( 'uint16' ) : np . float32 , np . dtype ( 'uint32' ) : np . float64 , np . dtype ( 'uint64' ) : np . float64 } intType = img . dtype img = img . astype ( TO_FLOAT_TYPES...
def check_valid_rx_can_msg ( result ) : """Checks if function : meth : ` UcanServer . read _ can _ msg ` returns a valid CAN message . : param ReturnCode result : Error code of the function . : return : True if a valid CAN messages was received , otherwise False . : rtype : bool"""
return ( result . value == ReturnCode . SUCCESSFUL ) or ( result . value > ReturnCode . WARNING )
def top_priority_effect_per_transcript_id ( self ) : """Highest priority effect for each unique transcript ID"""
return OrderedDict ( ( transcript_id , top_priority_effect ( variant_effects ) ) for ( transcript_id , variant_effects ) in self . groupby_transcript_id ( ) . items ( ) )
def get_runs ( ) : """Send a dictionary of runs associated with the selected project . Usage description : This function is usually called to get and display the list of runs associated with a selected project available in the database . : return : JSON , { < int _ keys > : < run _ name > }"""
assert request . method == "POST" , "POST request expected received {}" . format ( request . method ) if request . method == "POST" : try : selected_project = request . form [ "selected_project" ] runs = utils . get_runs ( selected_project ) return jsonify ( runs ) except Exception as e ...
def load ( self , format = None , * , kwargs = { } ) : '''deserialize object from the file . auto detect format by file extension name if ` format ` is None . for example , ` . json ` will detect as ` json ` . * raise ` FormatNotFoundError ` on unknown format . * raise ` SerializeError ` on any serialize ex...
return load ( self , format = format , kwargs = kwargs )
def wait_for_conns ( self , timeout = 60 , start_delay = 0 , interval = 5 , ** kwargs ) : '''delays unitil all connections are working args : timeout : number of seconds to try to connecting . Error out when timeout is reached start _ delay : number of seconds to wait before checking status interval : num...
log . setLevel ( kwargs . get ( 'log_level' , self . log_level ) ) timestamp = time . time ( ) last_check = time . time ( ) + start_delay - interval last_delay_notification = time . time ( ) - interval timeout += 1 failing = True up_conns = { } # loop until the server is up or the timeout is reached while ( ( time . ti...
def key_handle_to_int ( this ) : """Turn " 123 " into 123 and " KSM1 " into 827151179 (0x314d534b , ' K ' = 0x4b , S = ' 0x53 ' , M = 0x4d ) . YHSM is little endian , so this makes the bytes KSM1 appear in the most human readable form in packet traces ."""
try : num = int ( this ) return num except ValueError : if this [ : 2 ] == "0x" : return int ( this , 16 ) if ( len ( this ) == 4 ) : num = struct . unpack ( '<I' , this ) [ 0 ] return num raise pyhsm . exception . YHSM_Error ( "Could not parse key_handle '%s'" % ( this ) )
def _process_pub_dbxref ( self , limit ) : """Xrefs for publications ( ie FBrf = PMID ) : param limit : : return :"""
if self . test_mode : graph = self . testgraph else : graph = self . graph model = Model ( graph ) raw = '/' . join ( ( self . rawdir , 'pub_dbxref' ) ) LOG . info ( "processing pub_dbxref" ) line_counter = 0 with open ( raw , 'r' ) as f : filereader = csv . reader ( f , delimiter = '\t' , quotechar = '\"' ...
def selectOptimalChunk ( self , peer ) : """select an optimal chunk to send to a peer . @ return : int ( chunkNumber ) , str ( chunkData ) if there is data to be sent , otherwise None , None"""
# stuff I have have = sets . Set ( self . mask . positions ( 1 ) ) # stuff that this peer wants want = sets . Set ( self . peers [ peer ] . mask . positions ( 0 ) ) exchangeable = have . intersection ( want ) finalSet = dict . fromkeys ( exchangeable , 0 ) # taking a page from bittorrent , rarest - first for chunkNumbe...
def from_lasio ( cls , l , remap = None , funcs = None ) : """Make a Location object from a lasio object . Assumes we ' re starting with a lasio object , l . Args : l ( lasio ) . remap ( dict ) : Optional . A dict of ' old ' : ' new ' LAS field names . funcs ( dict ) : Optional . A dict of ' las field ' :...
params = { } funcs = funcs or { } funcs [ 'location' ] = str for field , ( sect , code ) in las_fields [ 'location' ] . items ( ) : params [ field ] = utils . lasio_get ( l , sect , code , remap = remap , funcs = funcs ) return cls ( params )
def ifelse ( arg , true_expr , false_expr ) : """Shorthand for implementing ternary expressions bool _ expr . ifelse ( 0 , 1) e . g . , in SQL : CASE WHEN bool _ expr THEN 0 else 1 END"""
# Result will be the result of promotion of true / false exprs . These # might be conflicting types ; same type resolution as case expressions # must be used . case = ops . SearchedCaseBuilder ( ) return case . when ( arg , true_expr ) . else_ ( false_expr ) . end ( )
def get_last_weeks ( number_of_weeks ) : """Get the last weeks ."""
time_now = datetime . now ( ) year = time_now . isocalendar ( ) [ 0 ] week = time_now . isocalendar ( ) [ 1 ] weeks = [ ] for i in range ( 0 , number_of_weeks ) : start = get_week_dates ( year , week - i , as_timestamp = True ) [ 0 ] n_year , n_week = get_year_week ( start ) weeks . append ( ( n_year , n_we...
def get_channel_access_token ( self , channel ) : """Return the token and sig for the given channel : param channel : the channel or channel name to get the access token for : type channel : : class : ` channel ` | : class : ` str ` : returns : The token and sig for the given channel : rtype : ( : class : `...
if isinstance ( channel , models . Channel ) : channel = channel . name r = self . oldapi_request ( 'GET' , 'channels/%s/access_token' % channel ) . json ( ) return r [ 'token' ] , r [ 'sig' ]
def fmap_info ( metadata , img , config , layout ) : """Generate a paragraph describing field map acquisition information . Parameters metadata : : obj : ` dict ` Data from the json file associated with the field map , in dictionary form . img : : obj : ` nibabel . Nifti1Image ` The nifti image of the f...
dir_ = config [ 'dir' ] [ metadata [ 'PhaseEncodingDirection' ] ] n_slices , vs_str , ms_str , fov_str = get_sizestr ( img ) seqs , variants = get_seqstr ( config , metadata ) if 'EchoTime' in metadata . keys ( ) : te = num_to_str ( metadata [ 'EchoTime' ] * 1000 ) else : te = 'UNKNOWN' if 'IntendedFor' in meta...
def ExtractEvents ( self , parser_mediator , registry_key , ** kwargs ) : """Extracts events from a Windows Registry key . Args : parser _ mediator ( ParserMediator ) : mediates interactions between parsers and other components , such as storage and dfvfs . registry _ key ( dfwinreg . WinRegistryKey ) : Win...
value = registry_key . GetValueByName ( 'AppCompatCache' ) if not value : return value_data = value . data value_data_size = len ( value . data ) format_type = self . _CheckSignature ( value_data ) if not format_type : parser_mediator . ProduceExtractionWarning ( 'Unsupported signature in AppCompatCache key: {0...
def focusInEvent ( self , e ) : """Qt Override ."""
super ( ShortcutsTable , self ) . focusInEvent ( e ) self . selectRow ( self . currentIndex ( ) . row ( ) )
def return_hdr ( self ) : """Return the header for further use . Returns subj _ id : str subject identification code start _ time : datetime start time of the dataset s _ freq : float sampling frequency chan _ name : list of str list of all the channels n _ samples : int number of samples in t...
subj_id = self . filename . stem # use directory name as subject name start_time = _read_date ( self . settings_xml ) s_freq , channels = _read_openephys ( self . openephys_file ) # only use channels that are actually in the folder chan_name = [ ] self . channels = [ ] gain = [ ] for chan in channels : channel_file...
def search_order ( self , limit = 100 , offset = 0 , common_name_pattern = None , status = None , contact_handle = None ) : """Search all SSL certificate orders ."""
response = self . request ( E . searchOrderSslCertRequest ( E . limit ( limit ) , E . offset ( offset ) , OE ( 'commonNamePattern' , common_name_pattern ) , OE ( 'status' , status , transform = _simple_array ) , OE ( 'contactHandle' , contact_handle ) , ) ) return response . as_models ( SSLOrder )
def validate_timeout_or_zero ( option , value ) : """Validates a timeout specified in milliseconds returning a value in floating point seconds for the case where None is an error and 0 is valid . Setting the timeout to nothing in the URI string is a config error ."""
if value is None : raise ConfigurationError ( "%s cannot be None" % ( option , ) ) if value == 0 or value == "0" : return 0 return validate_positive_float ( option , value ) / 1000.0
def get_supported_methods ( self , url ) : """Get a list of supported methods for a url and optional host . : param url : URL string ( including host ) : return : frozenset of supported methods"""
route = self . routes_all . get ( url ) # if methods are None then this logic will prevent an error return getattr ( route , "methods" , None ) or frozenset ( )
async def set_led_mode ( self , led_id , mode , timeout = OTGW_DEFAULT_TIMEOUT ) : """Configure the functions of the six LEDs ( A - F ) that can optionally be connected to pins RB3 / RB4 / RB6 / RB7 and the GPIO pins of the PIC . The following functions are currently available : R Receiving an Opentherm mes...
if led_id in "ABCDEF" and mode in "RXTBOFHWCEMP" : cmd = globals ( ) . get ( "OTGW_CMD_LED_{}" . format ( led_id ) ) status = { } ret = await self . _wait_for_cmd ( cmd , mode , timeout ) if ret is None : return var = globals ( ) . get ( "OTGW_LED_{}" . format ( led_id ) ) status [ var ]...
def mimetype ( self ) : """The mimetype ( content type without charset etc . )"""
ct = self . headers . get ( "content-type" ) if ct : return ct . split ( ";" ) [ 0 ] . strip ( )
def _disconnect ( self ) : """Disconnect from the transport ."""
if not self . protocol or not self . protocol . transport : self . protocol = None # Make sure protocol is None return _LOGGER . info ( 'Disconnecting from gateway' ) self . protocol . transport . close ( ) self . protocol = None
def _deserialize ( self , value , attr , data ) : """Deserialize string value ."""
value = super ( TrimmedString , self ) . _deserialize ( value , attr , data ) return value . strip ( )
def _to_dict ( self ) : """Return a json dictionary representing this model ."""
_dict = { } if hasattr ( self , 'type' ) and self . type is not None : _dict [ 'type' ] = self . type if hasattr ( self , 'data' ) and self . data is not None : _dict [ 'data' ] = self . data . _to_dict ( ) return _dict
def _get_consent_id ( self , requester , user_id , filtered_attr ) : """Get a hashed id based on requester , user id and filtered attributes : type requester : str : type user _ id : str : type filtered _ attr : dict [ str , str ] : param requester : The calling requester : param user _ id : The authorize...
filtered_attr_key_list = sorted ( filtered_attr . keys ( ) ) hash_str = "" for key in filtered_attr_key_list : _hash_value = "" . join ( sorted ( filtered_attr [ key ] ) ) hash_str += key + _hash_value id_string = "%s%s%s" % ( requester , user_id , hash_str ) return urlsafe_b64encode ( hashlib . sha512 ( id_str...
def create ( description = '<Created by Python>' , connection = None ) : """Creates a new changelist : param connection : Connection to use to create the changelist : type connection : : class : ` . Connection ` : param description : Description for new changelist : type description : str : returns : : cl...
connection = connection or Connection ( ) description = description . replace ( '\n' , '\n\t' ) form = NEW_FORMAT . format ( client = str ( connection . client ) , description = description ) result = connection . run ( [ 'change' , '-i' ] , stdin = form , marshal_output = False ) return Changelist ( int ( result . spl...
def prior_transform ( self , unit_coords , priors , prior_args = [ ] ) : """An example of one way to use the ` Prior ` objects below to go from unit cube to parameter space , for nested sampling . This takes and returns a list instead of an array , to accomodate possible vector parameters . Thus one will need...
theta = [ ] for i , ( u , p ) in enumerate ( zip ( unit_coords , priors ) ) : func = p . unit_transform try : kwargs = prior_args [ i ] except ( IndexError ) : kwargs = { } theta . append ( func ( u , ** kwargs ) ) return theta
def build_groups ( self , tokens ) : """Build dict of groups from list of tokens"""
groups = { } for token in tokens : match_type = MatchType . start if token . group_end else MatchType . single groups [ token . group_start ] = ( token , match_type ) if token . group_end : groups [ token . group_end ] = ( token , MatchType . end ) return groups
def create_volume ( self , volume_name : str , driver_spec : str = None ) : """Create new docker volumes . Only the manager nodes can create a volume Args : volume _ name ( string ) : Name for the new docker volume driver _ spec ( string ) : Driver for the docker volume"""
# Default values if driver_spec : driver = driver_spec else : driver = 'local' # Raise an exception if we are not a manager if not self . _manager : raise RuntimeError ( 'Services can only be deleted ' 'on swarm manager nodes' ) self . _client . volumes . create ( name = volume_name , driver = driver )
def clear ( self ) : """Erase the contents of the object"""
self . country_code = None self . national_number = None self . extension = None self . italian_leading_zero = None self . number_of_leading_zeros = None self . raw_input = None self . country_code_source = CountryCodeSource . UNSPECIFIED self . preferred_domestic_carrier_code = None
def pretty_objname ( self , obj = None , maxlen = 50 , color = "boldcyan" ) : """Pretty prints object name @ obj : the object whose name you want to pretty print @ maxlen : # int maximum length of an object name to print @ color : your choice of : mod : colors or | None | - > # str pretty object name from...
parent_name = lambda_sub ( "" , get_parent_name ( obj ) or "" ) objname = get_obj_name ( obj ) if color : objname += colorize ( "<{}>" . format ( parent_name ) , color , close = False ) else : objname += "<{}>" . format ( parent_name ) objname = objname if len ( objname ) < maxlen else objname [ : ( maxlen - 1 ...
def encode ( self ) : '''Compress the associated encodable payload , prepend the header then encode with base64 if requested Returns : the b64 encoded wire encoding of the histogram ( as a string ) or the compressed payload ( as a string , if b64 wrappinb is disabled )'''
# only compress the first non zero buckets # if histogram is empty we do not encode any counter if self . histogram . total_count : relevant_length = self . histogram . get_counts_array_index ( self . histogram . max_value ) + 1 else : relevant_length = 0 cpayload = self . payload . compress ( relevant_length )...
def install_program ( self ) : """install supervisor program config file"""
text = templ_program . render ( ** self . options ) config = Configuration ( self . buildout , self . program + '.conf' , { 'deployment' : self . deployment_name , 'directory' : os . path . join ( self . options [ 'etc-directory' ] , 'conf.d' ) , 'text' : text } ) return [ config . install ( ) ]
def group_by_month ( self ) : """Return a dictionary of this collection ' s values grouped by each month . Key values are between 1-12."""
hourly_data_by_month = OrderedDict ( ) for d in xrange ( 1 , 13 ) : hourly_data_by_month [ d ] = [ ] a_per = self . header . analysis_period a_per_months = a_per . months_int indx = 24 * a_per . timestep * abs ( a_per . st_day - 1 - a_per . _num_of_days_each_month [ a_per_months [ 0 ] - 1 ] ) hourly_data_by_month [...
def get_assessment_notification_session ( self , assessment_receiver ) : """Gets the notification session for notifications pertaining to assessment changes . arg : assessment _ receiver ( osid . assessment . AssessmentReceiver ) : the assessment receiver interface return : ( osid . assessment . AssessmentN...
if not self . supports_assessment_notification ( ) : raise errors . Unimplemented ( ) # pylint : disable = no - member return sessions . ItemNotificationSession ( runtime = self . _runtime , receiver = assessment_receiver )
def plot ( config , image , file ) : """Plot a single CIFAR image ."""
image = np . squeeze ( image ) print ( file , image . shape ) imsave ( file , image )
def current_target ( self ) : """Return current target ."""
actions = self . state [ self . state [ 'current_step' ] ] [ 'actions' ] for action , value in reversed ( actions ) : if action == 'target' : return value
def validate ( collection , onerror : Callable [ [ str , List ] , None ] = None ) : """Validate BioC data structure ."""
BioCValidator ( onerror ) . validate ( collection )
def make_filename_hash ( key ) : """Convert the given key ( a simple Python object ) to a unique - ish hash suitable for a filename ."""
key_repr = repr ( key ) . replace ( BASE_DIR , '' ) . encode ( 'utf8' ) # This is really stupid but necessary for making the repr ( ) s be the same on # Python 2 and 3 and thus allowing the test suite to run on both . # TODO better solutions include : not using a repr , not embedding hashes in # the expected test resul...
def handle_detached ( sender , device ) : """Handles detached events from USBDevice . start _ detection ( ) ."""
vendor , product , sernum , ifcount , description = device # Close and remove the device from our list . if sernum in list ( __devices . keys ( ) ) : __devices [ sernum ] . close ( ) del __devices [ sernum ] print ( 'detached' , sernum )
def require_remote_ref_path ( func ) : """A decorator raising a TypeError if we are not a valid remote , based on the path"""
def wrapper ( self , * args ) : if not self . is_remote ( ) : raise ValueError ( "ref path does not point to a remote reference: %s" % self . path ) return func ( self , * args ) # END wrapper wrapper . __name__ = func . __name__ return wrapper
def _oval_string ( self , p1 , p2 , p3 , p4 ) : """Return / AP string defining an oval within a 4 - polygon provided as points"""
def bezier ( p , q , r ) : f = "%f %f %f %f %f %f c\n" return f % ( p . x , p . y , q . x , q . y , r . x , r . y ) kappa = 0.55228474983 # magic number ml = p1 + ( p4 - p1 ) * 0.5 # middle points . . . mo = p1 + ( p2 - p1 ) * 0.5 # for each . . . mr = p2 + ( p3 - p2 ) * 0.5 # polygon . . . mu = p4 + ( p3 - p4 ...
def get_all_indirect_statements ( self ) : """Get all indirect increases / decreases BEL statements . This method stores the results of the query in self . all _ indirect _ stmts as a list of strings . The SPARQL query used to find indirect BEL statements searches for all statements whose predicate is either ...
q_stmts = prefixes + """ SELECT ?stmt WHERE { ?stmt a belvoc:Statement . { { ?stmt belvoc:hasRelationship belvoc:Increases . } UNION { ?stmt belvoc:hasRelationship belvoc:Decreases . } } ...
def read_sj_out_tab ( filename ) : """Read an SJ . out . tab file as produced by the RNA - STAR aligner into a pandas Dataframe . Parameters filename : str of filename or file handle Filename of the SJ . out . tab file you want to read in Returns sj : pandas . DataFrame Dataframe of splice junctions""...
def int_to_intron_motif ( n ) : if n == 0 : return 'non-canonical' if n == 1 : return 'GT/AG' if n == 2 : return 'CT/AC' if n == 3 : return 'GC/AG' if n == 4 : return 'CT/GC' if n == 5 : return 'AT/AC' if n == 6 : return 'GT/AT' sj = pd...
def annotations_func ( func ) : """Works like annotations , but is only applicable to functions , methods and properties ."""
if not has_type_hints ( func ) : # What about defaults ? func . __annotations__ = { } func . __annotations__ = _get_type_hints ( func , infer_defaults = False ) return func
def openOrders ( self ) -> List [ Order ] : """List of all open orders ."""
return [ trade . order for trade in self . wrapper . trades . values ( ) if trade . orderStatus . status not in OrderStatus . DoneStates ]
def close_client_stream ( client_stream , unix_path ) : """Closes provided client stream"""
try : client_stream . shutdown ( socket . SHUT_RDWR ) if unix_path : logger . debug ( '%s: Connection closed' , unix_path ) else : peer = client_stream . getpeername ( ) logger . debug ( '%s:%s: Connection closed' , peer [ 0 ] , peer [ 1 ] ) except ( socket . error , OSError ) as exc...
def OpenUrlWithBasicAuth ( url , user = 'root' , pwd = '' ) : """Open the specified URL , using HTTP basic authentication to provide the specified credentials to the server as part of the request . Returns the response as a file - like object ."""
return requests . get ( url , auth = HTTPBasicAuth ( user , pwd ) , verify = False )
def p_contextualize_items ( self , t ) : """contextualize _ items : contextualize _ items contextualize _ item | contextualize _ item | empty"""
if len ( t ) == 3 : t [ 0 ] = t [ 1 ] t [ 0 ] . append ( t [ 2 ] ) elif t [ 1 ] : t [ 0 ] = [ t [ 1 ] ] else : t [ 0 ] = [ ]