signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def get_associated_profile_names ( profile_path , result_role , org_vm , server , include_classnames = False ) : """Get the Associated profiles and return the string names ( org : name : version ) for each profile as a list ."""
insts = get_associated_profiles ( profile_path , result_role , server ) names = [ ] for inst in insts : if include_classnames : names . append ( "(%s)%s" % ( inst . classname , profile_name ( org_vm , inst ) ) ) else : names . append ( profile_name ( org_vm , inst ) ) return names
def get_template_sources ( self , template_name , template_dirs = None ) : """Returns the absolute paths to " template _ name " in the specified app . If the name does not contain an app name ( no colon ) , an empty list is returned . The parent FilesystemLoader . load _ template _ source ( ) will take care ...
if ':' not in template_name : return [ ] app_name , template_name = template_name . split ( ":" , 1 ) template_dir = get_app_template_dir ( app_name ) if template_dir : try : from django . template import Origin origin = Origin ( name = join ( template_dir , template_name ) , template_name = tem...
def transaction ( self , request ) : """Ideally at this method , you will check the caller reference against a user id or uniquely identifiable attribute ( if you are already not using it as the caller reference ) and the type of transaction ( either pay , reserve etc ) . For the sake of the example , we ...
request_url = request . build_absolute_uri ( ) parsed_url = urlparse . urlparse ( request_url ) query = parsed_url . query dd = dict ( map ( lambda x : x . split ( "=" ) , query . split ( "&" ) ) ) resp = self . purchase ( 100 , dd ) return HttpResponseRedirect ( "%s?status=%s" % ( reverse ( "app_offsite_amazon_fps" ) ...
def pts_on_bezier_curve ( P = [ ( 0.0 , 0.0 ) ] , n_seg = 0 ) : '''Return list N + 1 points representing N line segments on bezier curve defined by control points P .'''
assert isinstance ( P , list ) assert len ( P ) > 0 for p in P : assert isinstance ( p , tuple ) for i in p : assert len ( p ) > 1 assert isinstance ( i , float ) assert isinstance ( n_seg , int ) assert n_seg >= 0 return [ pt_on_bezier_curve ( P , float ( i ) / n_seg ) for i in range ( n_seg ) ...
def tempoAdjust2 ( self , tempoFactor ) : """Adjust tempo by aggregating active basal cell votes for pre vs . post : param tempoFactor : scaling signal to MC clock from last sequence item : return : adjusted scaling signal"""
late_votes = ( len ( self . adtm . getNextBasalPredictedCells ( ) ) - len ( self . apicalIntersect ) ) * - 1 early_votes = len ( self . apicalIntersect ) votes = late_votes + early_votes print ( 'vote tally' , votes ) if votes > 0 : tempoFactor = tempoFactor * 0.5 print 'speed up' elif votes < 0 : tempoFact...
def get_raw ( self ) : """: rtype : bytearray"""
buff = bytearray ( ) buff += writesleb128 ( self . size ) for i in self . handlers : buff += i . get_raw ( ) if self . size <= 0 : buff += writeuleb128 ( self . catch_all_addr ) return buff
def saturation_equivalent_potential_temperature ( pressure , temperature ) : r"""Calculate saturation equivalent potential temperature . This calculation must be given an air parcel ' s pressure and temperature . The implementation uses the formula outlined in [ Bolton1980 ] _ for the equivalent potential tem...
t = temperature . to ( 'kelvin' ) . magnitude p = pressure . to ( 'hPa' ) . magnitude e = saturation_vapor_pressure ( temperature ) . to ( 'hPa' ) . magnitude r = saturation_mixing_ratio ( pressure , temperature ) . magnitude th_l = t * ( 1000 / ( p - e ) ) ** mpconsts . kappa th_es = th_l * np . exp ( ( 3036. / t - 1....
def recognized_release ( self ) : """Check if this Release value is something we can parse . : rtype : bool"""
_ , _ , rest = self . get_release_parts ( ) # If " rest " is not a well - known value here , then this package is # using a Release value pattern we cannot recognize . if rest == '' or re . match ( r'%{\??dist}' , rest ) : return True return False
def load ( self ) : """Loads a user ' s inventory Queries the user ' s inventory , parses each item , and adds each item to the inventory . Note this class should not be used directly , but rather usr . inventory should be used to access a user ' s inventory . Parameters usr ( User ) - The user to load ...
self . items = { } pg = self . usr . getPage ( "http://www.neopets.com/objects.phtml?type=inventory" ) # Indicates an empty inventory if "You aren't carrying anything" in pg . content : return try : for row in pg . find_all ( "td" , "contentModuleContent" ) [ 1 ] . table . find_all ( "tr" ) : for item i...
def copy ( self , other ) : """Copy metadata from another : py : class : ` Metadata ` object . Returns the : py : class : ` Metadata ` object , allowing convenient code like this : : md = Metadata ( ) . copy ( other _ md ) : param Metadata other : The metadata to copy . : rtype : : py : class : ` Metadata...
# copy from other to self self . data . update ( other . data ) if other . comment is not None : self . comment = other . comment return self
def get_reversed_statuses ( context ) : """Return a mapping of exit codes to status strings . Args : context ( scriptworker . context . Context ) : the scriptworker context Returns : dict : the mapping of exit codes to status strings ."""
_rev = { v : k for k , v in STATUSES . items ( ) } _rev . update ( dict ( context . config [ 'reversed_statuses' ] ) ) return _rev
def _incoming ( self , packet ) : """Callback for data received from the copter ."""
if len ( packet . data ) < 1 : logger . warning ( 'Localization packet received with incorrect' + 'length (length is {})' . format ( len ( packet . data ) ) ) return pk_type = struct . unpack ( '<B' , packet . data [ : 1 ] ) [ 0 ] data = packet . data [ 1 : ] # Decoding the known packet types # TODO : more gene...
def Description ( self ) : """Returns searchable data as Description"""
descr = " " . join ( ( self . getId ( ) , self . aq_parent . Title ( ) ) ) return safe_unicode ( descr ) . encode ( 'utf-8' )
def firstAnnot ( self ) : """Points to first annotation on page"""
CheckParent ( self ) val = _fitz . Page_firstAnnot ( self ) if val : val . thisown = True val . parent = weakref . proxy ( self ) # owning page object self . _annot_refs [ id ( val ) ] = val return val
def resample ( old_wavelengths , new_wavelengths ) : """Resample a spectrum to a new wavelengths map while conserving total flux . : param old _ wavelengths : The original wavelengths array . : type old _ wavelengths : : class : ` numpy . array ` : param new _ wavelengths : The new wavelengths array to ...
data = [ ] old_px_indices = [ ] new_px_indices = [ ] for i , new_wl_i in enumerate ( new_wavelengths ) : # These indices should span just over the new wavelength pixel . indices = np . unique ( np . clip ( old_wavelengths . searchsorted ( new_wavelengths [ i : i + 2 ] , side = "left" ) + [ - 1 , + 1 ] , 0 , old_wav...
def update_ptr_record ( self , device , record , domain_name , data = None , ttl = None , comment = None ) : """Updates a PTR record with the supplied values ."""
device_type = self . _resolve_device_type ( device ) href , svc_name = self . _get_ptr_details ( device , device_type ) try : rec_id = record . id except AttributeError : rec_id = record rec = { "name" : domain_name , "id" : rec_id , "type" : "PTR" , "data" : data , } if ttl is not None : # Minimum TTL is 300 s...
def setArg ( self , namespace , key , value ) : """Set a single argument in this namespace"""
assert key is not None assert value is not None namespace = self . _fixNS ( namespace ) # try to ensure that internally it ' s consistent , at least : str - > str if isinstance ( value , bytes ) : value = str ( value , encoding = "utf-8" ) self . args [ ( namespace , key ) ] = value if not ( namespace is BARE_NS ) ...
def get_crystal_system ( self ) : """Get the crystal system for the structure , e . g . , ( triclinic , orthorhombic , cubic , etc . ) . Returns : ( str ) : Crystal system for structure or None if system cannot be detected ."""
n = self . _space_group_data [ "number" ] f = lambda i , j : i <= n <= j cs = { "triclinic" : ( 1 , 2 ) , "monoclinic" : ( 3 , 15 ) , "orthorhombic" : ( 16 , 74 ) , "tetragonal" : ( 75 , 142 ) , "trigonal" : ( 143 , 167 ) , "hexagonal" : ( 168 , 194 ) , "cubic" : ( 195 , 230 ) } crystal_sytem = None for k , v in cs . i...
def solve ( self ) : """Start ( or re - start ) optimisation . This method implements the framework for the alternation between ` X ` and ` D ` updates in a dictionary learning algorithm . If option ` ` Verbose ` ` is ` ` True ` ` , the progress of the optimisation is displayed at every iteration . At termi...
# Construct tuple of status display column titles and set status # display strings hdrtxt = [ 'Itn' , 'Fnc' , 'DFid' , u ( 'Regℓ1' ) ] hdrstr , fmtstr , nsep = common . solve_status_str ( hdrtxt , fwdth0 = type ( self ) . fwiter , fprec = type ( self ) . fpothr ) # Print header and separator strings if self . opt [ 'Ve...
def stopThread ( self ) : """Stops spawned NSThread ."""
if self . _thread is not None : self . performSelector_onThread_withObject_waitUntilDone_ ( 'stopPowerNotificationsThread' , self . _thread , None , objc . YES ) self . _thread = None
def __getFormat ( self , format ) : """Defaults to JSON [ ps : ' RDF ' is the native rdflib representation ]"""
if format == "XML" : self . sparql . setReturnFormat ( XML ) self . format = "XML" elif format == "RDF" : self . sparql . setReturnFormat ( RDF ) self . format = "RDF" else : self . sparql . setReturnFormat ( JSON ) self . format = "JSON"
def init ( ) : """Execute init tasks for all components ( virtualenv , pip ) ."""
print ( yellow ( "# Setting up development environment...\n" , True ) ) virtualenv . init ( ) virtualenv . update ( ) print ( green ( "\n# DONE." , True ) ) print ( green ( "Type " ) + green ( "activate" , True ) + green ( " to enable your dev virtual environment." ) )
def maybe_sendraw ( self , host_port : Tuple [ int , int ] , messagedata : bytes ) : """Send message to recipient if the transport is running ."""
# Don ' t sleep if timeout is zero , otherwise a context - switch is done # and the message is delayed , increasing its latency sleep_timeout = self . throttle_policy . consume ( 1 ) if sleep_timeout : gevent . sleep ( sleep_timeout ) # Check the udp socket is still available before trying to send the # message . T...
def run_outdated ( cls , options ) : """Print outdated user packages ."""
latest_versions = sorted ( cls . find_packages_latest_versions ( cls . options ) , key = lambda p : p [ 0 ] . project_name . lower ( ) ) for dist , latest_version , typ in latest_versions : if latest_version > dist . parsed_version : if options . all : pass elif options . pinned : ...
def disable_node ( self , service_name , node_name ) : """Disables a given node name for the given service name via the " disable server " HAProxy command ."""
logger . info ( "Disabling server %s/%s" , service_name , node_name ) return self . send_command ( "disable server %s/%s" % ( service_name , node_name ) )
def parse_transform ( transform_str ) : """Converts a valid SVG transformation string into a 3x3 matrix . If the string is empty or null , this returns a 3x3 identity matrix"""
if not transform_str : return np . identity ( 3 ) elif not isinstance ( transform_str , str ) : raise TypeError ( 'Must provide a string to parse' ) total_transform = np . identity ( 3 ) transform_substrs = transform_str . split ( ')' ) [ : - 1 ] # Skip the last element , because it should be empty for substr i...
def frontend_routing ( self , context ) : """Returns the targeted frontend and original state : type context : satosa . context . Context : rtype satosa . frontends . base . FrontendModule : param context : The response context : return : frontend"""
target_frontend = context . state [ STATE_KEY ] satosa_logging ( logger , logging . DEBUG , "Routing to frontend: %s " % target_frontend , context . state ) context . target_frontend = target_frontend frontend = self . frontends [ context . target_frontend ] [ "instance" ] return frontend
def item_links_addition ( self , data ) : """Add the links for each community ."""
links_item_factory = self . context . get ( 'links_item_factory' , default_links_item_factory ) data [ 'links' ] = links_item_factory ( data ) return data
def tenant_quota_usages ( request , tenant_id = None , targets = None ) : """Get our quotas and construct our usage object . : param tenant _ id : Target tenant ID . If no tenant _ id is provided , a the request . user . project _ id is assumed to be used . : param targets : A tuple of quota names to be retri...
if not tenant_id : tenant_id = request . user . project_id disabled_quotas = get_disabled_quotas ( request , targets ) usages = QuotaUsage ( ) futurist_utils . call_functions_parallel ( ( _get_tenant_compute_usages , [ request , usages , disabled_quotas , tenant_id ] ) , ( _get_tenant_network_usages , [ request , u...
def load_descendant_articles_for_section ( context , section , featured_in_homepage = None , featured_in_section = None , featured_in_latest = None , count = 5 ) : """Returns all descendant articles ( filtered using the parameters ) If the ` locale _ code ` in the context is not the main language , it will retu...
request = context . get ( 'request' ) locale = context . get ( 'locale_code' ) page = section . get_main_language_page ( ) settings = SiteSettings . for_site ( request . site ) if request else None qs = ArticlePage . objects . descendant_of ( page ) . filter ( language__is_main_language = True ) article_ordering = sett...
def insertBefore ( self , child , beforeChild ) : '''insertBefore - Inserts a child before # beforeChild @ param child < AdvancedTag / str > - Child block to insert @ param beforeChild < AdvancedTag / str > - Child block to insert before . if None , will be appended @ return - The added child . Note , if it i...
# When the second arg is null / None , the node is appended . The argument is required per JS API , but null is acceptable . . if beforeChild is None : return self . appendBlock ( child ) # If # child is an AdvancedTag , we need to add it to both blocks and children . isChildTag = isTagNode ( child ) myBlocks = sel...
def _build_src_index ( self ) : """Build an indices for fast lookup of a source given its name or coordinates ."""
self . _srcs = sorted ( self . _srcs , key = lambda t : t [ 'offset' ] ) nsrc = len ( self . _srcs ) radec = np . zeros ( ( 2 , nsrc ) ) for i , src in enumerate ( self . _srcs ) : radec [ : , i ] = src . radec self . _src_skydir = SkyCoord ( ra = radec [ 0 ] , dec = radec [ 1 ] , unit = u . deg ) self . _src_radiu...
def __execute_sext ( self , instr ) : """Execute SEXT instruction ."""
op0_size = instr . operands [ 0 ] . size op2_size = instr . operands [ 2 ] . size op0_val = self . read_operand ( instr . operands [ 0 ] ) op0_msb = extract_sign_bit ( op0_val , op0_size ) op2_mask = ( 2 ** op2_size - 1 ) & ~ ( 2 ** op0_size - 1 ) if op0_msb == 1 else 0x0 op2_val = op0_val | op2_mask self . write_opera...
def _builtin_from_array_list ( required_type , value , list_level ) : """Helper method to make : func : ` from _ array _ list ` available to all classes extending this , without the need for additional imports . : param required _ type : Type as what it should be parsed as . Any builtin . : param value : The ...
return from_array_list ( required_type , value , list_level , is_builtin = True )
def next_chunk ( self ) : """Returns the chunk immediately following ( and adjacent to ) this one ."""
raise NotImplementedError ( "%s not implemented for %s" % ( self . next_chunk . __func__ . __name__ , self . __class__ . __name__ ) )
def flatten_blocks ( lines , num_indents = - 1 ) : """Take a list ( block ) or string ( statement ) and flattens it into a string with indentation ."""
# The standard indent is four spaces INDENTATION = " " * 4 if not lines : return "" # If this is a string , add the indentation and finish here if isinstance ( lines , six . string_types ) : return INDENTATION * num_indents + lines # If this is not a string , join the lines and recurse return "\n" . join ( [ fl...
def MafMotifSelect ( mafblock , pwm , motif = None , threshold = 0 ) : if motif != None and len ( motif ) != len ( pwm ) : raise Exception ( "pwm and motif must be the same length" ) # generic alignment alignlist = [ c . text for c in mafblock . components ] align = pwmx . Align ( alignlist ) ...
def get_region ( service , region , profile ) : """Retrieve the region for a particular AWS service based on configured region and / or profile ."""
_ , region , _ , _ = _get_profile ( service , region , None , None , profile ) return region
def find_closest_calculated_frequencies ( input_freqs , metric_freqs ) : """Given a value ( or array ) of input frequencies find the closest values in the list of frequencies calculated in the metric . Parameters input _ freqs : numpy . array or float The frequency ( ies ) that you want to find the closest ...
try : refEv = numpy . zeros ( len ( input_freqs ) , dtype = float ) except TypeError : refEv = numpy . zeros ( 1 , dtype = float ) input_freqs = numpy . array ( [ input_freqs ] ) if len ( metric_freqs ) == 1 : refEv [ : ] = metric_freqs [ 0 ] return refEv # FIXME : This seems complicated for what is...
def sorted ( self ) : """Return a ( start , end ) tuple where start < = end ."""
if self . start < self . end : return self . start , self . end else : return self . end , self . start
def dumps ( self , cnf , ** kwargs ) : """Dump config ' cnf ' to a string . : param cnf : Configuration data to dump : param kwargs : optional keyword parameters to be sanitized : : dict : return : string represents the configuration"""
kwargs = anyconfig . utils . filter_options ( self . _dump_opts , kwargs ) return self . dump_to_string ( cnf , ** kwargs )
def email_embed_image ( email , img_content_id , img_data ) : """email is a django . core . mail . EmailMessage object"""
img = MIMEImage ( img_data ) img . add_header ( 'Content-ID' , '<%s>' % img_content_id ) img . add_header ( 'Content-Disposition' , 'inline' ) email . attach ( img )
def deprecated ( func ) : '''This is a decorator which can be used to mark functions as deprecated . It will result in a warning being emitted when the function is used . https : / / wiki . python . org / moin / PythonDecoratorLibrary # Generating _ Deprecation _ Warnings'''
def new_func ( * args , ** kwargs ) : warn ( "Call to deprecated function {}." . format ( func . __name__ ) , category = DeprecationWarning ) return func ( * args , ** kwargs ) new_func . __name__ = func . __name__ new_func . __doc__ = func . __doc__ new_func . __dict__ . update ( func . __dict__ ) return new_f...
def plot_freq ( self , x , y , title = '' , ylabel = None , scale = 'semilogy' ) : """Plot mean frequency spectrum and display in dialog . Parameters x : list vector with frequencies y : ndarray vector with amplitudes title : str plot title ylabel : str plot y label scale : str semilogy , logl...
freq = self . frequency scaling = freq [ 'scaling' ] . get_value ( ) if ylabel is None : if freq [ 'complex' ] . get_value ( ) : ylabel = 'Amplitude (uV)' elif 'power' == scaling : ylabel = 'Power spectral density (uV ** 2 / Hz)' elif 'energy' == scaling : ylabel = 'Energy spectral d...
def install_firmware ( self , firmware_information ) : """Installs firmware to a logical interconnect . The three operations that are supported for the firmware update are Stage ( uploads firmware to the interconnect ) , Activate ( installs firmware on the interconnect ) , and Update ( which does a Stage and Ac...
firmware_uri = self . _helper . build_subresource_uri ( self . data [ "uri" ] , subresource_path = self . FIRMWARE_PATH ) return self . _helper . update ( firmware_information , firmware_uri )
def _read_with_sitk ( datapath ) : """Reads file using SimpleITK . Returns array of pixels ( image located in datapath ) and its metadata . : param datapath : path to file ( img or dicom ) : return : tuple ( data3d , metadata ) , where data3d is array of pixels"""
try : import SimpleITK as Sitk except ImportError as e : logger . error ( "Unable to import SimpleITK. On Windows try version 1.0.1" ) image = Sitk . ReadImage ( datapath ) data3d = dcmtools . get_pixel_array_from_sitk ( image ) # data3d , original _ dtype = dcmreaddata . get _ pixel _ array _ from _ dcmobj ( i...
def set_clear_color ( self , color = 'black' , alpha = None ) : """Set the screen clear color This is a wrapper for gl . glClearColor . Parameters color : str | tuple | instance of Color Color to use . See vispy . color . Color for options . alpha : float | None Alpha to use ."""
self . glir . command ( 'FUNC' , 'glClearColor' , * Color ( color , alpha ) . rgba )
def _plot ( self ) : """Plot all dots for series"""
r_max = min ( self . view . x ( 1 ) - self . view . x ( 0 ) , ( self . view . y ( 0 ) or 0 ) - self . view . y ( 1 ) ) / ( 2 * 1.05 ) for serie in self . series : self . dot ( serie , r_max )
def seqannotation ( self , seqrecord , allele , loc ) : """Gets the Annotation from the found sequence : return : The Annotation from the found sequence : rtype : Annotation"""
# seqrecord = self . seqrecord ( allele , loc ) complete_annotation = get_features ( seqrecord ) annotation = Annotation ( annotation = complete_annotation , method = 'match' , complete_annotation = True ) if self . alignments : alignment = { f : self . annoated_alignments [ loc ] [ allele ] [ f ] [ 'Seq' ] for f i...
def fix_fasta ( fasta ) : """remove pesky characters from fasta file header"""
for seq in parse_fasta ( fasta ) : seq [ 0 ] = remove_char ( seq [ 0 ] ) if len ( seq [ 1 ] ) > 0 : yield seq
def symbol_list ( what_list ) : '''provide default symbol lists Parameters what _ list : string String name of symbol lists provided ; " list1 " , " list2 " , " lines1 " or " lines2 " .'''
if what_list is "list1" : symbol = [ 'ro' , 'bo' , 'ko' , 'go' , 'mo' , 'r-' , 'b-' , 'k-' , 'g-' , 'm-' , 'r--' , 'b--' , 'k--' , 'g--' , 'r1' ] # symbol = [ ' r + ' , ' ro ' , ' r - ' ] elif what_list is "list2" : symbol = [ 'r-' , 'b--' , 'g-.' , 'k:' , 'md' , '.' , 'o' , 'v' , '^' , '<' , '>' , '1' , '2...
def standard_aggregation ( C ) : """Compute the sparsity pattern of the tentative prolongator . Parameters C : csr _ matrix strength of connection matrix Returns AggOp : csr _ matrix aggregation operator which determines the sparsity pattern of the tentative prolongator Cpts : array array of Cpts ...
if not isspmatrix_csr ( C ) : raise TypeError ( 'expected csr_matrix' ) if C . shape [ 0 ] != C . shape [ 1 ] : raise ValueError ( 'expected square matrix' ) index_type = C . indptr . dtype num_rows = C . shape [ 0 ] Tj = np . empty ( num_rows , dtype = index_type ) # stores the aggregate # s Cpts = np . empty ...
def paint ( self , p , * args ) : '''I have no idea why , but we need to generate the picture after painting otherwise it draws incorrectly .'''
if self . picturenotgened : self . generatePicture ( self . getBoundingParents ( ) [ 0 ] . rect ( ) ) self . picturenotgened = False pg . ImageItem . paint ( self , p , * args ) self . generatePicture ( self . getBoundingParents ( ) [ 0 ] . rect ( ) )
def validate ( self , config ) : """Validate the given config against the ` Scheme ` . Args : config ( dict ) : The configuration to validate . Raises : errors . SchemeValidationError : The configuration fails validation against the ` Schema ` ."""
if not isinstance ( config , dict ) : raise errors . SchemeValidationError ( 'Scheme can only validate a dictionary config, but was given ' '{} (type: {})' . format ( config , type ( config ) ) ) for arg in self . args : # the option exists in the config if arg . name in config : arg . validate ( config...
def cbpdn_class_label_lookup ( label ) : """Get a CBPDN class from a label string ."""
clsmod = { 'admm' : admm_cbpdn . ConvBPDN , 'fista' : fista_cbpdn . ConvBPDN } if label in clsmod : return clsmod [ label ] else : raise ValueError ( 'Unknown ConvBPDN solver method %s' % label )
def transaction ( commit = True ) : """Wrap a context with a commit / rollback ."""
try : yield SessionContext . session if commit : SessionContext . session . commit ( ) except Exception : if SessionContext . session : SessionContext . session . rollback ( ) raise
def subscribe ( self , event , hook ) : """Subscribe a callback to an event Parameters event : str Available events are ' precall ' , ' postcall ' , and ' capacity ' . precall is called with : ( connection , command , query _ kwargs ) postcall is called with : ( connection , command , query _ kwargs , res...
if hook not in self . _hooks [ event ] : self . _hooks [ event ] . append ( hook )
def recount_view ( request ) : """Recount number _ of _ messages for all threads and number _ of _ responses for all requests . Also set the change _ date for every thread to the post _ date of the latest message associated with that thread ."""
requests_changed = 0 for req in Request . objects . all ( ) : recount = Response . objects . filter ( request = req ) . count ( ) if req . number_of_responses != recount : req . number_of_responses = recount req . save ( ) requests_changed += 1 threads_changed = 0 for thread in Thread . ...
def encode ( cls , s ) : """converts a plain text string to base64 encoding : param s : unicode str | bytes , the base64 encoded string : returns : unicode str"""
b = ByteString ( s ) be = base64 . b64encode ( b ) . strip ( ) return String ( be )
def _use_tables ( objs ) : '''Whether a collection of Bokeh objects contains a TableWidget Args : objs ( seq [ Model or Document ] ) : Returns : bool'''
from . . models . widgets import TableWidget return _any ( objs , lambda obj : isinstance ( obj , TableWidget ) )
def get ( cls , parent = None , id = None , data = None ) : """Inherit info from parent and return new object"""
# TODO - allow fetching of parent based on child ? if parent is not None : route = copy ( parent . route ) else : route = { } if id is not None and cls . ID_NAME is not None : route [ cls . ID_NAME ] = id obj = cls ( key = parent . key , route = route , config = parent . config ) if data : # This is used in...
def add ( self , tid , result , role , session , oid = None , content = None , anony = None ) : '''taobao . traderate . add 新增单个评价 新增单个评价 ( 注 : 在评价之前需要对订单成功的时间进行判定 ( end _ time ) , 如果超过15天 , 不能再通过该接口进行评价 )'''
request = TOPRequest ( 'taobao.traderate.add' ) request [ 'tid' ] = tid request [ 'result' ] = result request [ 'role' ] = role if oid != None : request [ 'oid' ] = oid if content != None : request [ 'content' ] = content if anony != None : request [ 'anony' ] = anony self . create ( self . execute ( reques...
def get ( self , blocking = True ) : """Gets a connection . Args : blocking : Whether to block when max _ size connections are already in use . If false , may return None . Returns : A connection to the database . Raises : PoolAlreadyClosedError : if close ( ) method was already called on this pool ...
if self . closed : raise PoolAlreadyClosedError ( "Connection pool is already closed." ) # NOTE : Once we acquire capacity from the semaphore , it is essential that we # return it eventually . On success , this responsibility is delegated to # _ ConnectionProxy . if not self . limiter . acquire ( blocking = blockin...
def get_partial_DOS ( self ) : """Return frequency points and partial DOS as a tuple . Projection is done to atoms and may be also done along directions depending on the parameters at run _ partial _ dos . Returns A tuple with ( frequency _ points , partial _ dos ) . frequency _ points : ndarray shape =...
warnings . warn ( "Phonopy.get_partial_DOS is deprecated. " "Use Phonopy.get_projected_dos_dict." , DeprecationWarning ) pdos = self . get_projected_dos_dict ( ) return pdos [ 'frequency_points' ] , pdos [ 'projected_dos' ]
def handle_dump ( args ) : """usage : cosmic - ray dump < session - file > JSON dump of session data . This output is typically run through other programs to produce reports . Each line of output is a list with two elements : a WorkItem and a WorkResult , both JSON - serialized . The WorkResult can be null ...
session_file = get_db_name ( args [ '<session-file>' ] ) with use_db ( session_file , WorkDB . Mode . open ) as database : for work_item , result in database . completed_work_items : print ( json . dumps ( ( work_item , result ) , cls = WorkItemJsonEncoder ) ) for work_item in database . pending_work_it...
def cached_idxs ( method ) : """this function is used as a decorator for caching"""
def method_wrapper ( self , * args , ** kwargs ) : tail = '_' . join ( str ( idx ) for idx in args ) _cache_attr_name = '_cache_' + method . __name__ + '_' + tail _bool_attr_name = '_cached_' + method . __name__ + '_' + tail is_cached = getattr ( self , _bool_attr_name ) if not is_cached : r...
def find_statements ( self , query , language = 'spo' , type = 'triples' , flush = None , limit = None ) : """Run a query in a format supported by the Fedora Resource Index ( e . g . , SPO or Sparql ) and return the results . : param query : query as a string : param language : query language to use ; default...
http_args = { 'type' : type , 'lang' : language , 'query' : query , } if type == 'triples' : result_format = 'N-Triples' elif type == 'tuples' : result_format = 'CSV' if limit is not None : http_args [ 'limit' ] = limit # else - error / exception ? http_args [ 'format' ] = result_format return self . _query...
def swipe ( self , element , x , y , duration = None ) : """Swipe over an element : param element : either a WebElement , PageElement or element locator as a tuple ( locator _ type , locator _ value ) : param x : horizontal movement : param y : vertical movement : param duration : time to take the swipe , i...
if not self . driver_wrapper . is_mobile_test ( ) : raise Exception ( 'Swipe method is not implemented in Selenium' ) # Get center coordinates of element center = self . get_center ( element ) initial_context = self . driver_wrapper . driver . current_context if self . driver_wrapper . is_web_test ( ) or initial_co...
def detect_r_peaks ( ecg_signal , sample_rate , time_units = False , volts = False , resolution = None , device = "biosignalsplux" , plot_result = False ) : """Brief Python implementation of R peak detection algorithm ( proposed by Raja Selvaraj ) . Description Pan - Tompkins algorithm is one of the gold - st...
if volts is True : if resolution is not None : # ecg _ signal = ( ( ecg _ signal / 2 * * resolution ) - 0.5 ) * 3 ecg_signal = raw_to_phy ( "ECG" , device , ecg_signal , resolution , option = "mV" ) else : raise RuntimeError ( "For converting raw units to mV is mandatory the specification of " "...
def users_for_perm ( cls , instance , perm_name , user_ids = None , group_ids = None , limit_group_permissions = False , skip_group_perms = False , db_session = None , ) : """return PermissionTuples for users AND groups that have given permission for the resource , perm _ name is _ _ any _ permission _ _ then u...
# noqa db_session = get_db_session ( db_session , instance ) users_perms = resource_permissions_for_users ( cls . models_proxy , [ perm_name ] , [ instance . resource_id ] , user_ids = user_ids , group_ids = group_ids , limit_group_permissions = limit_group_permissions , skip_group_perms = skip_group_perms , db_session...
def search_first ( self , * criterion , ** kwargs ) : """Returns the first match based on criteria or None ."""
query = self . _query ( * criterion ) query = self . _order_by ( query , ** kwargs ) query = self . _filter ( query , ** kwargs ) # NB : pagination must go last query = self . _paginate ( query , ** kwargs ) return query . first ( )
def stupid_hack ( most = 10 , wait = None ) : """Return a random time between 1 - 10 Seconds ."""
# Stupid Hack For Public Cloud so it is not overwhelmed with API requests . if wait is not None : time . sleep ( wait ) else : time . sleep ( random . randrange ( 1 , most ) )
def gpg_command ( args , env = None ) : """Prepare common GPG command line arguments ."""
if env is None : env = os . environ cmd = get_gnupg_binary ( neopg_binary = env . get ( 'NEOPG_BINARY' ) ) return [ cmd ] + args
def send_apdu ( self , cla , ins , p1 , p2 , data = None , mrl = 0 , check_status = True ) : """Send an ISO / IEC 7816-4 APDU to the Type 4 Tag . The 4 byte APDU header ( class , instruction , parameter 1 and 2) is constructed from the first four parameters ( cla , ins , p1, p2 ) without interpretation . The ...
apdu = bytearray ( [ cla , ins , p1 , p2 ] ) if not self . _extended_length_support : if data and len ( data ) > 255 : raise ValueError ( "unsupported command data length" ) if mrl and mrl > 256 : raise ValueError ( "unsupported max response length" ) if data : apdu += pack ( '>B' , ...
def match_in_kwargs ( self , match_args , kwargs ) : """Matches against kwargs ."""
for match , default in match_args : names = get_match_names ( match ) if names : tempvar = self . get_temp_var ( ) self . add_def ( tempvar + " = " + "" . join ( kwargs + '.pop("' + name + '") if "' + name + '" in ' + kwargs + " else " for name in names ) + default , ) with self . down_a...
def get_devices ( self , refresh = False , generic_type = None ) : """Get all devices from Abode ."""
if refresh or self . _devices is None : if self . _devices is None : self . _devices = { } _LOGGER . info ( "Updating all devices..." ) response = self . send_request ( "get" , CONST . DEVICES_URL ) response_object = json . loads ( response . text ) if ( response_object and not isinstance ( ...
def insert_tasks_ignore_duplicate_names ( tasks , queue , * args , ** kwargs ) : """Insert a batch of tasks into a specific queue . If a DuplicateTaskNameError is raised , loop through the tasks and insert the remaining , ignoring and logging the duplicate tasks . Returns the number of successfully inserted t...
from google . appengine . api import taskqueue try : inserted = _insert_tasks ( tasks , queue , * args , ** kwargs ) return inserted except taskqueue . DuplicateTaskNameError : # At least one task failed in our batch , attempt to re - insert the # remaining tasks . Named tasks can never be transactional . r...
def get ( self , username , width = None , height = None ) : """Retrieve public details on a given user . Note : Supplying the optional w or h parameters will result in the ' custom ' photo URL being added to the ' profile _ image ' object : : param username [ string ] : The user ’ s username . Required . :...
url = "/users/{username}" . format ( username = username ) params = { "w" : width , "h" : height } result = self . _get ( url , params = params ) return UserModel . parse ( result )
def findmin ( psr , method = 'Nelder-Mead' , history = False , formbats = False , renormalize = True , bounds = { } , ** kwargs ) : """Use scipy . optimize . minimize to find minimum - chisq timing solution , passing through all extra options . Resets psr [ . . . ] . val to the final solution , and returns the ...
ctr , err = psr . vals ( ) , psr . errs ( ) # to avoid losing precision , we ' re searching in units of parameter errors if numpy . any ( err == 0.0 ) : print ( "Warning: one or more fit parameters have zero a priori error, and won't be searched." ) hloc , hval = [ ] , [ ] def func ( xs ) : psr . vals ( [ c + x...
def running_covar ( xx = True , xy = False , yy = False , remove_mean = False , symmetrize = False , sparse_mode = 'auto' , modify_data = False , column_selection = None , diag_only = False , nsave = 5 ) : """Returns a running covariance estimator Returns an estimator object that can be fed chunks of X and Y data...
return RunningCovar ( compute_XX = xx , compute_XY = xy , compute_YY = yy , sparse_mode = sparse_mode , modify_data = modify_data , remove_mean = remove_mean , symmetrize = symmetrize , column_selection = column_selection , diag_only = diag_only , nsave = nsave )
def list_all_free_shipping_coupons ( cls , ** kwargs ) : """List FreeShippingCoupons Return a list of FreeShippingCoupons This method makes a synchronous HTTP request by default . To make an asynchronous HTTP request , please pass async = True > > > thread = api . list _ all _ free _ shipping _ coupons ( as...
kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'async' ) : return cls . _list_all_free_shipping_coupons_with_http_info ( ** kwargs ) else : ( data ) = cls . _list_all_free_shipping_coupons_with_http_info ( ** kwargs ) return data
def git_pretty ( ) : """returns a pretty summary of the commit or unkown if not in git repo"""
if git_repo ( ) is None : return "unknown" pretty = subprocess . check_output ( [ "git" , "log" , "--pretty=format:%h %s" , "-n" , "1" ] ) pretty = pretty . decode ( "utf-8" ) pretty = pretty . strip ( ) return pretty
def porosimetry ( im , sizes = 25 , inlets = None , access_limited = True , mode = 'hybrid' ) : r"""Performs a porosimetry simulution on the image Parameters im : ND - array An ND image of the porous material containing True values in the pore space . sizes : array _ like or scalar The sizes to invade ....
if im . ndim != im . squeeze ( ) . ndim : warnings . warn ( 'Input image conains a singleton axis:' + str ( im . shape ) + ' Reduce dimensionality with np.squeeze(im) to avoid' + ' unexpected behavior.' ) dt = spim . distance_transform_edt ( im > 0 ) if inlets is None : inlets = get_border ( im . shape , mode =...
def satisfies ( self , other ) : """Check if the capabilities of a primitive are enough to satisfy a requirement . Should be called on a Requirement that is acting as a capability of a primitive . This method returning true means that the capability advertised here is enough to handle representing the data ...
if other . isnocare : return True if self . isnocare : return False if self . arbitrary : return True if self . constant and not other . arbitrary : return True if self . value is other . value and not other . arbitrary and not other . constant : return True return False
def rounded_rectangle_region ( width , height , radius ) : """Returns a rounded rectangle wx . Region"""
bmp = wx . Bitmap . FromRGBA ( width , height ) # Mask color is # 00000 dc = wx . MemoryDC ( bmp ) dc . Brush = wx . Brush ( ( 255 , ) * 3 ) # Any non - black would do dc . DrawRoundedRectangle ( 0 , 0 , width , height , radius ) dc . SelectObject ( wx . NullBitmap ) bmp . SetMaskColour ( ( 0 , ) * 3 ) return wx . Regi...
def write_sequences_to_xlsx ( path , seqs ) : """Create a XLSX file listing the given sequences . Arguments path : str or pathlib . Path The name of the file to create . seqs : dict A mapping of names to sequences , which can be either protein or DNA ."""
from openpyxl import Workbook wb = Workbook ( ) ws = wb . active for row , id in enumerate ( seqs , 1 ) : ws . cell ( row , 1 ) . value = id ws . cell ( row , 2 ) . value = seqs [ id ] wb . save ( path )
def create_handlers_map ( prefix = '.*' ) : """Create new handlers map . Args : prefix : url prefix to use . Returns : list of ( regexp , handler ) pairs for WSGIApplication constructor ."""
return [ ( prefix + '/output' , _BarrierHandler ) , ( prefix + '/run' , _PipelineHandler ) , ( prefix + '/finalized' , _PipelineHandler ) , ( prefix + '/cleanup' , _CleanupHandler ) , ( prefix + '/abort' , _PipelineHandler ) , ( prefix + '/fanout' , _FanoutHandler ) , ( prefix + '/fanout_abort' , _FanoutAbortHandler ) ...
def number_of_attributes ( self ) : """int : number of attributes ."""
if not self . _is_parsed : self . _Parse ( ) self . _is_parsed = True return len ( self . _attributes )
def confidenceInterval ( n , k , alpha = 0.68 , errorbar = False ) : """Given n tests and k successes , return efficiency and confidence interval ."""
try : e = float ( k ) / float ( n ) except ZeroDivisionError : return np . nan , [ np . nan , np . nan ] bins = 1000001 dx = 1. / bins efficiency = np . linspace ( 0 , 1 , bins ) # MODIFIED FOR LARGE NUMBERS if n + 2 > 1000 : a = gammalnStirling ( n + 2 ) else : a = scipy . special . gammaln ( n + 2 ) i...
def keyring_refresh ( ** kwargs ) : """Refresh the keyring in the cocaine - runtime ."""
ctx = Context ( ** kwargs ) ctx . execute_action ( 'keyring:refresh' , ** { 'tvm' : ctx . repo . create_secure_service ( 'tvm' ) , } )
def warn_or_error ( removal_version , deprecated_entity_description , hint = None , deprecation_start_version = None , stacklevel = 3 , frame_info = None , context = 1 , ensure_stderr = False ) : """Check the removal _ version against the current pants version . Issues a warning if the removal version is > curren...
removal_semver = validate_deprecation_semver ( removal_version , 'removal version' ) if deprecation_start_version : deprecation_start_semver = validate_deprecation_semver ( deprecation_start_version , 'deprecation start version' ) if deprecation_start_semver >= removal_semver : raise InvalidSemanticVers...
def compile ( definition , handlers = { } ) : """Generates validation function for validating JSON schema passed in ` ` definition ` ` . Example : . . code - block : : python import fastjsonschema validate = fastjsonschema . compile ( { ' type ' : ' string ' } ) validate ( ' hello ' ) This implementatio...
resolver , code_generator = _factory ( definition , handlers ) global_state = code_generator . global_state # Do not pass local state so it can recursively call itself . exec ( code_generator . func_code , global_state ) return global_state [ resolver . get_scope_name ( ) ]
def anyword_substring_search ( target_words , query_words ) : """return True if all query _ words match"""
matches_required = len ( query_words ) matches_found = 0 for query_word in query_words : reply = anyword_substring_search_inner ( query_word , target_words ) if reply is not False : matches_found += 1 else : # this is imp , otherwise will keep checking # when the final answer is already False ...
def templateDoc ( self ) : """JSON serializable template to will all necessary details to recreate this stimulus in another session . : returns : dict"""
doc = dict ( self . componentDoc ( False ) . items ( ) + self . testDoc ( ) . items ( ) ) # go through auto - parameter selected components and use location index autoparams = copy . deepcopy ( self . _autoParams . allData ( ) ) for p in autoparams : selection = p [ 'selection' ] serializable_selection = [ ] ...
def reboot ( self , ** params ) : """Reboot outlet Args : params ( dict ) , must contain parameter " outlet " - outlet number Example : params = { ' outlet ' : 1}"""
outlet = params [ 'outlet' ] # main menu self . tn . write ( '\x1b\r\n' ) self . until_done ( ) # Device Manager self . tn . write ( '1\r\n' ) self . until_done ( ) # Outlet Management self . tn . write ( '2\r\n' ) self . until_done ( ) # Outlet Control self . tn . write ( '1\r\n' ) self . until_done ( ) # Select outle...
async def wait_for_body_middleware ( environ , start_response = None ) : '''Use this middleware to wait for the full body . This middleware wait for the full body to be received before letting other middleware to be processed . Useful when using synchronous web - frameworks such as : django : ` django < > ` ....
if environ . get ( 'wsgi.async' ) : try : chunk = await environ [ 'wsgi.input' ] . read ( ) except TypeError : chunk = b'' environ [ 'wsgi.input' ] = BytesIO ( chunk ) environ . pop ( 'wsgi.async' )
def convertReadAlignment ( self , read , readGroupSet , readGroupId ) : """Convert a pysam ReadAlignment to a GA4GH ReadAlignment"""
samFile = self . getFileHandle ( self . _dataUrl ) # TODO fill out remaining fields # TODO refine in tandem with code in converters module ret = protocol . ReadAlignment ( ) # ret . fragmentId = ' TODO ' ret . aligned_quality . extend ( read . query_qualities ) ret . aligned_sequence = read . query_sequence if SamFlags...
def get_reply ( self , method , replyroot ) : """Process the I { reply } for the specified I { method } by unmarshalling it into into Python object ( s ) . @ param method : The name of the invoked method . @ type method : str @ param replyroot : The reply XML root node received after invoking the specifie...
soapenv = replyroot . getChild ( "Envelope" , envns ) soapenv . promotePrefixes ( ) soapbody = soapenv . getChild ( "Body" , envns ) soapbody = self . multiref . process ( soapbody ) nodes = self . replycontent ( method , soapbody ) rtypes = self . returned_types ( method ) if len ( rtypes ) > 1 : return self . rep...
def _assemble_influence ( stmt ) : """Assemble an Influence statement into text ."""
subj_str = _assemble_agent_str ( stmt . subj . concept ) obj_str = _assemble_agent_str ( stmt . obj . concept ) # Note that n is prepended to increase to make it " an increase " if stmt . subj . delta [ 'polarity' ] is not None : subj_delta_str = ' decrease' if stmt . subj . delta [ 'polarity' ] == - 1 else 'n incr...
def read_object_array ( f , data , options ) : """Reads an array of objects recursively . Read the elements of the given HDF5 Reference array recursively in the and constructs a ` ` numpy . object _ ` ` array from its elements , which is returned . Parameters f : h5py . File The HDF5 file handle that is...
# Go through all the elements of data and read them using their # references , and the putting the output in new object array . data_derefed = np . zeros ( shape = data . shape , dtype = 'object' ) for index , x in np . ndenumerate ( data ) : data_derefed [ index ] = read_data ( f , None , None , options , dsetgrp ...