signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def ceil_nearest ( x , dx = 1 ) : """ceil a number to within a given rounding accuracy"""
precision = get_sig_digits ( dx ) return round ( math . ceil ( float ( x ) / dx ) * dx , precision )
def distanceMetric ( thing_A , thing_B ) : '''A " universal distance " metric that can be used as a default in many settings . Parameters thing _ A : object A generic object . thing _ B : object Another generic object . Returns : distance : float The " distance " between thing _ A and thing _ B .'''
# Get the types of the two inputs typeA = type ( thing_A ) typeB = type ( thing_B ) if typeA is list and typeB is list : lenA = len ( thing_A ) # If both inputs are lists , then the distance between lenB = len ( thing_B ) # them is the maximum distance between corresponding if lenA == lenB : # eleme...
def process_extensions ( headers : Headers , available_extensions : Optional [ Sequence [ ClientExtensionFactory ] ] , ) -> List [ Extension ] : """Handle the Sec - WebSocket - Extensions HTTP response header . Check that each extension is supported , as well as its parameters . Return the list of accepted exte...
accepted_extensions : List [ Extension ] = [ ] header_values = headers . get_all ( "Sec-WebSocket-Extensions" ) if header_values : if available_extensions is None : raise InvalidHandshake ( "No extensions supported" ) parsed_header_values : List [ ExtensionHeader ] = sum ( [ parse_extension ( header_val...
def handle_hotmaps_results ( permutation_result ) : """Takes in output from multiprocess _ permutation function and converts to a better formatted dataframe . Parameters permutation _ result : list output from multiprocess _ permutation Returns permutation _ df : pd . DataFrame formatted output suitab...
if len ( permutation_result [ 0 ] ) == 6 : mycols = [ 'gene' , 'window length' , 'codon position' , 'mutation count' , 'windowed sum' , 'p-value' ] else : mycols = [ 'gene' , 'window length' , 'codon position' , 'index' , 'mutation count' , 'windowed sum' , 'p-value' ] permutation_df = pd . DataFrame ( permutat...
def is_url_ok ( self ) : """Verify Keystone Auth URL"""
response = requests . head ( settings . KEYSTONE_AUTH_URL ) if response . status_code == 200 : return True return False
def md5 ( self , path ) : """Use different md5 commands depending on the OS : - Darwin ' s ` md5 ` returns BSD - style checksums by default - Linux ' s ` md5sum ` needs the ` - - tag ` flag for a similar output Example : MD5 ( foo . txt ) = f3d220a856b52aabbf294351e8a24300"""
uname = self . execute ( "uname" ) . strip ( ) command = { "Darwin" : "md5 {}" . format ( path ) , "Linux" : "md5sum --tag {}" . format ( path ) , } . get ( uname ) if not command : raise DvcException ( "'{uname}' is not supported as a remote" . format ( uname = uname ) ) md5 = self . execute ( command ) . split ( ...
def sample_from_distribution ( self , distribution , k , proportions = False ) : """Return a new table with the same number of rows and a new column . The values in the distribution column are define a multinomial . They are replaced by sample counts / proportions in the output . > > > sizes = Table ( [ ' siz...
dist = self . _get_column ( distribution ) total = sum ( dist ) assert total > 0 and np . all ( dist >= 0 ) , 'Counts or a distribution required' dist = dist / sum ( dist ) sample = np . random . multinomial ( k , dist ) if proportions : sample = sample / sum ( sample ) label = self . _unused_label ( self . _as_lab...
def readBerSANS ( filename ) : """Read a header from a SANS file ( produced usually by BerSANS )"""
hed = { 'Comment' : '' } translate = { 'Lambda' : 'Wavelength' , 'Title' : 'Owner' , 'SampleName' : 'Title' , 'BeamcenterX' : 'BeamPosY' , 'BeamcenterY' : 'BeamPosX' , 'Time' : 'MeasTime' , 'TotalTime' : 'MeasTime' , 'Moni1' : 'Monitor' , 'Moni2' : 'Monitor' , 'Moni' : 'Monitor' , 'Transmission' : 'Transm' , } with ope...
def conference ( self , id , ** options ) : """This object allows multiple lines in separate sessions to be conferenced together so that the parties on each line can talk to each other simultaneously . This is a voice channel only feature . Argument : " id " is a String Argument : * * options is a set of opti...
self . _steps . append ( Conference ( id , ** options ) . obj )
def best_training_job ( self ) : """Return name of the best training job for the latest hyperparameter tuning job . Raises : Exception : If there is no best training job available for the hyperparameter tuning job ."""
self . _ensure_last_tuning_job ( ) tuning_job_describe_result = self . estimator . sagemaker_session . sagemaker_client . describe_hyper_parameter_tuning_job ( HyperParameterTuningJobName = self . latest_tuning_job . name ) try : return tuning_job_describe_result [ 'BestTrainingJob' ] [ 'TrainingJobName' ] except K...
def _parse_redirect ( self , element ) : """Parse a trigger redirect : param element : The XML Element object : type element : etree . _ Element"""
self . _log . info ( 'Parsing new redirected Response' ) self . _responses . add ( Response ( self , element , self . file_path ) )
def convert_to_relative_paths ( src , dst ) : """Converts all file paths in a smother report to relative paths , relative to the current directory ."""
result = Smother . convert_to_relative_paths ( Smother . load ( src ) ) result . write ( dst )
def _generate_route_method_decl ( self , namespace , route , arg_data_type , request_binary_body , method_name_suffix = '' , extra_args = None ) : """Generates the method prototype for a route ."""
args = [ 'self' ] if extra_args : args += extra_args if request_binary_body : args . append ( 'f' ) if is_struct_type ( arg_data_type ) : for field in arg_data_type . all_fields : if is_nullable_type ( field . data_type ) : args . append ( '{}=None' . format ( field . name ) ) el...
def configure_for_kerberos ( self , datanode_transceiver_port = None , datanode_web_port = None ) : """Command to configure the cluster to use Kerberos for authentication . This command will configure all relevant services on a cluster for Kerberos usage . This command will trigger a GenerateCredentials command...
args = dict ( ) if datanode_transceiver_port : args [ 'datanodeTransceiverPort' ] = datanode_transceiver_port if datanode_web_port : args [ 'datanodeWebPort' ] = datanode_web_port return self . _cmd ( 'configureForKerberos' , data = args , api_version = 11 )
def run_one ( self , name , migrator , fake = True , downgrade = False , force = False ) : """Run / emulate a migration with given name ."""
try : migrate , rollback = self . read ( name ) if fake : with mock . patch ( 'peewee.Model.select' ) : with mock . patch ( 'peewee.Query._execute' ) : migrate ( migrator , self . database , fake = fake ) if force : self . model . create ( name = name ) ...
def bandstructure_flow ( workdir , scf_input , nscf_input , dos_inputs = None , manager = None , flow_class = Flow , allocate = True ) : """Build a : class : ` Flow ` for band structure calculations . Args : workdir : Working directory . scf _ input : Input for the GS SCF run . nscf _ input : Input for the ...
flow = flow_class ( workdir , manager = manager ) work = BandStructureWork ( scf_input , nscf_input , dos_inputs = dos_inputs ) flow . register_work ( work ) # Handy aliases flow . scf_task , flow . nscf_task , flow . dos_tasks = work . scf_task , work . nscf_task , work . dos_tasks if allocate : flow . allocate ( ...
def _profile_loglike ( self , x ) : """Internal function to calculate and cache the profile likelihood"""
x = np . array ( x , ndmin = 1 ) z = [ ] y = [ ] for xtmp in x : def fn ( t ) : return - self . loglike ( xtmp , t ) ytmp = opt . fmin ( fn , 1.0 , disp = False ) [ 0 ] ztmp = self . loglike ( xtmp , ytmp ) z . append ( ztmp ) y . append ( ytmp ) self . _prof_y = np . array ( y ) self . _pro...
def Romeo_2002 ( Re , eD ) : r'''Calculates Darcy friction factor using the method in Romeo ( 2002) [2 ] _ as shown in [ 1 ] _ . . . math : : \ frac { 1 } { \ sqrt { f _ d } } = - 2 \ log \ left \ { \ frac { \ epsilon } { 3.7065D } \ times \ frac { 5.0272 } { Re } \ times \ log \ left [ \ frac { \ epsilon }...
fd = ( - 2 * log10 ( eD / 3.7065 - 5.0272 / Re * log10 ( eD / 3.827 - 4.567 / Re * log10 ( ( eD / 7.7918 ) ** 0.9924 + ( 5.3326 / ( 208.815 + Re ) ) ** 0.9345 ) ) ) ) ** - 2 return fd
def flush ( self , overlap = 0 ) : """Flush buffered data and return it ."""
self . buf += self . empty . join ( self . tmpbuf ) self . tmpbuf = [ ] if overlap and overlap < self . pos : data = self . buf [ : - overlap ] self . buf = self . buf [ - overlap : ] else : data = self . buf self . buf = self . empty return data
def resolve_nested_dict ( nested_dict ) : """Flattens a nested dict by joining keys into tuple of paths . Can then be passed into ` format _ vars ` ."""
res = { } for k , v in nested_dict . items ( ) : if isinstance ( v , dict ) : for k_ , v_ in resolve_nested_dict ( v ) . items ( ) : res [ ( k , ) + k_ ] = v_ else : res [ ( k , ) ] = v return res
def timestamps ( self , col : str , ** kwargs ) : """Add a timestamps column from a date column : param col : name of the timestamps column to add : type col : str : param \ * \ * kwargs : keyword arguments for ` ` pd . to _ datetime ` ` for date conversions : type \ * \ * kwargs : optional : example : ...
try : name = "Timestamps" if "name" in kwargs : name = kwargs [ "name" ] if "errors" not in kwargs : kwargs [ "errors" ] = "coerce" if "unit" in kwargs : kwargs [ "unit" ] = "ms" try : self . df [ col ] = pd . to_datetime ( self . df [ col ] , ** kwargs ) except T...
def tryload_cache_list ( dpath , fname , cfgstr_list , verbose = False ) : """loads a list of similar cached datas . Returns flags that needs to be computed"""
data_list = [ tryload_cache ( dpath , fname , cfgstr , verbose ) for cfgstr in cfgstr_list ] ismiss_list = [ data is None for data in data_list ] return data_list , ismiss_list
def dispatch_event ( event ) : """Dispatch the event being represented by the Event object . Args : event : Object holding information about the request to be dispatched to the Optimizely backend ."""
try : if event . http_verb == enums . HTTPVerbs . GET : requests . get ( event . url , params = event . params , timeout = REQUEST_TIMEOUT ) . raise_for_status ( ) elif event . http_verb == enums . HTTPVerbs . POST : requests . post ( event . url , data = json . dumps ( event . params ) , header...
def unpack ( self , gpsd_socket_response ) : """Sets new socket data as DataStream attributes in those initialised dictionaries Arguments : gpsd _ socket _ response ( json object ) : Provides : self attributes , e . g . , self . lat , self . gdop Raises : AttributeError : ' str ' object has no attribute...
try : fresh_data = json . loads ( gpsd_socket_response ) # ' class ' is popped for iterator lead class_name = fresh_data . pop ( 'class' ) for key in self . packages [ class_name ] : # Fudge around the namespace collision with GST data package lat / lon being standard deviations if class_name ==...
def minicalendar ( context ) : """Displays a little ajax version of the calendar ."""
today = dt . date . today ( ) request = context [ 'request' ] home = request . site . root_page cal = CalendarPage . objects . live ( ) . descendant_of ( home ) . first ( ) calUrl = cal . get_url ( request ) if cal else None if cal : events = cal . _getEventsByWeek ( request , today . year , today . month ) else : ...
def run_script ( self , script , in_shell = True , echo = None , note = None , loglevel = logging . DEBUG ) : """Run the passed - in string as a script on the target ' s command line . @ param script : String representing the script . It will be de - indented and stripped before being run . @ param in _ shell...
shutit = self . shutit shutit . handle_note ( note , 'Script: ' + str ( script ) ) shutit . log ( 'Running script beginning: "' + '' . join ( script . split ( ) ) [ : 30 ] + ' [...]' , level = logging . INFO ) # Trim any whitespace lines from start and end of script , then dedent lines = script . split ( '\n' ) while l...
def _GetEventLogProviderKey ( self , log_source ) : """Retrieves the Event Log provider key . Args : log _ source ( str ) : Event Log source . Returns : str : Event Log provider key or None if not available . Raises : RuntimeError : if more than one value is found in the database ."""
table_names = [ 'event_log_providers' ] column_names = [ 'event_log_provider_key' ] condition = 'log_source == "{0:s}"' . format ( log_source ) values_list = list ( self . _database_file . GetValues ( table_names , column_names , condition ) ) number_of_values = len ( values_list ) if number_of_values == 0 : return...
def _set_esp ( self , v , load = False ) : """Setter method for esp , mapped from YANG variable / routing _ system / interface / ve / ipv6 / interface _ ospfv3 _ conf / authentication / ipsec _ auth _ key _ config / esp ( algorithm - type - esp ) If this variable is read - only ( config : false ) in the source ...
if hasattr ( v , "_utype" ) : v = v . _utype ( v ) try : t = YANGDynClass ( v , base = RestrictedClassType ( base_type = unicode , restriction_type = "dict_key" , restriction_arg = { u'NULL' : { 'value' : 1 } } , ) , is_leaf = True , yang_name = "esp" , rest_name = "esp" , parent = self , choice = ( u'ch-algori...
def _variant_sv ( checkpoints ) : """Structural variant workflow ."""
if not checkpoints . get ( "sv" ) : return [ ] , [ ] sv = [ s ( "detect_sv" , "batch-single" , [ [ "sv_batch_rec" ] ] , [ cwlout ( "sv_rec" , "record" , fields = [ cwlout ( [ "sv" , "variantcaller" ] , [ "string" , "null" ] ) , cwlout ( [ "sv" , "vrn_file" ] , [ "File" , "null" ] , [ ".tbi" ] ) , cwlout ( [ "sv" , ...
def parse_fingerprint ( self , cmdline , key = None , sep = None ) : """Given a psutil . Process . cmdline , parse and return a fingerprint . : param list cmdline : The psutil . Process . cmdline of the current process . : param string key : The key for fingerprint discovery . : param string sep : The key / v...
key = key or self . FINGERPRINT_CMD_KEY if key : sep = sep or self . FINGERPRINT_CMD_SEP cmdline = cmdline or [ ] for cmd_part in cmdline : if cmd_part . startswith ( '{}{}' . format ( key , sep ) ) : return cmd_part . split ( sep ) [ 1 ]
def set_beam_prop ( self , prop , values , repeat = "up" ) : """Specify the properties of the beams : param values : : param repeat : if ' up ' then duplicate up the structure : return :"""
values = np . array ( values ) if repeat == "up" : assert len ( values . shape ) == 1 values = [ values for ss in range ( self . n_storeys ) ] else : assert len ( values . shape ) == 2 if len ( values [ 0 ] ) != self . n_bays : raise ModelError ( "beam depths does not match number of bays (%i)." % self ...
def get_format_modules ( lang = None , reverse = False ) : """Returns a list of the format modules found"""
if lang is None : lang = get_language ( ) modules = _format_modules_cache . setdefault ( lang , list ( iter_format_modules ( lang ) ) ) if reverse : return list ( reversed ( modules ) ) return modules
def activate ( self , * , filter_func = None ) : '''Activate the type safety checker . After the call all functions that need to be checked will be .'''
if self . active : raise RuntimeError ( "Type safety check already active" ) self . __module_finder = ModuleFinder ( Validator . decorate ) if filter_func is not None : self . __module_finder . set_filter ( filter_func ) self . __module_finder . install ( )
def get_graph ( self ) : """Returns the most recent solve graph . This gives a graph showing the latest state of the solve . The specific graph returned depends on the solve status . When status is : unsolved : latest unsolved graph is returned ; solved : final solved graph is returned ; failed : most app...
st = self . status if st in ( SolverStatus . solved , SolverStatus . unsolved ) : phase = self . _latest_nonfailed_phase ( ) return phase . get_graph ( ) else : return self . get_fail_graph ( )
def _fake_enumerateclassnames ( self , namespace , ** params ) : """Implements a mock server responder for : meth : ` ~ pywbem . WBEMConnection . EnumerateClassNames ` . Enumerates the classnames of the classname in the ' classname ' parameter or from the top of the tree if ' classname is None . Returns : ...
self . _validate_namespace ( namespace ) classname = params . get ( 'ClassName' , None ) if classname : assert ( isinstance ( classname , CIMClassName ) ) if not self . _class_exists ( classname . classname , namespace ) : raise CIMError ( CIM_ERR_INVALID_CLASS , _format ( "The class {0!A} defined by 'C...
def _str_desc ( self , reader ) : """String containing information about the current GO DAG ."""
data_version = reader . data_version if data_version is not None : data_version = data_version . replace ( "releases/" , "" ) desc = "{OBO}: fmt({FMT}) rel({REL}) {N:,} GO Terms" . format ( OBO = reader . obo_file , FMT = reader . format_version , REL = data_version , N = len ( self ) ) if reader . optobj : des...
def generate ( self , local_go_targets ) : """Automatically generates a Go target graph for the given local go targets . : param iter local _ go _ targets : The target roots to fill in a target graph for . : raises : : class : ` GoTargetGenerator . GenerationError ` if any missing targets cannot be generated ."...
visited = { l . import_path : l . address for l in local_go_targets } with temporary_dir ( ) as gopath : for local_go_target in local_go_targets : deps = self . _list_deps ( gopath , local_go_target . address ) self . _generate_missing ( gopath , local_go_target . address , deps , visited ) return l...
def low ( data , ** kwargs ) : '''Execute a single low data call This function is mostly intended for testing the state system CLI Example : . . code - block : : bash salt ' * ' state . low ' { " state " : " pkg " , " fun " : " installed " , " name " : " vi " } ' '''
st_kwargs = __salt__ . kwargs __opts__ [ 'grains' ] = __grains__ chunks = [ data ] st_ = salt . client . ssh . state . SSHHighState ( __opts__ , __pillar__ , __salt__ , __context__ [ 'fileclient' ] ) for chunk in chunks : chunk [ '__id__' ] = chunk [ 'name' ] if not chunk . get ( '__id__' ) else chunk [ '__id__' ] ...
def dropdb ( self , name ) : '''Deletes an * * entire database * * ( i . e . a table ) , losing all data .'''
if self . readonly : raise s_exc . IsReadOnly ( ) while True : try : if not self . dbexists ( name ) : return db = self . initdb ( name ) self . dirty = True self . xact . drop ( db . db , delete = True ) self . forcecommit ( ) return except lmdb ....
def get_health ( self ) : """Summarize health of managed system This provides a summary of the health of the managed system . It additionally provides an iterable list of reasons for warning , critical , or failed assessments ."""
summary = { 'badreadings' : [ ] , 'health' : const . Health . Ok } fallbackreadings = [ ] try : self . oem_init ( ) fallbackreadings = self . _oem . get_health ( summary ) for reading in self . get_sensor_data ( ) : if reading . health != const . Health . Ok : summary [ 'health' ] |= rea...
def pack ( self , value = None ) : r"""Pack the value as a binary representation . Considering an example with UBInt8 class , that inherits from GenericType : > > > from pyof . foundation . basic _ types import UBInt8 > > > objectA = UBInt8(1) > > > objectB = 5 > > > objectA . pack ( ) b ' \ x01' > ...
if isinstance ( value , type ( self ) ) : return value . pack ( ) if value is None : value = self . value elif 'value' in dir ( value ) : # if it is enum or bitmask gets only the ' int ' value value = value . value try : return struct . pack ( self . _fmt , value ) except struct . error : expected_t...
def parse_bound_data ( self , tmin0 , tmax0 , specimen ) : """converts Kelvin / Tesla temperature / AF data from the MagIC / Redo format to that of Celsius / milliTesla which is used by the GUI as it is often more intuitive Parameters tmin0 : the input temperature / AF lower bound value to convert tmax0 :...
if specimen not in self . Data : print ( ( "no measurement data found loaded for specimen %s and will be ignored" % ( specimen ) ) ) return ( None , None ) if self . Data [ specimen ] [ 'measurement_step_unit' ] == "C" : if float ( tmin0 ) == 0 or float ( tmin0 ) == 273 : tmin = "0" else : ...
def get_relation_fields_from_model ( model_class ) : """Get related fields ( m2m , FK , and reverse FK )"""
relation_fields = [ ] all_fields_names = _get_all_field_names ( model_class ) for field_name in all_fields_names : field , model , direct , m2m = _get_field_by_name ( model_class , field_name ) # get _ all _ field _ names will return the same field # both with and without _ id . Ignore the duplicate . i...
def first ( args ) : """% prog first N fastqfile ( s ) Get first N reads from file ."""
from jcvi . apps . base import need_update p = OptionParser ( first . __doc__ ) p . set_outfile ( ) opts , args = p . parse_args ( args ) if len ( args ) < 2 : sys . exit ( not p . print_help ( ) ) N = int ( args [ 0 ] ) nlines = N * 4 fastqfiles = args [ 1 : ] fastqfile = fastqfiles [ 0 ] outfile = opts . outfile ...
def has_column_at_position ( self , column_name , pos = 0 ) : """: type column _ name : str : type pos : int : rtype : bool"""
column_name = self . _trim_quotes ( column_name . lower ( ) ) index_columns = [ c . lower ( ) for c in self . get_unquoted_columns ( ) ] return index_columns . index ( column_name ) == pos
def get_directed_graph_paths ( element , arrow_length ) : """Computes paths for a directed path which include an arrow to indicate the directionality of each edge ."""
edgepaths = element . _split_edgepaths edges = edgepaths . split ( datatype = 'array' , dimensions = edgepaths . kdims ) arrows = [ ] for e in edges : sx , sy = e [ 0 ] ex , ey = e [ 1 ] rad = np . arctan2 ( ey - sy , ex - sx ) xa0 = ex - np . cos ( rad + np . pi / 8 ) * arrow_length ya0 = ey - np ....
def squeeze ( self , dim = None ) : """Return a new object with squeezed data . Parameters dim : None or str or tuple of str , optional Selects a subset of the length one dimensions . If a dimension is selected with length greater than one , an error is raised . If None , all length one dimensions are squ...
dims = common . get_squeeze_dims ( self , dim ) return self . isel ( { d : 0 for d in dims } )
def checkpath ( path_ , verbose = VERYVERBOSE , n = None , info = VERYVERBOSE ) : r"""verbose wrapper around ` ` os . path . exists ` ` Returns : true if ` ` path _ ` ` exists on the filesystem show only the top ` n ` directories Args : path _ ( str ) : path string verbose ( bool ) : verbosity flag ( de...
assert isinstance ( path_ , six . string_types ) , ( 'path_=%r is not a string. type(path_) = %r' % ( path_ , type ( path_ ) ) ) path_ = normpath ( path_ ) if sys . platform . startswith ( 'win32' ) : # convert back to windows style path if using unix style if path_ . startswith ( '\\' ) : dirs = path_ . sp...
def pi_zoom ( self , viewer , event , msg = True ) : """Zoom and / or rotate the viewer by a pinch gesture . ( the back end must support gestures )"""
return self . _pinch_zoom_rotate ( viewer , event . state , event . rot_deg , event . scale , msg = msg )
def _run_hooked_methods ( self , hook : str ) : """Iterate through decorated methods to find those that should be triggered by the current hook . If conditions exist , check them before running otherwise go ahead and run ."""
for method in self . _potentially_hooked_methods : for callback_specs in method . _hooked : if callback_specs [ 'hook' ] != hook : continue when = callback_specs . get ( 'when' ) if when : if self . _check_callback_conditions ( callback_specs ) : metho...
def urldecode ( query ) : """Decode a query string in x - www - form - urlencoded format into a sequence of two - element tuples . Unlike urlparse . parse _ qsl ( . . . , strict _ parsing = True ) urldecode will enforce correct formatting of the query string by validation . If validation fails a ValueError ...
# Check if query contains invalid characters if query and not set ( query ) <= urlencoded : error = ( "Error trying to decode a non urlencoded string. " "Found invalid characters: %s " "in the string: '%s'. " "Please ensure the request/response body is " "x-www-form-urlencoded." ) raise ValueError ( error % ( s...
def sensor_values ( self ) : """Returns the values of all sensors for this cluster"""
self . update_instance_sensors ( opt = "all" ) return { "light" : self . lux , "water" : self . soil_moisture , "humidity" : self . humidity , "temperature" : self . temp }
def cdc ( i ) : # pragma : no cover """Input : { ( repo _ uoa ) - repo UOA module _ uoa - module UOA data _ uoa - data UOA or cid Output : { Output of the ' load ' function"""
r = cd ( i ) if r [ 'return' ] > 0 : return r s = r . get ( 'string' , '' ) if s != '' : rx = copy_to_clipboard ( { 'string' : s } ) if rx [ 'return' ] > 0 : return rx return r
def from_ssl ( self , ca_certs , client_cert , client_key , hosts = default . ELASTICSEARCH_HOSTS , use_ssl = True , verify_certs = True , ** kwargs ) : """Initialize a Elasticsearch client by SSL . : param ca _ certs : optional path to CA bundle . See https : / / urllib3 . readthedocs . io / en / latest / secu...
self . client = Elasticsearch ( hosts = hosts , use_ssl = use_ssl , verify_certs = verify_certs , ca_certs = ca_certs , client_cert = client_cert , client_key = client_key , ** kwargs ) logger . info ( 'Initialize SSL Elasticsearch Client: %s.' % self . client )
def wait_on_event ( event , timeout = None ) : """Waits on a single threading Event , with an optional timeout . This is here for compatibility reasons as python 2 can ' t reliably wait on an event without a timeout and python 3 doesn ' t define a ` maxint ` ."""
if timeout is not None : event . wait ( timeout ) return if six . PY2 : # Thanks to a bug in python 2 ' s threading lib , we can ' t simply call # . wait ( ) with no timeout since it would wind up ignoring signals . while not event . is_set ( ) : event . wait ( sys . maxint ) else : event . wait...
def _page ( q , chunk = 1000 ) : """Quick utility to page a query , 1000 items at a time . We need this so we don ' t OOM ( out of memory ) ourselves loading the world ."""
offset = 0 while True : r = False for elem in q . limit ( chunk ) . offset ( offset ) : r = True yield elem offset += chunk if not r : break
def signed_session ( self , session = None ) : """Create token - friendly Requests session , using auto - refresh . Used internally when a request is made . If a session object is provided , configure it directly . Otherwise , create a new session and return it . : param session : The session to configure f...
self . set_token ( ) # Adal does the caching . self . _parse_token ( ) return super ( AADMixin , self ) . signed_session ( session )
def from_filename ( cls , path_string , origin = MISSING , ** kwargs ) : """Read Sass source from a String specifying the path"""
path = Path ( path_string ) return cls . from_path ( path , origin , ** kwargs )
def summarize ( urls ) : """Calls extract for each of the URLs , Returns the list of Extracted instances as summaries , the result of the process , and the speed ."""
import time from summary import Summary fails = 0 err = lambda e : e . __class__ . __name__ summaries = [ ] start = time . time ( ) for url in urls : try : print "-> %s" % url summary = Summary ( url ) summary . extract ( ) except KeyboardInterrupt : break except Exception , ...
def _debug ( self , out , print_prefix = True ) : """Print out to stderr , if debugging is enabled ."""
if self . debug : if print_prefix : pre = self . __class__ . __name__ if hasattr ( self , 'debug_prefix' ) : pre = getattr ( self , 'debug_prefix' ) sys . stderr . write ( "%s: " % pre ) sys . stderr . write ( out )
def _get_prog_memory ( resources , cores_per_job ) : """Get expected memory usage , in Gb per core , for a program from resource specification ."""
out = None for jvm_opt in resources . get ( "jvm_opts" , [ ] ) : if jvm_opt . startswith ( "-Xmx" ) : out = _str_memory_to_gb ( jvm_opt [ 4 : ] ) memory = resources . get ( "memory" ) if memory : out = _str_memory_to_gb ( memory ) prog_cores = resources . get ( "cores" ) # if a single core with memory i...
def lnlike ( self , X ) : """Use a softened version of the interpolant as a likelihood ."""
return - 3.5 * np . log ( self . _interpolant ( X [ 0 ] , X [ 1 ] , grid = False ) )
def stdlib ( self ) : """A boolean flag . ` ` True ` ` if frame is in stdlib . : type : bool"""
if self . module == 'pkg_resources' or self . module . startswith ( 'pkg_resources.' ) : return False elif self . filename . startswith ( SITE_PACKAGES_PATHS ) : # if it ' s in site - packages then its definitely not stdlib return False elif self . filename . startswith ( SYS_PREFIX_PATHS ) : return True el...
def verify_true ( self , expr , msg = None ) : """Soft assert for whether the condition is true : params expr : the statement to evaluate : params msg : ( Optional ) msg explaining the difference"""
try : self . assert_true ( expr , msg ) except AssertionError , e : if msg : m = "%s:\n%s" % ( msg , str ( e ) ) else : m = str ( e ) self . verification_erorrs . append ( m )
def send_feedback ( self , reason , type = None , author_ip = None , author_id = None , author_open_id = None , content_id = None , captcha_id = None , source = None ) : """Sends feedback to Mollom in the case of false negative or false positives . Keyword arguments : reason - - Feedback to give . Can be : " ap...
send_feedback_endpoint = Template ( "${rest_root}/feedback" ) url = send_feedback_endpoint . substitute ( rest_root = self . _rest_root ) data = { "contentId" : content_id , "reason" : reason } if type : data [ "type" ] = type if author_ip : data [ "authorIp" ] = author_ip if author_id : data [ "authorId" ]...
def add_edge_bearings ( G ) : """Calculate the compass bearing from origin node to destination node for each edge in the directed graph then add each bearing as a new edge attribute . Parameters G : networkx multidigraph Returns G : networkx multidigraph"""
for u , v , data in G . edges ( keys = False , data = True ) : if u == v : # a self - loop has an undefined compass bearing data [ 'bearing' ] = np . nan else : # calculate bearing from edge ' s origin to its destination origin_point = ( G . nodes [ u ] [ 'y' ] , G . nodes [ u ] [ 'x' ] ) ...
def production_url ( path , original ) : """For a production environment ( DEBUG = False ) , replaces original path created by Django ' s { % static % } template tag with relevant path from our mapping ."""
mapping = _get_mapping ( ) if mapping : if path in mapping : return original . replace ( path , mapping [ path ] ) return original else : return dev_url ( original )
def _bandpass ( self , fc_low = 5 , fc_high = 20 ) : """Apply a bandpass filter onto the signal , and save the filtered signal ."""
self . fc_low = fc_low self . fc_high = fc_high b , a = signal . butter ( 2 , [ float ( fc_low ) * 2 / self . fs , float ( fc_high ) * 2 / self . fs ] , 'pass' ) self . sig_f = signal . filtfilt ( b , a , self . sig [ self . sampfrom : self . sampto ] , axis = 0 ) # Save the passband gain ( x2 due to double filtering )...
def annToRLE ( self , ann ) : """Convert annotation which can be polygons , uncompressed RLE to RLE . : return : binary mask ( numpy 2D array )"""
t = self . imgs [ ann [ 'image_id' ] ] h , w = t [ 'height' ] , t [ 'width' ] segm = ann [ 'segmentation' ] if type ( segm ) == list : # polygon - - a single object might consist of multiple parts # we merge all parts into one mask rle code rles = maskUtils . frPyObjects ( segm , h , w ) rle = maskUtils . merge...
def cleanup ( self ) : """Clean up before quitting"""
self . pre_exit_trigger = True self . logger . info ( "Shutting down %s, please wait a moment." , self . name ) for t in threading . enumerate ( ) : if isinstance ( t , TimerClass ) : t . cancel ( ) self . logger . debug ( 'Timers cancelled' ) for i in self . objects : i . cleanup ( ) self . logger . de...
def get_parent_path ( index = 2 ) : # type : ( int ) - > str """Get the caller ' s parent path to sys . path If the caller is a CLI through stdin , the parent of the current working directory is used"""
try : path = _caller_path ( index ) except RuntimeError : path = os . getcwd ( ) path = os . path . abspath ( os . path . join ( path , os . pardir ) ) return path
def format_parameters ( self , params ) : # type : ( Dict [ str , str ] ) - > None """Format parameters into a valid query string . It ' s assumed all parameters have already been quoted as valid URL strings . : param dict params : A dictionary of parameters ."""
query = urlparse ( self . url ) . query if query : self . url = self . url . partition ( '?' ) [ 0 ] existing_params = { p [ 0 ] : p [ - 1 ] for p in [ p . partition ( '=' ) for p in query . split ( '&' ) ] } params . update ( existing_params ) query_params = [ "{}={}" . format ( k , v ) for k , v in params...
def loadPng ( varNumVol , tplPngSize , strPathPng ) : """Load PNG files . Parameters varNumVol : float Number of volumes , i . e . number of time points in all runs . tplPngSize : tuple Shape of the stimulus image ( i . e . png ) . strPathPng : str Path to the folder cointaining the png files . Retu...
print ( '------Load PNGs' ) # Create list of png files to load : lstPngPaths = [ None ] * varNumVol for idx01 in range ( 0 , varNumVol ) : lstPngPaths [ idx01 ] = ( strPathPng + str ( idx01 ) + '.png' ) # Load png files . The png data will be saved in a numpy array of the # following order : aryPngData [ x - pixel ...
def _pyproj_inv ( self , other , ellipse = 'WGS84' ) : '''Perform Pyproj ' s inv operation on two LatLon objects Returns the initial heading and reverse heading in degrees , and the distance in km .'''
lat1 , lon1 = self . lat . decimal_degree , self . lon . decimal_degree lat2 , lon2 = other . lat . decimal_degree , other . lon . decimal_degree g = pyproj . Geod ( ellps = ellipse ) heading_initial , heading_reverse , distance = g . inv ( lon1 , lat1 , lon2 , lat2 , radians = False ) distance = distance / 1000.0 if h...
def generate_random_missense_variants ( num_variants = 10 , max_search = 100000 , reference = "GRCh37" ) : """Generate a random collection of missense variants by trying random variants repeatedly ."""
variants = [ ] for i in range ( max_search ) : bases = [ "A" , "C" , "T" , "G" ] random_ref = choice ( bases ) bases . remove ( random_ref ) random_alt = choice ( bases ) random_contig = choice ( [ "1" , "2" , "3" , "4" , "5" ] ) random_variant = Variant ( contig = random_contig , start = randin...
def _annotation_stmt ( self , stmt : Statement , sctx : SchemaContext ) -> None : """Handle annotation statement ."""
if not sctx . schema_data . if_features ( stmt , sctx . text_mid ) : return dst = stmt . find1 ( "description" ) self . annotations [ ( stmt . argument , sctx . default_ns ) ] = Annotation ( DataType . _resolve_type ( stmt . find1 ( "type" , required = True ) , sctx ) , dst . argument if dst else None )
def exec ( self , command_str , ** command_env ) : """Execute the given command ( command will be split into tokens , every space that is a part of a token must be quoted ) : param command _ str : command to execute : param command _ env : command environment : return : WCommandResultProto"""
env = self . __vars . copy ( ) env . update ( command_env ) command_tokens = WCommandProto . split_command ( command_str ) command_obj = self . commands ( ) . select ( * command_tokens , ** env ) if command_obj is None : raise WCommandSet . NoCommandFound ( 'No suitable command found: "%s"' % command_str ) result =...
def _read_object ( self , correlation_id , parameters ) : """Reads configuration file , parameterizes its content and converts it into JSON object . : param correlation _ id : ( optional ) transaction id to trace execution through call chain . : param parameters : values to parameters the configuration . : re...
path = self . get_path ( ) if path == None : raise ConfigException ( correlation_id , "NO_PATH" , "Missing config file path" ) if not os . path . isfile ( path ) : raise FileException ( correlation_id , 'FILE_NOT_FOUND' , 'Config file was not found at ' + path ) try : with open ( path , 'r' ) as file : ...
def get_sample_data ( sample_file ) : """Read and returns sample data to fill form with default sample sequence ."""
sequence_sample_in_fasta = None with open ( sample_file ) as handle : sequence_sample_in_fasta = handle . read ( ) return sequence_sample_in_fasta
def median_filter ( data , size = 3 , cval = 0 , res_g = None , sub_blocks = None ) : """median filter of given size Parameters data : 2 or 3 dimensional ndarray or OCLArray of type float32 input data size : scalar , tuple the size of the patch to consider cval : scalar , the constant value for out of...
if data . ndim == 2 : _filt = make_filter ( _median_filter_gpu_2d ( ) ) elif data . ndim == 3 : _filt = make_filter ( _median_filter_gpu_3d ( ) ) else : raise ValueError ( "currently only 2 or 3 dimensional data is supported" ) return _filt ( data = data , size = size , cval = cval , res_g = res_g , sub_blo...
def get ( self , instance_name ) : """Get an ObjectRocket instance by name . : param str instance _ name : The name of the instance to retrieve . : returns : A subclass of : py : class : ` bases . BaseInstance ` , or None if instance does not exist . : rtype : : py : class : ` bases . BaseInstance `"""
url = self . _url + instance_name + '/' response = requests . get ( url , ** self . _default_request_kwargs ) data = self . _get_response_data ( response ) return self . _concrete_instance ( data )
def setup_logger ( log_level , log_file = None ) : """setup root logger with ColoredFormatter ."""
level = getattr ( logging , log_level . upper ( ) , None ) if not level : color_print ( "Invalid log level: %s" % log_level , "RED" ) sys . exit ( 1 ) # hide traceback when log level is INFO / WARNING / ERROR / CRITICAL if level >= logging . INFO : sys . tracebacklimit = 0 formatter = ColoredFormatter ( u"%...
def cancelled ( self ) : """Return if the gesture ended normally , or if it was cancelled . For gesture events that are not of type : attr : ` ~ libinput . constant . EventType . GESTURE _ SWIPE _ END ` or : attr : ` ~ libinput . constant . EventType . GESTURE _ PINCH _ END ` , this property raises : exc : ...
if self . type not in { EventType . GESTURE_SWIPE_END , EventType . GESTURE_PINCH_END } : raise AttributeError ( _wrong_prop . format ( self . type ) ) return self . _libinput . libinput_event_gesture_get_cancelled ( self . _handle )
def find_column ( self , token ) : """Compute column : - token is a token instance"""
i = token . lexpos while i > 0 : if self . input_data [ i - 1 ] == '\n' : break i -= 1 column = token . lexpos - i + 1 return column
def is_string ( val ) : """Determines whether the passed value is a string , safe for 2/3."""
try : basestring except NameError : return isinstance ( val , str ) return isinstance ( val , basestring )
def version_keyword ( dist , attr , value ) : """Implements the actual version setup ( ) keyword ."""
if value == "PBR" : from pbr . util import setup_cfg_to_setup_kwargs path = "setup.cfg" parser = ConfigParser ( ) if not os . path . exists ( path ) : raise ValueError ( "file '%s' does not exist" % os . path . abspath ( path ) ) parser . read ( path ) config = { } for section in par...
def xcoord ( self ) : """The x coordinate : class : ` xarray . Variable `"""
return self . decoder . get_x ( self . data , coords = self . data . coords )
def _CheckAndCreateNewGroup ( self , group_name , group_class ) : """Checks if the last method ( a possible group ) is an instance of our group _ class . Adds the current method to this group or creates a new one . Args : group _ name : the name of the group . group _ class : the class used to create instan...
group = self . GetPossibleGroup ( ) # If this is a group , and it is the correct group , add the method . if isinstance ( group , group_class ) and group . group_name ( ) == group_name : group . AddMethod ( self ) return self # Create a new group and add the method . new_group = group_class ( group_name ) new_g...
def update_cnt ( uid , post_data ) : '''Update the content by ID .'''
entry = TabPostHist . update ( user_name = post_data [ 'user_name' ] , cnt_md = tornado . escape . xhtml_escape ( post_data [ 'cnt_md' ] ) , time_update = tools . timestamp ( ) , ) . where ( TabPostHist . uid == uid ) entry . execute ( )
def _set_socket_timeout ( cls , sock , timeout = None ) : """Temporarily set a socket timeout in order to respect a timeout provided to . iter _ chunks ( ) ."""
if timeout is not None : prev_timeout = sock . gettimeout ( ) try : if timeout is not None : sock . settimeout ( timeout ) yield except socket . timeout : raise cls . ProcessStreamTimeout ( "socket read timed out with timeout {}" . format ( timeout ) ) finally : if timeout is not None : ...
def match_zipfile_members ( zipfile_path : str , pattern : Pattern ) : """Match files to a pattern within a zip file ' s content ."""
with ZipFile ( zipfile_path , mode = 'r' ) as zfile : members = zfile . namelist ( ) yield from match_files ( members , pattern )
def toggle_grid ( self , event = None , show = None ) : "toggle grid on top / bottom panels"
if show is None : show = not self . panel . conf . show_grid for p in ( self . panel , self . panel_bot ) : p . conf . enable_grid ( show )
def convert_halo_to_array_form ( self , halo ) : """Converts the : samp : ` { halo } ` argument to a : samp : ` ( { self } . array _ shape . size , 2 ) ` shaped array . : type halo : : samp : ` None ` , : obj : ` int ` , : samp : ` self . array _ shape . size ` length sequence of : samp : ` int ` or : samp : ...
return convert_halo_to_array_form ( halo = halo , ndim = len ( self . array_shape ) )
def pdf ( self ) : """Returns the probability density function ( pdf ) . Returns function : The probability density function of the distribution . Examples > > > from pgmpy . factors . distributions import GaussianDistribution > > > dist = GD ( variables = [ ' x1 ' , ' x2 ' , ' x3 ' ] , . . . mean = [ 1...
return lambda * args : multivariate_normal . pdf ( args , self . mean . reshape ( 1 , len ( self . variables ) ) [ 0 ] , self . covariance )
def sum2diag ( A , D , out = None ) : r"""Add values ` ` D ` ` to the diagonal of matrix ` ` A ` ` . Args : A ( array _ like ) : Left - hand side . D ( array _ like or float ) : Values to add . out ( : class : ` numpy . ndarray ` , optional ) : copy result to . Returns : : class : ` numpy . ndarray ` : ...
A = asarray ( A , float ) D = asarray ( D , float ) if out is None : out = copy ( A ) else : copyto ( out , A ) einsum ( "ii->i" , out ) [ : ] += D return out
def equals ( self , controller ) : """Verify if the controller corresponds to the current one ."""
if controller is None : return False return self . user == controller . user and self . enterprise == controller . enterprise and self . url == controller . url
def libvlc_media_save_meta ( p_md ) : '''Save the meta previously set . @ param p _ md : the media desriptor . @ return : true if the write operation was successful .'''
f = _Cfunctions . get ( 'libvlc_media_save_meta' , None ) or _Cfunction ( 'libvlc_media_save_meta' , ( ( 1 , ) , ) , None , ctypes . c_int , Media ) return f ( p_md )
def today ( self , symbol ) : """GET / today / : symbol curl " https : / / api . bitfinex . com / v1 / today / btcusd " { " low " : " 550.09 " , " high " : " 572.2398 " , " volume " : " 7305.33119836 " }"""
data = self . _get ( self . url_for ( PATH_TODAY , ( symbol ) ) ) # convert all values to floats return self . _convert_to_floats ( data )
def remove_duplicates ( lst ) : """Emulate what a Python ` ` set ( ) ` ` does , but keeping the element ' s order ."""
dset = set ( ) return [ l for l in lst if l not in dset and not dset . add ( l ) ]
def writeNumber ( self , n ) : """Write number to the data stream . @ param n : The number data to be encoded to the AMF0 data stream ."""
self . writeType ( TYPE_NUMBER ) self . stream . write_double ( float ( n ) )