signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def _prepare_statement ( sql_statement , parameters ) : """Prepare the specified SQL statement , replacing the placeholders by the value of the given parameters @ param sql _ statement : the string expression of a SQL statement . @ param parameters : a dictionary of parameters where the key represents the n...
placehoolders = RdbmsConnection . _get_placeholders ( sql_statement , parameters ) for ( variable_name , ( variable_type , variable_value ) ) in placehoolders . iteritems ( ) : # Only expand parameters whose value corresponds to a list . if isinstance ( variable_value , ( list , set , tuple ) ) : sql_statem...
def load ( self , name = None ) : """load from file"""
import pickle name = name if name else self . name s = pickle . load ( open ( name + '.pkl' , 'rb' ) ) self . res = s . res # disregard the class return self
def fetch_page_async ( self , page_size , ** q_options ) : """Fetch a page of results . This is the asynchronous version of Query . fetch _ page ( ) ."""
qry = self . _fix_namespace ( ) return qry . _fetch_page_async ( page_size , ** q_options )
def get_grammar ( self ) : """Returns the grammar of the UAI file ."""
network_name = Word ( alphas ) . setResultsName ( 'network_name' ) no_variables = Word ( nums ) . setResultsName ( 'no_variables' ) grammar = network_name + no_variables self . no_variables = int ( grammar . parseString ( self . network ) [ 'no_variables' ] ) domain_variables = ( Word ( nums ) * self . no_variables ) ....
def blast_records_to_object ( blast_records ) : """Transforms biopython ' s blast record into blast object defined in django - blastplus app ."""
# container for transformed objects blast_objects_list = [ ] for blast_record in blast_records : br = BlastRecord ( ** { 'query' : blast_record . query , 'version' : blast_record . version , 'expect' : blast_record . expect , 'application' : blast_record . application , 'reference' : blast_record . reference } ) ...
def __construct_object ( self , obj , exclude_list = [ ] ) : """Loop dict / class object and parse values"""
new_obj = { } for key , value in obj . items ( ) : if str ( key ) . startswith ( '_' ) or key is 'json_exclude_list' or key in exclude_list : continue new_obj [ self . camel_case ( key ) ] = self . __iterate_value ( value ) return new_obj
def checkStock ( self ) : """check stocks in preference"""
if not self . preferences : logger . debug ( "no preferences" ) return None soup = BeautifulSoup ( self . xpath ( path [ 'stock-table' ] ) [ 0 ] . html , "html.parser" ) count = 0 # iterate through product in left panel for product in soup . select ( "div.tradebox" ) : prod_name = product . select ( "span.i...
def last_activity_time ( self ) : """获取用户最后一次活动的时间 : return : 用户最后一次活动的时间 , 返回值为 unix 时间戳 : rtype : int"""
self . _make_soup ( ) act = self . soup . find ( 'div' , class_ = 'zm-profile-section-item zm-item clearfix' ) return int ( act [ 'data-time' ] ) if act is not None else - 1
def thumbnail_url ( source , alias ) : """Return the thumbnail url for a source file using an aliased set of thumbnail options . If no matching alias is found , returns an empty string . Example usage : : < img src = " { { person . photo | thumbnail _ url : ' small ' } } " alt = " " >"""
try : thumb = get_thumbnailer ( source ) [ alias ] except Exception : return '' return thumb . url
def _get_py_dictionary ( self , var , names = None , used___dict__ = False ) : ''': return tuple ( names , used _ _ _ dict _ _ ) , where used _ _ _ dict _ _ means we have to access using obj . _ _ dict _ _ [ name ] instead of getattr ( obj , name )'''
# TODO : Those should be options ( would fix https : / / github . com / Microsoft / ptvsd / issues / 66 ) . filter_private = False filter_special = True filter_function = True filter_builtin = True if not names : names , used___dict__ = self . get_names ( var ) d = { } # Be aware that the order in which the filters...
def get_interval ( note , interval , key = 'C' ) : """Return the note an interval ( in half notes ) away from the given note . This will produce mostly theoretical sound results , but you should use the minor and major functions to work around the corner cases ."""
intervals = map ( lambda x : ( notes . note_to_int ( key ) + x ) % 12 , [ 0 , 2 , 4 , 5 , 7 , 9 , 11 , ] ) key_notes = keys . get_notes ( key ) for x in key_notes : if x [ 0 ] == note [ 0 ] : result = ( intervals [ key_notes . index ( x ) ] + interval ) % 12 if result in intervals : return key_notes [ i...
def read_ASCII_cols ( infile , cols = [ 1 , 2 , 3 ] ) : # noqa : N802 """Interpret input ASCII file to return arrays for specified columns . Notes The specification of the columns should be expected to have lists for each ' column ' , with all columns in each list combined into a single entry . For exampl...
# build dictionary representing format of each row # Format of dictionary : { ' colname ' : col _ number , . . . } # This provides the mapping between column name and column number coldict = { } with open ( infile , 'r' ) as f : flines = f . readlines ( ) for l in flines : # interpret each line from catalog file ...
def _set_show_mpls_route ( self , v , load = False ) : """Setter method for show _ mpls _ route , mapped from YANG variable / brocade _ mpls _ rpc / show _ mpls _ route ( rpc ) If this variable is read - only ( config : false ) in the source YANG file , then _ set _ show _ mpls _ route is considered as a privat...
if hasattr ( v , "_utype" ) : v = v . _utype ( v ) try : t = YANGDynClass ( v , base = show_mpls_route . show_mpls_route , is_leaf = True , yang_name = "show-mpls-route" , rest_name = "show-mpls-route" , parent = self , path_helper = self . _path_helper , extmethods = self . _extmethods , register_paths = False...
def get_full_filename_by_suffixes ( dir_src , suffixes ) : # type : ( AnyStr , Union [ AnyStr , List [ AnyStr ] ] ) - > Optional [ List [ AnyStr ] ] """get full file names with the given suffixes in the given directory Args : dir _ src : directory path suffixes : wanted suffixes Returns : full file names ...
file_names = FileClass . get_filename_by_suffixes ( dir_src , suffixes ) if file_names is None : return None return list ( dir_src + os . sep + name for name in file_names )
def FileEntryExistsByPathSpec ( self , path_spec ) : """Determines if a file entry for a path specification exists . Args : path _ spec ( PathSpec ) : path specification . Returns : bool : True if the file entry exists ."""
location = getattr ( path_spec , 'location' , None ) if ( location is None or not location . startswith ( self . LOCATION_ROOT ) ) : return False if len ( location ) == 1 : return True try : self . _tar_file . getmember ( location [ 1 : ] ) return True except KeyError : pass # Check if location coul...
def data_filler_company ( self , number_of_rows , db ) : '''creates and fills the table with company data'''
try : company = db data_list = list ( ) for i in range ( 0 , number_of_rows ) : post_comp_reg = { "id" : rnd_id_generator ( self ) , "name" : self . faker . company ( ) , "date" : self . faker . date ( pattern = "%d-%m-%Y" ) , "email" : self . faker . company_email ( ) , "domain" : self . faker . sa...
def _parse_canonical_decimal128 ( doc ) : """Decode a JSON decimal128 to bson . decimal128 . Decimal128."""
d_str = doc [ '$numberDecimal' ] if len ( doc ) != 1 : raise TypeError ( 'Bad $numberDecimal, extra field(s): %s' % ( doc , ) ) if not isinstance ( d_str , string_type ) : raise TypeError ( '$numberDecimal must be string: %s' % ( doc , ) ) return Decimal128 ( d_str )
def info ( ctx ) : """Display status of OATH application ."""
controller = ctx . obj [ 'controller' ] version = controller . version click . echo ( 'OATH version: {}.{}.{}' . format ( version [ 0 ] , version [ 1 ] , version [ 2 ] ) ) click . echo ( 'Password protection ' + ( 'enabled' if controller . locked else 'disabled' ) ) keys = ctx . obj [ 'settings' ] . get ( 'keys' , { } ...
def output ( id , url ) : """View the files from a dataset ."""
data_source = get_data_object ( id , use_data_config = False ) if not data_source : sys . exit ( ) data_url = "%s/%s" % ( floyd . floyd_web_host , data_source . name ) if url : floyd_logger . info ( data_url ) else : floyd_logger . info ( "Opening output directory in your browser ..." ) webbrowser . ope...
def frange ( start , stop , step = 1.0 ) : """Implementation of Python ' s ` ` range ( ) ` ` function which works with floats . Reference to this implementation : https : / / stackoverflow . com / a / 36091634 : param start : start value : type start : float : param stop : end value : type stop : float ...
i = 0.0 x = float ( start ) # Prevent yielding integers . x0 = x epsilon = step / 2.0 yield x # always yield first value while x + epsilon < stop : i += 1.0 x = x0 + i * step yield x if stop > x : yield stop
def _is_protein ( pe ) : """Return True if the element is a protein"""
val = isinstance ( pe , _bp ( 'Protein' ) ) or isinstance ( pe , _bpimpl ( 'Protein' ) ) or isinstance ( pe , _bp ( 'ProteinReference' ) ) or isinstance ( pe , _bpimpl ( 'ProteinReference' ) ) return val
def get_column ( self , col ) : """Loop over files getting the requested dataset values from each Parameters col : string Name of the dataset to be returned Returns numpy array Values from the dataset , filtered if requested and concatenated in order of file list"""
logging . info ( 'getting %s' % col ) vals = [ ] for f in self . files : d = FileData ( f , group = self . group , columnlist = self . columns , filter_func = self . filter_func ) vals . append ( d . get_column ( col ) ) # Close each file since h5py has an upper limit on the number of # open file object...
def _gc_dead_sinks ( self ) : """Remove any dead weakrefs ."""
deadsinks = [ ] for i in self . _sinks : if i ( ) is None : deadsinks . append ( i ) for i in deadsinks : self . _sinks . remove ( i )
def price_value_renderer ( value , currency = None , ** options ) : """Format price value , with current locale and CURRENCY in settings"""
if not currency : currency = getattr ( settings , 'CURRENCY' , 'USD' ) return format_currency ( value , currency , locale = utils . get_current_locale ( ) )
def _decode ( self , s ) : '''This converts from the external coding system ( as passed to the constructor ) to the internal one ( unicode ) .'''
if self . decoder is not None : return self . decoder . decode ( s ) else : raise TypeError ( "This screen was constructed with encoding=None, " "so it does not handle bytes." )
async def main ( ) -> None : """Create the aiohttp session and run the example ."""
loglevels = dict ( ( logging . getLevelName ( level ) , level ) for level in [ 10 , 20 , 30 , 40 , 50 ] ) logging . basicConfig ( level = loglevels [ LOGLEVEL ] , format = '%(asctime)s:%(levelname)s:\t%(name)s\t%(message)s' ) async with ClientSession ( ) as websession : try : myq = await pymyq . login ( MYQ...
def _solution_factory ( self , basis_kwargs , coefs_array , nodes , problem , result ) : """Construct a representation of the solution to the boundary value problem . Parameters basis _ kwargs : dict ( str : ) coefs _ array : numpy . ndarray problem : TwoPointBVPLike result : OptimizeResult Returns so...
soln_coefs = self . _array_to_list ( coefs_array , problem . number_odes ) soln_derivs = self . _construct_derivatives ( soln_coefs , ** basis_kwargs ) soln_funcs = self . _construct_functions ( soln_coefs , ** basis_kwargs ) soln_residual_func = self . _interior_residuals_factory ( soln_derivs , soln_funcs , problem )...
def decomposed_diffusion_program ( qubits : List [ int ] ) -> Program : """Constructs the diffusion operator used in Grover ' s Algorithm , acted on both sides by an a Hadamard gate on each qubit . Note that this means that the matrix representation of this operator is diag ( 1 , - 1 , . . . , - 1 ) . In partic...
program = Program ( ) if len ( qubits ) == 1 : program . inst ( Z ( qubits [ 0 ] ) ) else : program . inst ( [ X ( q ) for q in qubits ] ) program . inst ( H ( qubits [ - 1 ] ) ) program . inst ( RZ ( - np . pi , qubits [ 0 ] ) ) program += ( ControlledProgramBuilder ( ) . with_controls ( qubits [ :...
def check_for_required_columns ( problems : List , table : str , df : DataFrame ) -> List : """Check that the given GTFS table has the required columns . Parameters problems : list A four - tuple containing 1 . A problem type ( string ) equal to ` ` ' error ' ` ` or ` ` ' warning ' ` ` ; ` ` ' error ' ` `...
r = cs . GTFS_REF req_columns = r . loc [ ( r [ "table" ] == table ) & r [ "column_required" ] , "column" ] . values for col in req_columns : if col not in df . columns : problems . append ( [ "error" , f"Missing column {col}" , table , [ ] ] ) return problems
def dict_to_dataset ( data , * , attrs = None , library = None , coords = None , dims = None ) : """Convert a dictionary of numpy arrays to an xarray . Dataset . Parameters data : dict [ str ] - > ndarray Data to convert . Keys are variable names . attrs : dict Json serializable metadata to attach to the ...
if dims is None : dims = { } data_vars = { } for key , values in data . items ( ) : data_vars [ key ] = numpy_to_data_array ( values , var_name = key , coords = coords , dims = dims . get ( key ) ) return xr . Dataset ( data_vars = data_vars , attrs = make_attrs ( attrs = attrs , library = library ) )
def maybe_download_and_extract ( ) : """Download and extract the tarball from Alex ' s website ."""
dest_directory = "/tmp/cifar" if not os . path . exists ( dest_directory ) : os . makedirs ( dest_directory ) filename = DATA_URL . split ( '/' ) [ - 1 ] filepath = os . path . join ( dest_directory , filename ) if not os . path . exists ( filepath ) : def _progress ( count , block_size , total_size ) : ...
def getFailureMessage ( failure ) : """Return a short message based on L { twisted . python . failure . Failure } . Tries to find where the exception was triggered ."""
str ( failure . type ) failure . getErrorMessage ( ) if len ( failure . frames ) == 0 : return "failure %(exc)s: %(msg)s" % locals ( ) ( func , filename , line , some , other ) = failure . frames [ - 1 ] filename = scrubFilename ( filename ) return "failure %(exc)s at %(filename)s:%(line)s: %(func)s(): %(msg)s" % l...
def indices_to_points ( indices , pitch , origin ) : """Convert indices of an ( n , m , p ) matrix into a set of voxel center points . Parameters indices : ( q , 3 ) int , index of voxel matrix ( n , m , p ) pitch : float , what pitch was the voxel matrix computed with origin : ( 3 , ) float , what is the o...
indices = np . asanyarray ( indices , dtype = np . float64 ) origin = np . asanyarray ( origin , dtype = np . float64 ) pitch = float ( pitch ) if indices . shape != ( indices . shape [ 0 ] , 3 ) : from IPython import embed embed ( ) raise ValueError ( 'shape of indices must be (q, 3)' ) if origin . shape !...
def move ( self , item , new_index ) : """Move an item to the given position . > > > u = Unique ( [ ' spam ' , ' eggs ' ] ) > > > u . move ( ' spam ' , 1) Unique ( [ ' eggs ' , ' spam ' ] ) > > > u . move ( ' ham ' , 0) Traceback ( most recent call last ) : ValueError : ' ham ' is not in list"""
idx = self . _items . index ( item ) if idx != new_index : item = self . _items . pop ( idx ) self . _items . insert ( new_index , item )
def _interfaces_added ( self , object_path , interfaces_and_properties ) : """Internal method ."""
added = object_path not in self . _objects self . _objects . setdefault ( object_path , { } ) old_state = copy ( self . _objects [ object_path ] ) self . _objects [ object_path ] . update ( interfaces_and_properties ) new_state = self . _objects [ object_path ] if added : kind = object_kind ( object_path ) if k...
def p_throw_statement ( self , p ) : """throw _ statement : THROW expr SEMI | THROW expr AUTOSEMI"""
p [ 0 ] = self . asttypes . Throw ( expr = p [ 2 ] ) p [ 0 ] . setpos ( p )
def pack ( self , value , nocheck = False , major = DEFAULT_KATCP_MAJOR ) : """Return the value formatted as a KATCP parameter . Parameters value : object The value to pack . nocheck : bool , optional Whether to check that the value is valid before packing it . major : int , optional Major version o...
if value is None : value = self . get_default ( ) if value is None : raise ValueError ( "Cannot pack a None value." ) if not nocheck : self . check ( value , major ) return self . encode ( value , major )
def delete ( filething ) : """delete ( filething ) Arguments : filething ( filething ) Raises : mutagen . MutagenError Remove tags from a file ."""
t = OggFLAC ( filething ) filething . fileobj . seek ( 0 ) t . delete ( filething )
def axis_names_without ( self , axis ) : """Return axis names without axis , or None if axis _ names is None"""
if self . axis_names is None : return None return itemgetter ( * self . other_axes ( axis ) ) ( self . axis_names )
def delete ( self ) : """Deletes the directory if it exists ."""
if self . exists : logger . info ( "Deleting %s" % self . path ) shutil . rmtree ( self . path )
def build ( self , text , matrix , skim_depth = 10 , d_weights = False ) : """1 . For each term in the passed matrix , score its KDE similarity with all other indexed terms . 2 . With the ordered stack of similarities in hand , skim off the top X pairs and add them as edges . Args : text ( Text ) : The so...
for anchor in bar ( matrix . keys ) : n1 = text . unstem ( anchor ) # Heaviest pair scores : pairs = matrix . anchored_pairs ( anchor ) . items ( ) for term , weight in list ( pairs ) [ : skim_depth ] : # If edges represent distance , use the complement of the raw # score , so that similar words are...
def get_route ( self , file_id ) : '''a method to retrieve route information for file on telegram api : param file _ id : string with id of file in a message send to bot : return : dictionary of response details with route details in [ json ] [ result ]'''
title = '%s.get_route' % self . __class__ . __name__ # validate inputs input_fields = { 'file_id' : file_id , } for key , value in input_fields . items ( ) : if value : object_title = '%s(%s=%s)' % ( title , key , str ( value ) ) self . fields . validate ( value , '.%s' % key , object_title ) # cons...
def get_points_within_r ( center_points , target_points , r ) : r"""Get all target _ points within a specified radius of a center point . All data must be in same coordinate system , or you will get undetermined results . Parameters center _ points : ( X , Y ) ndarray location from which to grab surrounding...
tree = cKDTree ( target_points ) indices = tree . query_ball_point ( center_points , r ) return tree . data [ indices ] . T
def update_available ( after_days = 1 ) : """Check whether updated NRFA data is available . : param after _ days : Only check if not checked previously since a certain number of days ago : type after _ days : float : return : ` True ` if update available , ` False ` if not , ` None ` if remote location cannot...
never_downloaded = not bool ( config . get ( 'nrfa' , 'downloaded_on' , fallback = None ) or None ) if never_downloaded : config . set_datetime ( 'nrfa' , 'update_checked_on' , datetime . utcnow ( ) ) config . save ( ) return True last_checked_on = config . get_datetime ( 'nrfa' , 'update_checked_on' , fall...
def add_r_ending_to_syllable ( last_syllable : str , is_first = True ) -> str : """Adds an the - r ending to the last syllable of an Old Norse word . In some cases , it really adds an - r . In other cases , it on doubles the last character or left the syllable unchanged . > > > add _ r _ ending _ to _ syllabl...
if len ( last_syllable ) >= 2 : if last_syllable [ - 1 ] in [ 'l' , 'n' , 's' , 'r' ] : if last_syllable [ - 2 ] in CONSONANTS : # Apocope of r return last_syllable else : # Assimilation of r if len ( last_syllable ) >= 3 and last_syllable [ - 3 : - 1 ] in DIPHTHONGS : ...
def dump_feature ( self , feature_name , feature , force_extraction = True ) : """Dumps a list of lists or ndarray of features into database ( allows to copy features from a pre - existing . txt / . csv / . whatever file , for example ) Parameters feature : list of lists or ndarray , contains the data to be w...
dump_feature_base ( self . dbpath , self . _set_object , self . points_amt , feature_name , feature , force_extraction ) return None
def _adjust_inserted_indices ( inserted_indices_list , prune_indices_list ) : """Adjust inserted indices , if there are pruned elements ."""
# Created a copy , to preserve cached property updated_inserted = [ [ i for i in dim_inds ] for dim_inds in inserted_indices_list ] pruned_and_inserted = zip ( prune_indices_list , updated_inserted ) for prune_inds , inserted_inds in pruned_and_inserted : # Only prune indices if they ' re not H & S ( inserted ) pru...
def is_mutating ( status ) : """Determines if the statement is mutating based on the status ."""
if not status : return False mutating = set ( [ 'insert' , 'update' , 'delete' , 'alter' , 'create' , 'drop' , 'replace' , 'truncate' , 'load' ] ) return status . split ( None , 1 ) [ 0 ] . lower ( ) in mutating
def deploy ( jboss_config , source_file ) : '''Deploy the application on the jboss instance from the local file system where minion is running . jboss _ config Configuration dictionary with properties specified above . source _ file Source file to deploy from CLI Example : . . code - block : : bash sa...
log . debug ( "======================== MODULE FUNCTION: jboss7.deploy, source_file=%s" , source_file ) command = 'deploy {source_file} --force ' . format ( source_file = source_file ) return __salt__ [ 'jboss7_cli.run_command' ] ( jboss_config , command , fail_on_error = False )
def until_state ( self , state , timeout = None ) : """Return a tornado Future that will resolve when the requested state is set"""
if state not in self . _valid_states : raise ValueError ( 'State must be one of {0}, not {1}' . format ( self . _valid_states , state ) ) if state != self . _state : if timeout : return with_timeout ( self . _ioloop . time ( ) + timeout , self . _waiting_futures [ state ] , self . _ioloop ) else : ...
def get_version_records ( self ) : """Yield RASH version information stored in DB . Latest first . : rtype : [ VersionRecord ]"""
keys = [ 'id' , 'rash_version' , 'schema_version' , 'updated' ] sql = """ SELECT id, rash_version, schema_version, updated FROM rash_info ORDER BY id DESC """ with self . connection ( ) as connection : for row in connection . execute ( sql ) : yield VersionRecord ( ** dict ( ...
def DbDeleteDeviceAlias ( self , argin ) : """Delete a device alias . : param argin : device alias name : type : tango . DevString : return : : rtype : tango . DevVoid"""
self . _log . debug ( "In DbDeleteDeviceAlias()" ) self . db . delete_device_alias ( argin )
def remove_outliers ( self , thresh = 3 , ** predict_kwargs ) : """Remove outliers from the GP with very simplistic outlier detection . Removes points that are more than ` thresh ` * ` err _ y ` away from the GP mean . Note that this is only very rough in that it ignores the uncertainty in the GP mean at any ...
mean = self . predict ( self . X , n = self . n , noise = False , return_std = False , output_transform = self . T , ** predict_kwargs ) deltas = scipy . absolute ( mean - self . y ) / self . err_y deltas [ self . err_y == 0 ] = 0 bad_idxs = ( deltas >= thresh ) good_idxs = ~ bad_idxs # Pull out the old values so they ...
def agent ( agent_id ) : '''Show the information about the given agent .'''
fields = [ ( 'ID' , 'id' ) , ( 'Status' , 'status' ) , ( 'Region' , 'region' ) , ( 'First Contact' , 'first_contact' ) , ( 'CPU Usage (%)' , 'cpu_cur_pct' ) , ( 'Used Memory (MiB)' , 'mem_cur_bytes' ) , ( 'Total slots' , 'available_slots' ) , ( 'Occupied slots' , 'occupied_slots' ) , ] if is_legacy_server ( ) : del...
def accept_connection ( self , name = None , alias = None , timeout = 0 ) : """Accepts a connection to server identified by ` name ` or the latest server if ` name ` is empty . If given an ` alias ` , the connection is named and can be later referenced with that name . If ` timeout ` is > 0 , the connection...
server = self . _servers . get ( name ) server . accept_connection ( alias , timeout )
def HasNonLSCTables ( elem ) : """Return True if the document tree below elem contains non - LSC tables , otherwise return False ."""
return any ( t . Name not in TableByName for t in elem . getElementsByTagName ( ligolw . Table . tagName ) )
def gate ( self , gate , ID = None , apply_now = True ) : '''Applies the gate to each Measurement in the Collection , returning a new Collection with gated data . { _ containers _ held _ in _ memory _ warning } Parameters gate : { _ gate _ available _ classes } ID : [ str , numeric , None ] New ID to be g...
def func ( well ) : return well . gate ( gate , apply_now = apply_now ) return self . apply ( func , output_format = 'collection' , ID = ID )
def change_mime ( self , bucket , key , mime ) : """修改文件mimeType : 主动修改指定资源的文件类型 , 具体规格参考 : http : / / developer . qiniu . com / docs / v6 / api / reference / rs / chgm . html Args : bucket : 待操作资源所在空间 key : 待操作资源文件名 mime : 待操作文件目标mimeType"""
resource = entry ( bucket , key ) encode_mime = urlsafe_base64_encode ( mime ) return self . __rs_do ( 'chgm' , resource , 'mime/{0}' . format ( encode_mime ) )
def _read_pyMatch ( fn , precursors ) : """read pyMatch file and perform realignment of hits"""
with open ( fn ) as handle : reads = defaultdict ( realign ) for line in handle : query_name , seq , chrom , reference_start , end , mism , add = line . split ( ) reference_start = int ( reference_start ) # chrom = handle . getrname ( cols [ 1 ] ) # print ( " % s % s % s % s " % ...
def fit_toy_potential ( orbit , force_harmonic_oscillator = False ) : """Fit a best fitting toy potential to the orbit provided . If the orbit is a tube ( loop ) orbit , use the Isochrone potential . If the orbit is a box potential , use the harmonic oscillator potential . An option is available to force usin...
circulation = orbit . circulation ( ) if np . any ( circulation == 1 ) and not force_harmonic_oscillator : # tube orbit logger . debug ( "===== Tube orbit =====" ) logger . debug ( "Using Isochrone toy potential" ) toy_potential = fit_isochrone ( orbit ) logger . debug ( "Best m={}, b={}" . format ( toy...
def memoize ( obj ) : """Decorator to create memoized functions , methods or classes ."""
cache = obj . cache = { } @ functools . wraps ( obj ) def memoizer ( * args , ** kwargs ) : if args not in cache : cache [ args ] = obj ( * args , ** kwargs ) return cache [ args ] return memoizer
def rm_gos ( self , rm_goids ) : """Remove any edges that contain user - specified edges ."""
self . edges = self . _rm_gos_edges ( rm_goids , self . edges ) self . edges_rel = self . _rm_gos_edges_rel ( rm_goids , self . edges_rel )
def bool ( cls , must = None , should = None , must_not = None , minimum_number_should_match = None , boost = None ) : '''http : / / www . elasticsearch . org / guide / reference / query - dsl / bool - query . html A query that matches documents matching boolean combinations of other queris . The bool query maps ...
instance = cls ( bool = { } ) if must is not None : instance [ 'bool' ] [ 'must' ] = must if should is not None : instance [ 'bool' ] [ 'should' ] = should if must_not is not None : instance [ 'bool' ] [ 'must_not' ] = must_not if minimum_number_should_match is not None : instance [ 'bool' ] [ 'minimum_...
def wcxf2arrays ( d ) : """Convert a dictionary with a Wilson coefficient name followed by underscore and numeric indices as keys and numbers as values to a dictionary with Wilson coefficient names as keys and numbers or numpy arrays as values . This is needed for the parsing of input in WCxf format ."""
C = { } for k , v in d . items ( ) : name = k . split ( '_' ) [ 0 ] s = C_keys_shape [ name ] if s == 1 : C [ k ] = v else : ind = k . split ( '_' ) [ - 1 ] if name not in C : C [ name ] = np . zeros ( s , dtype = complex ) C [ name ] [ tuple ( [ int ( i ) - 1...
def get_export ( self , export_type , generate = False , wait = False , wait_timeout = None , ) : """Downloads a data export over HTTP . Returns a ` Requests Response < http : / / docs . python - requests . org / en / master / api / # requests . Response > ` _ object containing the content of the export . - *...
if generate : self . generate_export ( export_type ) if generate or wait : export = self . wait_export ( export_type , wait_timeout ) else : export = self . describe_export ( export_type ) if export_type in TALK_EXPORT_TYPES : media_url = export [ 'data_requests' ] [ 0 ] [ 'url' ] else : media_url =...
def readlines ( filename , encoding = 'utf-8' ) : """Read lines from file ( ' filename ' ) Return lines and encoding"""
text , encoding = read ( filename , encoding ) return text . split ( os . linesep ) , encoding
def xpathRegisterNs ( self , prefix , ns_uri ) : """Register a new namespace . If @ ns _ uri is None it unregisters the namespace"""
ret = libxml2mod . xmlXPathRegisterNs ( self . _o , prefix , ns_uri ) return ret
def save_state ( self , out_path ) : """Save the current state of this emulated object to a file . Args : out _ path ( str ) : The path to save the dumped state of this emulated object ."""
state = self . dump_state ( ) # Remove all IntEnums from state since they cannot be json - serialized on python 2.7 # See https : / / bitbucket . org / stoneleaf / enum34 / issues / 17 / difference - between - enum34 - and - enum - json state = _clean_intenum ( state ) with open ( out_path , "w" ) as outfile : json...
def __auth_descriptor ( self , api_info ) : """Builds an auth descriptor from API info . Args : api _ info : An _ ApiInfo object . Returns : A dictionary with ' allowCookieAuth ' and / or ' blockedRegions ' keys ."""
if api_info . auth is None : return None auth_descriptor = { } if api_info . auth . allow_cookie_auth is not None : auth_descriptor [ 'allowCookieAuth' ] = api_info . auth . allow_cookie_auth if api_info . auth . blocked_regions : auth_descriptor [ 'blockedRegions' ] = api_info . auth . blocked_regions retu...
def _setup_ctx ( self , ctx ) : "Should be called by any derived plugin ' s setup _ ctx ( ) function ."
ctx . strict = True ctx . canonical = True ctx . max_identifier_len = 64 ctx . implicit_errors = False # always add additional prefixes given on the command line self . namespace_prefixes . extend ( ctx . opts . lint_namespace_prefixes ) self . modulename_prefixes . extend ( ctx . opts . lint_modulename_prefixes ) # re...
def backend_routing ( self , context ) : """Returns the targeted backend and an updated state : type context : satosa . context . Context : rtype satosa . backends . base . BackendModule : param context : The request context : return : backend"""
satosa_logging ( logger , logging . DEBUG , "Routing to backend: %s " % context . target_backend , context . state ) backend = self . backends [ context . target_backend ] [ "instance" ] context . state [ STATE_KEY ] = context . target_frontend return backend
def sizeAdjust ( self ) : """If the glyph is bigger than the font ( because the user set it smaller ) this should be able to shorten the size"""
font_width , font_height = self . font_bbox [ : 2 ] self . width = min ( self . width , font_width ) self . height = min ( self . height , font_height ) self . bbox [ : 2 ] = self . width , self . height self . crop ( )
def swagger_definition ( self , base_path = None , ** kwargs ) : """return a valid swagger spec , with the values passed ."""
return Swagger ( { "info" : Info ( { key : kwargs . get ( key , self . DEFAULT_INFO . get ( key ) ) for key in Info . fields . keys ( ) if key in kwargs or key in self . DEFAULT_INFO } ) , "paths" : self . paths , "swagger" : "2.0" , "basePath" : base_path , } ) . to_primitive ( )
def read_tx_witnesses ( ptr , tx , num_witnesses ) : """Returns an array of witness scripts . Each witness will be a bytestring ( i . e . encoding the witness script )"""
witnesses = [ ] for i in xrange ( 0 , num_witnesses ) : witness_stack_len = read_var_int ( ptr , tx ) witness_stack = [ ] for j in xrange ( 0 , witness_stack_len ) : stack_item = read_var_string ( ptr , tx ) witness_stack . append ( stack_item ) witness_script = btc_witness_script_serial...
def sparse_toy_linear_1d_classification_uncertain_input ( num_inducing = 10 , seed = default_seed , optimize = True , plot = True ) : """Sparse 1D classification example : param seed : seed value for data generation ( default is 4 ) . : type seed : int"""
try : import pods except ImportError : print ( 'pods unavailable, see https://github.com/sods/ods for example datasets' ) import numpy as np data = pods . datasets . toy_linear_1d_classification ( seed = seed ) Y = data [ 'Y' ] [ : , 0 : 1 ] Y [ Y . flatten ( ) == - 1 ] = 0 X = data [ 'X' ] X_var = np . random ...
def getCachedOrUpdatedValue ( self , key ) : """Gets the device ' s value with the given key . If the key is not found in the cache , the value is queried from the host ."""
try : return self . _VALUES [ key ] except KeyError : return self . getValue ( key )
def markdown_filter ( value , typogrify = True , extensions = ( 'extra' , 'codehilite' ) ) : """A smart wrapper around the ` ` markdown ` ` and ` ` typogrify ` ` functions that automatically removes leading whitespace before every line . This is necessary because Markdown is whitespace - sensitive . Consider some...
# Determine how many leading spaces there are , then remove that number from the beginning of each line . match = re . match ( r'(\n*)(\s*)' , value ) s , e = match . span ( 2 ) pattern = re . compile ( r'^ {%s}' % ( e - s ) , # use ^ in the pattern so mid - string matches won ' t be removed flags = re . MULTILINE ) # ...
def upload ( c , directory , index = None , sign = False , dry_run = False ) : """Upload ( potentially also signing ) all artifacts in ` ` directory ` ` . : param str index : Custom upload index / repository name . By default , uses whatever the invoked ` ` pip ` ` is configured to use . Modify your ` ` pyp...
# Obtain list of archive filenames , then ensure any wheels come first # so their improved metadata is what PyPI sees initially ( otherwise , it # only honors the sdist ' s lesser data ) . archives = list ( itertools . chain . from_iterable ( glob ( os . path . join ( directory , "dist" , "*.{0}" . format ( extension )...
def datagram_received ( self , data , addr ) : '''On datagram receive . : param data : : param addr : : return :'''
message = salt . utils . stringutils . to_unicode ( data ) if message . startswith ( self . signature ) : try : timestamp = float ( message [ len ( self . signature ) : ] ) except ( TypeError , ValueError ) : self . log . debug ( 'Received invalid timestamp in package from %s:%s' , * addr ) ...
def start_all ( self ) : """Starts all inactive service instances ."""
for alias , service in self . _service_objects . items ( ) : if not service . is_alive : with expects . expect_no_raises ( 'Failed to start service "%s".' % alias ) : service . start ( )
def multiline_repr ( text , special_chars = ( '\n' , '"' ) ) : """Get string representation for triple quoted context . Make string representation as normal except do not transform " special characters " into an escaped representation to support use of the representation in a triple quoted multi - line string...
try : char = special_chars [ 0 ] except IndexError : text = ascii ( text ) [ 2 if PY2 else 1 : - 1 ] else : text = char . join ( multiline_repr ( s , special_chars [ 1 : ] ) for s in text . split ( char ) ) return text
def list_member_events ( self , upcoming = True ) : '''a method to retrieve a list of events member attended or will attend : param upcoming : [ optional ] boolean to filter list to only future events : return : dictionary with list of event details inside [ json ] key event _ details = self . _ reconstruct _...
# https : / / www . meetup . com / meetup _ api / docs / self / events / # construct request fields url = '%s/self/events' % self . endpoint params = { 'status' : 'past' , 'fields' : 'comment_count,event_hosts,rsvp_rules,short_link,survey_questions,rsvpable' } if upcoming : params [ 'status' ] = 'upcoming' # send r...
def summarize ( self , text , topics = 4 , length = 5 , binary_matrix = True , topic_sigma_threshold = 0.5 ) : """Implements the method of latent semantic analysis described by Steinberger and Jezek in the paper : J . Steinberger and K . Jezek ( 2004 ) . Using latent semantic analysis in text summarization and su...
text = self . _parse_input ( text ) sentences , unprocessed_sentences = self . _tokenizer . tokenize_sentences ( text ) length = self . _parse_summary_length ( length , len ( sentences ) ) if length == len ( sentences ) : return unprocessed_sentences topics = self . _validate_num_topics ( topics , sentences ) # Gen...
def _calc_avg_and_last_val ( self , has_no_column , sum_existing_columns ) : """Calculate the average of all columns and return a rounded down number . Store the remainder and add it to the last row . Could be implemented better . If the enduser wants more control , he can also just add the amount of columns ...
sum_no_columns = len ( has_no_column ) columns_left = self . ALLOWED_COLUMNS - sum_existing_columns if sum_no_columns == 0 : columns_avg = columns_left else : columns_avg = int ( columns_left / sum_no_columns ) remainder = columns_left - ( columns_avg * sum_no_columns ) columns_for_last_element = columns_avg + ...
def _Rzderiv ( self , R , z , phi = 0. , t = 0. ) : """NAME : _ Rzderiv PURPOSE : evaluate the mixed radial , vertical derivative for this potential INPUT : R - Galactocentric cylindrical radius z - vertical height phi - azimuth t - time OUTPUT : the mixed radial , vertical derivative"""
if not self . isNonAxi : phi = 0. x , y , z = self . _compute_xyz ( R , phi , z , t ) phixza = self . _2ndderiv_xyz ( x , y , z , 0 , 2 ) phiyza = self . _2ndderiv_xyz ( x , y , z , 1 , 2 ) ang = self . _omegab * t + self . _pa c , s = np . cos ( ang ) , np . sin ( ang ) phixz = c * phixza + s * phiyza phiyz = - s ...
def put ( self , path , body ) : """PUT request ."""
return self . _make_request ( 'put' , self . _format_url ( API_ROOT + path ) , { 'json' : body } )
def _render_rows ( self ) : """Render the rows in the current stylesheet"""
_datas = getattr ( self , '_datas' , ( ) ) headers = getattr ( self , 'headers' , ( ) ) for index , row in enumerate ( _datas ) : row_number = index + 2 for col_num , value in enumerate ( row ) : cell = self . worksheet . cell ( row = row_number , column = col_num + 1 ) if value is not None : ...
def display_output ( data , out = None , opts = None , ** kwargs ) : '''Print the passed data using the desired output'''
if opts is None : opts = { } display_data = try_printout ( data , out , opts , ** kwargs ) output_filename = opts . get ( 'output_file' , None ) log . trace ( 'data = %s' , data ) try : # output filename can be either ' ' or None if output_filename : if not hasattr ( output_filename , 'write' ) : ...
def _prepare_configs ( configs , requires_filters , temporal_timeouts ) : """Overrides the filters specified in the decorator with the given ones : param configs : Field → ( Requirement , key , allow _ none ) dictionary : param requires _ filters : Content of the ' requires . filter ' component property ( fie...
if not isinstance ( requires_filters , dict ) : requires_filters = { } if not isinstance ( temporal_timeouts , dict ) : temporal_timeouts = { } if not requires_filters and not temporal_timeouts : # No explicit configuration given return configs # We need to change a part of the requirements new_configs = { ...
def check_wlcalib_sp ( sp , crpix1 , crval1 , cdelt1 , wv_master , coeff_ini = None , naxis1_ini = None , min_nlines_to_refine = 0 , interactive = False , threshold = 0 , nwinwidth_initial = 7 , nwinwidth_refined = 5 , ntimes_match_wv = 2 , poldeg_residuals = 1 , times_sigma_reject = 5 , use_r = False , title = None , ...
# protections if type ( sp ) is not np . ndarray : raise ValueError ( "sp must be a numpy.ndarray" ) elif sp . ndim != 1 : raise ValueError ( "sp.ndim is not 1" ) if coeff_ini is None and naxis1_ini is None : pass elif coeff_ini is not None and naxis1_ini is not None : pass else : raise ValueError (...
def minimum_dtype ( x , dtype = np . bool_ ) : """returns the " most basic " dtype which represents ` x ` properly , which provides at least the same value range as the specified dtype ."""
def check_type ( x , dtype ) : try : converted = dtype . type ( x ) except ( ValueError , OverflowError ) : return False # False if some overflow has happened return converted == x or np . isnan ( x ) def type_loop ( x , dtype , dtype_dict , default = None ) : while True : tr...
def init_app ( self , app ) : """Flask application initialization ."""
self . init_config ( app ) app . extensions [ 'inspire-crawler' ] = self app . cli . add_command ( crawler_cmd )
def naturaldate ( value ) : """Like naturalday , but will append a year for dates that are a year ago or more ."""
try : value = date ( value . year , value . month , value . day ) except AttributeError : # Passed value wasn ' t date - ish return value except ( OverflowError , ValueError ) : # Date arguments out of range return value delta = abs_timedelta ( value - date . today ( ) ) if delta . days >= 365 : return ...
def _read_channel ( channel , stream , start , duration ) : """Get channel using lalframe"""
channel_type = lalframe . FrStreamGetTimeSeriesType ( channel , stream ) read_func = _fr_type_map [ channel_type ] [ 0 ] d_type = _fr_type_map [ channel_type ] [ 1 ] data = read_func ( stream , channel , start , duration , 0 ) return TimeSeries ( data . data . data , delta_t = data . deltaT , epoch = start , dtype = d_...
def delete ( self , url , params = None ) : """Executes an HTTP DELETE request for the given URL . ` ` params ` ` should be a dictionary"""
response = self . http . delete ( url , params = params , ** self . requests_params ) return self . process ( response )
def interpolate ( self , ** options ) : """Interpolate Irradiance to a specified evenly spaced resolution / grid This is necessary to make integration and folding ( with a channel relative spectral response ) straightforward . dlambda = wavelength interval in microns start = Start of the wavelength interval...
from scipy . interpolate import InterpolatedUnivariateSpline # The user defined wavelength span is not yet used : # FIXME ! if 'ival_wavelength' in options : ival_wavelength = options [ 'ival_wavelength' ] else : ival_wavelength = None if 'dlambda' in options : self . _dlambda = options [ 'dlambda' ] if iva...
def tweets_default ( * args ) : """Tweets for the default settings ."""
query_type = settings . TWITTER_DEFAULT_QUERY_TYPE args = ( settings . TWITTER_DEFAULT_QUERY , settings . TWITTER_DEFAULT_NUM_TWEETS ) per_user = None if query_type == QUERY_TYPE_LIST : per_user = 1 return tweets_for ( query_type , args , per_user = per_user )
def serialize ( self , tag ) : """Return the literal representation of a tag ."""
handler = getattr ( self , f'serialize_{tag.serializer}' , None ) if handler is None : raise TypeError ( f'Can\'t serialize {type(tag)!r} instance' ) return handler ( tag )
def client_receives_message ( self , * parameters ) : """Receive a message with template defined using ` New Message ` and validate field values . Message template has to be defined with ` New Message ` before calling this . Optional parameters : - ` name ` the client name ( default is the latest used ) e...
with self . _receive ( self . _clients , * parameters ) as ( msg , message_fields , header_fields ) : self . _validate_message ( msg , message_fields , header_fields ) return msg
def enrich ( self , column ) : """This method calculates thanks to the genderize . io API the gender of a given name . This method initially assumes that for the given string , only the first word is the one containing the name eg : Daniel Izquierdo < dizquierdo @ bitergia . com > , Daniel would be the name...
if column not in self . data . columns : return self . data splits = self . data [ column ] . str . split ( " " ) splits = splits . str [ 0 ] self . data [ "gender_analyzed_name" ] = splits . fillna ( "noname" ) self . data [ "gender_probability" ] = 0 self . data [ "gender" ] = "Unknown" self . data [ "gender_coun...