signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def postinit ( self , items = None , body = None , type_annotation = None ) : """Do some setup after initialisation . : param items : The pairs of context managers and the names they are assigned to . : type items : list ( tuple ( NodeNG , AssignName or None ) ) or None : param body : The contents of the ` ...
self . items = items self . body = body self . type_annotation = type_annotation
def get_jids ( ) : '''Return a list of all job ids'''
serv = _get_serv ( ret = None ) sql = "select distinct(jid) from jids group by load" # [ { u ' points ' : [ [ 0 , jid , load ] , # [0 , jid , load ] ] , # u ' name ' : u ' jids ' , # u ' columns ' : [ u ' time ' , u ' distinct ' , u ' load ' ] } ] data = serv . query ( sql ) ret = { } if data : for _ , jid , load i...
def set_last_component_continued ( self ) : # type : ( ) - > None '''Set the previous component of this SL record to continued . Parameters : None . Returns : Nothing .'''
if not self . _initialized : raise pycdlibexception . PyCdlibInternalError ( 'SL record not yet initialized!' ) if not self . symlink_components : raise pycdlibexception . PyCdlibInternalError ( 'Trying to set continued on a non-existent component!' ) self . symlink_components [ - 1 ] . set_continued ( )
def _CreateFolder ( self , parent , name , visible = True , description = None ) : """Create a KML Folder element . Args : parent : The parent ElementTree . Element instance . name : The folder name as a string . visible : Whether the folder is initially visible or not . description : A description string...
folder = ET . SubElement ( parent , 'Folder' ) name_tag = ET . SubElement ( folder , 'name' ) name_tag . text = name if description is not None : desc_tag = ET . SubElement ( folder , 'description' ) desc_tag . text = description if not visible : visibility = ET . SubElement ( folder , 'visibility' ) vi...
def _connection_parameters ( self ) : """Return connection parameters for a pika connection . : rtype : pika . ConnectionParameters"""
return pika . ConnectionParameters ( self . config . get ( 'host' , 'localhost' ) , self . config . get ( 'port' , 5672 ) , self . config . get ( 'vhost' , '/' ) , pika . PlainCredentials ( self . config . get ( 'user' , 'guest' ) , self . config . get ( 'password' , self . config . get ( 'pass' , 'guest' ) ) ) , ssl =...
def _get_hover_data ( self , data , element ) : """Initializes hover data based on Element dimension values ."""
if 'hover' not in self . handles or self . static_source : return for k , v in self . overlay_dims . items ( ) : dim = util . dimension_sanitizer ( k . name ) if dim not in data : data [ dim ] = [ v for _ in range ( len ( list ( data . values ( ) ) [ 0 ] ) ) ]
def create_payload ( self ) : """Wrap submitted data within an extra dict . For more information , see ` Bugzilla # 1151220 < https : / / bugzilla . redhat . com / show _ bug . cgi ? id = 1151220 > ` _ ."""
payload = super ( ConfigTemplate , self ) . create_payload ( ) if 'template_combinations' in payload : payload [ 'template_combinations_attributes' ] = payload . pop ( 'template_combinations' ) return { u'config_template' : payload }
def deltet ( epoch , eptype ) : """Return the value of Delta ET ( ET - UTC ) for an input epoch . http : / / naif . jpl . nasa . gov / pub / naif / toolkit _ docs / C / cspice / deltet _ c . html : param epoch : Input epoch ( seconds past J2000 ) . : type epoch : float : param eptype : Type of input epoch (...
epoch = ctypes . c_double ( epoch ) eptype = stypes . stringToCharP ( eptype ) delta = ctypes . c_double ( ) libspice . deltet_c ( epoch , eptype , ctypes . byref ( delta ) ) return delta . value
def _clean_html ( html ) : """Removes links ( ` ` < a href = " . . . " > . . . < / a > ` ` ) from the provided HTML input . Further , it replaces " & # x000A ; " with ` ` \n ` ` and removes " ¶ " from the texts ."""
content = html . replace ( u'&#x000A;' , u'\n' ) . replace ( u'¶' , '' ) content = _LINK_PATTERN . sub ( u'' , content ) content = _HTML_TAG_PATTERN . sub ( u'' , content ) content = _BACKSLASH_PATTERN . sub ( u'\n' , content ) return content
def _render_content ( self , content , ** settings ) : """Perform widget rendering , but do not print anything ."""
if not self . SETTING_WIDTH in settings or not settings [ self . SETTING_WIDTH ] : settings [ self . SETTING_WIDTH ] = TERMINAL_WIDTH s = { k : settings [ k ] for k in ( self . SETTING_WIDTH , self . SETTING_FLAG_BORDER , self . SETTING_MARGIN , self . SETTING_MARGIN_LEFT , self . SETTING_MARGIN_RIGHT , self . SETT...
def gpg_list_profile_keys ( blockchain_id , proxy = None , wallet_keys = None , config_dir = None ) : """List all GPG keys in a user profile : Return a list of { ' identifier ' : key ID , ' contentUrl ' : URL to the key data } on success Raise on error Return { ' error ' : . . . } on failure"""
config_dir = get_config_dir ( config_dir ) client_config_path = os . path . join ( config_dir , blockstack_client . CONFIG_FILENAME ) if proxy is None : proxy = blockstack_client . get_default_proxy ( config_path = client_config_path ) accounts = blockstack_client . list_accounts ( blockchain_id , proxy = proxy ) i...
def partition ( self , ref = None , ** kwargs ) : """Return a partition in this bundle for a vid reference or name parts"""
from ambry . orm . exc import NotFoundError from sqlalchemy . orm . exc import NoResultFound if not ref and not kwargs : return None if ref : for p in self . partitions : if ref == p . name or ref == p . vname or ref == p . vid or ref == p . id : p . _bundle = self return p r...
def ports ( self ) : '''The list of all ports belonging to this component .'''
with self . _mutex : if not self . _ports : self . _ports = [ ports . parse_port ( port , self ) for port in self . _obj . get_ports ( ) ] return self . _ports
def residual_unit ( data , num_filter , stride , dim_match , name , bottle_neck = True , num_group = 32 , bn_mom = 0.9 , workspace = 256 , memonger = False ) : """Return ResNet Unit symbol for building ResNet Parameters data : str Input data num _ filter : int Number of output channels bnf : int Bottl...
if bottle_neck : # the same as https : / / github . com / facebook / fb . resnet . torch # notes , a bit difference with origin paper conv1 = mx . sym . Convolution ( data = data , num_filter = int ( num_filter * 0.5 ) , kernel = ( 1 , 1 ) , stride = ( 1 , 1 ) , pad = ( 0 , 0 ) , no_bias = True , workspace = worksp...
def _get_esxdatacenter_proxy_details ( ) : '''Returns the running esxdatacenter ' s proxy details'''
det = __salt__ [ 'esxdatacenter.get_details' ] ( ) return det . get ( 'vcenter' ) , det . get ( 'username' ) , det . get ( 'password' ) , det . get ( 'protocol' ) , det . get ( 'port' ) , det . get ( 'mechanism' ) , det . get ( 'principal' ) , det . get ( 'domain' ) , det . get ( 'datacenter' )
def hash_file_contents ( requirements_option : RequirementsOptions , path : Path ) -> str : """Returns a SHA256 hash of the contents of ` ` path ` ` combined with the Arca version ."""
return hashlib . sha256 ( path . read_bytes ( ) + bytes ( requirements_option . name + arca . __version__ , "utf-8" ) ) . hexdigest ( )
def cn_occupation_energy ( self , delta_occupation = None ) : """The coordination - number dependent energy for this site . Args : delta _ occupation ( : obj : Dict ( Str : Int ) , optional ) : A dictionary of a change in ( site - type specific ) coordination number , e . g . { ' A ' : 1 , ' B ' : - 1 } . If ...
nn_occupations = self . site_specific_nn_occupation ( ) if delta_occupation : for site in delta_occupation : assert ( site in nn_occupations ) nn_occupations [ site ] += delta_occupation [ site ] return sum ( [ self . cn_occupation_energies [ s ] [ n ] for s , n in nn_occupations . items ( ) ] )
def _dump_linestring ( obj , big_endian , meta ) : """Dump a GeoJSON - like ` dict ` to a linestring WKB string . Input parameters and output are similar to : func : ` _ dump _ point ` ."""
coords = obj [ 'coordinates' ] vertex = coords [ 0 ] # Infer the number of dimensions from the first vertex num_dims = len ( vertex ) wkb_string , byte_fmt , byte_order = _header_bytefmt_byteorder ( 'LineString' , num_dims , big_endian , meta ) # append number of vertices in linestring wkb_string += struct . pack ( '%s...
def total_amount ( qs ) -> Total : """Sums the amounts of the objects in the queryset , keeping each currency separate . : param qs : A querystring containing objects that have an amount field of type Money . : return : A Total object ."""
aggregate = qs . values ( 'amount_currency' ) . annotate ( sum = Sum ( 'amount' ) ) return Total ( Money ( amount = r [ 'sum' ] , currency = r [ 'amount_currency' ] ) for r in aggregate )
def _sprite ( map , sprite , offset_x = None , offset_y = None ) : """Returns the image and background position for use in a single shorthand property"""
map = StringValue ( map ) . value sprite_name = StringValue ( sprite ) . value sprite_map = sprite_maps . get ( map ) sprite = sprite_map and sprite_map . get ( sprite_name ) if not sprite_map : log . error ( "No sprite map found: %s" , map ) elif not sprite : log . error ( "No sprite found: %s in %s" , sprite_...
def get_closest_match ( self , motifs , dbmotifs = None , match = "partial" , metric = "wic" , combine = "mean" , parallel = True , ncpus = None ) : """Return best match in database for motifs . Parameters motifs : list or str Filename of motifs or list of motifs . dbmotifs : list or str , optional Databa...
if dbmotifs is None : pwm = self . config . get_default_params ( ) [ "motif_db" ] pwmdir = self . config . get_motif_dir ( ) dbmotifs = os . path . join ( pwmdir , pwm ) motifs = parse_motifs ( motifs ) dbmotifs = parse_motifs ( dbmotifs ) dbmotif_lookup = dict ( [ ( m . id , m ) for m in dbmotifs ] ) score...
def run ( self ) : """Main entrypoint method . Returns new _ nodes : ` list ` Nodes to add to the doctree ."""
if getLogger is not None : # Sphinx 1.6 + logger = getLogger ( __name__ ) else : # Previously Sphinx ' s app was also the logger logger = self . state . document . settings . env . app env = self . state . document . settings . env new_nodes = [ ] # Get skip list skipped_modules = self . _parse_skip_option ( ) ...
def export_users ( self , body ) : """Export all users to a file using a long running job . Check job status with get ( ) . URL pointing to the export file will be included in the status once the job is complete . Args : body ( dict ) : Please see : https : / / auth0 . com / docs / api / management / v2 # !...
return self . client . post ( self . _url ( 'users-exports' ) , data = body )
def read_files ( * sources , ** kwds ) : """Construct a generator that yields file instances . : param sources : One or more strings representing path to file ( s ) ."""
filenames = _generate_filenames ( sources ) filehandles = _generate_handles ( filenames ) for fh , source in filehandles : try : f = mwtab . MWTabFile ( source ) f . read ( fh ) if kwds . get ( 'validate' ) : validator . validate_file ( mwtabfile = f , section_schema_mapping = mw...
def _alerter_thread_func ( self ) -> None : """Prints alerts and updates the prompt any time the prompt is showing"""
self . _alert_count = 0 self . _next_alert_time = 0 while not self . _stop_thread : # Always acquire terminal _ lock before printing alerts or updating the prompt # To keep the app responsive , do not block on this call if self . terminal_lock . acquire ( blocking = False ) : # Get any alerts that need to be printe...
def execute_command ( self ) : """The generate command uses ` Jinja2 < http : / / jinja . pocoo . org / > ` _ templates to create Python scripts , according to the specification in the configuration file . The predefined templates use the extract _ content ( ) method of the : ref : ` selector classes < implementati...
print ( Back . GREEN + Fore . BLACK + "Scrapple Generate" ) print ( Back . RESET + Fore . RESET ) directory = os . path . join ( scrapple . __path__ [ 0 ] , 'templates' , 'scripts' ) with open ( os . path . join ( directory , 'generate.txt' ) , 'r' ) as f : template_content = f . read ( ) template = Template ( temp...
def remove ( self , key , preserve_data = False ) : """: param key : Document unique identifier . Remove the document from the search index ."""
if self . members . remove ( key ) != 1 : raise KeyError ( 'Document with key "%s" not found.' % key ) document_hash = self . _get_hash ( key ) content = decode ( document_hash [ 'content' ] ) if not preserve_data : document_hash . clear ( ) for word in self . tokenizer . tokenize ( content ) : word_key = s...
def system_find_databases ( input_params = { } , always_retry = True , ** kwargs ) : """Invokes the / system / findDatabases API method . For more info , see : https : / / wiki . dnanexus . com / API - Specification - v1.0.0 / Search # API - method % 3A - % 2Fsystem % 2FfindDatabases"""
return DXHTTPRequest ( '/system/findDatabases' , input_params , always_retry = always_retry , ** kwargs )
def unwrapArray ( a , recursive = True , readH5pyDataset = True ) : """This function takes an object ( like a dictionary ) and recursively unwraps it solving issues like : * the fact that many objects are packaged as 0d array This funciton has also some specific hack for handling h5py limits : * handle the ...
try : # # # take care of hdf5 groups if isinstance ( a , h5py . Group ) : # take care of special flags first if isinstance ( a , h5py . Group ) and ( ( "IS_LIST" in a . attrs ) or ( "IS_LIST_OF_ARRAYS" in a . attrs ) ) : items = list ( a . keys ( ) ) items . sort ( ) a = ...
def _ReadCompressedData ( self , read_size ) : """Reads compressed data from the file - like object . Args : read _ size ( int ) : number of bytes of compressed data to read . Returns : int : number of bytes of compressed data read ."""
compressed_data = self . _file_object . read ( read_size ) read_count = len ( compressed_data ) self . _compressed_data = b'' . join ( [ self . _compressed_data , compressed_data ] ) self . _uncompressed_data , self . _compressed_data = ( self . _decompressor . Decompress ( self . _compressed_data ) ) self . _uncompres...
def caesar_app ( parser , cmd , args ) : # pragma : no cover """Caesar crypt a value with a key ."""
parser . add_argument ( 'shift' , type = int , help = 'the shift to apply' ) parser . add_argument ( 'value' , help = 'the value to caesar crypt, read from stdin if omitted' , nargs = '?' ) parser . add_argument ( '-s' , '--shift-range' , dest = 'shift_ranges' , action = 'append' , help = 'specify a character range to ...
def group_protocols ( self ) : """Returns list of preferred ( protocols , metadata )"""
if self . _subscription . subscription is None : raise Errors . IllegalStateError ( 'Consumer has not subscribed to topics' ) # dpkp note : I really dislike this . # why ? because we are using this strange method group _ protocols , # which is seemingly innocuous , to set internal state ( _ joined _ subscription ) ...
def p_delays_intnumber ( self , p ) : 'delays : DELAY intnumber'
p [ 0 ] = DelayStatement ( IntConst ( p [ 2 ] , lineno = p . lineno ( 1 ) ) , lineno = p . lineno ( 1 ) ) p . set_lineno ( 0 , p . lineno ( 1 ) )
def get_column_flat ( self , field , components = None , computed_type = 'for_observations' ) : """TODO : add documentation return a single merged value ( hstacked ) from all meshes : parameter str field : name of the mesh columnname : parameter components :"""
return self . pack_column_flat ( self . get_column ( field , components , computed_type ) , components , offset = field == 'triangles' )
def make_response ( self , rv , status = 200 , headers = None , mime = 'application/json' ) : """Create a response object using the : class : ` flask . Response ` class . : param rv : Response value . If the value is not an instance of : class : ` werkzeug . wrappers . Response ` it will be converted into a R...
if not isinstance ( rv , Response ) : resp = Response ( response = rv , headers = headers , mimetype = mime , status = status ) else : resp = rv return resp
def has_shared ( arg , shared ) : """Verifica se ci sono shared ."""
try : if isinstance ( shared , list ) : shared_arguments = shared else : shared_arguments = shared . __shared_arguments__ for idx , ( args , kwargs ) in enumerate ( shared_arguments ) : arg_name = kwargs . get ( 'dest' , args [ - 1 ] . lstrip ( '-' ) . replace ( '-' , '_' ) ) ...
def parse_delta ( filename ) : """Returns ( alignment length , similarity errors ) tuple from passed . delta . - filename - path to the input . delta file Extracts the aligned length and number of similarity errors for each aligned uniquely - matched region , and returns the cumulative total for each as a t...
aln_length , sim_errors = 0 , 0 for line in [ l . strip ( ) . split ( ) for l in open ( filename , "r" ) . readlines ( ) ] : if line [ 0 ] == "NUCMER" or line [ 0 ] . startswith ( ">" ) : # Skip headers continue # We only process lines with seven columns : if len ( line ) == 7 : aln_length +...
def _split_diff ( merge_result , context_lines = 3 ) : """Split diffs and context lines into groups based on None sentinel"""
collect = [ ] for item in _visible_in_diff ( merge_result , context_lines = context_lines ) : if item is None : if collect : yield collect collect = [ ] else : collect . append ( item )
def construct_surface ( direction , * args , ** kwargs ) : """Generates surfaces from curves . Arguments : * ` ` args ` ` : a list of curve instances Keyword Arguments ( optional ) : * ` ` degree ` ` : degree of the 2nd parametric direction * ` ` knotvector ` ` : knot vector of the 2nd parametric directio...
# Input validation possible_dirs = [ 'u' , 'v' ] if direction not in possible_dirs : raise GeomdlException ( "Possible direction values: " + ", " . join ( [ val for val in possible_dirs ] ) , data = dict ( input_dir = direction ) ) size_other = len ( args ) if size_other < 2 : raise GeomdlException ( "You need ...
def plot ( self , win = None , newfig = True , figsize = None , orientation = 'hor' , topfigfrac = 0.8 ) : """Plot layout Parameters win : list or tuple [ x1 , x2 , y1 , y2]"""
if newfig : plt . figure ( figsize = figsize ) ax1 = None ax2 = None if orientation == 'both' : ax1 = plt . axes ( [ 0.125 , 0.18 + ( 1 - topfigfrac ) * 0.7 , ( 0.9 - 0.125 ) , topfigfrac * 0.7 ] ) ax2 = plt . axes ( [ 0.125 , 0.11 , ( 0.9 - 0.125 ) , ( 1 - topfigfrac ) * 0.7 ] , sharex ...
def load_parameters ( self , source ) : """For YML , the source it the file path"""
with open ( source ) as parameters_source : loaded = yaml . safe_load ( parameters_source . read ( ) ) for k , v in loaded . items ( ) : if isinstance ( v , str ) : loaded [ k ] = "'" + v + "'" return loaded
def AddStopObject ( self , stop , problem_reporter = None ) : """Add Stop object to this schedule if stop _ id is non - blank ."""
assert stop . _schedule is None if not problem_reporter : problem_reporter = self . problem_reporter if not stop . stop_id : return if stop . stop_id in self . stops : problem_reporter . DuplicateID ( 'stop_id' , stop . stop_id ) return stop . _schedule = weakref . proxy ( self ) self . AddTableColumns ...
def main ( self ) -> None : """Main entry point . Runs : func : ` service ` ."""
# Actual main service code . try : self . service ( ) except Exception as e : self . error ( "Unexpected exception: {e}\n{t}" . format ( e = e , t = traceback . format_exc ( ) ) )
def get_identities ( self , item ) : """Return the identities from an item"""
# All identities are in the post stream # The first post is the question . Next replies posts = item [ 'data' ] [ 'post_stream' ] [ 'posts' ] for post in posts : user = self . get_sh_identity ( post ) yield user
def bind ( self , context ) -> None : """Bind a context to this computation . The context allows the computation to convert object specifiers to actual objects ."""
# make a computation context based on the enclosing context . self . __computation_context = ComputationContext ( self , context ) # re - bind is not valid . be careful to set the computation after the data item is already in document . for variable in self . variables : assert variable . bound_item is None for res...
def environment_list ( self , io_handler ) : """Lists the framework process environment variables"""
# Head of the table headers = ( "Environment Variable" , "Value" ) # Lines lines = [ item for item in os . environ . items ( ) ] # Sort lines lines . sort ( ) # Print the table io_handler . write ( self . _utils . make_table ( headers , lines ) )
def see_tooltip ( step , tooltip ) : """Press a button having a given tooltip ."""
elem = world . browser . find_elements_by_xpath ( str ( '//*[@title="%(tooltip)s" or @data-original-title="%(tooltip)s"]' % dict ( tooltip = tooltip ) ) ) elem = [ e for e in elem if e . is_displayed ( ) ] assert_true ( step , elem )
def flagants ( self , threshold = 50 ) : """Flags solutions with amplitude more than threshold larger than median ."""
# identify very low gain amps not already flagged badsols = n . where ( ( n . median ( self . amp ) / self . amp > threshold ) & ( self . flagged == False ) ) [ 0 ] if len ( badsols ) : self . logger . info ( 'Solutions %s flagged (times %s, ants %s, freqs %s) for low gain amplitude.' % ( str ( badsols ) , self . m...
def get ( self , deviceId ) : """lists all known active measurements ."""
measurementsByName = self . measurements . get ( deviceId ) if measurementsByName is None : return [ ] else : return list ( measurementsByName . values ( ) )
def theme ( self , text ) : '''Theme style .'''
return self . theme_color + self . BRIGHT + text + self . RESET
def _interpretPayload ( functioncode , payload ) : r"""Generate a human readable description of a Modbus payload . Args : * functioncode ( int ) : Function code * payload ( str ) : The payload that should be interpreted . It should be a byte string . Returns : A descriptive string . For example , the pa...
raise NotImplementedError ( ) output = '' output += 'Modbus payload decoder\n' output += 'Input payload (length {} characters): {!r} \n' . format ( len ( payload ) , payload ) output += 'Function code: {} (dec).\n' . format ( functioncode ) if len ( payload ) == 4 : FourbyteMessageFirstHalfValue = _twoByteStringToN...
def _autofill_spec_record ( record ) : """Returns an astropy table with columns auto - filled from FITS header Parameters record : astropy . io . fits . table . table . Row The spectrum table row to scrape Returns record : astropy . io . fits . table . table . Row The spectrum table row with possible ne...
try : record [ 'filename' ] = os . path . basename ( record [ 'spectrum' ] ) if record [ 'spectrum' ] . endswith ( '.fits' ) : header = pf . getheader ( record [ 'spectrum' ] ) # Wavelength units if not record [ 'wavelength_units' ] : try : record [ 'wavelengt...
def _api_config ( self ) : """Glances API RESTful implementation . Return the JSON representation of the Glances configuration file HTTP / 200 if OK HTTP / 404 if others error"""
response . content_type = 'application/json; charset=utf-8' try : # Get the JSON value of the config ' dict args_json = json . dumps ( self . config . as_dict ( ) ) except Exception as e : abort ( 404 , "Cannot get config (%s)" % str ( e ) ) return args_json
def Rzderiv ( self , R , Z , phi = 0. , t = 0. ) : """NAME : Rzderiv PURPOSE : evaluate the mixed R , z derivative INPUT : R - Galactocentric radius ( can be Quantity ) Z - vertical height ( can be Quantity ) phi - Galactocentric azimuth ( can be Quantity ) t - time ( can be Quantity ) OUTPUT : ...
try : return self . _amp * self . _Rzderiv ( R , Z , phi = phi , t = t ) except AttributeError : # pragma : no cover raise PotentialError ( "'_Rzderiv' function not implemented for this potential" )
def query ( self , coords , ** kwargs ) : """Returns E ( B - V ) ( or a different Planck dust inference , depending on how the class was intialized ) at the specified location ( s ) on the sky . Args : coords ( : obj : ` astropy . coordinates . SkyCoord ` ) : The coordinates to query . Returns : A float a...
return self . _scale * super ( PlanckQuery , self ) . query ( coords , ** kwargs )
def find ( self , text ) : """Print all substitutions that include the given text string ."""
for key , value in self : if ( text in key ) or ( text in value ) : print ( key , value )
def star ( args ) : """% prog star folder reference Run star on a folder with reads ."""
p = OptionParser ( star . __doc__ ) p . add_option ( "--single" , default = False , action = "store_true" , help = "Single end mapping" ) p . set_fastq_names ( ) p . set_cpus ( ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) folder , reference = args cpus = opts ...
def json_compat_obj_encode ( data_type , obj , caller_permissions = None , alias_validators = None , old_style = False , for_msgpack = False , should_redact = False ) : """Encodes an object into a JSON - compatible dict based on its type . Args : data _ type ( Validator ) : Validator for obj . obj ( object ) ...
serializer = StoneToPythonPrimitiveSerializer ( caller_permissions , alias_validators , for_msgpack , old_style , should_redact ) return serializer . encode ( data_type , obj )
def _find_cont_fitfunc_regions ( fluxes , ivars , contmask , deg , ranges , ffunc , n_proc = 1 ) : """Run fit _ cont , dealing with spectrum in regions or chunks This is useful if a spectrum has gaps . Parameters fluxes : ndarray of shape ( nstars , npixels ) training set or test set pixel intensities iva...
nstars = fluxes . shape [ 0 ] npixels = fluxes . shape [ 1 ] cont = np . zeros ( fluxes . shape ) for chunk in ranges : start = chunk [ 0 ] stop = chunk [ 1 ] if ffunc == "chebyshev" : output = _find_cont_fitfunc ( fluxes [ : , start : stop ] , ivars [ : , start : stop ] , contmask [ start : stop ] ...
def _generate_random_node_values ( height ) : """Return random node values for building binary trees . : param height : Height of the binary tree . : type height : int : return : Randomly generated node values . : rtype : [ int ]"""
max_node_count = 2 ** ( height + 1 ) - 1 node_values = list ( range ( max_node_count ) ) random . shuffle ( node_values ) return node_values
def usermacro_update ( hostmacroid , value , ** kwargs ) : '''Update existing host usermacro . : param hostmacroid : id of the host usermacro : param value : new value of the host usermacro : param _ connection _ user : Optional - zabbix user ( can also be set in opts or pillar , see module ' s docstring ) ...
conn_args = _login ( ** kwargs ) ret = { } try : if conn_args : params = { } method = 'usermacro.update' params [ 'hostmacroid' ] = hostmacroid params [ 'value' ] = value params = _params_extend ( params , _ignore_name = True , ** kwargs ) ret = _query ( method , para...
def Authenticate ( self , app_id , challenge , registered_keys ) : """Authenticates app _ id with the security key . Executes the U2F authentication / signature flow with the security key . Args : app _ id : The app _ id to register the security key against . challenge : Server challenge passed to the secur...
client_data = model . ClientData ( model . ClientData . TYP_AUTHENTICATION , challenge , self . origin ) app_param = self . InternalSHA256 ( app_id ) challenge_param = self . InternalSHA256 ( client_data . GetJson ( ) ) num_invalid_keys = 0 for key in registered_keys : try : if key . version != u'U2F_V2' : ...
def overloaded_build ( type_ , add_name = None ) : """Factory for constant transformers that apply to a given build instruction . Parameters type _ : type The object type to overload the construction of . This must be one of " buildable " types , or types with a " BUILD _ * " instruction . add _ name : ...
typename = type_ . __name__ instrname = 'BUILD_' + typename . upper ( ) dict_ = OrderedDict ( __doc__ = dedent ( """ A CodeTransformer for overloading {name} instructions. """ . format ( name = instrname ) ) ) try : build_instr = getattr ( instructions , instrname ) except AttributeError : ...
def roll_data ( self , data ) : """Append new data to the right side of every line strip and remove as much data from the left . Parameters data : array - like A data array to append ."""
data = data . astype ( 'float32' ) [ ... , np . newaxis ] s1 = self . _data_shape [ 1 ] - self . _offset if data . shape [ 1 ] > s1 : self . _pos_tex [ : , self . _offset : ] = data [ : , : s1 ] self . _pos_tex [ : , : data . shape [ 1 ] - s1 ] = data [ : , s1 : ] self . _offset = ( self . _offset + data . ...
def get_assessments_taken ( self ) : """Gets all ` ` AssessmentTaken ` ` elements . In plenary mode , the returned list contains all known assessments taken or an error results . Otherwise , the returned list may contain only those assessments taken that are accessible through this session . return : ( os...
# Implemented from template for # osid . resource . ResourceLookupSession . get _ resources # NOTE : This implementation currently ignores plenary view collection = JSONClientValidated ( 'assessment' , collection = 'AssessmentTaken' , runtime = self . _runtime ) result = collection . find ( self . _view_filter ( ) ) . ...
def warn_deprecated ( message , stacklevel = 2 ) : # pragma : no cover """Warn deprecated ."""
warnings . warn ( message , category = DeprecationWarning , stacklevel = stacklevel )
def iter_ROOT_classes ( ) : """Iterator over all available ROOT classes"""
class_index = "http://root.cern.ch/root/html/ClassIndex.html" for s in minidom . parse ( urlopen ( class_index ) ) . getElementsByTagName ( "span" ) : if ( "class" , "typename" ) in s . attributes . items ( ) : class_name = s . childNodes [ 0 ] . nodeValue try : yield getattr ( QROOT , c...
def predict_retinotopy ( sub , template = 'benson14' , registration = 'fsaverage' ) : '''predict _ retinotopy ( subject ) yields a pair of dictionaries each with four keys : angle , eccen , sigma , and varea . Each of these keys maps to a numpy array with one entry per vertex . The first element of the yielded ...
template = template . lower ( ) retino_tmpls = predict_retinotopy . retinotopy_templates [ registration ] hemis = [ 'lh' , 'rh' ] if registration == 'fsaverage' else [ 'sym' ] if template not in retino_tmpls : libdir = os . path . join ( library_path ( ) , 'data' ) search_paths = [ libdir ] # just hard - ba...
def line ( self , plunge , bearing , * args , ** kwargs ) : """Plot points representing linear features on the axes . Additional arguments and keyword arguments are passed on to ` plot ` . Parameters plunge , bearing : number or sequence of numbers The plunge and bearing of the line ( s ) in degrees . The p...
lon , lat = stereonet_math . line ( plunge , bearing ) args , kwargs = self . _point_plot_defaults ( args , kwargs ) return self . plot ( [ lon ] , [ lat ] , * args , ** kwargs )
def read_xml ( self ) : """read metadata from xml and set all the found properties . : return : the root element of the xml : rtype : ElementTree . Element"""
if self . xml_uri is None : root = self . _read_xml_db ( ) else : root = self . _read_xml_file ( ) if root is not None : for name , path in list ( self . _standard_properties . items ( ) ) : value = read_property_from_xml ( root , path ) if value is not None : # this calls the default setter...
def _remove_subsequent_result_because_of_batch_failure ( self , sig ) : """Remove transactions from scheduled and txn _ results for successors of txns in a failed batch . These transactions will now , or in the future be rescheduled in next _ transaction ; giving a replay ability . Args : sig ( str ) : Tr...
batch = self . _batches_by_txn_id [ sig ] seen = [ ] for txn in batch . transactions : txn_id = txn . header_signature for poss_successor in self . _scheduled . copy ( ) : if not self . is_transaction_in_schedule ( poss_successor ) : continue if self . _is_txn_to_replay ( txn_id , po...
def confirmation_option ( * param_decls , ** attrs ) : """Shortcut for confirmation prompts that can be ignored by passing ` ` - - yes ` ` as parameter . This is equivalent to decorating a function with : func : ` option ` with the following parameters : : def callback ( ctx , param , value ) : if not val...
def decorator ( f ) : def callback ( ctx , param , value ) : if not value : ctx . abort ( ) attrs . setdefault ( 'is_flag' , True ) attrs . setdefault ( 'callback' , callback ) attrs . setdefault ( 'expose_value' , False ) attrs . setdefault ( 'prompt' , 'Do you want to continue?...
def osmlem ( op , x , data , niter , callback = None , ** kwargs ) : r"""Ordered Subsets Maximum Likelihood Expectation Maximation algorithm . This solver attempts to solve : : max _ x L ( x | data ) where ` ` L ( x , | data ) ` ` is the likelihood of ` ` x ` ` given ` ` data ` ` . The likelihood depends on...
n_ops = len ( op ) if len ( data ) != n_ops : raise ValueError ( 'number of data ({}) does not match number of ' 'operators ({})' . format ( len ( data ) , n_ops ) ) if not all ( x in opi . domain for opi in op ) : raise ValueError ( '`x` not an element in the domains of all operators' ) # Convert data to range...
def encode_quorum ( self , rw ) : """Converts a symbolic quorum value into its on - the - wire equivalent . : param rw : the quorum : type rw : string , integer : rtype : integer"""
if rw in QUORUM_TO_PB : return QUORUM_TO_PB [ rw ] elif type ( rw ) is int and rw >= 0 : return rw else : return None
def mxnet_prefer_gpu ( ) : """If gpu available return gpu , else cpu Returns context : Context The preferable GPU context ."""
gpu = int ( os . environ . get ( 'MXNET_GPU' , default = 0 ) ) if gpu in mx . test_utils . list_gpus ( ) : return mx . gpu ( gpu ) return mx . cpu ( )
def get ( key , service = None , profile = None ) : # pylint : disable = W0613 '''Get a value from the etcd service'''
client = _get_conn ( profile ) result = client . get ( key ) return result . value
def apply_getters ( self , task ) : """This function is called when we specify the task dependencies with the syntax : deps = { node : " @ property " } In this case the task has to the get ` property ` from ` node ` before starting the calculation . At present , the following properties are supported : - @ ...
if not self . getters : return for getter in self . getters : if getter == "@structure" : task . history . info ( "Getting structure from %s" % self . node ) new_structure = self . node . get_final_structure ( ) task . _change_structure ( new_structure ) else : raise ValueErr...
def guess_strategy_type ( file_name_or_ext ) : """Guess strategy type to use for file by extension . Args : file _ name _ or _ ext : Either a file name with an extension or just an extension Returns : Strategy : Type corresponding to extension or None if there ' s no corresponding strategy type"""
if '.' not in file_name_or_ext : ext = file_name_or_ext else : name , ext = os . path . splitext ( file_name_or_ext ) ext = ext . lstrip ( '.' ) file_type_map = get_file_type_map ( ) return file_type_map . get ( ext , None )
def get_minor_version ( version , remove = None ) : """Return minor version of a provided version string . Minor version is the second component in the dot - separated version string . For non - version - like strings this function returns ` ` None ` ` . The ` ` remove ` ` parameter is deprecated since versio...
if remove : warnings . warn ( "remove argument is deprecated" , DeprecationWarning ) version_split = version . split ( "." ) try : # Assume MAJOR . MINOR . REST . . . return version_split [ 1 ] except IndexError : return None
def expect ( self , use_proportions = True ) : """The Expectation step of the CEM algorithm"""
changed = self . get_changed ( self . partition , self . prev_partition ) lk_table = self . generate_lktable ( self . partition , changed , use_proportions ) self . table = self . likelihood_table_to_probs ( lk_table )
def build_kernel ( self ) : """Build the KNN kernel . Build a k nearest neighbors kernel , optionally with alpha decay . If ` precomputed ` is not ` None ` , the appropriate steps in the kernel building process are skipped . Must return a symmetric matrix Returns K : kernel matrix , shape = [ n _ sample...
if self . precomputed == "affinity" : # already done # TODO : should we check that precomputed matrices look okay ? # e . g . check the diagonal K = self . data_nu elif self . precomputed == "adjacency" : # need to set diagonal to one to make it an affinity matrix K = self . data_nu if sparse . issparse ( K...
def moves_from_games ( self , start_game , end_game , moves , shuffle , column_family , column ) : """Dataset of samples and / or shuffled moves from game range . Args : n : an integer indicating how many past games should be sourced . moves : an integer indicating how many moves should be sampled from thos...
start_row = ROW_PREFIX . format ( start_game ) end_row = ROW_PREFIX . format ( end_game ) # NOTE : Choose a probability high enough to guarantee at least the # required number of moves , by using a slightly lower estimate # of the total moves , then trimming the result . total_moves = self . count_moves_in_game_range (...
def _filter_matrix_rows ( cls , matrix ) : '''matrix = output from _ to _ matrix'''
indexes_to_keep = [ ] for i in range ( len ( matrix ) ) : keep_row = False for element in matrix [ i ] : if element not in { 'NA' , 'no' } : keep_row = True break if keep_row : indexes_to_keep . append ( i ) return [ matrix [ i ] for i in indexes_to_keep ]
def _sanity_check_mark_location_preceding_optional_traverse ( ir_blocks ) : """Assert that optional Traverse blocks are preceded by a MarkLocation ."""
# Once all fold blocks are removed , each optional Traverse must have # a MarkLocation block immediately before it . _ , new_ir_blocks = extract_folds_from_ir_blocks ( ir_blocks ) for first_block , second_block in pairwise ( new_ir_blocks ) : # Traverse blocks with optional = True are immediately preceded by a MarkLoca...
def _generate_default_grp_constraints ( roles , network_constraints ) : """Generate default symetric grp constraints ."""
default_delay = network_constraints . get ( 'default_delay' ) default_rate = network_constraints . get ( 'default_rate' ) default_loss = network_constraints . get ( 'default_loss' , 0 ) except_groups = network_constraints . get ( 'except' , [ ] ) grps = network_constraints . get ( 'groups' , roles . keys ( ) ) # expand...
def sample ( self , nsamples , nburn = 0 , nthin = 1 , save_hidden_state_trajectory = False , call_back = None ) : """Sample from the BHMM posterior . Parameters nsamples : int The number of samples to generate . nburn : int , optional , default = 0 The number of samples to discard to burn - in , followin...
# Run burn - in . for iteration in range ( nburn ) : logger ( ) . info ( "Burn-in %8d / %8d" % ( iteration , nburn ) ) self . _update ( ) # Collect data . models = list ( ) for iteration in range ( nsamples ) : logger ( ) . info ( "Iteration %8d / %8d" % ( iteration , nsamples ) ) # Run a number of Gi...
def invariant_image_similarity ( image1 , image2 , local_search_iterations = 0 , metric = 'MI' , thetas = np . linspace ( 0 , 360 , 5 ) , thetas2 = np . linspace ( 0 , 360 , 5 ) , thetas3 = np . linspace ( 0 , 360 , 5 ) , scale_image = 1 , do_reflection = False , txfn = None , transform = 'Affine' ) : """Similarity...
if transform not in { 'Rigid' , 'Similarity' , 'Affine' } : raise ValueError ( 'transform must be one of Rigid/Similarity/Affine' ) if image1 . pixeltype != 'float' : image1 = image1 . clone ( 'float' ) if image2 . pixeltype != 'float' : image2 = image2 . clone ( 'float' ) if txfn is None : txfn = mktem...
def fix_pbc ( structure , matrix = None ) : """Set all frac _ coords of the input structure within [ 0,1 ] . Args : structure ( pymatgen structure object ) : input structure matrix ( lattice matrix , 3 by 3 array / matrix ) new structure ' s lattice matrix , if none , use input structure ' s matrix Re...
spec = [ ] coords = [ ] if matrix is None : latte = Lattice ( structure . lattice . matrix ) else : latte = Lattice ( matrix ) for site in structure : spec . append ( site . specie ) coord = np . array ( site . frac_coords ) for i in range ( 3 ) : coord [ i ] -= floor ( coord [ i ] ) ...
def unpack_response ( self , cursor_id = None , codec_options = _UNICODE_REPLACE_CODEC_OPTIONS , user_fields = None , legacy_response = False ) : """Unpack a OP _ MSG command response . : Parameters : - ` cursor _ id ` ( optional ) : Ignored , for compatibility with _ OpReply . - ` codec _ options ` ( optiona...
# If _ OpMsg is in - use , this cannot be a legacy response . assert not legacy_response return bson . _decode_all_selective ( self . payload_document , codec_options , user_fields )
def load_tags ( self , max_pages = 30 ) : """Load all WordPress tags from the given site . : param max _ pages : kill counter to avoid infinite looping : return : None"""
logger . info ( "loading tags" ) # clear them all out so we don ' t get dupes if requested if self . purge_first : Tag . objects . filter ( site_id = self . site_id ) . delete ( ) path = "sites/{}/tags" . format ( self . site_id ) params = { "number" : 1000 } page = 1 response = self . get ( path , params ) if not ...
def browse_history ( self , backward ) : """Browse history"""
if self . is_cursor_before ( 'eol' ) and self . hist_wholeline : self . hist_wholeline = False tocursor = self . get_current_line_to_cursor ( ) text , self . histidx = self . find_in_history ( tocursor , self . histidx , backward ) if text is not None : if self . hist_wholeline : self . clear_line ( ) ...
def butter ( dt_list , val , lowpass = 1.0 ) : """This is framework for a butterworth bandpass for 1D data Needs to be cleaned up and generalized"""
import scipy . signal import matplotlib . pyplot as plt # dt is 300 s , 5 min dt_diff = np . diff ( dt_list ) dt_diff = np . array ( [ dt . total_seconds ( ) for dt in dt_diff ] ) dt = malib . fast_median ( dt_diff ) # f is 0.00333 Hz # 288 samples / day fs = 1. / dt nyq = fs / 2. if False : # psd , f = psd ( z _ msl ,...
def item_path_or ( default , keys , dict_or_obj ) : """Optional version of item _ path with a default value . keys can be dict keys or object attributes , or a combination : param default : : param keys : List of keys or dot - separated string : param dict _ or _ obj : A dict or obj : return :"""
if not keys : raise ValueError ( "Expected at least one key, got {0}" . format ( keys ) ) resolved_keys = keys . split ( '.' ) if isinstance ( str , keys ) else keys current_value = dict_or_obj for key in resolved_keys : current_value = prop_or ( default , key , default_to ( { } , current_value ) ) return curre...
async def power ( dev : Device , cmd , target , value ) : """Turn on and off , control power settings . Accepts commands ' on ' , ' off ' , and ' settings ' ."""
async def try_turn ( cmd ) : state = True if cmd == "on" else False try : return await dev . set_power ( state ) except SongpalException as ex : if ex . code == 3 : err ( "The device is already %s." % cmd ) else : raise ex if cmd == "on" or cmd == "off" : ...
def cmd_gyrocal ( self , args ) : '''do a full gyro calibration'''
mav = self . master mav . mav . command_long_send ( mav . target_system , mav . target_component , mavutil . mavlink . MAV_CMD_PREFLIGHT_CALIBRATION , 0 , 1 , 0 , 0 , 0 , 0 , 0 , 0 )
def _makeplot ( self , ax , fig , data , ymin = None , ymax = None , height = 6 , width = 6 , dos = None , color = None ) : """Utility method to tidy phonon band structure diagrams ."""
# Define colours if color is None : color = 'C0' # Default to first colour in matplotlib series # set x and y limits tymax = ymax if ( ymax is not None ) else max ( flatten ( data [ 'frequency' ] ) ) tymin = ymin if ( ymin is not None ) else min ( flatten ( data [ 'frequency' ] ) ) pad = ( tymax - tymin ) * 0.05 if...
def build_D3treepie ( old , MAX_DEPTH , level = 1 , toplayer = None ) : """Create the JSON needed by the treePie viz http : / / bl . ocks . org / adewes / 4710330/94a7c0aeb6f09d681dbfdd0e5150578e4935c6ae Eg [ ' origin ' , [ n1 , n2 ] , { ' name1 ' : [ ' name1 ' , [ n1 , n2 ] , { ' name1-1 ' : . . . }"""
d = { } if not old : old = toplayer for x in old : label = x . bestLabel ( quotes = False ) . replace ( "_" , " " ) if x . children ( ) and level < MAX_DEPTH : size = len ( x . children ( ) ) d [ x . qname ] = [ label , [ size , size ] , build_D3treepie ( x . children ( ) , MAX_DEPTH , level...
def get_eval_func ( obj , feature , slice = np . s_ [ ... ] ) : """Return the function of interest ( kernel or mean ) for the expectation depending on the type of : obj : and whether any features are given"""
if feature is not None : # kernel + feature combination if not isinstance ( feature , InducingFeature ) or not isinstance ( obj , kernels . Kernel ) : raise TypeError ( "If `feature` is supplied, `obj` must be a kernel." ) return lambda x : tf . transpose ( Kuf ( feature , obj , x ) ) [ slice ] elif isi...
def _to_power_basis_degree4 ( nodes1 , nodes2 ) : r"""Compute the coefficients of an * * intersection polynomial * * . Helper for : func : ` to _ power _ basis ` in the case that B | eacute | zout ' s ` theorem ` _ tells us the * * intersection polynomial * * is degree : math : ` 4 ` . This happens if the two...
# We manually invert the Vandermonde matrix : # [1 0 0 0 0 ] [ c0 ] = [ n0] # [1 1/4 1/16 1/64 1/256 ] [ c1 ] [ n1] # [1 1/2 1/4 1/8 1/16 ] [ c2 ] [ n2] # [1 3/4 9/16 27/64 81/256 ] [ c3 ] [ n3] # [1 1 1 1 1 ] [ c4 ] [ n4] val0 = eval_intersection_polynomial ( nodes1 , nodes2 , 0.0 ) val1 = eval_intersection_polynomial...
def score_for_percentile_in ( self , leaderboard_name , percentile ) : '''Calculate the score for a given percentile value in the leaderboard . @ param leaderboard _ name [ String ] Name of the leaderboard . @ param percentile [ float ] Percentile value ( 0.0 to 100.0 inclusive ) . @ return the score correspo...
if not 0 <= percentile <= 100 : return None total_members = self . total_members_in ( leaderboard_name ) if total_members < 1 : return None if self . order == self . ASC : percentile = 100 - percentile index = ( total_members - 1 ) * ( percentile / 100.0 ) scores = [ pair [ 1 ] for pair in self . redis_conn...