signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def get_sqla_coltype_from_dialect_str ( coltype : str , dialect : Dialect ) -> TypeEngine : """Returns an SQLAlchemy column type , given a column type name ( a string ) and an SQLAlchemy dialect . For example , this might convert the string ` ` INTEGER ( 11 ) ` ` to an SQLAlchemy ` ` Integer ( length = 11 ) ` `...
size = None # type : Optional [ int ] dp = None # type : Optional [ int ] args = [ ] # type : List [ Any ] kwargs = { } # type : Dict [ str , Any ] basetype = '' # noinspection PyPep8 , PyBroadException try : # Split e . g . " VARCHAR ( 32 ) COLLATE blah " into " VARCHAR ( 32 ) " , " who cares " m = RE_COLTYPE_WITH...
def setCellUser ( self , iden ) : '''Switch to another user ( admin only ) . This API allows remote admin / service accounts to impersonate a user . Used mostly by services that manage their own authentication / sessions .'''
if not self . user . admin : mesg = 'setCellUser() caller must be admin.' raise s_exc . AuthDeny ( mesg = mesg ) user = self . cell . auth . user ( iden ) if user is None : raise s_exc . NoSuchUser ( iden = iden ) self . user = user return True
def _iter_info ( self , niter , level = logging . INFO ) : """Log iteration number and mismatch Parameters level logging level Returns None"""
max_mis = self . iter_mis [ niter - 1 ] msg = ' Iter {:<d}. max mismatch = {:8.7f}' . format ( niter , max_mis ) logger . info ( msg )
def get_mst ( points ) : """Parameters points : list of points ( geometry . Point ) The first element of the list is the center of the bounding box of the first stroke , the second one belongs to the seconds stroke , . . . Returns mst : square matrix 0 nodes the edges are not connected , > 0 means they ...
graph = Graph ( ) for point in points : graph . add_node ( point ) graph . generate_euclidean_edges ( ) matrix = scipy . sparse . csgraph . minimum_spanning_tree ( graph . w ) mst = matrix . toarray ( ) . astype ( int ) # returned matrix is not symmetrical ! make it symmetrical for i in range ( len ( mst ) ) : ...
def is_allowed ( self , name_or_class , mask ) : # pragma : no cover """Return True is a new connection is allowed"""
if isinstance ( name_or_class , type ) : name = name_or_class . type else : name = name_or_class info = self . connections [ name ] limit = self . config [ name + '_limit' ] if limit and info [ 'total' ] >= limit : msg = ( "Sorry, there is too much DCC %s active. Please try again " "later." ) % name . upper...
def _find_last_good_run ( build ) : """Finds the last good release and run for a build ."""
run_name = request . form . get ( 'run_name' , type = str ) utils . jsonify_assert ( run_name , 'run_name required' ) last_good_release = ( models . Release . query . filter_by ( build_id = build . id , status = models . Release . GOOD ) . order_by ( models . Release . created . desc ( ) ) . first ( ) ) last_good_run =...
def verify_tree_consistency ( self , old_tree_size : int , new_tree_size : int , old_root : bytes , new_root : bytes , proof : Sequence [ bytes ] ) : """Verify the consistency between two root hashes . old _ tree _ size must be < = new _ tree _ size . Args : old _ tree _ size : size of the older tree . new ...
old_size = old_tree_size new_size = new_tree_size if old_size < 0 or new_size < 0 : raise ValueError ( "Negative tree size" ) if old_size > new_size : raise ValueError ( "Older tree has bigger size (%d vs %d), did " "you supply inputs in the wrong order?" % ( old_size , new_size ) ) if old_size == new_size : ...
def _assignSignature ( self , chip ) : """Assign a unique signature for the image based on the instrument , detector , chip , and size this will be used to uniquely identify the appropriate static mask for the image . This also records the filename for the static mask to the outputNames dictionary ."""
sci_chip = self . _image [ self . scienceExt , chip ] ny = sci_chip . _naxis1 nx = sci_chip . _naxis2 detnum = sci_chip . detnum instr = self . _instrument sig = ( instr + self . _detector , ( nx , ny ) , int ( detnum ) ) # signature is a tuple sci_chip . signature = sig
def _validate_namespace ( self , namespace ) : """Validates a namespace , raising a ResponseFailed error if invalid . Args : state _ root ( str ) : The state _ root to validate Raises : ResponseFailed : The state _ root was invalid , and a status of INVALID _ ROOT will be sent with the response ."""
if self . _namespace_regex . fullmatch ( namespace ) is None : LOGGER . debug ( 'Invalid namespace: %s' , namespace ) raise _ResponseFailed ( self . _status . INVALID_ADDRESS )
def send_vm_info ( self , vm_info ) : """Send vm info to the compute host . it will return True / False"""
agent_host = vm_info . get ( 'host' ) if not agent_host : LOG . info ( "vm/port is not bound to host, not sending vm info" ) return True try : self . neutron_event . send_vm_info ( agent_host , str ( vm_info ) ) except ( rpc . MessagingTimeout , rpc . RPCException , rpc . RemoteError ) : # Failed to send in...
def _arrays_to_sections ( self , arrays ) : '''input : unprocessed numpy arrays . returns : columns of the size that they will appear in the image , not scaled for display . That needs to wait until after variance is computed .'''
sections = [ ] sections_to_resize_later = { } show_all = self . config [ 'show_all' ] image_width = self . _determine_image_width ( arrays , show_all ) for array_number , array in enumerate ( arrays ) : rank = len ( array . shape ) section_height = self . _determine_section_height ( array , show_all ) if ra...
def check_streamers ( self , blacklist = None ) : """Check if any streamers are ready to produce a report . You can limit what streamers are checked by passing a set - like object into blacklist . This method is the primary way to see when you should poll a given streamer for its next report . Note , this...
ready = [ ] selected = set ( ) for i , streamer in enumerate ( self . streamers ) : if blacklist is not None and i in blacklist : continue if i in selected : continue marked = False if i in self . _manually_triggered_streamers : marked = True self . _manually_triggered_st...
def PrimaryHDU ( model ) : '''Construct the primary HDU file containing basic header info .'''
# Get mission cards cards = model . _mission . HDUCards ( model . meta , hdu = 0 ) if 'KEPMAG' not in [ c [ 0 ] for c in cards ] : cards . append ( ( 'KEPMAG' , model . mag , 'Kepler magnitude' ) ) # Add EVEREST info cards . append ( ( 'COMMENT' , '************************' ) ) cards . append ( ( 'COMMENT' , '* ...
def generate_context ( context_file = 'cookiecutter.json' , default_context = None , extra_context = None ) : """Generate the context for a Cookiecutter project template . Loads the JSON file as a Python object , with key being the JSON filename . : param context _ file : JSON file containing key / value pairs ...
context = OrderedDict ( [ ] ) try : with open ( context_file ) as file_handle : obj = json . load ( file_handle , object_pairs_hook = OrderedDict ) except ValueError as e : # JSON decoding error . Let ' s throw a new exception that is more # friendly for the developer or user . full_fpath = os . path . ...
def search_mappings ( kb , key = None , value = None , match_type = None , sortby = None , page = None , per_page = None ) : """Search tags for knowledge ."""
if kb . kbtype == models . KnwKB . KNWKB_TYPES [ 'written_as' ] : return pagination . RestfulSQLAlchemyPagination ( api . query_kb_mappings ( kbid = kb . id , key = key or '' , value = value or '' , match_type = match_type or 's' , sortby = sortby or 'to' , ) , page = page or 1 , per_page = per_page or 10 ) . items...
def draw ( self , mode = "triangles" ) : """Draw collection"""
gl . glDepthMask ( 0 ) Collection . draw ( self , mode ) gl . glDepthMask ( 1 )
def _pre_compute_secondary ( self , positive_vals , negative_vals ) : """Compute secondary y min and max"""
self . _secondary_max = max ( max ( positive_vals ) , max ( negative_vals ) ) self . _secondary_min = - self . _secondary_max
def _computeUniqueReadCounts ( self ) : """Add all pathogen / sample combinations to self . pathogenSampleFiles . This will make all de - duplicated ( by id ) FASTA / FASTQ files and store the number of de - duplicated reads into C { self . pathogenNames } ."""
for pathogenName , samples in self . pathogenNames . items ( ) : for sampleName in samples : self . pathogenSampleFiles . add ( pathogenName , sampleName )
def _is_intrinsic_dict ( self , input ) : """Can the input represent an intrinsic function in it ? : param input : Object to be checked : return : True , if the input contains a supported intrinsic function . False otherwise"""
# All intrinsic functions are dictionaries with just one key return isinstance ( input , dict ) and len ( input ) == 1 and list ( input . keys ( ) ) [ 0 ] in self . supported_intrinsics
def filter_tree ( tree ) : """Filter all 401 errors ."""
to_remove = [ ] for elem in tree . findall ( 'urldata' ) : valid = elem . find ( 'valid' ) if valid is not None and valid . text == '0' and valid . attrib . get ( 'result' , '' ) . startswith ( '401' ) : to_remove . append ( elem ) root = tree . getroot ( ) for elem in to_remove : root . remove ( el...
def pipeline_refine ( d0 , candloc , scaledm = 2.1 , scalepix = 2 , scaleuv = 1.0 , chans = [ ] , returndata = False ) : """Reproduces candidate and potentially improves sensitivity through better DM and imaging parameters . scale * parameters enhance sensitivity by making refining dmgrid and images . Other opt...
import rtpipe . parseparams as pp assert len ( candloc ) == 6 , 'candloc should be (scan, segment, candint, dmind, dtind, beamnum).' scan , segment , candint , dmind , dtind , beamnum = candloc d1 = d0 . copy ( ) # dont mess with original ( mutable ! ) segmenttimes = d1 [ 'segmenttimesdict' ] [ scan ] # if file not at ...
def parse_color ( src = None ) : # type : ( Optional [ str ] ) - > Optional [ Union [ Tuple [ int , . . . ] , int ] ] """Parse a string representing a color value . Color is either a fixed color ( when coloring something from the UI , see the GLYPHS _ COLORS constant ) or a list of the format [ u8 , u8 , u8 , u...
if src is None : return None # Tuple . if src [ 0 ] == "(" : rgba = tuple ( int ( v ) for v in src [ 1 : - 1 ] . split ( "," ) if v ) if not ( len ( rgba ) == 4 and all ( 0 <= v < 256 for v in rgba ) ) : raise ValueError ( "Broken color tuple: {}. Must have four values from 0 to 255." . format ( src...
def toradialvelocity ( self , rf , v0 ) : """Convert a Doppler type value ( e . g . in radio mode ) to a real radialvelocity . The type of velocity ( e . g . * LSRK * ) should be specified : param rf : radialvelocity reference code ( see : meth : ` radialvelocity ` ) : param v0 : a doppler measure Example :...
if is_measure ( v0 ) and v0 [ 'type' ] == 'doppler' : return self . doptorv ( rf , v0 ) else : raise TypeError ( 'Illegal Doppler specified' )
def rename_set ( set = None , new_set = None , family = 'ipv4' ) : '''. . versionadded : : 2014.7.0 Delete ipset set . CLI Example : . . code - block : : bash salt ' * ' ipset . rename _ set custom _ set new _ set = new _ set _ name IPv6: salt ' * ' ipset . rename _ set custom _ set new _ set = new _ se...
if not set : return 'Error: Set needs to be specified' if not new_set : return 'Error: New name for set needs to be specified' settype = _find_set_type ( set ) if not settype : return 'Error: Set does not exist' settype = _find_set_type ( new_set ) if settype : return 'Error: New Set already exists' cmd...
def get_objective_objective_bank_assignment_session ( self ) : """Gets the session for assigning objective to objective bank mappings . return : ( osid . learning . ObjectiveObjectiveBankAssignmentSession ) - an ` ` ObjectiveObjectiveBankAssignmentSession ` ` raise : OperationFailed - unable to complete reque...
if not self . supports_objective_objective_bank_assignment ( ) : raise errors . Unimplemented ( ) # pylint : disable = no - member return sessions . ObjectiveObjectiveBankAssignmentSession ( runtime = self . _runtime )
def get_keyboard_mapping ( self , first_keycode , count ) : """Return the current keyboard mapping as a list of tuples , starting at first _ keycount and no more than count ."""
r = request . GetKeyboardMapping ( display = self . display , first_keycode = first_keycode , count = count ) return r . keysyms
def compute_nats_and_bits_per_dim ( data_dim , latent_dim , average_reconstruction , average_prior ) : """Computes negative ELBO , which is an upper bound on the negative likelihood . Args : data _ dim : int - like indicating data dimensionality . latent _ dim : int - like indicating latent dimensionality . ...
with tf . name_scope ( None , default_name = "compute_nats_per_dim" ) : data_dim = tf . cast ( data_dim , average_reconstruction . dtype ) latent_dim = tf . cast ( latent_dim , average_prior . dtype ) negative_log_likelihood = data_dim * average_reconstruction negative_log_prior = latent_dim * average_p...
def surface_measure ( self , param ) : """Density function of the surface measure . This is the default implementation relying on the ` surface _ deriv ` method . For a detector with ` ndim ` equal to 1 , the density is given by the ` Arc length ` _ , for a surface with ` ndim ` 2 in a 3D space , it is the ...
# Checking is done by ` surface _ deriv ` if self . ndim == 1 : scalar_out = ( np . shape ( param ) == ( ) ) measure = np . linalg . norm ( self . surface_deriv ( param ) , axis = - 1 ) if scalar_out : measure = float ( measure ) return measure elif self . ndim == 2 and self . space_ndim == 3 : ...
def _check_requirements ( self ) : """Checks the IOU image ."""
if not self . _path : raise IOUError ( "IOU image is not configured" ) if not os . path . isfile ( self . _path ) or not os . path . exists ( self . _path ) : if os . path . islink ( self . _path ) : raise IOUError ( "IOU image '{}' linked to '{}' is not accessible" . format ( self . _path , os . path ....
def sync ( state , host , source , destination , user = None , group = None , mode = None , delete = False , exclude = None , exclude_dir = None , add_deploy_dir = True , ) : '''Syncs a local directory with a remote one , with delete support . Note that delete will remove extra files on the remote side , but not ...
# If we don ' t enforce the source ending with / , remote _ dirname below might start with # a / , which makes the path . join cut off the destination bit . if not source . endswith ( path . sep ) : source = '{0}{1}' . format ( source , path . sep ) # Add deploy directory ? if add_deploy_dir and state . deploy_dir ...
def constant_time_cmp ( a , b ) : '''Compare two strings using constant time .'''
result = True for x , y in zip ( a , b ) : result &= ( x == y ) return result
def render_path ( self ) -> str : """Render path by filling the path template with video information ."""
# TODO : Fix defaults when date is not found ( empty string or None ) # https : / / stackoverflow . com / questions / 23407295 / default - kwarg - values - for - pythons - str - format - method from string import Formatter class UnseenFormatter ( Formatter ) : def get_value ( self , key , args , kwds ) : if...
def for_sponsor ( self , sponsor , include_cancelled = False ) : """Return a QueryList of EighthScheduledActivities where the given EighthSponsor is sponsoring . If a sponsorship is defined in an EighthActivity , it may be overridden on a block by block basis in an EighthScheduledActivity . Sponsors from th...
sponsoring_filter = ( Q ( sponsors = sponsor ) | ( Q ( sponsors = None ) & Q ( activity__sponsors = sponsor ) ) ) sched_acts = ( EighthScheduledActivity . objects . exclude ( activity__deleted = True ) . filter ( sponsoring_filter ) . distinct ( ) ) if not include_cancelled : sched_acts = sched_acts . exclude ( can...
def get_xyz ( self , xyz_axis = 0 ) : """Return a vector array of the x , y , and z coordinates . Parameters xyz _ axis : int , optional The axis in the final array along which the x , y , z components should be stored ( default : 0 ) . Returns xs : ` ~ astropy . units . Quantity ` With dimension 3 al...
# Add new axis in x , y , z so one can concatenate them around it . # NOTE : just use np . stack once our minimum numpy version is 1.10. result_ndim = self . ndim + 1 if not - result_ndim <= xyz_axis < result_ndim : raise IndexError ( 'xyz_axis {0} out of bounds [-{1}, {1})' . format ( xyz_axis , result_ndim ) ) if...
def searchbyno ( self , no ) : """搜尋股票代碼 : param str no : 欲搜尋的字串 : rtype : dict"""
pattern = re . compile ( str ( no ) ) result = { } for i in self . __allstockno : query = re . search ( pattern , str ( i ) ) if query : query . group ( ) result [ i ] = self . __allstockno [ i ] return result
def addDataFrameColumn ( self , columnName , dtype = str , defaultValue = None ) : """Adds a column to the dataframe as long as the model ' s editable property is set to True and the dtype is supported . : param columnName : str name of the column . : param dtype : qtpandas . models . SupportedDtypes opti...
if not self . editable or dtype not in SupportedDtypes . allTypes ( ) : return False elements = self . rowCount ( ) columnPosition = self . columnCount ( ) newColumn = pandas . Series ( [ defaultValue ] * elements , index = self . _dataFrame . index , dtype = dtype ) self . beginInsertColumns ( QtCore . QModelIndex...
def thumbnail_exists ( self , thumbnail_name ) : """Calculate whether the thumbnail already exists and that the source is not newer than the thumbnail . If the source and thumbnail file storages are local , their file modification times are used . Otherwise the database cached modification times are used ."...
if self . remote_source : return False if utils . is_storage_local ( self . source_storage ) : source_modtime = utils . get_modified_time ( self . source_storage , self . name ) else : source = self . get_source_cache ( ) if not source : return False source_modtime = source . modified if not...
def get_tree ( self , list_of_keys ) : """gettree will extract the value from a nested tree INPUT list _ of _ keys : a list of keys ie . [ ' key1 ' , ' key2 ' ] USAGE > > > # Access the value for key2 within the nested dictionary > > > adv _ dict ( { ' key1 ' : { ' key2 ' : ' value ' } } ) . gettree ( [ '...
cur_obj = self for key in list_of_keys : cur_obj = cur_obj . get ( key ) if not cur_obj : break return cur_obj
def assign_extension_to_users ( self , body ) : """AssignExtensionToUsers . [ Preview API ] Assigns the access to the given extension for a given list of users : param : class : ` < ExtensionAssignment > < azure . devops . v5_0 . licensing . models . ExtensionAssignment > ` body : The extension assignment detai...
content = self . _serialize . body ( body , 'ExtensionAssignment' ) response = self . _send ( http_method = 'PUT' , location_id = '8cec75ea-044f-4245-ab0d-a82dafcc85ea' , version = '5.0-preview.1' , content = content ) return self . _deserialize ( '[ExtensionOperationResult]' , self . _unwrap_collection ( response ) )
def disable_all_breakpoints ( cls ) : """Disable all breakpoints and udate ` active _ breakpoint _ flag ` ."""
for bp in cls . breakpoints_by_number : if bp : # breakpoint # 0 exists and is always None bp . enabled = False cls . update_active_breakpoint_flag ( ) return
def _finalize_block_blob ( self , sd , metadata , digest ) : # type : ( SyncCopy , blobxfer . models . synccopy . Descriptor , dict , # str ) - > None """Finalize Block blob : param SyncCopy self : this : param blobxfer . models . synccopy . Descriptor sd : synccopy descriptor : param dict metadata : metadata...
blobxfer . operations . azure . blob . block . put_block_list ( sd . dst_entity , sd . last_block_num , digest , metadata ) if blobxfer . util . is_not_empty ( sd . dst_entity . replica_targets ) : for ase in sd . dst_entity . replica_targets : blobxfer . operations . azure . blob . block . put_block_list (...
def mse ( vref , vcmp ) : """Compute Mean Squared Error ( MSE ) between two images . Parameters vref : array _ like Reference image vcmp : array _ like Comparison image Returns x : float MSE between ` vref ` and ` vcmp `"""
r = np . asarray ( vref , dtype = np . float64 ) . ravel ( ) c = np . asarray ( vcmp , dtype = np . float64 ) . ravel ( ) return np . mean ( np . abs ( r - c ) ** 2 )
def get_product ( self , standard , key ) : """查询商品信息 详情请参考 http : / / mp . weixin . qq . com / wiki / 15/7fa787701295b884410b5163e13313af . html : param standard : 商品编码标准 : param key : 商品编码内容 : return : 返回的 JSON 数据包"""
data = { 'keystandard' : standard , 'keystr' : key , } return self . _post ( 'product/get' , data = data )
def wrap_function_cols ( self , name , package_name = None , object_name = None , java_class_instance = None , doc = "" ) : """Utility method for wrapping a scala / java function that returns a spark sql Column . This assumes that the function that you are wrapping takes a list of spark sql Column objects as its ...
def _ ( * cols ) : jcontainer = self . get_java_container ( package_name = package_name , object_name = object_name , java_class_instance = java_class_instance ) # Ensure that your argument is a column col_args = [ col . _jc if isinstance ( col , Column ) else _make_col ( col ) . _jc for col in cols ] f...
def answer ( self ) : """Return the answer for the question from the validator . This will ultimately only be called on the first validator if multiple validators have been added ."""
if isinstance ( self . validator , list ) : return self . validator [ 0 ] . choice ( ) return self . validator . choice ( )
def reject_entry ( request , entry_id ) : """Admins can reject an entry that has been verified or approved but not invoiced to set its status to ' unverified ' for the user to fix ."""
return_url = request . GET . get ( 'next' , reverse ( 'dashboard' ) ) try : entry = Entry . no_join . get ( pk = entry_id ) except : message = 'No such log entry.' messages . error ( request , message ) return redirect ( return_url ) if entry . status == Entry . UNVERIFIED or entry . status == Entry . I...
def score_task ( self , X , Y , t = 0 , metric = "accuracy" , verbose = True , ** kwargs ) : """Scores the predictive performance of the Classifier on task t Args : X : The input for the predict _ task method Y : A [ n ] or [ n , 1 ] np . ndarray or torch . Tensor of gold labels in {1 , . . . , K _ t } t ...
Y = self . _to_numpy ( Y ) Y_tp = self . predict_task ( X , t = t , ** kwargs ) probs = self . predict_proba ( X ) [ t ] score = metric_score ( Y [ t ] , Y_tp , metric , ignore_in_gold = [ 0 ] , probs = probs , ** kwargs ) if verbose : print ( f"[t={t}] {metric.capitalize()}: {score:.3f}" ) return score
def user_active_directory_enabled ( user , attributes , created , updated ) : """Activate / deactivate user accounts based on Active Directory ' s userAccountControl flags . Requires ' userAccountControl ' to be included in LDAP _ SYNC _ USER _ EXTRA _ ATTRIBUTES ."""
try : user_account_control = int ( attributes [ 'userAccountControl' ] [ 0 ] ) if user_account_control & 2 : user . is_active = False else : user . is_active = True except KeyError : pass
def helper_import ( module_name , class_name = None ) : """Return class or module object . if the argument is only a module name and return a module object . if the argument is a module and class name , and return a class object ."""
try : module = __import__ ( module_name , globals ( ) , locals ( ) , [ class_name ] ) except ( BlackbirdError , ImportError ) as error : raise BlackbirdError ( 'can not load {0} module [{1}]' '' . format ( module_name , str ( error ) ) ) if not class_name : return module else : try : return geta...
def pairs ( iterable ) : """: return : iterator yielding overlapping pairs from iterable : Example : > > > list ( pairs ( [ 1 , 2 , 3 , 4 ] ) [ ( 1 , 2 ) , ( 2 , 3 ) , ( 3 , 4 ) ]"""
a , b = itertools . tee ( iterable ) next ( b , None ) return zip ( a , b )
def build_digest_challenge ( timestamp , secret , realm , opaque , stale ) : '''Builds a Digest challenge that may be sent as the value of the ' WWW - Authenticate ' header in a 401 or 403 response . ' opaque ' may be any value - it will be returned by the client . ' timestamp ' will be incorporated and signe...
nonce = calculate_nonce ( timestamp , secret ) return 'Digest %s' % format_parts ( realm = realm , qop = 'auth' , nonce = nonce , opaque = opaque , algorithm = 'MD5' , stale = stale and 'true' or 'false' )
def get_payment_transaction_by_id ( cls , payment_transaction_id , ** kwargs ) : """Find PaymentTransaction Return single instance of PaymentTransaction by its ID . This method makes a synchronous HTTP request by default . To make an asynchronous HTTP request , please pass async = True > > > thread = api . ...
kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'async' ) : return cls . _get_payment_transaction_by_id_with_http_info ( payment_transaction_id , ** kwargs ) else : ( data ) = cls . _get_payment_transaction_by_id_with_http_info ( payment_transaction_id , ** kwargs ) return data
def _unmarshal ( self , obj ) : """Walks an object and unmarshals any MORs into psphere objects ."""
if isinstance ( obj , suds . sudsobject . Object ) is False : logger . debug ( "%s is not a suds instance, skipping" , obj ) return obj logger . debug ( "Processing:" ) logger . debug ( obj ) logger . debug ( "...with keylist:" ) logger . debug ( obj . __keylist__ ) # If the obj that we ' re looking at has a _ ...
def update_model ( raw_model , app_model , forbidden_keys = None , inverse = False ) : """Updates the ` raw _ model ` according to the values in the ` app _ model ` . : param raw _ model : Raw model which gets updated . : param app _ model : App model holding the data . : param forbidden _ keys : Data / attri...
if forbidden_keys is None : forbidden_keys = [ ] if type ( app_model ) != dict : app_model = app_model . __dict__ if inverse : for k in app_model : logging . debug ( "Considering property {0}." . format ( k ) ) if ( hasattr ( raw_model , k ) ) and ( k not in forbidden_keys ) : lo...
def _get_variant_region ( self ) : """Categorize variant by location in transcript ( 5 ' utr , exon , intron , 3 ' utr ) : return " exon " , " intron " , " five _ utr " , " three _ utr " , " whole _ gene " : rtype str"""
if self . _var_c . posedit . pos . start . datum == Datum . CDS_END and self . _var_c . posedit . pos . end . datum == Datum . CDS_END : result = self . T_UTR elif self . _var_c . posedit . pos . start . base < 0 and self . _var_c . posedit . pos . end . base < 0 : result = self . F_UTR elif self . _var_c . pos...
def bytes_to_str ( self , b ) : "convert bytes array to raw string"
if PYTHON_MAJOR_VER == 3 : return b . decode ( charset_map . get ( self . charset , self . charset ) ) return b
def _set_bank_view ( self , session ) : """Sets the underlying bank view to match current view"""
if self . _bank_view == COMPARATIVE : try : session . use_comparative_bank_view ( ) except AttributeError : pass else : try : session . use_plenary_bank_view ( ) except AttributeError : pass
def velocity_dispersion ( self , kwargs_lens , kwargs_lens_light , lens_light_model_bool_list = None , aniso_param = 1 , r_eff = None , R_slit = 0.81 , dR_slit = 0.1 , psf_fwhm = 0.7 , num_evaluate = 1000 ) : """computes the LOS velocity dispersion of the lens within a slit of size R _ slit x dR _ slit and seeing p...
gamma = kwargs_lens [ 0 ] [ 'gamma' ] if 'center_x' in kwargs_lens_light [ 0 ] : center_x , center_y = kwargs_lens_light [ 0 ] [ 'center_x' ] , kwargs_lens_light [ 0 ] [ 'center_y' ] else : center_x , center_y = 0 , 0 if r_eff is None : r_eff = self . lens_analysis . half_light_radius_lens ( kwargs_lens_lig...
def load_yamlf ( fpath , encoding ) : """: param unicode fpath : : param unicode encoding : : rtype : dict | list"""
with codecs . open ( fpath , encoding = encoding ) as f : return yaml . safe_load ( f )
def save_model ( self , request , obj , form , change ) : """sends the email and does not save it"""
email = message . EmailMessage ( subject = obj . subject , body = obj . body , from_email = obj . from_email , to = [ t . strip ( ) for t in obj . to_emails . split ( ',' ) ] , bcc = [ t . strip ( ) for t in obj . bcc_emails . split ( ',' ) ] , cc = [ t . strip ( ) for t in obj . cc_emails . split ( ',' ) ] ) email . s...
def delete_multi ( self , keys , time = 0 , key_prefix = '' ) : '''Delete multiple keys in the memcache doing just one query . > > > notset _ keys = mc . set _ multi ( { ' key1 ' : ' val1 ' , ' key2 ' : ' val2 ' } ) > > > mc . get _ multi ( [ ' key1 ' , ' key2 ' ] ) = = { ' key1 ' : ' val1 ' , ' key2 ' : ' val2...
self . _statlog ( 'delete_multi' ) server_keys , prefixed_to_orig_key = self . _map_and_prefix_keys ( keys , key_prefix ) # send out all requests on each server before reading anything dead_servers = [ ] rc = 1 for server in server_keys . iterkeys ( ) : bigcmd = [ ] write = bigcmd . append if time != None :...
def access_token_response ( self , access_token ) : """Returns a successful response after creating the access token as defined in : rfc : ` 5.1 ` ."""
response_data = { 'access_token' : access_token . token , 'token_type' : constants . TOKEN_TYPE , 'expires_in' : access_token . get_expire_delta ( ) , 'scope' : ' ' . join ( scope . names ( access_token . scope ) ) , } # Not all access _ tokens are given a refresh _ token # ( for example , public clients doing password...
def _create_function ( name , doc = "" ) : """Create a PySpark function by its name"""
def _ ( col ) : sc = SparkContext . _active_spark_context jc = getattr ( sc . _jvm . functions , name ) ( col . _jc if isinstance ( col , Column ) else col ) return Column ( jc ) _ . __name__ = name _ . __doc__ = doc return _
def get_historical_prices ( self , ** kwargs ) : """Historical Prices Reference : https : / / iexcloud . io / docs / api / # chart Data Weighting : See IEX Cloud Docs Parameters range : str , default ' 1m ' , optional Chart range to return . See docs . Choose from [ ` 5y ` , ` 2y ` , ` 1y ` , ` ytd ` , ...
def fmt_p ( out ) : result = { } for symbol in self . symbols : d = out . pop ( symbol ) df = pd . DataFrame ( d ) df . set_index ( pd . DatetimeIndex ( df [ "date" ] ) , inplace = True ) values = [ "open" , "high" , "low" , "close" , "volume" ] df = df [ values ] ...
def matrix_multiply ( m1 , m2 ) : """Matrix multiplication ( iterative algorithm ) . The running time of the iterative matrix multiplication algorithm is : math : ` O ( n ^ { 3 } ) ` . : param m1 : 1st matrix with dimensions : math : ` ( n \\ times p ) ` : type m1 : list , tuple : param m2 : 2nd matrix with...
mm = [ [ 0.0 for _ in range ( len ( m2 [ 0 ] ) ) ] for _ in range ( len ( m1 ) ) ] for i in range ( len ( m1 ) ) : for j in range ( len ( m2 [ 0 ] ) ) : for k in range ( len ( m2 ) ) : mm [ i ] [ j ] += float ( m1 [ i ] [ k ] * m2 [ k ] [ j ] ) return mm
def allocate ( n , dtype = numpy . float32 ) : """allocate context - portable pinned host memory"""
return drv . pagelocked_empty ( int ( n ) , dtype , order = 'C' , mem_flags = drv . host_alloc_flags . PORTABLE )
def wrap ( cls , meth ) : '''Wraps a connection opening method in this class .'''
async def inner ( * args , ** kwargs ) : sock = await meth ( * args , ** kwargs ) return cls ( sock ) return inner
def process_ticket ( self ) : """validate ticket from SAML XML body : raises : SamlValidateError : if the ticket is not found or not valid , or if we fail to parse the posted XML . : return : a ticket object : rtype : : class : ` models . Ticket < cas _ server . models . Ticket > `"""
try : auth_req = self . root . getchildren ( ) [ 1 ] . getchildren ( ) [ 0 ] ticket = auth_req . getchildren ( ) [ 0 ] . text ticket = models . Ticket . get ( ticket ) if ticket . service != self . target : raise SamlValidateError ( u'AuthnFailed' , u'TARGET %s does not match ticket service' % s...
def getContacts ( self , only_active = True ) : """Return an array containing the contacts from this Client"""
contacts = self . objectValues ( "Contact" ) if only_active : contacts = filter ( api . is_active , contacts ) return contacts
def _map_to_cfg ( self ) : """Map our current slice to CFG . Based on self . _ statements _ per _ run and self . _ exit _ statements _ per _ run , this method will traverse the CFG and check if there is any missing block on the path . If there is , the default exit of that missing block will be included in th...
exit_statements_per_run = self . chosen_exits new_exit_statements_per_run = defaultdict ( list ) while len ( exit_statements_per_run ) : for block_address , exits in exit_statements_per_run . items ( ) : for stmt_idx , exit_target in exits : if exit_target not in self . chosen_exits : # Oh we fo...
def adapter_add_nio_binding ( self , adapter_number , port_number , nio ) : """Adds a adapter NIO binding . : param adapter _ number : adapter number : param port _ number : port number : param nio : NIO instance to add to the adapter / port"""
try : adapter = self . _adapters [ adapter_number ] except IndexError : raise IOUError ( 'Adapter {adapter_number} does not exist for IOU "{name}"' . format ( name = self . _name , adapter_number = adapter_number ) ) if not adapter . port_exists ( port_number ) : raise IOUError ( "Port {port_number} does no...
def verify_fft_options ( opt , parser ) : """Parses the FFT options and verifies that they are reasonable . Parameters opt : object Result of parsing the CLI with OptionParser , or any object with the required attributes . parser : object OptionParser instance ."""
if opt . fftw_measure_level not in [ 0 , 1 , 2 , 3 ] : parser . error ( "{0} is not a valid FFTW measure level." . format ( opt . fftw_measure_level ) ) if opt . fftw_import_system_wisdom and ( ( opt . fftw_input_float_wisdom_file is not None ) or ( opt . fftw_input_double_wisdom_file is not None ) ) : parser ....
def get_subnet_nwk_excl ( self , tenant_id , excl_list , excl_part = False ) : """Retrieve the subnets of a network . Get the subnets inside a network after applying the exclusion list ."""
net_list = self . get_network_by_tenant ( tenant_id ) ret_subnet_list = [ ] for net in net_list : if excl_part : name = net . get ( 'name' ) part = name . partition ( '::' ) [ 2 ] if part : continue subnet_lst = self . get_subnets_for_net ( net . get ( 'id' ) ) for subnet...
def create_from_intermediate ( cls , crypto , intermediate_point , seed , compressed = True , include_cfrm = True ) : """Given an intermediate point , given to us by " owner " , generate an address and encrypted private key that can be decoded by the passphrase used to generate the intermediate point ."""
flagbyte = b'\x20' if compressed else b'\x00' payload = b58decode_check ( str ( intermediate_point ) ) ownerentropy = payload [ 8 : 16 ] passpoint = payload [ 16 : - 4 ] x , y = uncompress ( passpoint ) if not is_py2 : seed = bytes ( seed , 'ascii' ) seedb = hexlify ( sha256 ( seed ) . digest ( ) ) [ : 24 ] factorb...
def get_es_label ( obj , def_obj ) : """Returns object with label for an object that goes into the elacticsearch ' label ' field args : obj : data object to update def _ obj : the class instance that has defintion values"""
label_flds = LABEL_FIELDS if def_obj . es_defs . get ( 'kds_esLabel' ) : label_flds = def_obj . es_defs [ 'kds_esLabel' ] + LABEL_FIELDS try : for label in label_flds : if def_obj . cls_defs . get ( label ) : obj [ 'label' ] = def_obj . cls_defs [ label ] [ 0 ] break if not o...
def get_events ( self , from_ = None , to = None ) : """Query a slice of the events . Events are always returned in the order the were added . Parameters : from _ - - if not None , return only events added after the event with id ` from _ ` . If None , return from the start of history . to - - if not None...
assert from_ is None or isinstance ( from_ , str ) assert to is None or isinstance ( to , str ) if from_ and not self . key_exists ( from_ ) : msg = 'from_={0}' . format ( from_ ) raise EventStore . EventKeyDoesNotExistError ( msg ) if to and not self . key_exists ( to ) : msg = 'to={0}' . format ( to ) ...
def error ( self , line_number , offset , text , check ) : """Run the checks and collect the errors ."""
code = super ( _Report , self ) . error ( line_number , offset , text , check ) if code : self . errors . append ( ( line_number , offset + 1 , code , text , check ) )
def get_function_id ( sig ) : '''Return the function id of the given signature Args : sig ( str ) Return : ( int )'''
s = sha3 . keccak_256 ( ) s . update ( sig . encode ( 'utf-8' ) ) return int ( "0x" + s . hexdigest ( ) [ : 8 ] , 16 )
def _map_update ( self , prior_mean , prior_cov , global_cov_scaled , new_observation ) : """Maximum A Posterior ( MAP ) update of a parameter Parameters prior _ mean : float or 1D array Prior mean of parameters . prior _ cov : float or 1D array Prior variance of scalar parameter , or prior covariance o...
common = np . linalg . inv ( prior_cov + global_cov_scaled ) observation_mean = np . mean ( new_observation , axis = 1 ) posterior_mean = prior_cov . dot ( common . dot ( observation_mean ) ) + global_cov_scaled . dot ( common . dot ( prior_mean ) ) posterior_cov = prior_cov . dot ( common . dot ( global_cov_scaled ) )...
def merge_lists ( * args ) : """Merge an arbitrary number of lists into a single list and dedupe it Args : * args : Two or more lists Returns : A deduped merged list of all the provided lists as a single list"""
out = { } for contacts in filter ( None , args ) : for contact in contacts : out [ contact . value ] = contact return list ( out . values ( ) )
def add_children ( self , root ) : """Add child objects using the factory"""
for c in root . getChildren ( ns = wsdlns ) : child = Factory . create ( c , self ) if child is None : continue self . children . append ( child ) if isinstance ( child , Import ) : self . imports . append ( child ) continue if isinstance ( child , Types ) : self . ty...
def has_provider_support ( provider , media_type ) : """Verifies if API provider has support for requested media type"""
if provider . lower ( ) not in API_ALL : return False provider_const = "API_" + media_type . upper ( ) return provider in globals ( ) . get ( provider_const , { } )
def main_build_index ( args = [ ] , prog_name = sys . argv [ 0 ] ) : """main entry point for the index script . : param args : the arguments for this script , as a list of string . Should already have had the script name stripped . That is , if there are no args provided , this should be an empty list . : p...
# get options and arguments ui = getUI_build_index ( prog_name , args ) # just run unit tests if ui . optionIsSet ( "test" ) : unittest . main ( argv = [ sys . argv [ 0 ] ] ) sys . exit ( ) # just show help if ui . optionIsSet ( "help" ) : ui . usage ( ) sys . exit ( ) verbose = ( ui . optionIsSet ( "ve...
def dashfn ( handle , lenout = _default_len_out ) : """Return the name of the DAS file associated with a handle . https : / / naif . jpl . nasa . gov / pub / naif / toolkit _ docs / C / cspice / dashfn _ c . html : param handle : Handle of a DAS file . : type handle : int : param lenout : Length of output f...
handle = ctypes . c_int ( handle ) namlen = ctypes . c_int ( lenout ) fname = stypes . stringToCharP ( lenout ) libspice . dashfn_c ( handle , namlen , fname ) return stypes . toPythonString ( fname )
def forget ( self ) : """Reset _ observed events . Remove self from observers . : return : Nothing"""
self . _observed_events = { } if self in self . _observers : self . _observers . remove ( self )
def get_bucket_file_list ( self ) : """Little utility method that handles pagination and returns all objects in given bucket ."""
logger . debug ( "Retrieving bucket object list" ) paginator = self . s3_client . get_paginator ( 'list_objects' ) options = { 'Bucket' : self . aws_bucket_name } if self . aws_bucket_prefix : logger . debug ( "Adding prefix {} to bucket list as a filter" . format ( self . aws_bucket_prefix ) ) options [ 'Prefi...
def get_tables ( self ) : """Get all table names . Returns ` set ` of ` str `"""
self . cursor . execute ( 'SELECT name FROM sqlite_master WHERE type="table"' ) return set ( x [ 0 ] for x in self . cursor . fetchall ( ) )
def clicks ( times , fs , click = None , length = None ) : """Returns a signal with the signal ' click ' placed at each specified time Parameters times : np . ndarray times to place clicks , in seconds fs : int desired sampling rate of the output signal click : np . ndarray click signal , defaults to ...
# Create default click signal if click is None : # 1 kHz tone , 100ms click = np . sin ( 2 * np . pi * np . arange ( fs * .1 ) * 1000 / ( 1. * fs ) ) # Exponential decay click *= np . exp ( - np . arange ( fs * .1 ) / ( fs * .01 ) ) # Set default length if length is None : length = int ( times . max ( )...
def addDerivedMSCal ( msname ) : """Add the derived columns like HA to an MS or CalTable . It adds the columns HA , HA1 , HA2 , PA1 , PA2 , LAST , LAST1 , LAST2 , AZEL1, AZEL2 , and UVW _ J2000. They are all bound to the DerivedMSCal virtual data manager . It fails if one of the columns already exists ."""
# Open the MS t = table ( msname , readonly = False , ack = False ) colnames = t . colnames ( ) # Check that the columns needed by DerivedMSCal are present . # Note that ANTENNA2 and FEED2 are not required . for col in [ "TIME" , "ANTENNA1" , "FIELD_ID" , "FEED1" ] : if col not in colnames : raise ValueErro...
def toTheOrdinal ( n , inTitleCase = True ) : """Returns the definite article with the ordinal name of a number e . g . ' the second ' Becomes important for languages with multiple definite articles ( e . g . French )"""
if n == - 1 : retval = _ ( "the last" ) elif n == - 2 : retval = _ ( "the penultimate" ) elif n == 1 : retval = _ ( "the first" ) elif n == 2 : retval = _ ( "the second" ) elif n == 3 : retval = _ ( "the third" ) elif n == 4 : retval = _ ( "the fourth" ) elif n == 5 : retval = _ ( "the fifth...
def sort ( self , sortlist , name = '' , limit = 0 , offset = 0 , style = 'Python' ) : """Sort the table and return the result as a reference table . This method sorts the table . It forms a ` TaQL < . . / . . / doc / 199 . html > ` _ command from the given arguments and executes it using the : func : ` taq...
command = 'select from $1 orderby ' + sortlist if limit > 0 : command += ' limit %d' % limit if offset > 0 : command += ' offset %d' % offset if name : command += ' giving ' + name return tablecommand ( command , style , [ self ] )
def scale ( config = None , name = None , replicas = None ) : """Scales the number of pods in the specified K8sReplicationController to the desired replica count . : param config : an instance of K8sConfig : param name : the name of the ReplicationController we want to scale . : param replicas : the desired n...
rc = K8sReplicationController ( config = config , name = name ) . get ( ) rc . desired_replicas = replicas rc . update ( ) rc . _wait_for_desired_replicas ( ) return rc
def interp ( var , indexes_coords , method , ** kwargs ) : """Make an interpolation of Variable Parameters var : Variable index _ coords : Mapping from dimension name to a pair of original and new coordinates . Original coordinates should be sorted in strictly ascending order . Note that all the coordin...
if not indexes_coords : return var . copy ( ) # simple speed up for the local interpolation if method in [ 'linear' , 'nearest' ] : var , indexes_coords = _localize ( var , indexes_coords ) # default behavior kwargs [ 'bounds_error' ] = kwargs . get ( 'bounds_error' , False ) # target dimensions dims = list ( i...
def release ( self , xcoord , ycoord ) : """Release previously issued tap ' and hold ' command at specified location . : Args : - xcoord : X Coordinate to release . - ycoord : Y Coordinate to release ."""
self . _actions . append ( lambda : self . _driver . execute ( Command . TOUCH_UP , { 'x' : int ( xcoord ) , 'y' : int ( ycoord ) } ) ) return self
def get_python_args ( fname , python_args , interact , debug , end_args ) : """Construct Python interpreter arguments"""
p_args = [ ] if python_args is not None : p_args += python_args . split ( ) if interact : p_args . append ( '-i' ) if debug : p_args . extend ( [ '-m' , 'pdb' ] ) if fname is not None : if os . name == 'nt' and debug : # When calling pdb on Windows , one has to replace backslashes by # slashes to av...
def _jog ( self , axis , direction , step ) : """Move the pipette on ` axis ` in ` direction ` by ` step ` and update the position tracker"""
jog ( axis , direction , step , self . hardware , self . _current_mount ) self . current_position = self . _position ( ) return 'Jog: {}' . format ( [ axis , str ( direction ) , str ( step ) ] )
def as_plural ( result_key ) : """Given a result key , return in the plural form ."""
# Not at all guaranteed to work in all cases . . . if result_key . endswith ( 'y' ) : return re . sub ( "y$" , "ies" , result_key ) elif result_key . endswith ( 'address' ) : return result_key + 'es' elif result_key . endswith ( 'us' ) : return re . sub ( "us$" , "uses" , result_key ) elif not result_key . ...
def char_code ( columns , name = None ) : """Character set code field . : param name : name for the field : return : an instance of the Character set code field rules"""
if name is None : name = 'Char Code Field (' + str ( columns ) + ' columns)' if columns <= 0 : raise BaseException ( ) char_sets = None for char_set in _tables . get_data ( 'character_set' ) : regex = '[ ]{' + str ( 15 - len ( char_set ) ) + '}' + char_set if char_sets is None : char_sets = rege...
def airport_codes ( ) : """Returns the set of airport codes that is available to be requested ."""
html = requests . get ( URL ) . text data_block = _find_data_block ( html ) return _airport_codes_from_data_block ( data_block )
def debug_ratelimit ( g ) : """Log debug of github ratelimit information from last API call Parameters org : github . MainClass . Github github object"""
assert isinstance ( g , github . MainClass . Github ) , type ( g ) debug ( "github ratelimit: {rl}" . format ( rl = g . rate_limiting ) )