signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def chambers ( self ) : """Return distinct chambers . You probably want to prefetch documents _ _ chamber before calling that ."""
# Use sorted ( ) because using order _ by will hit the database no matter # what was prefetched return set ( sorted ( [ d . chamber for d in self . documents . all ( ) ] ) )
def check_if_ready ( self ) : """Check for and fetch the results if ready ."""
try : results = self . manager . check ( self . results_id ) except exceptions . ResultsNotReady as e : self . _is_ready = False self . _not_ready_exception = e except exceptions . ResultsExpired as e : self . _is_ready = True self . _expired_exception = e else : failures = self . get_failed_req...
def return_future ( f ) : """Decorator to make a function that returns via callback return a ` Future ` . The wrapped function should take a ` ` callback ` ` keyword argument and invoke it with one argument when it has finished . To signal failure , the function can simply raise an exception ( which will be...
replacer = ArgReplacer ( f , 'callback' ) @ functools . wraps ( f ) def wrapper ( * args , ** kwargs ) : future = TracebackFuture ( ) callback , args , kwargs = replacer . replace ( lambda value = _NO_RESULT : future . set_result ( value ) , args , kwargs ) def handle_error ( typ , value , tb ) : fu...
def remove_attribute ( self , attribute : str ) -> None : """Remove an attribute from the node . Use only if is _ mapping ( ) returns True . Args : attribute : The name of the attribute to remove ."""
attr_index = self . __attr_index ( attribute ) if attr_index is not None : self . yaml_node . value . pop ( attr_index )
def _ordered_keys ( dict_ ) : """: param dict _ : dict of OrderedDict to be processed : return : list of str of keys in the original order or in alphabetical order"""
return isinstance ( dict_ , OrderedDict ) and dict_ . keys ( ) or dict_ and sorted ( dict_ . keys ( ) ) or [ ]
def wrapped_setups ( self ) : """Create tokens for Described . setup = noy _ wrap _ setup ( Described , Described . setup ) for setup / teardown"""
lst = [ ] for group in self . all_groups : if not group . root : if group . has_after_each : lst . extend ( self . tokens . wrap_after_each ( group . kls_name , group . async_after_each ) ) if group . has_before_each : lst . extend ( self . tokens . wrap_before_each ( group ....
def remove ( self , address ) : """Remove an address from the connection pool , if present , closing all connections to that address ."""
with self . lock : for connection in self . connections . pop ( address , ( ) ) : try : connection . close ( ) except IOError : pass
def _FloatDecoder ( ) : """Returns a decoder for a float field . This code works around a bug in struct . unpack for non - finite 32 - bit floating - point values ."""
local_unpack = struct . unpack def InnerDecode ( buffer , pos ) : # We expect a 32 - bit value in little - endian byte order . Bit 1 is the sign # bit , bits 2-9 represent the exponent , and bits 10-32 are the significand . new_pos = pos + 4 float_bytes = buffer [ pos : new_pos ] # If this value has all its...
def feedback ( self , * , out_port = None , in_port = None ) : """Return a circuit with self - feedback from the output port ( zero - based ) ` ` out _ port ` ` to the input port ` ` in _ port ` ` . Args : out _ port ( int or None ) : The output port from which the feedback connection leaves ( zero - based ...
if out_port is None : out_port = self . cdim - 1 if in_port is None : in_port = self . cdim - 1 return self . _feedback ( out_port = out_port , in_port = in_port )
async def sources ( client : Client , pubkey : str ) -> dict : """GET transaction sources : param client : Client to connect to the api : param pubkey : Public key : return :"""
return await client . get ( MODULE + '/sources/%s' % pubkey , schema = SOURCES_SCHEMA )
def get_folder ( self , title ) : """Retrieve a folder by its title Usage : C { engine . get _ folder ( title ) } Note that if more than one folder has the same title , only the first match will be returned ."""
for folder in self . configManager . allFolders : if folder . title == title : return folder return None
def value_from_datadict ( self , data , files , name ) : """Ensure the payload is a list of values . In the case of a sub form , we need to ensure the data is returned as a list and not a dictionary . When a dict is found in the given data , we need to ensure the data is converted to a list perseving the fi...
if name in data : payload = data . get ( name ) if isinstance ( payload , ( dict , ) ) : # Make sure we get the data in the correct roder return [ payload . get ( f . name ) for f in self . fields ] return payload return super ( FormFieldWidget , self ) . value_from_datadict ( data , files , name )
def as_fs ( self ) : """Returns the value of component encoded as formatted string . Inspect each character in value of component . Certain nonalpha characters pass thru without escaping into the result , but most retain escaping . : returns : Formatted string associated with component : rtype : string"""
s = self . _standard_value result = [ ] idx = 0 while ( idx < len ( s ) ) : c = s [ idx ] # get the idx ' th character of s if c != "\\" : # unquoted characters pass thru unharmed result . append ( c ) else : # Escaped characters are examined nextchr = s [ idx + 1 ] if ( nextchr ...
def parse_params ( self , eps = 0.3 , eps_iter = 0.05 , nb_iter = 10 , y = None , ord = np . inf , clip_min = None , clip_max = None , y_target = None , rand_init = None , rand_minmax = 0.3 , sanity_checks = True , ** kwargs ) : """Take in a dictionary of parameters and applies attack - specific checks before sav...
# Save attack - specific parameters self . eps = eps if rand_init is None : rand_init = self . default_rand_init self . rand_init = rand_init if self . rand_init : self . rand_minmax = eps else : self . rand_minmax = 0. self . eps_iter = eps_iter self . nb_iter = nb_iter self . y = y self . y_target = y_tar...
def _get_per_data_dir ( self , dir_base , subpath ) : """Extend the given base directory with a per - data component . The method creates a private path for the : class : ` ~ resolwe . flow . models . Data ` object , such as : : . / test _ data / 1/ if ` ` base _ dir ` ` is ` ` ' . / test _ data ' ` ` and `...
# Use Django settings here , because the state must be preserved # across events . This also implies the directory settings can ' t # be patched outside the manager and then just sent along in the # command packets . result = self . settings_actual . get ( 'FLOW_EXECUTOR' , { } ) . get ( dir_base , '' ) return os . pat...
def apply ( self , hits , no_copy = False ) : """Add x , y , z , t0 ( and du , floor if DataFrame ) columns to the hits ."""
if not no_copy : hits = hits . copy ( ) if istype ( hits , 'DataFrame' ) : # do we ever see McHits here ? hits = Table . from_template ( hits , 'Hits' ) if hasattr ( hits , 'dom_id' ) and hasattr ( hits , 'channel_id' ) : dir_x , dir_y , dir_z , du , floor , pos_x , pos_y , pos_z , t0 = _get_calibration_for...
def get ( self , fragment_info ) : """Get the value associated with the given key . : param fragment _ info : the text key : type fragment _ info : tuple of str ` ` ( language , text ) ` ` : raises : KeyError if the key is not present in the cache"""
if not self . is_cached ( fragment_info ) : raise KeyError ( u"Attempt to get text not cached" ) return self . cache [ fragment_info ]
def Fahien_Schriver ( dp , voidage , vs , rho , mu , L = 1 ) : r'''Calculates pressure drop across a packed bed of spheres using a correlation developed in [ 1 ] _ , as shown in [ 2 ] _ . Second most accurate correlation overall in the review of [ 2 ] _ . . . math : : f _ p = \ left ( q \ frac { f _ { 1L } ...
Rem = dp * rho * vs / mu / ( 1 - voidage ) q = exp ( - voidage ** 2 * ( 1 - voidage ) / 12.6 * Rem ) f1L = 136 / ( 1 - voidage ) ** 0.38 f1T = 29 / ( ( 1 - voidage ) ** 1.45 * voidage ** 2 ) f2 = 1.87 * voidage ** 0.75 / ( 1 - voidage ) ** 0.26 fp = ( q * f1L / Rem + ( 1 - q ) * ( f2 + f1T / Rem ) ) * ( 1 - voidage ) /...
def guess_payload_class ( self , payload ) : """DEV : Guesses the next payload class from layer bonds . Can be overloaded to use a different mechanism . : param str payload : the layer ' s payload : return : the payload class"""
for t in self . aliastypes : for fval , cls in t . payload_guess : if all ( hasattr ( self , k ) and v == self . getfieldval ( k ) for k , v in six . iteritems ( fval ) ) : return cls return self . default_payload_class ( payload )
def find_objects ( self , linespec ) : """Find lines that match the linespec regex . : param linespec : regular expression of line to match : return : list of LineItem objects"""
# Note ( asr1kteam ) : In this code we are only adding children one - level # deep to a given parent ( linespec ) , as that satisfies the IOS conf # parsing . # Note ( asr1kteam ) : Not tested with tabs in the config . Currently used # with IOS config where we haven ' t seen tabs , but may be needed for a # more genera...
def create_or_update_proxy ( self , proxy ) : """CreateOrUpdateProxy . [ Preview API ] : param : class : ` < Proxy > < azure . devops . v5_0 . core . models . Proxy > ` proxy : : rtype : : class : ` < Proxy > < azure . devops . v5_0 . core . models . Proxy > `"""
content = self . _serialize . body ( proxy , 'Proxy' ) response = self . _send ( http_method = 'PUT' , location_id = 'ec1f4311-f2b4-4c15-b2b8-8990b80d2908' , version = '5.0-preview.2' , content = content ) return self . _deserialize ( 'Proxy' , response )
def create_session ( self , ticket , payload = None , expires = None ) : '''Create a session record from a service ticket .'''
assert isinstance ( self . session_storage_adapter , CASSessionAdapter ) logging . debug ( '[CAS] Creating session for ticket {}' . format ( ticket ) ) self . session_storage_adapter . create ( ticket , payload = payload , expires = expires , )
def _consume ( self ) : """Gets rid of the used parts of the buffer ."""
self . _stream_offset += self . _buff_i - self . _buf_checkpoint self . _buf_checkpoint = self . _buff_i
def get_all_activities ( self , autoscale_group , activity_ids = None , max_records = None , next_token = None ) : """Get all activities for the given autoscaling group . This action supports pagination by returning a token if there are more pages to retrieve . To get the next page , call this action again with...
name = autoscale_group if isinstance ( autoscale_group , AutoScalingGroup ) : name = autoscale_group . name params = { 'AutoScalingGroupName' : name } if max_records : params [ 'MaxRecords' ] = max_records if next_token : params [ 'NextToken' ] = next_token if activity_ids : self . build_list_params ( p...
def get_connections ( self ) : """Find and return all connections based on file format version ."""
if float ( self . _dsversion ) < 10 : connections = self . _extract_legacy_connection ( ) else : connections = self . _extract_federated_connections ( ) return connections
def make_rfft_factors ( axes , resshape , facshape , normshape , norm ) : """make the compression factors and compute the normalization for irfft and rfft ."""
N = 1.0 for n in normshape : N = N * n # inplace modification is fine because we produce a constant # which doesn ' t go into autograd . # For same reason could have used numpy rather than anp . # but we already imported anp , so use it instead . fac = anp . zeros ( resshape ) fac [ ... ] = 2 index = [ slice ( None...
def _ncc_c_2dim ( x , y ) : """Variant of NCCc that operates with 2 dimensional X arrays and 1 dimensional y vector Returns a 2 dimensional array of normalized fourier transforms"""
den = np . array ( norm ( x , axis = 1 ) * norm ( y ) ) den [ den == 0 ] = np . Inf x_len = x . shape [ - 1 ] fft_size = 1 << ( 2 * x_len - 1 ) . bit_length ( ) cc = ifft ( fft ( x , fft_size ) * np . conj ( fft ( y , fft_size ) ) ) cc = np . concatenate ( ( cc [ : , - ( x_len - 1 ) : ] , cc [ : , : x_len ] ) , axis = ...
def parse_gpx ( gpx_element , gpx_extensions_parser = None , metadata_extensions_parser = None , waypoint_extensions_parser = None , route_extensions_parser = None , track_extensions_parser = None , segment_extensions_parser = None , gpxns = None ) : """Parse a GPX file into a GpxModel . Args : gpx _ element : ...
gpxns = gpxns if gpxns is not None else determine_gpx_namespace ( gpx_element ) if gpx_element . tag != gpxns + 'gpx' : raise ValueError ( "No gpx root element" ) creator = gpx_element . attrib [ 'creator' ] version = gpx_element . attrib [ 'version' ] if not version . startswith ( '1.1' ) : raise ValueError ( ...
def get_config ( config_schema , env = None ) : """Parse config from the environment against a given schema Args : config _ schema : A dictionary mapping keys in the environment to envpy Schema objects describing the expected value . env : An optional dictionary used to override the environment rather ...
if env is None : env = os . environ return parser . parse_env ( config_schema , env , )
def loadNetworkbyID ( self , id , callback = None , errback = None ) : """Load an existing Network by ID into a high level Network object : param int id : id of an existing Network"""
import ns1 . ipam network = ns1 . ipam . Network ( self . config , id = id ) return network . load ( callback = callback , errback = errback )
def correct_entry ( self , entry ) : """Corrects a single entry . Args : entry : A DefectEntry object . Returns : An processed entry . Raises : CompatibilityError if entry is not compatible ."""
entry . correction . update ( self . get_correction ( entry ) ) return entry
def event ( request , id ) : "Displays a list of all services and their current status ."
try : evt = Event . objects . get ( pk = id ) except Event . DoesNotExist : return HttpResponseRedirect ( reverse ( 'overseer:index' ) ) update_list = list ( evt . eventupdate_set . order_by ( '-date_created' ) ) return respond ( 'overseer/event.html' , { 'event' : evt , 'update_list' : update_list , } , reques...
def chunks ( stream , size = None ) : '''Returns a generator of chunks from the ` stream ` with a maximum size of ` size ` . I don ' t know why this isn ' t part of core Python . : Parameters : stream : file - like object The stream to fetch the chunks from . Note that the stream will not be repositioned ...
if size == 'lines' : for item in stream : # for item in stream . readline ( ) : yield item return if size is None : size = MAXBUF while True : buf = stream . read ( size ) if not buf : return yield buf
def get_segment_definer_comments ( xml_file , include_version = True ) : """Returns a dict with the comment column as the value for each segment"""
from glue . ligolw . ligolw import LIGOLWContentHandler as h lsctables . use_in ( h ) # read segment definer table xmldoc , _ = ligolw_utils . load_fileobj ( xml_file , gz = xml_file . name . endswith ( ".gz" ) , contenthandler = h ) seg_def_table = table . get_table ( xmldoc , lsctables . SegmentDefTable . tableName )...
def tokenize ( self , unicode_sentence , mode = "default" , HMM = True ) : """Tokenize a sentence and yields tuples of ( word , start , end ) Parameter : - sentence : the str ( unicode ) to be segmented . - mode : " default " or " search " , " search " is for finer segmentation . - HMM : whether to use the ...
if not isinstance ( unicode_sentence , text_type ) : raise ValueError ( "jieba: the input parameter should be unicode." ) start = 0 if mode == 'default' : for w in self . cut ( unicode_sentence , HMM = HMM ) : width = len ( w ) yield ( w , start , start + width ) start += width else : ...
def rules ( ctx ) : """[ bookie ] List all rules"""
rules = Rules ( peerplays_instance = ctx . peerplays ) click . echo ( pretty_print ( rules , ctx = ctx ) )
def future ( self , in_days = None , in_hours = None , in_minutes = None , in_seconds = None ) : """Function to return a future timestep"""
future = None # Initialize variables to 0 dd , hh , mm , ss = [ 0 for i in range ( 4 ) ] if ( in_days != None ) : dd = dd + in_days if ( in_hours != None ) : hh = hh + in_hours if ( in_minutes != None ) : mm = mm + in_minutes if ( in_seconds != None ) : ss = ss + in_seconds # Set the hours , minutes and...
def parse_args ( ) : """Defines all arguments . Returns args object that contains all the params"""
parser = argparse . ArgumentParser ( formatter_class = argparse . ArgumentDefaultsHelpFormatter , description = 'Create an image list or \ make a record database by reading from an image list' ) parser . add_argument ( 'prefix' , help = 'prefix of input/output lst and rec files.' ) parser . add_argument ( 'root...
def find_closest_neighbours ( cell , all_cells , k , max_dist ) : """Find k closest neighbours of the given cell . : param CellFeatures cell : cell of interest : param all _ cells : cell to consider as neighbours : param int k : number of neighbours to be returned : param int max _ dist : maximal distance i...
all_cells = [ c for c in all_cells if c != cell ] sorted_cells = sorted ( [ ( cell . distance ( c ) , c ) for c in all_cells ] ) return [ sc [ 1 ] for sc in sorted_cells [ : k ] if sc [ 0 ] <= max_dist ]
def _wait_for_consistency ( checker ) : """Eventual consistency : wait until GCS reports something is true . This is necessary for e . g . create / delete where the operation might return , but won ' t be reflected for a bit ."""
for _ in xrange ( EVENTUAL_CONSISTENCY_MAX_SLEEPS ) : if checker ( ) : return time . sleep ( EVENTUAL_CONSISTENCY_SLEEP_INTERVAL ) logger . warning ( 'Exceeded wait for eventual GCS consistency - this may be a' 'bug in the library or something is terribly wrong.' )
def convert_hue ( self , hue , legacy_color_wheel = False ) : """Converts the hue from HSV color circle to the LimitlessLED color wheel . : param hue : The hue in decimal percent ( 0.0-1.0 ) . : param legacy _ color _ wheel : Whether or not use the old color wheel . : return : The hue regarding the LimitlessL...
hue = math . ceil ( hue * self . MAX_HUE ) if legacy_color_wheel : hue = ( 176 - hue ) % ( self . MAX_HUE + 1 ) hue = ( self . MAX_HUE - hue - 0x37 ) % ( self . MAX_HUE + 1 ) else : hue += 10 # The color wheel for RGBWW bulbs seems to be shifted return hue % ( self . MAX_HUE + 1 )
def get_raw_entry ( self , variant_line = None , variant_dict = None , vcf_header = None , individual_id = None , dict_key = None ) : """Return the raw entry from the vcf field If no entry was found return None Args : variant _ line ( str ) : A vcf formated variant line vcf _ header ( list ) : A list with t...
if variant_line : variant_line = variant_line . rstrip ( ) . split ( ) entry = None if self . field == 'CHROM' : if variant_line : entry = variant_line [ 0 ] elif variant_dict : entry = variant_dict [ 'CHROM' ] elif self . field == 'POS' : if variant_line : entry = variant_line [...
def move ( source , destination , adapter = None , fatal = True , logger = LOG . debug ) : """Move source - > destination : param str | None source : Source file or folder : param str | None destination : Destination file or folder : param callable adapter : Optional function to call on ' source ' before copy...
return _file_op ( source , destination , _move , adapter , fatal , logger )
def _generate_type ( self , data_type , indent_spaces , extra_args ) : """Generates a TypeScript type for the given type ."""
if is_alias ( data_type ) : self . _generate_alias_type ( data_type ) elif is_struct_type ( data_type ) : self . _generate_struct_type ( data_type , indent_spaces , extra_args ) elif is_union_type ( data_type ) : self . _generate_union_type ( data_type , indent_spaces )
def sin ( cls , x : 'TensorFluent' ) -> 'TensorFluent' : '''Returns a TensorFluent for the sin function . Args : x : The input fluent . Returns : A TensorFluent wrapping the sin function .'''
return cls . _unary_op ( x , tf . sin , tf . float32 )
def thumbUrl ( self ) : """Return the first first thumbnail url starting on the most specific thumbnail for that item ."""
thumb = self . firstAttr ( 'thumb' , 'parentThumb' , 'granparentThumb' ) return self . _server . url ( thumb , includeToken = True ) if thumb else None
def _delete_membership ( self , pipeline = None ) : """Removes the id of the object to the set of all objects of the same class ."""
Set ( self . _key [ 'all' ] , pipeline = pipeline ) . remove ( self . id )
def get_param_WLS ( A , C_D_inv , d , inv_bool = True ) : """returns the parameter values given : param A : response matrix Nd x Ns ( Nd = # data points , Ns = # parameters ) : param C _ D _ inv : inverse covariance matrix of the data , Nd x Nd , diagonal form : param d : data array , 1 - d Nd : param inv _...
M = A . T . dot ( np . multiply ( C_D_inv , A . T ) . T ) if inv_bool : if np . linalg . cond ( M ) < 5 / sys . float_info . epsilon : try : M_inv = np . linalg . inv ( M ) except : M_inv = np . zeros_like ( M ) else : M_inv = np . zeros_like ( M ) R = A . T ....
def confd_state_internal_callpoints_notification_stream_replay_registration_type_range_path ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) confd_state = ET . SubElement ( config , "confd-state" , xmlns = "http://tail-f.com/yang/confd-monitoring" ) internal = ET . SubElement ( confd_state , "internal" ) callpoints = ET . SubElement ( internal , "callpoints" ) notification_stream_replay = ET . SubElement ( callpoints , "no...
def action ( args ) : """Show information about reference packages ."""
log . info ( 'loading reference package' ) pkg = refpkg . Refpkg ( args . refpkg , create = False ) with open ( pkg . file_abspath ( 'seq_info' ) , 'rU' ) as seq_info : seqinfo = list ( csv . DictReader ( seq_info ) ) snames = [ row [ 'seqname' ] for row in seqinfo ] if args . seq_names : print ( '\n' . joi...
def set_exit_events ( self , no_workers = None , idle = None , reload = None , sig_term = None ) : """Do exit on certain events : param bool no _ workers : Shutdown uWSGI when no workers are running . : param bool idle : Shutdown uWSGI when idle . : param bool reload : Force exit even if a reload is requested...
self . _set ( 'die-on-no-workers' , no_workers , cast = bool ) self . _set ( 'exit-on-reload' , reload , cast = bool ) self . _set ( 'die-on-term' , sig_term , cast = bool ) self . set_idle_params ( exit = idle ) return self . _section
def of_text ( self , text , encoding = "utf-8" ) : """Use default hash method to return hash value of a piece of string default setting use ' utf - 8 ' encoding . : type text : text _ type : param text : a text object"""
m = self . hash_algo ( ) m . update ( text . encode ( encoding ) ) return self . digest ( m )
def _run_init_queries ( self ) : '''Initialization queries'''
for obj in ( Package , PackageCfgFile , PayloadFile , IgnoredDir , AllowedDir ) : self . _db . create_table_from_object ( obj ( ) )
def _ensure_url_string ( url ) : """Convert ` url ` to a string URL if it isn ' t one already ."""
if isinstance ( url , str ) : return url elif isinstance ( url , ( ParseResult , SplitResult ) ) : return url . geturl ( ) else : raise TypeError ( "Could not convert %r to a string URL." % ( url , ) )
def _convert_range_to_list ( self , tgt ) : '''convert a seco . range range into a list target'''
range_ = seco . range . Range ( self . opts [ 'range_server' ] ) try : return range_ . expand ( tgt ) except seco . range . RangeException as err : print ( 'Range server exception: {0}' . format ( err ) ) return [ ]
def agent_error ( e : requests . HTTPError , fatal = True ) : """Prints an agent error and exits"""
try : data = e . response . json ( ) details = data [ 'detail' ] # type : str except JSONDecodeError : details = e . response . text or str ( e . response ) lines = ( '[AGENT] {}' . format ( line ) for line in details . splitlines ( ) ) msg = '\n' + '\n' . join ( lines ) if fatal : fatal_error ( msg...
async def _handle_telegram_response ( self , response , ignore = None ) : """Parse a response from Telegram . If there ' s an error , an exception will be raised with an explicative message . : param response : Response to parse : return : Data"""
if ignore is None : ignore = set ( ) ok = response . status == 200 try : data = await response . json ( ) if not ok : desc = data [ 'description' ] if desc in ignore : return raise PlatformOperationError ( 'Telegram replied with an error: {}' . format ( desc ) ) except ( ...
def _is_valid_function ( module_name , function ) : '''Determine if a function is valid for a module'''
try : functions = __salt__ [ 'sys.list_functions' ] ( module_name ) except salt . exceptions . SaltException : functions = [ "unable to look up functions" ] return "{0}.{1}" . format ( module_name , function ) in functions
def innertext ( node ) : """Return the inner text of a node . If a node has no sub elements , this is just node . text . Otherwise , it ' s node . text + sub - element - text + node . tail ."""
if not len ( node ) : return node . text return ( node . text or '' ) + '' . join ( [ etree . tostring ( c ) for c in node ] ) + ( node . tail or '' )
def gradient ( self , q , t = 0. ) : """Compute the gradient of the potential at the given position ( s ) . Parameters q : ` ~ gala . dynamics . PhaseSpacePosition ` , ` ~ astropy . units . Quantity ` , array _ like The position to compute the value of the potential . If the input position object has no uni...
q = self . _remove_units_prepare_shape ( q ) orig_shape , q = self . _get_c_valid_arr ( q ) t = self . _validate_prepare_time ( t , q ) ret_unit = self . units [ 'length' ] / self . units [ 'time' ] ** 2 return ( self . _gradient ( q , t = t ) . T . reshape ( orig_shape ) * ret_unit ) . to ( self . units [ 'acceleratio...
def __init ( self ) : """populates server admin information"""
params = { "f" : "json" } json_dict = self . _get ( url = self . _currentURL , param_dict = params , securityHandler = self . _securityHandler , proxy_url = self . _proxy_url , proxy_port = self . _proxy_port ) self . _json = json . dumps ( json_dict ) self . _json_dict = json_dict attributes = [ attr for attr in dir (...
def restoreXml ( self , xml ) : """Restores the view ' s content from XML . : param xml | < str >"""
xscript = xml . find ( 'script' ) if xscript is not None and xscript . text is not None : self . _edit . setPlainText ( unescape ( xscript . text ) )
def group ( self , args ) : """Executes a search flickr : ( credsfile ) , search , ( arg1 ) = ( val1 ) , ( arg2 ) = ( val2 ) . . ."""
kwargs = { 'group_id' : args [ 0 ] } return self . _paged_api_call ( self . flickr . groups_pools_getPhotos , kwargs )
async def update_status ( self ) : """Update the current status of the LRO ."""
if self . _operation . async_url : self . _response = await self . request_status ( self . _operation . async_url ) self . _operation . set_async_url_if_present ( self . _response ) self . _operation . get_status_from_async ( self . _response ) elif self . _operation . location_url : self . _response = ...
def transformer_tall_finetune_uniencdec ( ) : """Fine - tune CNN / DM with a unidirectional encoder and decoder ."""
hparams = transformer_tall ( ) hparams . max_input_seq_length = 750 hparams . max_target_seq_length = 100 hparams . optimizer = "true_adam" hparams . learning_rate_schedule = ( "linear_warmup*constant*cosdecay" ) hparams . learning_rate_decay_steps = 80000 hparams . learning_rate_constant = 5e-5 hparams . learning_rate...
def get_devices_from_response_dict ( response_dict , device_type ) : """: rtype : list of WinkDevice"""
items = response_dict . get ( 'data' ) devices = [ ] api_interface = WinkApiInterface ( ) check_list = isinstance ( device_type , ( list , ) ) for item in items : if ( check_list and get_object_type ( item ) in device_type ) or ( not check_list and get_object_type ( item ) == device_type ) : _devices = buil...
def schedule_in ( secs , target = None , args = ( ) , kwargs = None ) : """insert a greenlet into the scheduler to run after a set time If provided a function , it is wrapped in a new greenlet : param secs : the number of seconds to wait before running the target : type unixtime : int or float : param targe...
return schedule_at ( time . time ( ) + secs , target , args , kwargs )
def _clean_directory ( self , name ) : """Clean a directory if exists and not in dry run"""
if not os . path . exists ( name ) : return self . announce ( "removing directory '{}' and all its contents" . format ( name ) ) if not self . dry_run : rmtree ( name , True )
def add_stale_devices_callback ( self , callback ) : """Register as callback for when stale devices exist ."""
self . _stale_devices_callbacks . append ( callback ) _LOGGER . debug ( 'Added stale devices callback to %s' , callback )
def accountSummary ( self , account : str = '' ) -> List [ AccountValue ] : """List of account values for the given account , or of all accounts if account is left blank . This method is blocking on first run , non - blocking after that . Args : account : If specified , filter for this account name ."""
if not self . wrapper . acctSummary : # loaded on demand since it takes ca . 250 ms self . reqAccountSummary ( ) if account : return [ v for v in self . wrapper . acctSummary . values ( ) if v . account == account ] else : return list ( self . wrapper . acctSummary . values ( ) )
def launch_shell ( username , hostname , password , port = 22 ) : """Launches an ssh shell"""
if not username or not hostname or not password : return False with tempfile . NamedTemporaryFile ( ) as tmpFile : os . system ( sshCmdLine . format ( password , tmpFile . name , username , hostname , port ) ) return True
def _timestamp_to_json_row ( value ) : """Coerce ' value ' to an JSON - compatible representation . This version returns floating - point seconds value used in row data ."""
if isinstance ( value , datetime . datetime ) : value = _microseconds_from_datetime ( value ) * 1e-6 return value
def dict_to_object ( self , d ) : """Decode datetime value from string to datetime"""
for k , v in list ( d . items ( ) ) : if isinstance ( v , six . string_types ) and len ( v ) == 19 : # Decode a datetime string to a datetime object try : d [ k ] = datetime . strptime ( v , "%Y-%m-%dT%H:%M:%S" ) except ValueError : pass elif isinstance ( v , six . string...
def infos ( self , type = None , failed = False ) : """Get infos in the network . type specifies the type of info ( defaults to Info ) . failed { False , True , " all " } specifies the failed state of the infos . To get infos from a specific node , see the infos ( ) method in class : class : ` ~ dallinger ....
if type is None : type = Info if failed not in [ "all" , False , True ] : raise ValueError ( "{} is not a valid failed" . format ( failed ) ) if failed == "all" : return type . query . filter_by ( network_id = self . id ) . all ( ) else : return type . query . filter_by ( network_id = self . id , failed...
def getLogger ( cls ) : """Get the logger that logs real - time to the leader . Note that if the returned logger is used on the leader , you will see the message twice , since it still goes to the normal log handlers , too ."""
# Only do the setup once , so we don ' t add a handler every time we log . Use a lock to do # so safely even if we ' re being called in different threads . Use double - checked locking # to reduce the overhead introduced by the lock . if cls . logger is None : with cls . lock : if cls . logger is None : ...
def load_grounding_map ( grounding_map_path , ignore_path = None , lineterminator = '\r\n' ) : """Return a grounding map dictionary loaded from a csv file . In the file pointed to by grounding _ map _ path , the number of name _ space ID pairs can vary per row and commas are used to pad out entries containing...
g_map = { } map_rows = read_unicode_csv ( grounding_map_path , delimiter = ',' , quotechar = '"' , quoting = csv . QUOTE_MINIMAL , lineterminator = '\r\n' ) if ignore_path and os . path . exists ( ignore_path ) : ignore_rows = read_unicode_csv ( ignore_path , delimiter = ',' , quotechar = '"' , quoting = csv . QUOT...
def get_covariance ( self , chain = 0 , parameters = None ) : """Takes a chain and returns the covariance between chain parameters . Parameters chain : int | str , optional The chain index or name . Defaults to first chain . parameters : list [ str ] , optional The list of parameters to compute correlatio...
index = self . parent . _get_chain ( chain ) assert len ( index ) == 1 , "Please specify only one chain, have %d chains" % len ( index ) chain = self . parent . chains [ index [ 0 ] ] if parameters is None : parameters = chain . parameters data = chain . get_data ( parameters ) cov = np . atleast_2d ( np . cov ( da...
def get_urlfield_cache_key ( model , pk , language_code = None ) : """The low - level function to get the cache key for a model ."""
return 'anyurlfield.{0}.{1}.{2}.{3}' . format ( model . _meta . app_label , model . __name__ , pk , language_code or get_language ( ) )
def maximumORFLength ( self , openORFs = True ) : """Return the length of the longest ( possibly partial ) ORF in a translated read . The ORF may originate or terminate outside the sequence , which is why the length is just a lower bound ."""
return max ( len ( orf ) for orf in self . ORFs ( openORFs ) )
def signup ( request , signup_form = SignupForm , template_name = 'userena/signup_form.html' , success_url = None , extra_context = None ) : """Signup of an account . Signup requiring a username , email and password . After signup a user gets an email with an activation link used to activate their account . Aft...
# If signup is disabled , return 403 if userena_settings . USERENA_DISABLE_SIGNUP : raise PermissionDenied # If no usernames are wanted and the default form is used , fallback to the # default form that doesn ' t display to enter the username . if userena_settings . USERENA_WITHOUT_USERNAMES and ( signup_form == Si...
def list_arguments ( self ) : """Lists all the arguments in the symbol . Example > > > a = mx . sym . var ( ' a ' ) > > > b = mx . sym . var ( ' b ' ) > > > c = a + b > > > c . list _ arguments [ ' a ' , ' b ' ] Returns args : list of string List containing the names of all the arguments required ...
size = ctypes . c_uint ( ) sarr = ctypes . POINTER ( ctypes . c_char_p ) ( ) check_call ( _LIB . MXSymbolListArguments ( self . handle , ctypes . byref ( size ) , ctypes . byref ( sarr ) ) ) return [ py_str ( sarr [ i ] ) for i in range ( size . value ) ]
def gimme_motifs ( inputfile , outdir , params = None , filter_significant = True , cluster = True , create_report = True ) : """De novo motif prediction based on an ensemble of different tools . Parameters inputfile : str Filename of input . Can be either BED , narrowPeak or FASTA . outdir : str Name of ...
if outdir is None : outdir = "gimmemotifs_{}" . format ( datetime . date . today ( ) . strftime ( "%d_%m_%Y" ) ) # Create output directories tmpdir = os . path . join ( outdir , "intermediate" ) for d in [ outdir , tmpdir ] : if not os . path . exists ( d ) : os . mkdir ( d ) # setup logfile logger = lo...
def _render_email_placeholder ( request , email_template , base_url , context ) : """Internal rendering of the placeholder / contentitems . This a simple variation of render _ placeholder ( ) , making is possible to render both a HTML and text item in a single call . Caching is currently not implemented . :...
placeholder = email_template . contents items = placeholder . get_content_items ( email_template ) if not items : # NOTES : performs query # There are no items , fetch the fallback language . language_code = fc_appsettings . FLUENT_CONTENTS_DEFAULT_LANGUAGE_CODE items = placeholder . get_content_items ( email_t...
def is_private ( self ) : """Test if this address is allocated for private networks . Returns : A boolean , True if the address is reserved per RFC 1918."""
private_10 = IPv4Network ( '10.0.0.0/8' ) private_172 = IPv4Network ( '172.16.0.0/12' ) private_192 = IPv4Network ( '192.168.0.0/16' ) return ( self in private_10 or self in private_172 or self in private_192 )
def to_docx ( self , filename = None , input_dataset = True , summary_table = True , recommendation_details = True , recommended_model = True , all_models = False , ) : """Write batch sessions to a Word file . Parameters filename : str or None If provided , the file is saved to this location , otherwise this ...
rep = Reporter ( ) for model in self : rep . add_session ( model , input_dataset , summary_table , recommendation_details , recommended_model , all_models , ) if filename : rep . save ( filename ) return rep
def read ( self , count = None , block = None ) : """Read unseen messages from all streams in the consumer group . Wrapper for : py : class : ` Database . xreadgroup ` method . : param int count : limit number of messages returned : param int block : milliseconds to block , 0 for indefinitely . : returns : ...
resp = super ( TimeSeries , self ) . read ( count , block ) return xread_to_messages ( resp )
def visit_named_arg ( self , _ , children ) : """Named argument of a filter . Arguments _ ( node ) : parsimonious . nodes . Node . children : list - 0 : name of the arg - 1 : for ` ` WS ` ` ( whitespace ) : ` ` None ` ` . - 2 : operator - 3 : for ` ` WS ` ` ( whitespace ) : ` ` None ` ` . - 4 : valu...
return self . NamedArg ( arg = children [ 0 ] , arg_type = children [ 2 ] , value = children [ 4 ] , )
def run ( self ) : """Actual run method that starts the processing of jobs and initiates the status polling , or performs job cancelling or cleaning , depending on the task parameters ."""
task = self . task self . _outputs = self . output ( ) # create the job dashboard interface self . dashboard = task . create_job_dashboard ( ) or NoJobDashboard ( ) # read submission data and reset some values submitted = not task . ignore_submission and self . _outputs [ "submission" ] . exists ( ) if submitted : ...
def explode ( self , escalations ) : """Create instance of Escalation for each HostEscalation object : param escalations : list of escalation , used to add new ones : type escalations : alignak . objects . escalation . Escalations : return : None"""
# Now we explode all escalations ( host _ name , hostgroup _ name ) to escalations for escalation in self : properties = escalation . __class__ . properties name = getattr ( escalation , 'host_name' , getattr ( escalation , 'hostgroup_name' , '' ) ) creation_dict = { 'escalation_name' : 'Generated-HE-%s-%s'...
def loads ( s , object_pairs_hook = dict ) : """Parse the contents of the string ` ` s ` ` as a simple line - oriented ` ` . properties ` ` file and return a ` dict ` of the key - value pairs . ` ` s ` ` may be either a text string or bytes string . If it is a bytes string , its contents are decoded as Latin ...
fp = BytesIO ( s ) if isinstance ( s , binary_type ) else StringIO ( s ) return load ( fp , object_pairs_hook = object_pairs_hook )
def restmethod ( method , reluri , * qargs , ** headers ) : """Decorate a method to inject an HTTPRequest . Generates an HTTPRequest using the given HTTP method and relative URI . If additional positional arguments are present , they are expected to be strings that name function arguments that should be inc...
def decorator ( func ) : @ functools . wraps ( func ) def wrapper ( * args , ** kwargs ) : # Process the arguments against the original function argmap , theSelf , req_name = _getcallargs ( func , args , kwargs ) # Build the URL url = _urljoin ( theSelf . _baseurl , reluri . format ( ** ...
def label_from_instance ( self , obj ) : """Create labels which represent the tree level of each node when generating option labels ."""
label = smart_text ( obj ) prefix = self . level_indicator * getattr ( obj , obj . _mptt_meta . level_attr ) if prefix : return '%s %s' % ( prefix , label ) return label
def export ( self ) : """Export all attributes of the user to a dict . : return : attributes of the user . : rtype : dict ."""
data = { } data [ "name" ] = self . name data [ "contributions" ] = self . contributions data [ "avatar" ] = self . avatar data [ "followers" ] = self . followers data [ "join" ] = self . join data [ "organizations" ] = self . organizations data [ "repositories" ] = self . numberOfRepos data [ "bio" ] = self . bio data...
def pull_all_external ( collector , ** kwargs ) : """Pull all the external dependencies of all the images"""
deps = set ( ) images = collector . configuration [ "images" ] for layer in Builder ( ) . layered ( images ) : for image_name , image in layer : for dep in image . commands . external_dependencies : deps . add ( dep ) for dep in sorted ( deps ) : kwargs [ "image" ] = dep pull_arbitrary (...
def dataset_to_markdown ( dataset ) : """Genera texto en markdown a partir de los metadatos de una ` dataset ` . Args : dataset ( dict ) : Diccionario con metadatos de una ` dataset ` . Returns : str : Texto que describe una ` dataset ` ."""
text_template = """ # {title} {description} ## Recursos del dataset {distributions} """ if "distribution" in dataset : distributions = "" . join ( map ( distribution_to_markdown , dataset [ "distribution" ] ) ) else : distributions = "" text = text_template . format ( title = dataset [ "title" ] , descriptio...
def _transform_delta ( f : Formula , formula2AtomicFormula ) : """From a Propositional Formula to a Propositional Formula with non - propositional subformulas replaced with a " freezed " atomic formula ."""
t = type ( f ) if t == PLNot : return PLNot ( _transform_delta ( f , formula2AtomicFormula ) ) # elif isinstance ( f , PLBinaryOperator ) : # PLAnd , PLOr , PLImplies , PLEquivalence elif t == PLAnd or t == PLOr or t == PLImplies or t == PLEquivalence : return t ( [ _transform_delta ( subf , formula2AtomicFormu...
def bit_for_bit ( model_path , bench_path , config ) : """Checks whether the given files have bit for bit solution matches on the given variable list . Args : model _ path : absolute path to the model dataset bench _ path : absolute path to the benchmark dataset config : the configuration of the set of an...
fname = model_path . split ( os . path . sep ) [ - 1 ] # Error handling if not ( os . path . isfile ( bench_path ) and os . path . isfile ( model_path ) ) : return elements . error ( "Bit for Bit" , "File named " + fname + " has no suitable match!" ) try : model_data = Dataset ( model_path ) bench_data = Da...
def close ( self ) : """closes render window"""
# must close out axes marker if hasattr ( self , 'axes_widget' ) : del self . axes_widget # reset scalar bar stuff self . _scalar_bar_slots = set ( range ( MAX_N_COLOR_BARS ) ) self . _scalar_bar_slot_lookup = { } self . _scalar_bar_ranges = { } self . _scalar_bar_mappers = { } if hasattr ( self , 'ren_win' ) : ...
def _AdjustForTimeZoneOffset ( self , year , month , day_of_month , hours , minutes , time_zone_offset ) : """Adjusts the date and time values for a time zone offset . Args : year ( int ) : year e . g . 1970. month ( int ) : month , where 1 represents January . day _ of _ month ( int ) : day of the month , ...
hours_from_utc , minutes_from_utc = divmod ( time_zone_offset , 60 ) minutes += minutes_from_utc # Since divmod makes sure the sign of minutes _ from _ utc is positive # we only need to check the upper bound here , because hours _ from _ utc # remains signed it is corrected accordingly . if minutes >= 60 : minutes ...
def fit ( self , X , y = None ) : '''Fit the transform . Does nothing , for compatibility with sklearn API . Parameters X : array - like , shape [ n _ series , . . . ] Time series data and ( optionally ) contextual data y : None There is no need of a target in a transformer , yet the pipeline API requires...
check_ts_data ( X , y ) if not X [ 0 ] . ndim > 1 : raise ValueError ( "X variable must have more than 1 channel" ) return self