signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def infer_dtype_from_scalar ( val , pandas_dtype = False ) : """interpret the dtype from a scalar Parameters pandas _ dtype : bool , default False whether to infer dtype including pandas extension types . If False , scalar belongs to pandas extension types is inferred as object"""
dtype = np . object_ # a 1 - element ndarray if isinstance ( val , np . ndarray ) : msg = "invalid ndarray passed to infer_dtype_from_scalar" if val . ndim != 0 : raise ValueError ( msg ) dtype = val . dtype val = val . item ( ) elif isinstance ( val , str ) : # If we create an empty array using...
def calculateDelay ( self , at , delay ) : """Creates the delay from now til the specified start time , uses " at " if available . : param at : the start time in % a % b % d % H : % M : % S % Y format . : param delay : the delay from now til start . : return : the delay ."""
if at is not None : return max ( ( datetime . strptime ( at , DATETIME_FORMAT ) - datetime . utcnow ( ) ) . total_seconds ( ) , 0 ) elif delay is not None : return delay else : return 0
def mode_to_str ( mode ) : """Converts a tf . estimator . ModeKeys in a nice readable string . : param mode : The mdoe as a tf . estimator . ModeKeys : return : A human readable string representing the mode ."""
if mode == tf . estimator . ModeKeys . TRAIN : return "train" if mode == tf . estimator . ModeKeys . EVAL : return "eval" if mode == tf . estimator . ModeKeys . PREDICT : return "predict" return "unknown"
def _get_nets_other ( self , * args , ** kwargs ) : """Deprecated . This will be removed in a future release ."""
from warnings import warn warn ( 'Whois._get_nets_other() has been deprecated and will be ' 'removed. You should now use Whois.get_nets_other().' ) return self . get_nets_other ( * args , ** kwargs )
def compute_position ( self , layout ) : """Compute the position of each geometric object in concert with the other objects in the panel"""
params = self . position . setup_params ( self . data ) data = self . position . setup_data ( self . data , params ) data = self . position . compute_layer ( data , params , layout ) self . data = data
def add_status_message ( self , message , severity = "info" ) : """Set a portal message"""
self . context . plone_utils . addPortalMessage ( message , severity )
def apply ( key , value ) : '''Set a single key . . note : : This will strip comments from your config file'''
path = __opts__ [ 'conf_file' ] if os . path . isdir ( path ) : path = os . path . join ( path , 'master' ) data = values ( ) data [ key ] = value with salt . utils . files . fopen ( path , 'w+' ) as fp_ : salt . utils . yaml . safe_dump ( data , default_flow_style = False )
def sync_headers ( cloud_obj , headers = None , header_patterns = HEADER_PATTERNS ) : """Overwrites the given cloud _ obj ' s headers with the ones given as ` ` headers ` and adds additional headers as defined in the HEADERS setting depending on the cloud _ obj ' s file name ."""
if headers is None : headers = { } # don ' t set headers on directories content_type = getattr ( cloud_obj , "content_type" , None ) if content_type == "application/directory" : return matched_headers = { } for pattern , pattern_headers in header_patterns : if pattern . match ( cloud_obj . name ) : ...
def multi ( self , lvl_list , msg , * args , ** kwargs ) : """Log a message at multiple levels"""
for level in lvl_list : self . log ( level , msg , args , ** kwargs )
def delete_security_group ( self , sec_grp ) : '''Deletes the specified security group'''
sec_grp_id = self . _find_security_group_id ( sec_grp ) ret = self . network_conn . delete_security_group ( sec_grp_id ) return ret if ret else True
def _sortByCreated ( a , b ) : """Sort function for object by created date"""
if a . created < b . created : return 1 elif a . created > b . created : return - 1 else : return 0
def process_link ( self , env , refnode , has_explicit_title , title , target ) : """Called after parsing title and target text , and creating the reference node . Alter the reference node and return it with chapel module and class information , if relevant ."""
refnode [ 'chpl:module' ] = env . temp_data . get ( 'chpl:module' ) refnode [ 'chpl:class' ] = env . temp_data . get ( 'chpl:class' ) if not has_explicit_title : # Only has a meaning for the target . title = title . lstrip ( '.' ) # Only has a meaning for the title . target = target . lstrip ( '~' ) if ...
def get_lldp_tlv ( self , port_name , is_ncb = True , is_nb = False ) : """Function to Query LLDP TLV on the interface ."""
reply = None if is_ncb : reply = self . run_lldptool ( [ "get-tlv" , "-n" , "-i" , port_name , "-g" , "ncb" ] ) elif is_nb : reply = self . run_lldptool ( [ "get-tlv" , "-n" , "-i" , port_name , "-g" , "nb" ] ) else : LOG . error ( "Both NCB and NB are not selected to " "query LLDP" ) return reply
def qos_map_cos_mutation_cos0 ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) qos = ET . SubElement ( config , "qos" , xmlns = "urn:brocade.com:mgmt:brocade-qos" ) map = ET . SubElement ( qos , "map" ) cos_mutation = ET . SubElement ( map , "cos-mutation" ) name_key = ET . SubElement ( cos_mutation , "name" ) name_key . text = kwargs . pop ( 'name' ) cos0 = ET ...
def json ( body , charset = 'utf-8' , ** kwargs ) : """Takes JSON formatted data , converting it into native Python objects"""
return json_converter . loads ( text ( body , charset = charset ) )
def bulk_invoke ( func , args , nargs ) : """Bulk invoke a function via queues Uses internal implementation details of rq ."""
# for comparison , simplest thing that works # for i in nargs : # argv = list ( args ) # argv . append ( i ) # func . delay ( * argv ) # some variances between cpy and pypy , sniff detect for closure in func . delay . func_closure : if getattr ( closure . cell_contents , 'queue' , None ) : ctx = closure . c...
def raw_body ( self ) -> bytes : """Encoded Body"""
if self . _raw_body is None and self . original_body is not None : if isinstance ( self . original_body , dict ) : self . _raw_body = self . parser . encode ( self . original_body ) if isinstance ( self . _raw_body , str ) : self . _raw_body = self . _raw_body . encode ( ) elif isins...
def gp_ptspec ( ) : """example for a 2D - panel plot etc ."""
fenergies = [ '19' , '27' , '39' , '62' , ] # '200 ' ] nen = len ( fenergies ) mee_keys = [ 'pi0' , 'LMR' , 'omega' , 'phi' , 'IMR' , 'jpsi' ] # mee _ keys = [ ' LMR ' , ] mee_dict = OrderedDict ( ( k , '' ) for k in mee_keys ) yscale = { '200' : '300' , '62' : '5000' , '39' : '50' , '27' : '0.3' , '19' : '0.001' } inD...
def union ( self ) : """Return the union of all flags in this dict Returns union : ` DataQualityFlag ` a new ` DataQualityFlag ` who ' s active and known segments are the union of those of the values of this dict"""
usegs = reduce ( operator . or_ , self . values ( ) ) usegs . name = ' | ' . join ( self . keys ( ) ) return usegs
def _do_prioritize ( items ) : """Determine if we should perform prioritization . Currently done on tumor - only input samples and feeding into PureCN which needs the germline annotations ."""
if not any ( "tumoronly-prioritization" in dd . get_tools_off ( d ) for d in items ) : if vcfutils . get_paired_phenotype ( items [ 0 ] ) : has_tumor = False has_normal = False for sub_data in items : if vcfutils . get_paired_phenotype ( sub_data ) == "tumor" : ha...
def fetch ( self , subscription_id , data = { } , ** kwargs ) : """Fetch Subscription for given Id Args : subscription _ id : Id for which subscription object is retrieved Returns : Subscription dict for given subscription Id"""
return super ( Subscription , self ) . fetch ( subscription_id , data , ** kwargs )
def dskgd ( handle , dladsc ) : """Return the DSK descriptor from a DSK segment identified by a DAS handle and DLA descriptor . https : / / naif . jpl . nasa . gov / pub / naif / toolkit _ docs / C / cspice / dskgd _ c . html : param handle : Handle assigned to the opened DSK file . : type handle : int : ...
handle = ctypes . c_int ( handle ) dskdsc = stypes . SpiceDSKDescr ( ) libspice . dskgd_c ( handle , ctypes . byref ( dladsc ) , ctypes . byref ( dskdsc ) ) return dskdsc
def absnormpath ( self , path ) : """Absolutize and minimalize the given path . Forces all relative paths to be absolute , and normalizes the path to eliminate dot and empty components . Args : path : Path to normalize . Returns : The normalized path relative to the current working directory , or the ...
path = self . normcase ( path ) cwd = self . _matching_string ( path , self . cwd ) if not path : path = self . path_separator elif not self . _starts_with_root_path ( path ) : # Prefix relative paths with cwd , if cwd is not root . root_name = self . _matching_string ( path , self . root . name ) empty = s...
def energy_entropy ( data , fs , numOfShortBlocks = 10 ) : """Computes entropy of energy"""
data = np . mean ( data , axis = 1 ) Eol = np . sum ( data ** 2 ) # total data energy L = len ( data ) subWinLength = int ( np . floor ( L / numOfShortBlocks ) ) if L != subWinLength * numOfShortBlocks : data = data [ 0 : subWinLength * numOfShortBlocks ] # subWindows is of size [ numOfShortBlocks x L ] subWindows ...
def to_rgba ( val ) : '''to _ rgba ( val ) is identical to matplotlib . colors . to _ rgba ( val ) except that it operates over lists as well as individual elements to yield matrices of rgba values . In addition , it always yields numpy vectors or matrices .'''
if pimms . is_npmatrix ( val ) and val . shape [ 1 ] == 4 : return val try : return np . asarray ( matplotlib . colors . to_rgba ( val ) ) except Exception : return np . asarray ( [ matplotlib . colors . to_rgba ( u ) for u in val ] )
def get_header_as_text ( file_content , reference_id ) : """Returns the cable ' s header as text . ` file _ content ` The HTML file content , c . f . ` get _ file _ content ` ."""
res = _CONTENT_PATTERN . findall ( file_content ) if len ( res ) == 2 : content = res [ 0 ] elif len ( res ) == 1 : return '' else : raise ValueError ( 'Unexpected <code><pre> sections: "%r"' % res ) return _clean_html ( content )
def before_insert ( mapper , conn , target ) : """event . listen method for Sqlalchemy to set the seqience _ id for this object and create an ObjectNumber value for the id _"""
# from identity import ObjectNumber # assert not target . fk _ vid or not ObjectNumber . parse ( target . fk _ vid ) . revision if target . sequence_id is None : from ambry . orm . exc import DatabaseError raise DatabaseError ( 'Must have sequence_id before insertion' ) # Check that the id column is always sequ...
def render_formset ( formset , ** kwargs ) : """Render a formset to a Bootstrap layout"""
renderer_cls = get_formset_renderer ( ** kwargs ) return renderer_cls ( formset , ** kwargs ) . render ( )
def get_plaintext_citations ( arxiv_id ) : """Get the citations of a given preprint , in plain text . . . note : : Bulk download of sources from arXiv is not permitted by their API . You should have a look at http : / / arxiv . org / help / bulk _ data _ s3. : param arxiv _ id : The arXiv id ( e . g . ` ` 140...
plaintext_citations = [ ] # Get the list of bbl files for this preprint bbl_files = arxiv . get_bbl ( arxiv_id ) for bbl_file in bbl_files : # Fetch the cited DOIs for each of the bbl files plaintext_citations . extend ( bbl . get_plaintext_citations ( bbl_file ) ) return plaintext_citations
def lazy_callable ( modname , * names , ** kwargs ) : """Performs lazy importing of one or more callables . : func : ` lazy _ callable ` creates functions that are thin wrappers that pass any and all arguments straight to the target module ' s callables . These can be functions or classes . The full loading o...
if not names : modname , _ , name = modname . rpartition ( "." ) lazy_mod_class = _setdef ( kwargs , 'lazy_mod_class' , LazyModule ) lazy_call_class = _setdef ( kwargs , 'lazy_call_class' , LazyCallable ) error_strings = _setdef ( kwargs , 'error_strings' , { } ) _set_default_errornames ( modname , error_strings , ...
def _coerce_to_ndarray ( self ) : """coerce to an ndarary of object dtype"""
# TODO ( jreback ) make this better data = self . _data . astype ( object ) data [ self . _mask ] = self . _na_value return data
def checkInfo ( email = None , username = None , api_key = None ) : '''Method that checks if the given hash is stored in the pipl . com website . : param email : queries to be launched . : param api _ key : api _ key to be used in pipl . com . If not provided , the API key will be searched in the config _ api _...
# This is for i3visio if api_key == None : # api _ key = raw _ input ( " Insert the API KEY here : \ t " ) allKeys = config_api_keys . returnListOfAPIKeys ( ) try : api_key = allKeys [ "pipl_com" ] except : # API _ Key not found . The samplekey will be used but it has a limit of 10 queries / day . ...
def hexdigest ( self ) : """Return the digest value as a string of hexadecimal digits ."""
if self . _pre_computed_hash is None : return libssdeep_wrapper . fuzzy_digest ( self . _state , 0 ) else : return self . _pre_computed_hash
def _unwindGenerator ( self , generator , _prev = None ) : """Unwind ( resume ) generator ."""
while True : if _prev : ret , _prev = _prev , None else : try : ret = next ( generator ) except StopIteration : break if isinstance ( ret , Request ) : if ret . callback : warnings . warn ( "Got a request with callback set, bypassing " "the...
def notify_thread_not_alive ( self , thread_id , use_lock = True ) : """if thread is not alive , cancel trace _ dispatch processing"""
if self . writer is None : return with self . _lock_running_thread_ids if use_lock else NULL : if not self . _enable_thread_notifications : return thread = self . _running_thread_ids . pop ( thread_id , None ) if thread is None : return was_notified = thread . additional_info . pydev...
def _add_thousand_g ( self , variant_obj , info_dict ) : """Add the thousand genomes frequency Args : variant _ obj ( puzzle . models . Variant ) info _ dict ( dict ) : A info dictionary"""
thousand_g = info_dict . get ( '1000GAF' ) if thousand_g : logger . debug ( "Updating thousand_g to: {0}" . format ( thousand_g ) ) variant_obj . thousand_g = float ( thousand_g ) variant_obj . add_frequency ( '1000GAF' , variant_obj . get ( 'thousand_g' ) )
def watch_instances ( self , flag ) : """Whether or not the Class Instances are being watched ."""
lib . EnvSetDefclassWatchInstances ( self . _env , int ( flag ) , self . _cls )
def draw_label ( self , layout_info , ax ) : """Draw facet label onto the axes . This function will only draw labels if they are needed . Parameters layout _ info : dict - like Layout information . Row from the ` layout ` table . ax : axes Axes to label"""
toprow = layout_info [ 'ROW' ] == 1 rightcol = layout_info [ 'COL' ] == self . ncol if toprow and len ( self . cols ) : label_info = layout_info [ list ( self . cols ) ] label_info . _meta = { 'dimension' : 'cols' } label_info = self . labeller ( label_info ) self . draw_strip_text ( label_info , 'top' ...
def get_rubric_metadata ( self ) : """Gets the metadata for a rubric assessment . return : ( osid . Metadata ) - metadata for the assesment * compliance : mandatory - - This method must be implemented . *"""
# Implemented from template for osid . resource . ResourceForm . get _ group _ metadata _ template metadata = dict ( self . _mdata [ 'rubric' ] ) metadata . update ( { 'existing_id_values' : self . _my_map [ 'rubricId' ] } ) return Metadata ( ** metadata )
def int_pair ( s , default = ( 0 , None ) ) : """Return the digits to either side of a single non - digit character as a 2 - tuple of integers > > > int _ pair ( ' 90210-007 ' ) (90210 , 7) > > > int _ pair ( ' 04321.0123 ' ) (4321 , 123)"""
s = re . split ( r'[^0-9]+' , str ( s ) . strip ( ) ) if len ( s ) and len ( s [ 0 ] ) : if len ( s ) > 1 and len ( s [ 1 ] ) : return ( int ( s [ 0 ] ) , int ( s [ 1 ] ) ) return ( int ( s [ 0 ] ) , default [ 1 ] ) return default
def _make_futures ( futmap_keys , class_check , make_result_fn ) : """Create futures and a futuremap for the keys in futmap _ keys , and create a request - level future to be bassed to the C API ."""
futmap = { } for key in futmap_keys : if class_check is not None and not isinstance ( key , class_check ) : raise ValueError ( "Expected list of {}" . format ( type ( class_check ) ) ) futmap [ key ] = concurrent . futures . Future ( ) if not futmap [ key ] . set_running_or_notify_cancel ( ) : ...
def get_version ( ) : """Get the Windows OS version running on the machine . Params : None Returns : The Windows OS version running on the machine ( comparables with the values list in the class ) ."""
# Other OS check if not 'win' in sys . platform : return NO_WIN # Get infos win_ver = sys . getwindowsversion ( ) try : # Python 3.6 . x or upper - > Use ' platform _ version ' attribute major , minor , build = win_ver . platform_version except AttributeError : if sys . version_info < ( 3 , 0 ) : # Python 2...
async def start_pairing ( self ) : """Start pairing procedure ."""
self . srp . initialize ( ) msg = messages . crypto_pairing ( { tlv8 . TLV_METHOD : b'\x00' , tlv8 . TLV_SEQ_NO : b'\x01' } ) resp = await self . protocol . send_and_receive ( msg , generate_identifier = False ) pairing_data = _get_pairing_data ( resp ) if tlv8 . TLV_BACK_OFF in pairing_data : time = int . from_byt...
def decode_varint_1 ( buffer , pos = 0 ) : """Decode an integer from a varint presentation . See https : / / developers . google . com / protocol - buffers / docs / encoding ? csw = 1 # varints on how those can be produced . Arguments : buffer ( bytes - like ) : any object acceptable by ` ` memoryview ` ` ...
value = 0 shift = 0 memview = memoryview ( buffer ) for i in range ( pos , pos + 10 ) : try : byte = _read_byte ( memview , i ) except IndexError : raise ValueError ( "End of byte stream" ) if byte & 0x80 != 0 : value |= ( byte & 0x7f ) << shift shift += 7 else : ...
async def on_error ( self , event_method , * args , ** kwargs ) : """| coro | The default error handler provided by the client . By default this prints to : data : ` sys . stderr ` however it could be overridden to have a different implementation . Check : func : ` discord . on _ error ` for more details ."...
print ( 'Ignoring exception in {}' . format ( event_method ) , file = sys . stderr ) traceback . print_exc ( )
def hurst_rs ( data , nvals = None , fit = "RANSAC" , debug_plot = False , debug_data = False , plot_file = None , corrected = True , unbiased = True ) : """Calculates the Hurst exponent by a standard rescaled range ( R / S ) approach . Explanation of Hurst exponent : The Hurst exponent is a measure for the " l...
data = np . asarray ( data ) total_N = len ( data ) if nvals is None : # chooses a default value for nvals that will give 15 logarithmically # spaced datapoints leaning towards the middle of the logarithmic range # ( since both too small and too large n introduce too much variance ) nvals = logmid_n ( total_N , rat...
def create_top_level_index_entry ( title , max_depth , subtitles ) : """Function for creating a text entry in index . rst for its content . : param title : Title for the content . : type title : str : param max _ depth : Value for max _ depth in the top level index content . : type max _ depth : int : par...
return_text = title + '\n' dash = '-' * len ( title ) + '\n' return_text += dash + '\n' return_text += '.. toctree::' + '\n' return_text += ' :maxdepth: ' + str ( max_depth ) + '\n\n' for subtitle in subtitles : return_text += ' ' + subtitle + '\n\n' return return_text
def delete_columns ( mat , columns_to_delete ) : '''> > > a = csr _ matrix ( np . array ( [ [ 0 , 1 , 3 , 0 , 1 , 0 ] , [0 , 0 , 1 , 0 , 1 , 1 ] ] ) > > > delete _ columns ( a , [ 1,2 ] ) . todense ( ) matrix ( [ [ 0 , 0 , 1 , 0 ] , [0 , 0 , 1 , 1 ] ] ) Parameters mat : csr _ matrix columns _ to _ del...
column_mask = np . ones ( mat . shape [ 1 ] , dtype = bool ) column_mask [ columns_to_delete ] = 0 return mat . tocsc ( ) [ : , column_mask ] . tocsr ( )
def add_apis ( self , logical_id , apis ) : """Stores the given APIs tagged under the given logicalId Parameters logical _ id : str LogicalId of the AWS : : Serverless : : Api resource apis : list of samcli . commands . local . lib . provider . Api List of APIs available in this resource"""
properties = self . _get_properties ( logical_id ) properties . apis . extend ( apis )
def makeMNBaseURL ( url ) : """Attempt to create a valid MN BaseURL when one or more sections of the URL are missing ."""
o = urllib . parse . urlparse ( url , scheme = d1_common . const . DEFAULT_MN_PROTOCOL ) if o . netloc and o . path : netloc = o . netloc path = o . path elif o . netloc : netloc = o . netloc path = d1_common . const . DEFAULT_MN_PATH elif o . path : s = o . path . split ( '/' , 1 ) netloc = s [...
def _regularize ( x , y , ties ) : """Regularize the values , make them ordered and remove duplicates . If the ` ` ties ` ` parameter is explicitly set to ' ordered ' then order is already assumed . Otherwise , the removal process will happen . Parameters x : array - like , shape = ( n _ samples , ) The x...
x , y = [ column_or_1d ( check_array ( arr , ensure_2d = False , force_all_finite = False , dtype = DTYPE ) ) for arr in ( x , y ) ] nx = x . shape [ 0 ] if nx != y . shape [ 0 ] : raise ValueError ( 'array dim mismatch: %i != %i' % ( nx , y . shape [ 0 ] ) ) # manipulate x if needed . if ties is ' ordered ' we ass...
def gatherBy ( self , func ) : 'Generate only rows for which the given func returns True .'
for i in rotate_range ( len ( self . rows ) , self . cursorRowIndex ) : try : r = self . rows [ i ] if func ( r ) : yield r except Exception : pass
def parse_args ( ) : """Parses command line arguments ."""
parser = ArgumentParser ( description = "ModelBase builder" ) subparsers = parser . add_subparsers ( ) sql_parser = subparsers . add_parser ( "get-query" , description = "Usage: e.g. psql -c \"copy ($(python3 lib/generate_models.py get-query)) to " + "stdout with csv header\" DB_NAME postgres" ) sql_parser . set_defaul...
def OnSearch ( self , event ) : """Event handler for starting the search"""
search_string = self . search . GetValue ( ) if search_string not in self . search_history : self . search_history . append ( search_string ) if len ( self . search_history ) > 10 : self . search_history . pop ( 0 ) self . menu = self . make_menu ( ) self . search . SetMenu ( self . menu ) search_flags = self ....
def handle_presence ( self , old_present ) : '''Fire presence events if enabled'''
# On the first run it may need more time for the EventPublisher # to come up and be ready . Set the timeout to account for this . if self . presence_events and self . event . connect_pull ( timeout = 3 ) : present = self . ckminions . connected_ids ( ) new = present . difference ( old_present ) lost = old_p...
def modify_process_properties ( self , key_value_map = { } , pid = None ) : '''modify _ process _ properties ( self , key _ value _ map = { } , pid = None ) Modify process output properties . Please note that process property key provided must be declared as an output property in the relevant service specificat...
pid = self . _get_pid ( pid ) request_data = { "properties" : key_value_map } return self . _call_rest_api ( 'post' , '/processes/' + pid + '/output' , data = request_data , error = 'Failed to output properties' )
def reset ( self , rg = None ) : '''Enable all offline cpus , and reset max and min frequencies files rg : range or list of threads to reset'''
if type ( rg ) == int : rg = [ rg ] to_reset = rg if rg else self . __get_ranges ( "present" ) self . enable_cpu ( to_reset ) for cpu in to_reset : fpath = path . join ( "cpu%i" % cpu , "cpufreq" , "cpuinfo_max_freq" ) max_freq = self . __read_cpu_file ( fpath ) fpath = path . join ( "cpu%i" % cpu , "cp...
def application_adapter ( obj , request ) : """Adapter for rendering a : class : ` pyramid _ urireferencer . models . ApplicationResponse ` to json . : param pyramid _ urireferencer . models . ApplicationResponse obj : The response to be rendered . : rtype : : class : ` dict `"""
return { 'title' : obj . title , 'uri' : obj . uri , 'service_url' : obj . service_url , 'success' : obj . success , 'has_references' : obj . has_references , 'count' : obj . count , 'items' : [ { 'uri' : i . uri , 'title' : i . title } for i in obj . items ] if obj . items is not None else None }
def set_base_url ( self , platform : str = "prod" ) : """Set Isogeo base URLs according to platform . : param str platform : platform to use . Options : * prod [ DEFAULT ] * qa * int"""
platform = platform . lower ( ) self . platform = platform if platform == "prod" : ssl = True logging . debug ( "Using production platform." ) elif platform == "qa" : ssl = False logging . debug ( "Using Quality Assurance platform (reduced perfs)." ) else : logging . error ( "Platform must be one of...
def open_dialog ( self , verbose = False ) : """The command line dialog provides a field to enter commands and view results . It also provides the help command to display namespaces , commands , and arguments . : param verbose : print more"""
response = api ( url = self . __url + "/open dialog" , verbose = verbose ) return response
def get_proficiency_query_session_for_objective_bank ( self , objective_bank_id , proxy ) : """Gets the ` ` OsidSession ` ` associated with the proficiency query service for the given objective bank . : param objective _ bank _ id : the ` ` Id ` ` of the obective bank : type objective _ bank _ id : ` ` osid . i...
if not objective_bank_id : raise NullArgument if not self . supports_proficiency_query ( ) : raise Unimplemented ( ) try : from . import sessions except ImportError : raise OperationFailed ( ) proxy = self . _convert_proxy ( proxy ) try : session = sessions . ProficiencyQuerySession ( objective_bank...
def _tiff_from_exif_segment ( cls , stream , offset , segment_length ) : """Return a | Tiff | instance parsed from the Exif APP1 segment of * segment _ length * at * offset * in * stream * ."""
# wrap full segment in its own stream and feed to Tiff ( ) stream . seek ( offset + 8 ) segment_bytes = stream . read ( segment_length - 8 ) substream = BytesIO ( segment_bytes ) return Tiff . from_stream ( substream )
def _AddPropertiesForNonRepeatedScalarField ( field , cls ) : """Adds a public property for a nonrepeated , scalar protocol message field . Clients can use this property to get and directly set the value of the field . Note that when the client sets the value of a field by using this property , all necessary ...
proto_field_name = field . name property_name = _PropertyName ( proto_field_name ) type_checker = type_checkers . GetTypeChecker ( field ) default_value = field . default_value valid_values = set ( ) is_proto3 = field . containing_type . syntax == "proto3" def getter ( self ) : # TODO ( protobuf - team ) : This may be ...
def render_template ( template ) : """takes a template to render to and returns a function that takes an object to render the data for this template . If callable _ or _ dict is callable , it will be called with the request and any additional arguments to produce the template paramaters . This is useful for...
def outer_wrapper ( callable_or_dict = None , statuscode = None , ** kwargs ) : def wrapper ( request , * args , ** wrapper_kwargs ) : if callable ( callable_or_dict ) : params = callable_or_dict ( request , * args , ** wrapper_kwargs ) else : params = callable_or_dict ...
def _rank ( self , ranking , n ) : """return the first n sentences with highest ranking"""
return nlargest ( n , ranking , key = ranking . get )
async def dump_variant ( self , elem , elem_type = None , params = None ) : """Dumps variant type to the writer . Supports both wrapped and raw variant . : param writer : : param elem : : param elem _ type : : param params : : return :"""
if isinstance ( elem , x . VariantType ) or elem_type . WRAPS_VALUE : await dump_uvarint ( self . iobj , elem . variant_elem_type . VARIANT_CODE ) await self . _dump_field ( getattr ( elem , elem . variant_elem ) , elem . variant_elem_type ) else : fdef = elem_type . find_fdef ( elem_type . f_specs ( ) , el...
def remap_overlapping_column_names ( table_op , root_table , data_columns ) : """Return an ` ` OrderedDict ` ` mapping possibly suffixed column names to column names without suffixes . Parameters table _ op : TableNode The ` ` TableNode ` ` we ' re selecting from . root _ table : TableNode The root tabl...
if not isinstance ( table_op , ops . Join ) : return None left_root , right_root = ops . distinct_roots ( table_op . left , table_op . right ) suffixes = { left_root : constants . LEFT_JOIN_SUFFIX , right_root : constants . RIGHT_JOIN_SUFFIX , } column_names = [ ( { name , name + suffixes [ root_table ] } & data_co...
def set_basic_params ( self , workers = None , zerg_server = None , fallback_node = None , concurrent_events = None , cheap_mode = None , stats_server = None , quiet = None , buffer_size = None , fallback_nokey = None , subscription_key = None , emperor_command_socket = None ) : """: param int workers : Number of w...
super ( RouterFast , self ) . set_basic_params ( ** filter_locals ( locals ( ) , [ 'fallback_nokey' , 'subscription_key' , 'emperor_command_socket' , ] ) ) self . _set_aliased ( 'fallback-on-no-key' , fallback_nokey , cast = bool ) self . _set_aliased ( 'force-key' , subscription_key ) self . _set_aliased ( 'emperor-so...
def get_available_plugins ( self ) : """check requested plugins availability and handle missing plugins : return : list of namedtuples , runnable plugins data"""
available_plugins = [ ] PluginData = namedtuple ( 'PluginData' , 'name, plugin_class, conf, is_allowed_to_fail' ) for plugin_request in self . plugins_conf : plugin_name = plugin_request [ 'name' ] try : plugin_class = self . plugin_classes [ plugin_name ] except KeyError : if plugin_request...
def delete_collection_initializer_configuration ( self , ** kwargs ) : # noqa : E501 """delete _ collection _ initializer _ configuration # noqa : E501 delete collection of InitializerConfiguration # noqa : E501 This method makes a synchronous HTTP request by default . To make an asynchronous HTTP request , p...
kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'async_req' ) : return self . delete_collection_initializer_configuration_with_http_info ( ** kwargs ) # noqa : E501 else : ( data ) = self . delete_collection_initializer_configuration_with_http_info ( ** kwargs ) # noqa : E501 return dat...
def _send_event ( self , title , text , tags , event_type , aggregation_key , severity = 'info' ) : """Emit an event to the Datadog Event Stream ."""
event_dict = { 'timestamp' : int ( time ( ) ) , 'source_type_name' : self . SOURCE_TYPE_NAME , 'msg_title' : title , 'event_type' : event_type , 'alert_type' : severity , 'msg_text' : text , 'tags' : tags , 'aggregation_key' : aggregation_key , } self . event ( event_dict )
def prob ( self , comparison_vectors , return_type = None ) : """Compute the probabilities for each record pair . For each pair of records , estimate the probability of being a match . Parameters comparison _ vectors : pandas . DataFrame The dataframe with comparison vectors . return _ type : str Deprec...
if return_type is not None : warnings . warn ( "The argument 'return_type' is removed. " "Default value is now 'series'." , VisibleDeprecationWarning , stacklevel = 2 ) logging . info ( "Classification - compute probabilities" ) prob_match = self . _prob_match ( comparison_vectors . values ) return pandas . Series ...
def get_serializer ( serializer_format ) : """Get the serializer for a specific format"""
if serializer_format == Format . JSON : return _serialize_json if serializer_format == Format . PICKLE : return _serialize_pickle
def _ParseRecordExtraField ( self , byte_stream , file_offset ) : """Parses a record extra field . Args : byte _ stream ( bytes ) : byte stream . file _ offset ( int ) : offset of the record extra field relative to the start of the file . Returns : asl _ record _ extra _ field : record extra field . R...
extra_field_map = self . _GetDataTypeMap ( 'asl_record_extra_field' ) try : record_extra_field = self . _ReadStructureFromByteStream ( byte_stream , file_offset , extra_field_map ) except ( ValueError , errors . ParseError ) as exception : raise errors . ParseError ( ( 'Unable to parse record extra field at off...
def analyze_string_content ( self , string , line_num , filename ) : """Searches string for custom pattern , and captures all high entropy strings that match self . regex , with a limit defined as self . entropy _ limit ."""
output = { } for result in self . secret_generator ( string ) : if self . _is_sequential_string ( result ) : continue secret = PotentialSecret ( self . secret_type , filename , result , line_num ) output [ secret ] = secret return output
def getFontsByFontInfoAttribute ( self , * attributeValuePairs ) : """Get a list of fonts that match the ( attribute , value ) combinations in ` ` attributeValuePairs ` ` . > > > subFonts = fonts . getFontsByFontInfoAttribute ( ( " xHeight " , 20 ) ) > > > subFonts = fonts . getFontsByFontInfoAttribute ( ( " ...
found = self for attr , value in attributeValuePairs : found = self . _matchFontInfoAttributes ( found , ( attr , value ) ) return found
def is_for_driver_task ( self ) : """See whether this function descriptor is for a driver or not . Returns : True if this function descriptor is for driver tasks ."""
return all ( len ( x ) == 0 for x in [ self . module_name , self . class_name , self . function_name ] )
def create_dialog ( self ) : """Create the dialog ."""
bbox = QDialogButtonBox ( QDialogButtonBox . Ok | QDialogButtonBox . Cancel ) self . idx_ok = bbox . button ( QDialogButtonBox . Ok ) self . idx_cancel = bbox . button ( QDialogButtonBox . Cancel ) filebutton = QPushButton ( ) filebutton . setText ( 'Choose' ) self . idx_filename = filebutton self . xp_format = FormMen...
def get_node ( self , process_name , timeperiod ) : """Method retrieves a tree node identified by the time _ qualifier and the timeperiod"""
if process_name not in self . process_hierarchy : raise ValueError ( 'unable to retrieve the node due to unknown process: {0}' . format ( process_name ) ) time_qualifier = self . process_hierarchy [ process_name ] . process_entry . time_qualifier return self . _get_node ( time_qualifier , timeperiod )
def create_reader ( name , * args , format = None , registry = default_registry , ** kwargs ) : """Create a reader instance , guessing its factory using filename ( and eventually format ) . : param name : : param args : : param format : : param registry : : param kwargs : : return : mixed"""
return registry . get_reader_factory_for ( name , format = format ) ( name , * args , ** kwargs )
def levenshtein ( str1 , s2 ) : '''Distance between two strings'''
N1 = len ( str1 ) N2 = len ( s2 ) stringRange = [ range ( N1 + 1 ) ] * ( N2 + 1 ) for i in range ( N2 + 1 ) : stringRange [ i ] = range ( i , i + N1 + 1 ) for i in range ( 0 , N2 ) : for j in range ( 0 , N1 ) : if str1 [ j ] == s2 [ i ] : stringRange [ i + 1 ] [ j + 1 ] = min ( stringRange [...
def enqueue_data ( self , event_type , data ) : """Enqueue a data item for specific event type"""
with self . lock : listeners = self . listeners . values ( ) for listener in listeners : listener . enqueue ( event_type , data ) self . must_process = True
def create_inverse_model ( self , encoded_state , encoded_next_state ) : """Creates inverse model TensorFlow ops for Curiosity module . Predicts action taken given current and future encoded states . : param encoded _ state : Tensor corresponding to encoded current state . : param encoded _ next _ state : Ten...
combined_input = tf . concat ( [ encoded_state , encoded_next_state ] , axis = 1 ) hidden = tf . layers . dense ( combined_input , 256 , activation = self . swish ) if self . brain . vector_action_space_type == "continuous" : pred_action = tf . layers . dense ( hidden , self . act_size [ 0 ] , activation = None ) ...
def _identify_heterogeneity_blocks_shared ( in_file , segment_fn , params , work_dir , somatic_info ) : """Identify heterogeneity blocks corresponding to segmentation from CNV input file ."""
out_file = os . path . join ( work_dir , "%s-hetblocks.bed" % utils . splitext_plus ( os . path . basename ( in_file ) ) [ 0 ] ) if not utils . file_uptodate ( out_file , in_file ) : with file_transaction ( somatic_info . tumor_data , out_file ) as tx_out_file : with open ( tx_out_file , "w" ) as out_handle...
def sharing_agreements ( self ) : """| Comment : The ids of the sharing agreements used for this ticket"""
if self . api and self . sharing_agreement_ids : return self . api . _get_sharing_agreements ( self . sharing_agreement_ids )
def tangent_lineation_plot ( ax , strikes , dips , rakes ) : """Makes a tangent lineation plot for normal faults with the given strikes , dips , and rakes ."""
# Calculate the position of the rake of the lineations , but don ' t plot yet rake_x , rake_y = mplstereonet . rake ( strikes , dips , rakes ) # Calculate the direction the arrows should point # These are all normal faults , so the arrows point away from the center # Because we ' re plotting at the pole location , howe...
def assert_has_calls ( self , calls , any_order = False ) : """assert the mock has been called with the specified calls . The ` mock _ calls ` list is checked for the calls . If ` any _ order ` is False ( the default ) then the calls must be sequential . There can be extra calls before or after the specifie...
if not any_order : if calls not in self . mock_calls : raise AssertionError ( 'Calls not found.\nExpected: %r\n' 'Actual: %r' % ( calls , self . mock_calls ) ) return all_calls = list ( self . mock_calls ) not_found = [ ] for kall in calls : try : all_calls . remove ( kall ) except Value...
def load ( fname ) : """Load an embedding dump generated by ` save `"""
content = _open ( fname ) . read ( ) if PY2 : state = pickle . loads ( content ) else : state = pickle . loads ( content , encoding = 'latin1' ) voc , vec = state if len ( voc ) == 2 : words , counts = voc word_count = dict ( zip ( words , counts ) ) vocab = CountedVocabulary ( word_count = word_cou...
def int_args ( self ) : """Iterate through all the possible arg positions that can only be used to store integer or pointer values Does not take into account customizations . Returns an iterator of SimFunctionArguments"""
if self . ARG_REGS is None : raise NotImplementedError ( ) for reg in self . ARG_REGS : # pylint : disable = not - an - iterable yield SimRegArg ( reg , self . arch . bytes )
def new_stories ( self , raw = False , limit = None ) : """Returns list of item ids of current new stories Args : limit ( int ) : specifies the number of stories to be returned . raw ( bool ) : Flag to indicate whether to transform all objects into raw json . Returns : ` list ` object containing ids of ...
new_stories = self . _get_stories ( 'newstories' , limit ) if raw : new_stories = [ story . raw for story in new_stories ] return new_stories
def dashboards ( self , filter = None , startAt = 0 , maxResults = 20 ) : """Return a ResultList of Dashboard resources and a ` ` total ` ` count . : param filter : either " favourite " or " my " , the type of dashboards to return : type filter : Optional [ str ] : param startAt : index of the first dashboard...
params = { } if filter is not None : params [ 'filter' ] = filter return self . _fetch_pages ( Dashboard , 'dashboards' , 'dashboard' , startAt , maxResults , params )
def split_input ( cls , job_config ) : """Inherit docs ."""
params = job_config . input_reader_params shard_count = job_config . shard_count query_spec = cls . _get_query_spec ( params ) if not property_range . should_shard_by_property_range ( query_spec . filters ) : return super ( ModelDatastoreInputReader , cls ) . split_input ( job_config ) p_range = property_range . Pr...
def crt_mdl_rsp ( arySptExpInf , tplPngSize , aryMdlParams , varPar , strCrd = 'crt' , lgcPrint = True ) : """Create responses of 2D Gauss models to spatial conditions . Parameters arySptExpInf : 3d numpy array , shape [ n _ x _ pix , n _ y _ pix , n _ conditions ] All spatial conditions stacked along second ...
if varPar == 1 : # if the number of cores requested by the user is equal to 1, # we save the overhead of multiprocessing by calling aryMdlCndRsp # directly aryMdlCndRsp = cnvl_2D_gauss ( 0 , aryMdlParams , arySptExpInf , tplPngSize , None , strCrd = strCrd ) else : # The long array with all the combinations of mode...
def get_privileges ( self , application = None , name = None , params = None ) : """` < TODO > ` _ : arg application : Application name : arg name : Privilege name"""
return self . transport . perform_request ( "GET" , _make_path ( "_security" , "privilege" , application , name ) , params = params , )
def add_receipt ( self , block_header : BlockHeader , index_key : int , receipt : Receipt ) -> Hash32 : """Adds the given receipt to the provided block header . Returns the updated ` receipts _ root ` for updated block header ."""
receipt_db = HexaryTrie ( db = self . db , root_hash = block_header . receipt_root ) receipt_db [ index_key ] = rlp . encode ( receipt ) return receipt_db . root_hash
def _init_decoder ( self ) : """Set - up the _ decoder attribute if necessary ."""
# Note : content - encoding value should be case - insensitive , per RFC 7230 # Section 3.2 content_encoding = self . headers . get ( 'content-encoding' , '' ) . lower ( ) if self . _decoder is None : if content_encoding in self . CONTENT_DECODERS : self . _decoder = _get_decoder ( content_encoding ) el...
def _transform ( self , q ) : """exp ( i q . r ( i ) ) v ( i )"""
s2p = self . _primitive . get_supercell_to_primitive_map ( ) p2s = self . _primitive . get_primitive_to_supercell_map ( ) num_s = self . _supercell . get_number_of_atoms ( ) num_p = self . _primitive . get_number_of_atoms ( ) v = self . _velocities q_array = np . reshape ( q , ( - 1 , 3 ) ) dtype = "c%d" % ( np . dtype...
def user_data ( self , access_token , * args , ** kwargs ) : """Load user data from OAuth Profile Google App Engine App"""
url = GOOGLE_APPENGINE_PROFILE_V2 return self . get_json ( url , headers = { 'Authorization' : 'Bearer ' + access_token } )
def get_abilities ( ) : """Visit Bulbapedia and pull names and descriptions from the table , ' list of Abilities . ' Save as JSON ."""
page = requests . get ( 'http://bulbapedia.bulbagarden.net/wiki/Ability' ) soup = bs4 . BeautifulSoup ( page . text ) table = soup . find ( "table" , { "class" : "sortable" } ) tablerows = [ tr for tr in table . children if tr != '\n' ] [ 1 : ] abilities = { } for tr in tablerows : cells = tr . find_all ( 'td' ) ...
def ending ( self , end , predicate = None , index = None ) : """Retrieves a set of Match objects that ends at given index . : param end : the ending index : type end : int : param predicate : : type predicate : : return : set of matches : rtype : set [ Match ]"""
return filter_index ( _BaseMatches . _base ( self . _end_dict [ end ] ) , predicate , index )