signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def invite_user_view ( self ) : """Allows users to send invitations to register an account"""
invite_user_form = self . InviteUserFormClass ( request . form ) if request . method == 'POST' and invite_user_form . validate ( ) : # Find User and UserEmail by email email = invite_user_form . email . data user , user_email = self . db_manager . get_user_and_user_email_by_email ( email ) if user : ...
def rename_fields ( layer , fields_to_copy ) : """Rename fields inside an attribute table . Only since QGIS 2.16. : param layer : The vector layer . : type layer : QgsVectorLayer : param fields _ to _ copy : Dictionary of fields to copy . : type fields _ to _ copy : dict"""
for field in fields_to_copy : index = layer . fields ( ) . lookupField ( field ) if index != - 1 : layer . startEditing ( ) layer . renameAttribute ( index , fields_to_copy [ field ] ) layer . commitChanges ( ) LOGGER . info ( 'Renaming field %s to %s' % ( field , fields_to_copy ...
def sprite_filepath_build ( sprite_type , sprite_id , ** kwargs ) : """returns the filepath of the sprite * relative to SPRITE _ CACHE *"""
options = parse_sprite_options ( sprite_type , ** kwargs ) filename = '.' . join ( [ str ( sprite_id ) , SPRITE_EXT ] ) filepath = os . path . join ( sprite_type , * options , filename ) return filepath
def stack_smooth ( s_orig , size = 7 , save = False ) : """Run Gaussian smoothing filter on exising stack object"""
from copy import deepcopy from pygeotools . lib import filtlib print ( "Copying original DEMStack" ) s = deepcopy ( s_orig ) s . stack_fn = os . path . splitext ( s_orig . stack_fn ) [ 0 ] + '_smooth%ipx.npz' % size # Loop through each array and smooth print ( "Smoothing all arrays in stack with %i px gaussian filter" ...
def clean ( ) : """Clear out any old screenshots"""
screenshot_dir = settings . SELENIUM_SCREENSHOT_DIR if screenshot_dir and os . path . isdir ( screenshot_dir ) : rmtree ( screenshot_dir , ignore_errors = True )
def list_upgrades ( refresh = True , ** kwargs ) : '''List those packages for which an upgrade is available The ` ` fromrepo ` ` argument is also supported , as used in pkg states . CLI Example : . . code - block : : bash salt ' * ' pkg . list _ upgrades jail List upgrades within the specified jail CL...
jail = kwargs . pop ( 'jail' , None ) chroot = kwargs . pop ( 'chroot' , None ) root = kwargs . pop ( 'root' , None ) fromrepo = kwargs . pop ( 'fromrepo' , None ) cmd = _pkg ( jail , chroot , root ) cmd . extend ( [ 'upgrade' , '--dry-run' , '--quiet' ] ) if not refresh : cmd . append ( '--no-repo-update' ) if fro...
def _cursorRight ( self ) : """Handles " cursor right " events"""
if self . cursorPos < len ( self . inputBuffer ) : self . cursorPos += 1 sys . stdout . write ( console . CURSOR_RIGHT ) sys . stdout . flush ( )
def set_timestamp ( self , data ) : """Interpret time - related options , apply queue - time parameter as needed"""
if 'hittime' in data : # an absolute timestamp data [ 'qt' ] = self . hittime ( timestamp = data . pop ( 'hittime' , None ) ) if 'hitage' in data : # a relative age ( in seconds ) data [ 'qt' ] = self . hittime ( age = data . pop ( 'hitage' , None ) )
def _clean_accents ( self , text ) : """Remove most accent marks . Note that the circumflexes over alphas and iotas in the text since they determine vocalic quantity . : param text : raw text : return : clean text with minimum accent marks : rtype : string"""
accents = { 'ὲέἐἑἒἓἕἔ' : 'ε' , 'ὺύὑὐὒὓὔὕ' : 'υ' , 'ὸόὀὁὂὃὄὅ' : 'ο' , 'ὶίἰἱἲἳἵἴ' : 'ι' , 'ὰάἁἀἂἃἅἄᾳᾂᾃ' : 'α' , 'ὴήἠἡἢἣἥἤἧἦῆῄῂῇῃᾓᾒᾗᾖᾑᾐ' : 'η' , 'ὼώὠὡὢὣὤὥὦὧῶῲῴῷῳᾧᾦᾢᾣᾡᾠ' : 'ω' , 'ἶἷ' : 'ῖ' , 'ἆἇᾷᾆᾇ' : 'ᾶ' , 'ὖὗ' : 'ῦ' , } text = self . _clean_text ( text ) for char in text : for key in accents . keys ( ) : if c...
def WriteStatEntries ( stat_entries , client_id , mutation_pool , token = None ) : """Persists information about stat entries . Args : stat _ entries : A list of ` StatEntry ` instances . client _ id : An id of a client the stat entries come from . mutation _ pool : A mutation pool used for writing into the...
for stat_response in stat_entries : if stat_response . pathspec . last . stream_name : # This is an ads . In that case we always need to create a file or # we won ' t be able to access the data . New clients send the correct mode # already but to make sure , we set this to a regular file anyways . # Cle...
def _get_proxies ( self ) : """Returns the : class : ` ProxyJSON < odoorpc . rpc . jsonrpclib . ProxyJSON > ` and : class : ` ProxyHTTP < odoorpc . rpc . jsonrpclib . ProxyHTTP > ` instances corresponding to the server version used ."""
proxy_json = jsonrpclib . ProxyJSON ( self . host , self . port , self . _timeout , ssl = self . ssl , deserialize = self . deserialize , opener = self . _opener ) proxy_http = jsonrpclib . ProxyHTTP ( self . host , self . port , self . _timeout , ssl = self . ssl , opener = self . _opener ) # Detect the server version...
def result ( self ) : """Formats the result ."""
return { "count" : self . _count , "total" : self . _total , "average" : float ( self . _total ) / self . _count if self . _count else 0 }
def instance_name ( string ) : """Check for valid instance name"""
invalid = ':/@' if set ( string ) . intersection ( invalid ) : msg = 'Invalid instance name {}' . format ( string ) raise argparse . ArgumentTypeError ( msg ) return string
def apply_scaling ( data , dicom_headers ) : """Rescale the data based on the RescaleSlope and RescaleOffset Based on the scaling from pydicomseries : param dicom _ headers : dicom headers to use to retreive the scaling factors : param data : the input data"""
# Apply the rescaling if needed private_scale_slope_tag = Tag ( 0x2005 , 0x100E ) private_scale_intercept_tag = Tag ( 0x2005 , 0x100D ) if 'RescaleSlope' in dicom_headers or 'RescaleIntercept' in dicom_headers or private_scale_slope_tag in dicom_headers or private_scale_intercept_tag in dicom_headers : rescale_slop...
def get_archive ( self , container , path , chunk_size = DEFAULT_DATA_CHUNK_SIZE ) : """Retrieve a file or folder from a container in the form of a tar archive . Args : container ( str ) : The container where the file is located path ( str ) : Path to the file or folder to retrieve chunk _ size ( int ) : ...
params = { 'path' : path } url = self . _url ( '/containers/{0}/archive' , container ) res = self . _get ( url , params = params , stream = True ) self . _raise_for_status ( res ) encoded_stat = res . headers . get ( 'x-docker-container-path-stat' ) return ( self . _stream_raw_result ( res , chunk_size , False ) , util...
def boxplot ( df , category , quantity , category_type = "N" , title = None , xlabel = None , ylabel = None ) : """Plot a simple boxplot using Altair . Parameters df : ` pandas . DataFrame ` Contains columns matching ' category ' and ' quantity ' labels , at a minimum . category : ` string ` The name of t...
# must be one of Nominal , Ordinal , Time per altair if category_type not in ( "N" , "O" , "T" ) : raise OneCodexException ( "If specifying category_type, must be N, O, or T" ) # adapted from https : / / altair - viz . github . io / gallery / boxplot _ max _ min . html lower_box = "q1({}):Q" . format ( quantity ) l...
def crop ( self , start = None , end = None , copy = False ) : """Crop this series to the given x - axis extent . Parameters start : ` float ` , optional lower limit of x - axis to crop to , defaults to current ` ~ Series . x0 ` end : ` float ` , optional upper limit of x - axis to crop to , defaults to...
x0 , x1 = self . xspan xtype = type ( x0 ) if isinstance ( start , Quantity ) : start = start . to ( self . xunit ) . value if isinstance ( end , Quantity ) : end = end . to ( self . xunit ) . value # pin early starts to time - series start if start == x0 : start = None elif start is not None and xtype ( st...
def set_pos_info_recurse ( self , node , start , finish , parent = None ) : """Set positions under node"""
self . set_pos_info ( node , start , finish ) if parent is None : parent = node for n in node : n . parent = parent if hasattr ( n , 'offset' ) : self . set_pos_info ( n , start , finish ) else : n . start = start n . finish = finish self . set_pos_info_recurse ( n , star...
def write_log_file ( namespace , document ) : """Writes a line to a log file Arguments : namespace { str } - - namespace of document document { dict } - - document to write to the logs"""
log_timestamp = asctime ( gmtime ( document [ TS ] ) ) with open ( "{}{}.{}.log" . format ( LOG_DIR , namespace , DAY_STRING ) , "a" ) as f : log_string = dumps ( { "datetime" : log_timestamp . upper ( ) , "namespace" : namespace , "log" : document [ LOG_KEY ] } ) f . write ( "{}\n" . format ( log_string ) )
def error ( self , msg ) : """Log Error Messages"""
self . _execActions ( 'error' , msg ) msg = self . _execFilters ( 'error' , msg ) self . _processMsg ( 'error' , msg ) self . _sendMsg ( 'error' , msg )
def _getDirection ( coord1 , coord2 ) : """Return the direction the line formed by the ( x , y ) points in ` coord1 ` and ` coord2 ` ."""
x1 , y1 = coord1 x2 , y2 = coord2 if x1 == x2 and y1 == y2 : return None # two coordinates are the same . elif x1 == x2 and y1 > y2 : return UP elif x1 == x2 and y1 < y2 : return DOWN elif x1 > x2 and y1 == y2 : return LEFT elif x1 < x2 and y1 == y2 : return RIGHT slope = float ( y2 - y1 ) / flo...
def open_read ( self , headers = None , query_args = '' , override_num_retries = None , response_headers = None ) : """Open this key for reading : type headers : dict : param headers : Headers to pass in the web request : type query _ args : string : param query _ args : Arguments to pass in the query strin...
if self . resp == None : self . mode = 'r' provider = self . bucket . connection . provider self . resp = self . bucket . connection . make_request ( 'GET' , self . bucket . name , self . name , headers , query_args = query_args , override_num_retries = override_num_retries ) if self . resp . status < 1...
def lock ( self ) : """Lock the device ."""
success = self . set_status ( CONST . STATUS_LOCKCLOSED_INT ) if success : self . _json_state [ 'status' ] = CONST . STATUS_LOCKCLOSED return success
def stat ( self , path ) : """safely gets the Znode ' s Stat"""
try : stat = self . exists ( str ( path ) ) except ( NoNodeError , NoAuthError ) : stat = None return stat
def get ( self , sid ) : """Constructs a ExecutionStepContext : param sid : Step Sid . : returns : twilio . rest . studio . v1 . flow . execution . execution _ step . ExecutionStepContext : rtype : twilio . rest . studio . v1 . flow . execution . execution _ step . ExecutionStepContext"""
return ExecutionStepContext ( self . _version , flow_sid = self . _solution [ 'flow_sid' ] , execution_sid = self . _solution [ 'execution_sid' ] , sid = sid , )
def execute ( self , run ) : """This function executes the tool with a sourcefile with options . It also calls functions for output before and after the run ."""
self . output_handler . output_before_run ( run ) benchmark = self . benchmark memlimit = benchmark . rlimits . get ( MEMLIMIT ) args = run . cmdline ( ) logging . debug ( 'Command line of run is %s' , args ) run_result = self . run_executor . execute_run ( args , output_filename = run . log_file , output_dir = run . r...
def debug_layer ( self , layer , check_fields = True , add_to_datastore = None ) : """Write the layer produced to the datastore if debug mode is on . : param layer : The QGIS layer to check and save . : type layer : QgsMapLayer : param check _ fields : Boolean to check or not inasafe _ fields . By default ,...
# This one checks the memory layer . check_layer ( layer , has_geometry = None ) if isinstance ( layer , QgsVectorLayer ) and check_fields : is_geojson = '.geojson' in layer . source ( ) . lower ( ) if layer . featureCount ( ) == 0 and is_geojson : # https : / / issues . qgis . org / issues / 18370 # We can...
def has_cjk ( self ) : """Checks if the word of the chunk contains CJK characters . This is using unicode codepoint ranges from https : / / github . com / nltk / nltk / blob / develop / nltk / tokenize / util . py # L149 Returns : bool : True if the chunk has any CJK character ."""
cjk_codepoint_ranges = [ ( 4352 , 4607 ) , ( 11904 , 42191 ) , ( 43072 , 43135 ) , ( 44032 , 55215 ) , ( 63744 , 64255 ) , ( 65072 , 65103 ) , ( 65381 , 65500 ) , ( 131072 , 196607 ) ] for char in self . word : if any ( [ start <= ord ( char ) <= end for start , end in cjk_codepoint_ranges ] ) : return True...
def get_parents ( self ) : """Returns the parents of the variables present in the network Examples > > > reader = XMLBIF . XMLBIFReader ( " xmlbif _ test . xml " ) > > > reader . get _ parents ( ) { ' bowel - problem ' : [ ] , ' dog - out ' : [ ' family - out ' , ' bowel - problem ' ] , ' family - out '...
variable_parents = { definition . find ( 'FOR' ) . text : [ edge . text for edge in definition . findall ( 'GIVEN' ) ] for definition in self . network . findall ( 'DEFINITION' ) } return variable_parents
def fillNoneValues ( column ) : """Fill all NaN / NaT values of a column with an empty string Args : column ( pandas . Series ) : A Series object with all rows . Returns : column : Series with filled NaN values ."""
if column . dtype == object : column . fillna ( '' , inplace = True ) return column
def parse_name ( parts , main_names , common_names , debug = 0 ) : """Parse all name ( s ) from a Backpage ad . parts - > The backpage ad ' s posting _ body , separated into substrings main _ names - > " Regular " names ( jessica , gabriel , etc . ) that can be trusted as names simply by its existence common ...
lowercase_parts = [ re . sub ( r'(in|out)call' , '' , p . lower ( ) ) for p in parts ] start = time . time ( ) # Intros to common names intros = { 'pre' : [ 'my name is' , 'i am' , 'call me' , 'call' , 'text' , 'my names' , 'my name' , 'known as' , 'go by' , 'Intro' , 'ask for' , 'call for' , 'ask' , 'this is' , 'one a...
def sample_size_necessary_under_cph ( power , ratio_of_participants , p_exp , p_con , postulated_hazard_ratio , alpha = 0.05 ) : """This computes the sample size for needed power to compare two groups under a Cox Proportional Hazard model . Parameters power : float power to detect the magnitude of the hazar...
def z ( p ) : return stats . norm . ppf ( p ) m = ( 1.0 / ratio_of_participants * ( ( ratio_of_participants * postulated_hazard_ratio + 1.0 ) / ( postulated_hazard_ratio - 1.0 ) ) ** 2 * ( z ( 1.0 - alpha / 2.0 ) + z ( power ) ) ** 2 ) n_exp = m * ratio_of_participants / ( ratio_of_participants * p_exp + p_con ) n_...
def is_required_version ( required_version = '0.0.0' ) : '''Because different versions of Palo Alto support different command sets , this function will return true if the current version of Palo Alto supports the required command .'''
if 'sw-version' in DETAILS [ 'grains_cache' ] : current_version = DETAILS [ 'grains_cache' ] [ 'sw-version' ] else : # If we do not have the current sw - version cached , we cannot check version requirements . return False required_version_split = required_version . split ( "." ) current_version_split = current...
def financials ( self , security ) : """get financials : google finance provide annual and quanter financials , if annual is true , we will use annual data Up to four lastest year / quanter data will be provided by google Refer to page as an example : http : / / www . google . com / finance ? q = TSE : CVG & ...
try : url = 'http://www.google.com/finance?q=%s&fstype=ii' % security try : page = self . _request ( url ) . read ( ) except UfException as ufExcep : # if symol is not right , will get 400 if Errors . NETWORK_400_ERROR == ufExcep . getCode : raise UfException ( Errors . STOCK_SYM...
def bqm_structured ( f ) : """Decorator to raise an error if the given bqm does not match the sampler ' s structure . Designed to be applied to : meth : ` . Sampler . sample ` . Expects the wrapped function or method to accept a : obj : ` . BinaryQuadraticModel ` as the second input and for the : class : ` ...
@ wraps ( f ) def new_f ( sampler , bqm , ** kwargs ) : try : structure = sampler . structure adjacency = structure . adjacency except AttributeError : if isinstance ( sampler , Structured ) : raise RuntimeError ( "something is wrong with the structured sampler" ) els...
def object_patch_set_data ( self , root , data , ** kwargs ) : """Creates a new merkledag object based on an existing one . The new object will have the same links as the old object but with the provided data instead of the old object ' s data contents . . . code - block : : python > > > c . object _ patch ...
args = ( root , ) body , headers = multipart . stream_files ( data , self . chunk_size ) return self . _client . request ( '/object/patch/set-data' , args , decoder = 'json' , data = body , headers = headers , ** kwargs )
def check_auth ( args , role = None ) : """Check the user authentication ."""
users = boto3 . resource ( "dynamodb" ) . Table ( os . environ [ 'people' ] ) if not ( args . get ( 'email' , None ) and args . get ( 'api_key' , None ) ) : mesg = "Invalid request: `email` and `api_key` are required" return { 'success' : False , 'message' : mesg } user = users . get_item ( Key = { 'email' : ar...
def _notify_media_transport_available ( self , path , transport ) : """Called by the endpoint when a new media transport is available"""
self . sink = BTAudioSink ( dev_path = path ) self . state = self . sink . State self . sink . add_signal_receiver ( self . _property_change_event_handler , BTAudioSource . SIGNAL_PROPERTY_CHANGED , # noqa transport )
def validate_fillna_kwargs ( value , method , validate_scalar_dict_value = True ) : """Validate the keyword arguments to ' fillna ' . This checks that exactly one of ' value ' and ' method ' is specified . If ' method ' is specified , this validates that it ' s a valid method . Parameters value , method : o...
from pandas . core . missing import clean_fill_method if value is None and method is None : raise ValueError ( "Must specify a fill 'value' or 'method'." ) elif value is None and method is not None : method = clean_fill_method ( method ) elif value is not None and method is None : if validate_scalar_dict_va...
def unbounded ( self ) : """Whether solution is unbounded"""
self . _check_valid ( ) status = self . _problem . _p . Status if ( status == gurobipy . GRB . INF_OR_UNBD and self . _problem . _p . params . DualReductions ) : # Disable dual reductions to obtain a definitve answer self . _problem . _p . params . DualReductions = 0 try : self . _problem . _p . optimiz...
def getCalculationDependencies ( self , flat = False , deps = None ) : """Recursively calculates all dependencies of this calculation . The return value is dictionary of dictionaries ( of dictionaries . . . ) { service _ UID1: { service _ UID2: { service _ UID3 : { } , service _ UID4 : { } , set flat = ...
if deps is None : deps = [ ] if flat is True else { } for service in self . getDependentServices ( ) : calc = service . getCalculation ( ) if calc : calc . getCalculationDependencies ( flat , deps ) if flat : deps . append ( service ) else : deps [ service . UID ( ) ] = { } r...
def _count_files_by_type ( self , path , pattern , ignore = True ) : """Count files in the given path , with the given pattern . If ` ignore = True ` , skip files in the ` _ IGNORE _ FILES ` list . Returns num _ files : int"""
# Get all files matching the given path and pattern files = glob ( os . path . join ( path , pattern ) ) # Count the files files = [ ff for ff in files if os . path . split ( ff ) [ - 1 ] not in self . _IGNORE_FILES or not ignore ] num_files = len ( files ) return num_files
def connect ( self ) : """Connects to RabbitMQ"""
self . connection = Connection ( self . broker_url ) e = Exchange ( 'mease' , type = 'fanout' , durable = False , delivery_mode = 1 ) self . exchange = e ( self . connection . default_channel ) self . exchange . declare ( )
def get_pdb_id ( self ) : '''Return the PDB ID . If one was passed in to the constructor , this takes precedence , otherwise the header is parsed to try to find an ID . The header does not always contain a PDB ID in regular PDB files and appears to always have an ID of ' XXXX ' in biological units so the constr...
if self . pdb_id : return self . pdb_id else : header = self . parsed_lines [ "HEADER" ] assert ( len ( header ) <= 1 ) if header : self . pdb_id = header [ 0 ] [ 62 : 66 ] return self . pdb_id return None
def predict_magnification ( self , Xnew , kern = None , mean = True , covariance = True , dimensions = None ) : """Predict the magnification factor as sqrt ( det ( G ) ) for each point N in Xnew . : param bool mean : whether to include the mean of the wishart embedding . : param bool covariance : whether to...
G = self . predict_wishart_embedding ( Xnew , kern , mean , covariance ) if dimensions is None : dimensions = self . get_most_significant_input_dimensions ( ) [ : 2 ] G = G [ : , dimensions ] [ : , : , dimensions ] from . . util . linalg import jitchol mag = np . empty ( Xnew . shape [ 0 ] ) for n in range ( Xnew ....
def format_csv ( self , delim = ',' , qu = '"' ) : """Prepares the data in CSV format"""
res = qu + self . name + qu + delim if self . data : for d in self . data : res += qu + str ( d ) + qu + delim return res + '\n'
def delete_cas ( self , key , * , index ) : """Deletes the Key with check - and - set semantics . Parameters : key ( str ) : Key to delete index ( ObjectIndex ) : Index ID The Key will only be deleted if its current modify index matches the supplied Index"""
self . append ( { "Verb" : "delete-cas" , "Key" : key , "Index" : extract_attr ( index , keys = [ "ModifyIndex" , "Index" ] ) } ) return self
def create ( name , grid , spacing , diameter , depth , volume = 0 ) : """Creates a labware definition based on a rectangular gird , depth , diameter , and spacing . Note that this function can only create labware with regularly spaced wells in a rectangular format , of equal height , depth , and radius . Irr...
columns , rows = grid col_spacing , row_spacing = spacing custom_container = Container ( ) properties = { 'type' : 'custom' , 'diameter' : diameter , 'height' : depth , 'total-liquid-volume' : volume } for c in range ( columns ) : for r in range ( rows ) : well = Well ( properties = properties ) wel...
def remover ( self , id_tipo_acesso ) : """Removes access type by its identifier . : param id _ tipo _ acesso : Access type identifier . : return : None : raise TipoAcessoError : Access type associated with equipment , cannot be removed . : raise InvalidParameterError : Protocol value is invalid or none . ...
if not is_valid_int_param ( id_tipo_acesso ) : raise InvalidParameterError ( u'Access type id is invalid or was not informed.' ) url = 'tipoacesso/' + str ( id_tipo_acesso ) + '/' code , xml = self . submit ( None , 'DELETE' , url ) return self . response ( code , xml )
def register_printer ( self , printer_class ) : """: param printer _ class : Class inheriting from ` AbstractPrinter ` ."""
self . _check_common_things ( 'printer' , printer_class , AbstractPrinter , self . _printers ) instance = printer_class ( self , logger_printer ) self . _printers . append ( instance )
def escape_path ( pth ) : """Hex / unicode escapes a path . Escapes a path so that it can be represented faithfully in an HDF5 file without changing directories . This means that leading ` ` ' . ' ` ` must be escaped . ` ` ' / ' ` ` and null must be escaped to . Backslashes are escaped as double backslashes...
if isinstance ( pth , bytes ) : pth = pth . decode ( 'utf-8' ) if sys . hexversion >= 0x03000000 : if not isinstance ( pth , str ) : raise TypeError ( 'pth must be str or bytes.' ) match = _find_dots_re . match ( pth ) if match is None : prefix = '' s = pth else : pre...
def get_type_hierarchy ( s ) : """Get the sequence of parents from ` s ` to Statement . Parameters s : a class or instance of a child of Statement For example the statement ` Phosphorylation ( MEK ( ) , ERK ( ) ) ` or just the class ` Phosphorylation ` . Returns parent _ list : list [ types ] A list o...
tp = type ( s ) if not isinstance ( s , type ) else s p_list = [ tp ] for p in tp . __bases__ : if p is not Statement : p_list . extend ( get_type_hierarchy ( p ) ) else : p_list . append ( p ) return p_list
def kronecker_decomposition ( gate : Gate ) -> Circuit : """Decompose a 2 - qubit unitary composed of two 1 - qubit local gates . Uses the " Nearest Kronecker Product " algorithm . Will give erratic results if the gate is not the direct product of two 1 - qubit gates ."""
# An alternative approach would be to take partial traces , but # this approach appears to be more robust . if gate . qubit_nb != 2 : raise ValueError ( 'Expected 2-qubit gate' ) U = asarray ( gate . asoperator ( ) ) rank = 2 ** gate . qubit_nb U /= np . linalg . det ( U ) ** ( 1 / rank ) R = np . stack ( [ U [ 0 :...
def _x_format ( self ) : """Return the value formatter for this graph"""
def datetime_to_str ( x ) : dt = datetime . utcfromtimestamp ( x ) return self . x_value_formatter ( dt ) return datetime_to_str
async def handler ( self , request : Request ) -> Tuple [ int , str , List [ Tuple [ str , str ] ] , bytes ] : """The handler handling each request : param request : the Request instance : return : The Response instance"""
response : 'Response' = Response ( ) handler : Callable = empty chain_reverse = self . middleware [ : : - 1 ] for middleware in chain_reverse : handler = map_context_to_middleware ( middleware , self , request , response , handler ) try : await handler ( ) except HttpException as e : response . code = e . c...
def _evaluate ( self , * args , ** kwargs ) : """NAME : _ _ call _ _ ( _ evaluate ) PURPOSE : evaluate the actions ( jr , lz , jz ) INPUT : Either : a ) R , vR , vT , z , vz [ , phi ] : 1 ) floats : phase - space value for single object ( phi is optional ) ( each can be a Quantity ) 2 ) numpy . ndar...
R , vR , vT , z , vz , phi = self . _parse_args ( False , False , * args ) if self . _c : # pragma : no cover pass else : # Use self . _ aAI to calculate the actions and angles in the isochrone potential acfs = self . _aAI . _actionsFreqsAngles ( R . flatten ( ) , vR . flatten ( ) , vT . flatten ( ) , z . flatt...
def setup ( self ) : """Configures the actor before execution . : return : None if successful , otherwise error message : rtype : str"""
result = super ( ActorHandler , self ) . setup ( ) if result is None : self . update_parent ( ) try : self . check_actors ( self . actors ) except Exception as e : result = str ( e ) if result is None : for actor in self . actors : name = actor . name newname = actor . un...
def bestfit_func ( self , bestfit_x ) : """Returns y value"""
if not self . bestfit_func : raise KeyError ( "Do do_bestfit first" ) return self . args [ "func" ] ( self . fit_args , bestfit_x )
def next ( self ) : """Returns the next row from the Instances object . : return : the next Instance object : rtype : Instance"""
if self . row < self . data . num_instances : index = self . row self . row += 1 return self . data . get_instance ( index ) else : raise StopIteration ( )
def join ( * paths ) : # type : ( * Text ) - > Text """Join any number of paths together . Arguments : * paths ( str ) : Paths to join , given as positional arguments . Returns : str : The joined path . Example : > > > join ( ' foo ' , ' bar ' , ' baz ' ) ' foo / bar / baz ' > > > join ( ' foo / bar...
absolute = False relpaths = [ ] # type : List [ Text ] for p in paths : if p : if p [ 0 ] == "/" : del relpaths [ : ] absolute = True relpaths . append ( p ) path = normpath ( "/" . join ( relpaths ) ) if absolute : path = abspath ( path ) return path
def text ( value , encoding = "utf-8" , errors = "strict" ) : """Convert a value to str on Python 3 and unicode on Python 2."""
if isinstance ( value , text_type ) : return value elif isinstance ( value , bytes ) : return text_type ( value , encoding , errors ) else : return text_type ( value )
def _add_event_in_element ( self , element , event ) : """Add a type of event in element . : param element : The element . : type element : hatemile . util . html . htmldomelement . HTMLDOMElement : param event : The type of event . : type event : str"""
if not self . main_script_added : self . _generate_main_scripts ( ) if self . script_list is not None : self . id_generator . generate_id ( element ) self . script_list . append_text ( event + "Elements.push('" + element . get_attribute ( 'id' ) + "');" )
def run ( ) : """Runs the linter and tests : return : A bool - if the linter and tests ran successfully"""
print ( 'Python ' + sys . version . replace ( '\n' , '' ) ) try : oscrypto_tests_module_info = imp . find_module ( 'tests' , [ os . path . join ( build_root , 'oscrypto' ) ] ) oscrypto_tests = imp . load_module ( 'oscrypto.tests' , * oscrypto_tests_module_info ) oscrypto = oscrypto_tests . local_oscrypto ( ...
def evaluate ( args ) : """% prog evaluate prediction . bed reality . bed fastafile Make a truth table like : True False - - - Reality True TP FP False FN TN | - - - - Prediction Sn = TP / ( all true in reality ) = TP / ( TP + FN ) Sp = TP / ( all true in prediction ) = TP / ( TP + FP ) Ac = ( TP + ...
from jcvi . formats . sizes import Sizes p = OptionParser ( evaluate . __doc__ ) p . add_option ( "--query" , help = "Chromosome location [default: %default]" ) opts , args = p . parse_args ( args ) if len ( args ) != 3 : sys . exit ( not p . print_help ( ) ) prediction , reality , fastafile = args query = opts . q...
def find_next_candidate ( self ) : """Returns the next candidate Node for ( potential ) evaluation . The candidate list ( really a stack ) initially consists of all of the top - level ( command line ) targets provided when the Taskmaster was initialized . While we walk the DAG , visiting Nodes , all the chi...
try : return self . candidates . pop ( ) except IndexError : pass try : node = self . top_targets_left . pop ( ) except IndexError : return None self . current_top = node alt , message = node . alter_targets ( ) if alt : self . message = message self . candidates . append ( node ) self . can...
def confirms ( self , txid ) : """Returns number of confirms or None if unpublished ."""
txid = deserialize . txid ( txid ) return self . service . confirms ( txid )
def append_fresh_table ( self , fresh_table ) : """Gets called by FreshTable instances when they get written to ."""
if fresh_table . name : elements = [ ] if fresh_table . is_array : elements += [ element_factory . create_array_of_tables_header_element ( fresh_table . name ) ] else : elements += [ element_factory . create_table_header_element ( fresh_table . name ) ] elements += [ fresh_table , elemen...
async def status ( self , switch = None ) : """Get current relay status ."""
if switch is not None : if self . waiters or self . in_transaction : fut = self . loop . create_future ( ) self . status_waiters . append ( fut ) states = await fut state = states [ switch ] else : packet = self . protocol . format_packet ( b"\x1e" ) states = awai...
def _create_and_send_json_bulk ( self , payload , req_url , request_type = "POST" ) : """Create a json , do a request to the URL and process the response . : param list payload : contains the informations necessary for the action . It ' s a list of dictionnary . : param str req _ url : URL to request with the...
# Extra header in addition to the main session ' s ct_header = { "Content-Type" : "application/json; charset=utf-8" } try : json_pl = json . dumps ( payload ) except TypeError as err : raise CraftAiBadRequestError ( "Error while dumping the payload into json" "format when converting it for the bulk request. {}"...
def execute ( self , env , args ) : """Removes a task . ` env ` Runtime ` ` Environment ` ` instance . ` args ` Arguments object from arg parser ."""
# extract args task_name = args . task_name force = args . force if env . task . active and env . task . name == task_name : raise errors . ActiveTask if not env . task . exists ( task_name ) : raise errors . TaskNotFound ( task_name ) if force : env . task . remove ( task_name ) else : try : wh...
def _control_vm ( self , command , expected = None ) : """Executes a command with QEMU monitor when this VM is running . : param command : QEMU monitor command ( e . g . info status , stop etc . ) : param expected : An array of expected strings : returns : result of the command ( matched object or None )"""
result = None if self . is_running ( ) and self . _monitor : log . debug ( "Execute QEMU monitor command: {}" . format ( command ) ) try : log . info ( "Connecting to Qemu monitor on {}:{}" . format ( self . _monitor_host , self . _monitor ) ) reader , writer = yield from asyncio . open_connecti...
def video_category ( self ) : """doc : http : / / open . youku . com / docs / doc ? id = 90"""
url = 'https://openapi.youku.com/v2/schemas/video/category.json' r = requests . get ( url ) check_error ( r ) return r . json ( )
def partitioned_repertoire ( self , direction , partition ) : """Compute the repertoire over the partition in the given direction ."""
system = self . system [ direction ] return system . partitioned_repertoire ( direction , partition )
def launch ( self , f ) : """Decorator maps a view function as the endpoint for an Alexa LaunchRequest and starts the skill . @ ask . launch def launched ( ) : return question ( ' Welcome to Foo ' ) The wrapped function is registered as the launch view function and renders the response for requests to the...
self . _launch_view_func = f @ wraps ( f ) def wrapper ( * args , ** kw ) : self . _flask_view_func ( * args , ** kw ) return f
def _start_keep_alive ( self ) : '''Start the keep alive thread as a daemon'''
keep_alive_thread = threading . Thread ( target = self . keep_alive ) keep_alive_thread . daemon = True keep_alive_thread . start ( )
def get_index_names ( self , db_name , tbl_name , max_indexes ) : """Parameters : - db _ name - tbl _ name - max _ indexes"""
self . send_get_index_names ( db_name , tbl_name , max_indexes ) return self . recv_get_index_names ( )
def gain_to_loss_ratio ( self ) : """Gain - to - loss ratio , ratio of positive to negative returns . Formula : ( n pos . / n neg . ) * ( avg . up - month return / avg . down - month return ) [ Source : CFA Institute ] Returns float"""
gt = self > 0 lt = self < 0 return ( nansum ( gt ) / nansum ( lt ) ) * ( self [ gt ] . mean ( ) / self [ lt ] . mean ( ) )
def run ( self , batch = True , interruptible = None , inplace = True ) : """Run task : param batch if False batching will be disabled . : param interruptible : If true interruptible instance will be used . : param inplace Apply action on the current object or return a new one . : return : Task object .""...
params = { } if not batch : params [ 'batch' ] = False if interruptible is not None : params [ 'use_interruptible_instances' ] = interruptible extra = { 'resource' : self . __class__ . __name__ , 'query' : { 'id' : self . id , 'batch' : batch } } logger . info ( 'Running task' , extra = extra ) task_data = self...
def support_support_param_username ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) support = ET . SubElement ( config , "support" , xmlns = "urn:brocade.com:mgmt:brocade-ras" ) support_param = ET . SubElement ( support , "support-param" ) username = ET . SubElement ( support_param , "username" ) username . text = kwargs . pop ( 'username' ) callback = kwargs . pop (...
def _parseRelocations ( self , sections ) : """Parses the relocations and add those to the section"""
for section in sections : if section . header . sh_link != SHN . UNDEF and section . header . sh_type in ( SHT . REL , SHT . RELA ) : symbols = sections [ section . header . sh_link ] . symbols relocations = self . __parseRelocationEntries ( section , symbols ) section . relocations = reloca...
def options ( self ) : """Dictionary of options which affect the curve fitting algorithm . Must contain the key ` fit _ function ` which must be set to the function that will perform the fit . All other options are passed as keyword arguments to the ` fit _ function ` . The default options use ` scipy . opt...
if not hasattr ( self , '_options' ) : self . _options = { 'fit_function' : scipy . optimize . curve_fit , 'maxfev' : 1000 , } return self . _options
def uri ( self ) : "Fedora URI for this object ( ` ` info : fedora / foo : # # # ` ` form of object pid )"
use_pid = self . pid if callable ( use_pid ) : use_pid = self . DUMMY_PID return 'info:fedora/' + use_pid
def _set_flow_rate ( pipette , params ) -> None : """Set flow rate in uL / mm , to value obtained from command ' s params ."""
flow_rate_param = params [ 'flowRate' ] if not ( flow_rate_param > 0 ) : raise RuntimeError ( 'Positive flowRate param required' ) pipette . flow_rate = { 'aspirate' : flow_rate_param , 'dispense' : flow_rate_param }
def distance_stats ( x , y , ** kwargs ) : """distance _ stats ( x , y , * , exponent = 1) Computes the usual ( biased ) estimators for the distance covariance and distance correlation between two random vectors , and the individual distance variances . Parameters x : array _ like First random vector . ...
return Stats ( * [ _sqrt ( s ) for s in distance_stats_sqr ( x , y , ** kwargs ) ] )
def wait_for_logs_matching ( self , matcher , timeout = 10 , encoding = 'utf-8' , ** logs_kwargs ) : """Wait for logs matching the given matcher ."""
wait_for_logs_matching ( self . inner ( ) , matcher , timeout = timeout , encoding = encoding , ** logs_kwargs )
def validate ( self , corpus ) : """Perform validation on the given corpus . Args : corpus ( Corpus ) : The corpus to test / validate ."""
passed = True results = { } for validator in self . validators : sub_result = validator . validate ( corpus ) results [ validator . name ( ) ] = sub_result if not sub_result . passed : passed = False return CombinedValidationResult ( passed , results )
def _fix_paths ( self , data ) : """All paths needs to be fixed - add PROJ _ DIR prefix + normalize"""
data [ 'include_paths' ] = [ join ( '$PROJ_DIR$' , path ) for path in data [ 'include_paths' ] ] if data [ 'linker_file' ] : data [ 'linker_file' ] = join ( '$PROJ_DIR$' , data [ 'linker_file' ] ) data [ 'groups' ] = { } for attribute in SOURCE_KEYS : for k , v in data [ attribute ] . items ( ) : if k n...
def dIbr_dV ( Yf , Yt , V ) : """Computes partial derivatives of branch currents w . r . t . voltage . Ray Zimmerman , " dIbr _ dV . m " , MATPOWER , version 4.0b1, PSERC ( Cornell ) , http : / / www . pserc . cornell . edu / matpower /"""
# nb = len ( V ) Vnorm = div ( V , abs ( V ) ) diagV = spdiag ( V ) diagVnorm = spdiag ( Vnorm ) dIf_dVa = Yf * 1j * diagV dIf_dVm = Yf * diagVnorm dIt_dVa = Yt * 1j * diagV dIt_dVm = Yt * diagVnorm # Compute currents . If = Yf * V It = Yt * V return dIf_dVa , dIf_dVm , dIt_dVa , dIt_dVm , If , It
def addSwitch ( self , name = None ) : '''Add a new switch to the topology .'''
if name is None : while True : name = 's' + str ( self . __snum ) self . __snum += 1 if name not in self . __nxgraph : break self . __addNode ( name , Switch ) return name
def create_runscript ( self , default = "/bin/bash" , force = False ) : '''create _ entrypoint is intended to create a singularity runscript based on a Docker entrypoint or command . We first use the Docker ENTRYPOINT , if defined . If not , we use the CMD . If neither is found , we use function default . P...
entrypoint = default # Only look at Docker if not enforcing default if force is False : if self . entrypoint is not None : entrypoint = '' . join ( self . entrypoint ) elif self . cmd is not None : entrypoint = '' . join ( self . cmd ) # Entrypoint should use exec if not entrypoint . startswith ...
def get_data ( self ) : """Gets the asset content data . return : ( osid . transport . DataInputStream ) - the length of the content data raise : OperationFailed - unable to complete request * compliance : mandatory - - This method must be implemented . *"""
if not bool ( self . _my_map [ 'data' ] ) : raise errors . IllegalState ( 'no data' ) dbase = JSONClientValidated ( 'repository' , runtime = self . _runtime ) . raw ( ) filesys = gridfs . GridFS ( dbase ) return DataInputStream ( filesys . get ( self . _my_map [ 'data' ] ) )
def extract ( self , dest_fldr , password = '' ) : """unzip the file contents to the dest _ folder ( create if it doesn ' t exist ) and then return the list of files extracted"""
# print ( ' extracting to ' + dest _ fldr ) if self . type == 'ZIP' : self . _extract_zip ( dest_fldr , password ) elif self . type == 'GZ' : self . _extract_gz ( dest_fldr , password ) elif self . type == 'TAR' : self . _extract_tar ( dest_fldr , self . fname ) else : raise ( 'Unknown archive file type...
def parse_cartouche_text ( lines ) : '''Parse text in cartouche format and return a reStructuredText equivalent Args : lines : A sequence of strings representing the lines of a single docstring as read from the source by Sphinx . This string should be in a format that can be parsed by cartouche . Returns ...
indent_lines = unindent ( lines ) indent_lines = pad_blank_lines ( indent_lines ) indent_lines = first_paragraph_indent ( indent_lines ) indent_paragraphs = gather_lines ( indent_lines ) parse_tree = group_paragraphs ( indent_paragraphs ) syntax_tree = extract_structure ( parse_tree ) result = syntax_tree . render_rst ...
def _language_exclusions ( stem : LanguageStemRange , exclusions : List [ ShExDocParser . LanguageExclusionContext ] ) -> None : """languageExclusion = ' - ' LANGTAG STEM _ MARK ?"""
for excl in exclusions : excl_langtag = LANGTAG ( excl . LANGTAG ( ) . getText ( ) [ 1 : ] ) stem . exclusions . append ( LanguageStem ( excl_langtag ) if excl . STEM_MARK ( ) else excl_langtag )
def query_cat_random ( catid , ** kwargs ) : '''Get random lists of certain category .'''
num = kwargs . get ( 'limit' , 8 ) if catid == '' : rand_recs = TabPost . select ( ) . order_by ( peewee . fn . Random ( ) ) . limit ( num ) else : rand_recs = TabPost . select ( ) . join ( TabPost2Tag , on = ( TabPost . uid == TabPost2Tag . post_id ) ) . where ( ( TabPost . valid == 1 ) & ( TabPost2Tag . tag_i...
def main ( argv = None ) : """Validate text parsed with FSM or validate an FSM via command line ."""
if argv is None : argv = sys . argv try : opts , args = getopt . getopt ( argv [ 1 : ] , 'h' , [ 'help' ] ) except getopt . error as msg : raise Usage ( msg ) for opt , _ in opts : if opt in ( '-h' , '--help' ) : print ( __doc__ ) print ( help_msg ) return 0 if not args or len ( ...
def getBottomRight ( self ) : """Retrieves a tuple with the x , y coordinates of the lower right point of the rect . Requires the coordinates , width , height to be numbers"""
return ( float ( self . get_x ( ) ) + float ( self . get_width ( ) ) , float ( self . get_y ( ) ) )
def report_dead_hosting_devices ( self , context , hd_ids = None ) : """Report that a hosting device cannot be contacted ( presumed dead ) . : param : context : session context : param : hosting _ device _ ids : list of non - responding hosting devices : return : None"""
cctxt = self . client . prepare ( ) cctxt . cast ( context , 'report_non_responding_hosting_devices' , host = self . host , hosting_device_ids = hd_ids )
def get_display_types ( ) : """Get ordered dict containing available display types from available luma sub - projects . : rtype : collections . OrderedDict"""
display_types = OrderedDict ( ) for namespace in get_supported_libraries ( ) : display_types [ namespace ] = get_choices ( 'luma.{0}.device' . format ( namespace ) ) return display_types
def from_file ( filename = "feff.inp" ) : """Creates a Feff _ tag dictionary from a PARAMETER or feff . inp file . Args : filename : Filename for either PARAMETER or feff . inp file Returns : Feff _ tag object"""
with zopen ( filename , "rt" ) as f : lines = list ( clean_lines ( f . readlines ( ) ) ) params = { } eels_params = [ ] ieels = - 1 ieels_max = - 1 for i , line in enumerate ( lines ) : m = re . match ( r"([A-Z]+\d*\d*)\s*(.*)" , line ) if m : key = m . group ( 1 ) . strip ( ) val = m . grou...