signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def wrap_tmpl ( self , tmpl ) : '''return the warpped template path . : param tmpl :'''
return 'admin/' + tmpl . format ( sig = 'p' ) if self . is_p else tmpl . format ( sig = '' )
def from_file ( cls , path ) : """Create a ` ` Configuration ` ` from a file : param path : path to YAML file : return : new configuration : rtype : ` ` Configuration ` `"""
if path == '-' : return Configuration ( yaml . safe_load ( sys . stdin ) ) if not osp . exists ( path ) and not osp . isabs ( path ) : path = osp . join ( osp . dirname ( osp . abspath ( __file__ ) ) , path ) with open ( path , 'r' ) as istr : return Configuration ( yaml . safe_load ( istr ) )
def query_paths ( self ) : """RETURN A LIST OF ALL NESTED COLUMNS"""
output = self . namespace . alias_to_query_paths . get ( self . name ) if output : return output Log . error ( "Can not find index {{index|quote}}" , index = self . name )
def xml_import ( self , filepath = None , xml_content = None , markings = None , identifier_ns_uri = None , initialize_importer = True , ** kwargs ) : """Import an OpenIOC indicator xml ( root element ' ioc ' ) from file < filepath > or from a string < xml _ content > You can provide : - a list of markings wi...
if initialize_importer : # Clear state in case xml _ import is used several times , but keep namespace info self . __init__ ( ) # Initialize default arguments # ' [ ] ' would be mutable , so we initialize here if not markings : markings = [ ] # Initializing here allows us to also get the default namespace when ...
def get_transaction_by_tx_hash ( self , tx_hash : str , is_full : bool = False ) -> dict : """This interface is used to get the corresponding transaction information based on the specified hash value . : param tx _ hash : str , a hexadecimal hash value . : param is _ full : : return : dict"""
payload = self . generate_json_rpc_payload ( RpcMethod . GET_TRANSACTION , [ tx_hash , 1 ] ) response = self . __post ( self . __url , payload ) if is_full : return response return response [ 'result' ]
def n_waiting ( self ) : """Return the number of jobs in various waiting states"""
return self . _counters [ JobStatus . no_job ] + self . _counters [ JobStatus . unknown ] + self . _counters [ JobStatus . not_ready ] + self . _counters [ JobStatus . ready ]
def wrap_method ( func , default_retry = None , default_timeout = None , client_info = client_info . DEFAULT_CLIENT_INFO , ) : """Wrap an RPC method with common behavior . This applies common error wrapping , retry , and timeout behavior a function . The wrapped function will take optional ` ` retry ` ` and ` `...
func = grpc_helpers . wrap_errors ( func ) if client_info is not None : user_agent_metadata = [ client_info . to_grpc_metadata ( ) ] else : user_agent_metadata = None return general_helpers . wraps ( func ) ( _GapicCallable ( func , default_retry , default_timeout , metadata = user_agent_metadata ) )
def run ( self , text ) : """Run each regex substitution on ` ` text ` ` . Args : text ( string ) : the input text . Returns : string : text after all substitutions have been sequentially applied ."""
for regex in self . regexes : text = regex . sub ( self . repl , text ) return text
def get_connection_by_slot ( self , slot ) : """Determine what server a specific slot belongs to and return a redis object that is connected"""
self . _checkpid ( ) try : return self . get_connection_by_node ( self . get_node_by_slot ( slot ) ) except KeyError : return self . get_random_connection ( )
def restore_state ( self , state ) : """Restore the current state of this emulated device . Note that restore _ state happens synchronously in the emulation thread to avoid any race conditions with accessing data members and ensure a consistent atomic restoration process . This method will block while the b...
state_name = state . get ( 'state_name' ) state_version = state . get ( 'state_version' ) if state_name != self . STATE_NAME or state_version != self . STATE_VERSION : raise ArgumentError ( "Invalid emulated device state name or version" , found = ( state_name , state_version ) , expected = ( self . STATE_NAME , se...
def get_assign_groups ( line , ops = ops ) : """Split a line into groups by assignment ( including augmented assignment )"""
group = [ ] for item in line : group . append ( item ) if item in ops : yield group group = [ ] yield group
def archive_wheelfile ( base_name , base_dir ) : """Archive all files under ` base _ dir ` in a whl file and name it like ` base _ name ` ."""
olddir = os . path . abspath ( os . curdir ) base_name = os . path . abspath ( base_name ) try : os . chdir ( base_dir ) return make_wheelfile_inner ( base_name ) finally : os . chdir ( olddir )
def make_entropy_col_consensus ( bg_freqs ) : """Consensus according to maximal relative entropy term ( MET ) . For a given column i , choose the residue j with the highest relative entropy term : : f _ ij ln ( f _ ij / b _ j ) where f _ ij = column aa frequency , b _ j = background aa frequency . Source ...
def col_consensus ( col ) : col_freqs = sequtils . aa_frequencies ( col ) entroper = entropy_func ( col_freqs , bg_freqs ) return max ( col_freqs . keys ( ) , key = entroper ) return col_consensus
def backup_minion ( path , bkroot ) : '''Backup a file on the minion'''
dname , bname = os . path . split ( path ) if salt . utils . platform . is_windows ( ) : src_dir = dname . replace ( ':' , '_' ) else : src_dir = dname [ 1 : ] if not salt . utils . platform . is_windows ( ) : fstat = os . stat ( path ) msecs = six . text_type ( int ( time . time ( ) * 1000000 ) ) [ - 6 : ]...
def get_virtual_machine_scale_set_network_interface ( name , scale_set , vm_index , resource_group , ** kwargs ) : '''. . versionadded : : 2019.2.0 Get information about a specfic network interface within a scale set . : param name : The name of the network interface to query . : param scale _ set : The name ...
expand = kwargs . get ( 'expand' ) netconn = __utils__ [ 'azurearm.get_client' ] ( 'network' , ** kwargs ) try : nic = netconn . network_interfaces . list_virtual_machine_scale_set_vm_network_interfaces ( network_interface_name = name , virtual_machine_scale_set_name = scale_set , virtualmachine_index = vm_index , ...
def with_empty_graph ( cls , molecule , name = "bonds" , edge_weight_name = None , edge_weight_units = None ) : """Constructor for MoleculeGraph , returns a MoleculeGraph object with an empty graph ( no edges , only nodes defined that correspond to Sites in Molecule ) . : param molecule ( Molecule ) : : par...
if edge_weight_name and ( edge_weight_units is None ) : raise ValueError ( "Please specify units associated " "with your edge weights. Can be " "empty string if arbitrary or " "dimensionless." ) # construct graph with one node per site # graph attributes don ' t change behavior of graph , # they ' re just for book ...
def get_current_item ( self ) : """Returns ( first ) selected item or None"""
l = self . selectedIndexes ( ) if len ( l ) > 0 : return self . model ( ) . get_item ( l [ 0 ] )
def copystat ( self , target ) : """Copies the permissions , times and flags from this to the ` target ` . The owner is not copied ."""
shutil . copystat ( self . path , self . _to_backend ( target ) )
def wipe_partition ( self , partition ) : """Deletes analysis result of partition , e . g . so a repeat optimisation of the same partition can be done with a different model"""
for grp in partition . get_membership ( ) : grpid = self . scorer . get_id ( grp ) cache_dir = self . scorer . cache_dir prog = self . scorer . task_interface . name filename = os . path . join ( cache_dir , '{}.{}.json' . format ( grpid , prog ) ) if os . path . exists ( filename ) : os . u...
def encode_to_json ( order_list ) : """Encodes this list of MarketOrder instances to a JSON string . : param MarketOrderList order _ list : The order list to serialize . : rtype : str"""
rowsets = [ ] for items_in_region_list in order_list . _orders . values ( ) : region_id = items_in_region_list . region_id type_id = items_in_region_list . type_id generated_at = gen_iso_datetime_str ( items_in_region_list . generated_at ) rows = [ ] for order in items_in_region_list . orders : ...
def core ( self , key , value ) : """Populate the ` ` core ` ` key . Also populates the ` ` deleted ` ` and ` ` project _ type ` ` keys through side effects ."""
core = self . get ( 'core' ) deleted = self . get ( 'deleted' ) project_type = self . get ( 'project_type' , [ ] ) if not core : normalized_a_values = [ el . upper ( ) for el in force_list ( value . get ( 'a' ) ) ] if 'CORE' in normalized_a_values : core = True if not deleted : normalized_c_values =...
def _form_datetimes ( days , msecs ) : """Calculate seconds since EPOCH from days and milliseconds for each of IASI scan ."""
all_datetimes = [ ] for i in range ( days . size ) : day = int ( days [ i ] ) msec = msecs [ i ] scanline_datetimes = [ ] for j in range ( int ( VALUES_PER_SCAN_LINE / 4 ) ) : usec = 1000 * ( j * VIEW_TIME_ADJUSTMENT + msec ) delta = ( dt . timedelta ( days = day , microseconds = usec ) ...
def grade ( PmagRec , ACCEPT , type , data_model = 2.5 ) : """Finds the ' grade ' ( pass / fail ; A / F ) of a record ( specimen , sample , site ) given the acceptance criteria"""
GREATERTHAN = [ 'specimen_q' , 'site_k' , 'site_n' , 'site_n_lines' , 'site_int_n' , 'measurement_step_min' , 'specimen_int_ptrm_n' , 'specimen_fvds' , 'specimen_frac' , 'specimen_f' , 'specimen_n' , 'specimen_int_n' , 'sample_int_n' , 'average_age_min' , 'average_k' , 'average_r' , 'specimen_magn_moment' , 'specimen_m...
def fail_print ( error ) : """Print an error in red text . Parameters error ( HTTPError ) Error object to print ."""
print ( COLORS . fail , error . message , COLORS . end ) print ( COLORS . fail , error . errors , COLORS . end )
def _dep_id ( self , dependency ) : """Returns a tuple of dependency _ id , is _ internal _ dep ."""
params = dict ( sep = self . separator ) if isinstance ( dependency , JarDependency ) : # TODO ( kwilson ) : handle ' classifier ' and ' type ' . params . update ( org = dependency . org , name = dependency . name , rev = dependency . rev ) is_internal_dep = False else : params . update ( org = 'internal' ,...
def get_param_list_for_prediction ( model_obj , replicates ) : """Create the ` param _ list ` argument for use with ` model _ obj . predict ` . Parameters model _ obj : an instance of an MNDC object . Should have the following attributes : ` [ ' ind _ var _ names ' , ' intercept _ names ' , ' shape _ names ...
# Check the validity of the passed arguments ensure_samples_is_ndim_ndarray ( replicates , ndim = 2 , name = 'replicates' ) # Determine the number of index coefficients , outside intercepts , # shape parameters , and nest parameters num_idx_coefs = len ( model_obj . ind_var_names ) intercept_names = model_obj . interce...
def _setup_logging ( args ) : """Set up logging for the script , based on the configuration specified by the ' logging ' attribute of the command line arguments . : param args : A Namespace object containing a ' logging ' attribute specifying the name of a logging configuration file to use . If not presen...
log_conf = getattr ( args , 'logging' , None ) if log_conf : logging . config . fileConfig ( log_conf ) else : logging . basicConfig ( )
def RightClick ( cls ) : '''右键点击1次'''
element = cls . _element ( ) action = ActionChains ( Web . driver ) action . context_click ( element ) action . perform ( )
def init_hmm ( observations , nstates , lag = 1 , output = None , reversible = True ) : """Use a heuristic scheme to generate an initial model . Parameters observations : list of ndarray ( ( T _ i ) ) list of arrays of length T _ i with observation data nstates : int The number of states . output : str ...
# select output model type if output is None : output = _guess_output_type ( observations ) if output == 'discrete' : return init_discrete_hmm ( observations , nstates , lag = lag , reversible = reversible ) elif output == 'gaussian' : return init_gaussian_hmm ( observations , nstates , lag = lag , reversib...
def get_bounds ( self ) : """Get the mesh bounds Returns bounds : list A list of tuples of mesh bounds ."""
if self . _vertices_indexed_by_faces is not None : v = self . _vertices_indexed_by_faces elif self . _vertices is not None : v = self . _vertices else : return None bounds = [ ( v [ : , ax ] . min ( ) , v [ : , ax ] . max ( ) ) for ax in range ( v . shape [ 1 ] ) ] return bounds
def put_mouse_event ( self , dx , dy , dz , dw , button_state ) : """Initiates a mouse event using relative pointer movements along x and y axis . in dx of type int Amount of pixels the mouse should move to the right . Negative values move the mouse to the left . in dy of type int Amount of pixels the m...
if not isinstance ( dx , baseinteger ) : raise TypeError ( "dx can only be an instance of type baseinteger" ) if not isinstance ( dy , baseinteger ) : raise TypeError ( "dy can only be an instance of type baseinteger" ) if not isinstance ( dz , baseinteger ) : raise TypeError ( "dz can only be an instance o...
def writeCache ( self , cachekey , content ) : """stores content in cache . ' cachekey ' must be the same key as returned from checkCache ( ) . Returns the content ."""
self . rendercache [ cachekey ] = content try : open ( cachekey , 'w' ) . write ( content ) except : print ( "Error writing cache file" , cachekey , ", will regenerate next time" ) traceback . print_exc ( ) return content
def _consistent ( self ) : """Checks the constency between self . _ _ index and self . _ _ order"""
if len ( self . __order ) != sum ( len ( values ) for values in self . __index . values ( ) ) : return False import copy tmp = copy . copy ( self . __order ) for key , values in self . __index . items ( ) : for value in values : if value . name != key : return False if value in tmp :...
def fetch ( cwd , remote = None , force = False , refspecs = None , opts = '' , git_opts = '' , user = None , password = None , identity = None , ignore_retcode = False , saltenv = 'base' , output_encoding = None ) : '''. . versionchanged : : 2015.8.2 Return data is now a dictionary containing information on bran...
cwd = _expand_path ( cwd , user ) command = [ 'git' ] + _format_git_opts ( git_opts ) command . append ( 'fetch' ) if force : command . append ( '--force' ) command . extend ( [ x for x in _format_opts ( opts ) if x not in ( '-f' , '--force' ) ] ) if remote : command . append ( remote ) if refspecs is not None ...
def isNot ( self , value ) : """Sets the operator type to Query . Op . IsNot and sets the value to the inputted value . : param value < variant > : return < Query > : sa _ _ ne _ _ : usage | > > > from orb import Query as Q | > > > query = Q ( ' test ' ) . isNot ( 1) | > > > print query | test is no...
newq = self . copy ( ) newq . setOp ( Query . Op . IsNot ) newq . setValue ( value ) return newq
def edit_comment ( repo : GithubRepository , text : str , comment_id : int ) -> None : """References : https : / / developer . github . com / v3 / issues / comments / # edit - a - comment"""
url = ( "https://api.github.com/repos/{}/{}/issues/comments/{}" "?access_token={}" . format ( repo . organization , repo . name , comment_id , repo . access_token ) ) data = { 'body' : text } response = requests . patch ( url , json = data ) if response . status_code != 200 : raise RuntimeError ( 'Edit comment fail...
def parent ( self , index ) : """Returns the parent of the model item with the given index . If the item has no parent , an invalid QModelIndex is returned . A common convention used in models that expose tree data structures is that only items in the first column have children . For that case , when reimplem...
if not index . isValid ( ) : return QtCore . QModelIndex ( ) childItem = self . getItem ( index , altItem = self . invisibleRootItem ) parentItem = childItem . parentItem if parentItem == self . invisibleRootItem : return QtCore . QModelIndex ( ) return self . createIndex ( parentItem . childNumber ( ) , 0 , pa...
def remove_entry ( self , entry ) : """Remove specified entry . : param entry : The Entry object to remove . : type entry : : class : ` keepassdb . model . Entry `"""
if not isinstance ( entry , Entry ) : raise TypeError ( "entry param must be of type Entry." ) if not entry in self . entries : raise ValueError ( "Entry doesn't exist / not bound to this datbase." ) entry . group . entries . remove ( entry ) self . entries . remove ( entry )
def main ( ) : """Update the ossuary Postgres db with images observed for OSSOS . iq : Go through and check all ossuary ' s images for new existence of IQs / zeropoints . comment : Go through all ossuary and Then updates ossuary with new images that are at any stage of processing . Constructs full image ent...
parser = argparse . ArgumentParser ( ) parser . add_argument ( "-iq" , "--iq" , action = "store_true" , help = "Check existing images in ossuary that do not yet have " "IQ/zeropoint information; update where possible." ) parser . add_argument ( "-comment" , action = "store_true" , help = "Add comments on images provide...
def parse ( self , mappings , use_default_path = False ) : """Parse a list of map strings ( mappings ) . Accepts two distinct formats : 1 . If there are exactly two entries then these may be the source base URI and the destination base path . Neither may contain an equals ( = ) sign . 2 . For any number o...
if ( use_default_path and len ( mappings ) == 1 and re . search ( r"=" , mappings [ 0 ] ) is None ) : path = self . path_from_uri ( mappings [ 0 ] ) self . logger . warning ( "Using URI mapping: %s -> %s" % ( mappings [ 0 ] , path ) ) self . mappings . append ( Map ( mappings [ 0 ] , path ) ) elif ( len ( m...
async def close_async ( self , exception = None ) : """Close down the handler . If the handler has already closed , this will be a no op . An optional exception can be passed in to indicate that the handler was shutdown due to error . : param exception : An optional exception if the handler is closing due t...
self . running = False if self . error : return if isinstance ( exception , errors . LinkRedirect ) : self . redirected = exception elif isinstance ( exception , EventHubError ) : self . error = exception elif isinstance ( exception , ( errors . LinkDetach , errors . ConnectionClose ) ) : self . error =...
def create_local_scope_from_def_args ( self , call_args , def_args , line_number , saved_function_call_index ) : """Create the local scope before entering the body of a function call . Args : call _ args ( list [ ast . Name ] ) : Of the call being made . def _ args ( ast _ helper . Arguments ) : Of the defini...
# Create e . g . def _ arg1 = temp _ N _ def _ arg1 for each argument for i in range ( len ( call_args ) ) : def_arg_local_name = def_args [ i ] def_arg_temp_name = 'temp_' + str ( saved_function_call_index ) + '_' + def_args [ i ] local_scope_node = RestoreNode ( def_arg_local_name + ' = ' + def_arg_temp_n...
def _disallow_catching_UnicodeDecodeError ( f ) : """Patches a template modules to prevent catching UnicodeDecodeError . Note that this has the effect of also making Template raise a UnicodeDecodeError instead of a TemplateEncodingError if the template string is not UTF - 8 or unicode ."""
patch_base = patch . object ( VariableNode , 'render' , variable_node_render ) patch_all = patch_base if django . VERSION < ( 1 , 9 ) : from django . template . debug import DebugVariableNode patch_debug = patch . object ( DebugVariableNode , 'render' , debug_variable_node_render ) patch_all = _compose ( pa...
def args_kwargs_to_initdict ( args : ArgsList , kwargs : KwargsDict ) -> InitDict : """Converts a set of ` ` args ` ` and ` ` kwargs ` ` to an ` ` InitDict ` ` ."""
return { ARGS_LABEL : args , KWARGS_LABEL : kwargs }
def handle_resource_update_success ( resource ) : """Recover resource if its state is ERRED and clear error message ."""
update_fields = [ ] if resource . state == resource . States . ERRED : resource . recover ( ) update_fields . append ( 'state' ) if resource . state in ( resource . States . UPDATING , resource . States . CREATING ) : resource . set_ok ( ) update_fields . append ( 'state' ) if resource . error_message :...
def create_yaml ( directory , project_name , board , output_dir ) : # lay out what the common section a project yaml file will look like # The value mapped to by each key are the file extensions that will help us get valid files for each section logger . debug ( "Project name: %s, Target: %s" % ( project_name , boa...
tools = _determine_tool ( project_yaml [ 'common' ] [ 'linker_file' ] ) linkers = { } # dictionary containing all linker files in the project directory # exhaust the iterator and add its yielded values to linkers for ( file , tool ) in tools : if tool in linkers : linkers [ tool ] . append ( file ) else...
def _get_db_names ( self , dbs , strict = True ) : """Accepts a single db ( name or object ) or a list of dbs , and returns a list of database names . If any of the supplied dbs do not exist , a NoSuchDatabase exception will be raised , unless you pass strict = False ."""
dbs = utils . coerce_to_list ( dbs ) db_names = [ utils . get_name ( db ) for db in dbs ] if strict : good_dbs = self . instance . list_databases ( ) good_names = [ utils . get_name ( good_db ) for good_db in good_dbs ] bad_names = [ db_name for db_name in db_names if db_name not in good_names ] if bad_...
def deploy_windows ( host , port = 445 , timeout = 900 , username = 'Administrator' , password = None , name = None , sock_dir = None , conf_file = None , start_action = None , parallel = False , minion_pub = None , minion_pem = None , minion_conf = None , keep_tmp = False , script_args = None , script_env = None , por...
if not isinstance ( opts , dict ) : opts = { } if use_winrm and not HAS_WINRM : log . error ( 'WinRM requested but module winrm could not be imported' ) return False if not use_winrm and has_winexe ( ) and not HAS_PSEXEC : salt . utils . versions . warn_until ( 'Sodium' , 'Support for winexe has been de...
def _walk_issuers ( self , path , paths , failed_paths ) : """Recursively looks through the list of known certificates for the issuer of the certificate specified , stopping once the certificate in question is one contained within the CA certs list : param path : A ValidationPath object representing the cur...
if path . first . signature in self . _ca_lookup : paths . append ( path ) return new_branches = 0 for issuer in self . _possible_issuers ( path . first ) : try : self . _walk_issuers ( path . copy ( ) . prepend ( issuer ) , paths , failed_paths ) new_branches += 1 except ( DuplicateCert...
def compact ( vertices , indices , tolerance = 1e-3 ) : """Compact vertices and indices within given tolerance"""
# Transform vertices into a structured array for np . unique to work n = len ( vertices ) V = np . zeros ( n , dtype = [ ( "pos" , np . float32 , 3 ) ] ) V [ "pos" ] [ : , 0 ] = vertices [ : , 0 ] V [ "pos" ] [ : , 1 ] = vertices [ : , 1 ] V [ "pos" ] [ : , 2 ] = vertices [ : , 2 ] epsilon = 1e-3 decimals = int ( np . ...
def aggregate ( self , start , end ) : '''This method encpsualte the metric aggregation logic . Override this method when you inherit this class . By default , it takes the last value .'''
last = self . objects ( level = 'daily' , date__lte = self . iso ( end ) , date__gte = self . iso ( start ) ) . order_by ( '-date' ) . first ( ) return last . values [ self . name ]
def _resolve_source ( self , source ) : """Resolve source to filepath if it is a directory ."""
if os . path . isdir ( source ) : sources = glob . glob ( os . path . join ( source , '*.sbml' ) ) if len ( sources ) == 0 : raise ModelLoadError ( 'No .sbml file found in source directory' ) elif len ( sources ) > 1 : raise ModelLoadError ( 'More than one .sbml file found in source director...
def resync_package ( ctx , opts , owner , repo , slug , skip_errors ) : """Resynchronise a package ."""
click . echo ( "Resynchonising the %(slug)s package ... " % { "slug" : click . style ( slug , bold = True ) } , nl = False , ) context_msg = "Failed to resynchronise package!" with handle_api_exceptions ( ctx , opts = opts , context_msg = context_msg , reraise_on_error = skip_errors ) : with maybe_spinner ( opts ) ...
def str_proc ( self , inputstring , ** kwargs ) : """Process strings and comments ."""
out = [ ] found = None # store of characters that might be the start of a string hold = None # hold = [ _ comment ] : _comment = 0 # the contents of the comment so far # hold = [ _ contents , _ start , _ stop ] : _contents = 0 # the contents of the string so far _start = 1 # the string of characters that started the st...
def create_jdbc_resource ( name , server = None , ** kwargs ) : '''Create a JDBC resource'''
defaults = { 'description' : '' , 'enabled' : True , 'id' : name , 'poolName' : '' , 'target' : 'server' } # Data = defaults + merge kwargs + poolname data = defaults data . update ( kwargs ) if not data [ 'poolName' ] : raise CommandExecutionError ( 'No pool name!' ) return _create_element ( name , 'resources/jdbc...
def _load_model ( self ) : """Loads the peg and the hole models ."""
super ( ) . _load_model ( ) self . mujoco_robot . set_base_xpos ( [ 0 , 0 , 0 ] ) # Add arena and robot self . model = MujocoWorldBase ( ) self . arena = EmptyArena ( ) if self . use_indicator_object : self . arena . add_pos_indicator ( ) self . model . merge ( self . arena ) self . model . merge ( self . mujoco_ro...
def stop ( self ) : """Stops and joins readthread . : return : Nothing"""
self . keep_reading = False if self . readthread is not None : self . readthread . join ( ) self . readthread = None
def main ( version = DEFAULT_VERSION ) : """Install or upgrade setuptools and EasyInstall"""
options = _parse_args ( ) tarball = download_setuptools ( download_base = options . download_base ) return _install ( tarball , _build_install_args ( options ) )
def report ( self , texts , n_examples = 10 , context_size = 10 , f = sys . stdout ) : """Compute statistics of invalid characters and print them . Parameters texts : list of str The texts to search for invalid characters . n _ examples : int How many examples to display per invalid character . context ...
result = list ( self . compute_report ( texts , context_size ) . items ( ) ) result . sort ( key = lambda x : ( len ( x [ 1 ] ) , x [ 0 ] ) , reverse = True ) s = 'Analyzed {0} texts.\n' . format ( len ( texts ) ) if ( len ( texts ) ) == 0 : f . write ( s ) return if len ( result ) > 0 : s += 'Invalid chara...
def populate ( self , source = DEFAULT_SEGMENT_SERVER , segments = None , pad = True , on_error = 'raise' , ** kwargs ) : """Query the segment database for each flag ' s active segments . This method assumes all of the metadata for each flag have been filled . Minimally , the following attributes must be filled...
# check on _ error flag if on_error not in [ 'raise' , 'warn' , 'ignore' ] : raise ValueError ( "on_error must be one of 'raise', 'warn', " "or 'ignore'" ) # format source source = urlparse ( source ) # perform query for all segments if source . netloc and segments is not None : segments = SegmentList ( map ( S...
def build ( c , sdist = True , wheel = False , directory = None , python = None , clean = True ) : """Build sdist and / or wheel archives , optionally in a temp base directory . All parameters save ` ` directory ` ` honor config settings of the same name , under the ` ` packaging ` ` tree . E . g . say ` ` . co...
# Config hooks config = c . config . get ( "packaging" , { } ) # TODO : update defaults to be None , then flip the below so non - None runtime # beats config . sdist = config . get ( "sdist" , sdist ) wheel = config . get ( "wheel" , wheel ) python = config . get ( "python" , python or "python" ) # buffalo buffalo # Sa...
def json ( self ) : """Return a JSON - serializable representation of this result . The output of this function can be converted to a serialized string with : any : ` json . dumps ` ."""
return { "model_type" : self . model_type , "formula" : self . formula , "status" : self . status , "model_params" : self . model_params , "r_squared_adj" : _noneify ( self . r_squared_adj ) , "warnings" : [ w . json ( ) for w in self . warnings ] , }
def report_errors_api ( self ) : """Helper for logging - related API calls . See https : / / cloud . google . com / logging / docs / reference / v2 / rest / v2 / entries https : / / cloud . google . com / logging / docs / reference / v2 / rest / v2 / projects . logs : rtype : : class : ` _ gapic . _ Error...
if self . _report_errors_api is None : if self . _use_grpc : self . _report_errors_api = make_report_error_api ( self ) else : self . _report_errors_api = _ErrorReportingLoggingAPI ( self . project , self . _credentials , self . _http ) return self . _report_errors_api
def get_filename_block_as_codepoints ( self ) : """TODO : Support tokenized BASIC . Now we only create ASCII BASIC ."""
codepoints = [ ] codepoints += list ( string2codepoint ( self . filename . ljust ( 8 , " " ) ) ) codepoints . append ( self . cfg . FTYPE_BASIC ) # one byte file type codepoints . append ( self . cfg . BASIC_ASCII ) # one byte ASCII flag # one byte gap flag ( 0x00 = no gaps , 0xFF = gaps ) # http : / / archive . worldo...
def allFileExists ( fileList ) : """Check that all file exists . : param fileList : the list of file to check . : type fileList : list Check if all the files in ` ` fileList ` ` exists ."""
allExists = True for fileName in fileList : allExists = allExists and os . path . isfile ( fileName ) return allExists
def _read_starlog ( self ) : """read history . data or star . log file again"""
sldir = self . sldir slname = self . slname slaname = slname + 'sa' if not os . path . exists ( sldir + '/' + slaname ) : print ( 'No ' + self . slname + 'sa file found, create new one from ' + self . slname ) _cleanstarlog ( sldir + '/' + slname ) else : if self . clean_starlog : print ( 'Requested...
def safe_int ( val , allow_zero = True ) : """This function converts the six . moves . input values to integers . It handles invalid entries , and optionally forbids values of zero ."""
try : ret = int ( val ) except ValueError : print ( "Sorry, '%s' is not a valid integer." % val ) return False if not allow_zero and ret == 0 : print ( "Please enter a non-zero integer." ) return False return ret
def visit_BoolOp ( self , node ) : '''Resulting node may alias to either operands : > > > from pythran import passmanager > > > pm = passmanager . PassManager ( ' demo ' ) > > > module = ast . parse ( ' def foo ( a , b ) : return a or b ' ) > > > result = pm . gather ( Aliases , module ) > > > Aliases . d...
return self . add ( node , set . union ( * [ self . visit ( n ) for n in node . values ] ) )
def prepare_include ( ctx , include , output ) : """Process and filter include file to produce list of names for dictionary ."""
click . echo ( 'chemdataextractor.dict.prepare_include' ) for i , line in enumerate ( include ) : print ( 'IN%s' % i ) for tokens in _make_tokens ( line . strip ( ) ) : output . write ( u' ' . join ( tokens ) ) output . write ( u'\n' )
def grab_selenium_driver ( driver_name = None ) : """pip install selenium - U"""
from selenium import webdriver if driver_name is None : driver_name = 'firefox' if driver_name . lower ( ) == 'chrome' : grab_selenium_chromedriver ( ) return webdriver . Chrome ( ) elif driver_name . lower ( ) == 'firefox' : # grab _ selenium _ chromedriver ( ) return webdriver . Firefox ( ) else : ...
def to_bed ( call , sample , work_dir , calls , data ) : """Create a simplified BED file from caller specific input ."""
out_file = os . path . join ( work_dir , "%s-%s-flat.bed" % ( sample , call [ "variantcaller" ] ) ) if call . get ( "vrn_file" ) and not utils . file_uptodate ( out_file , call [ "vrn_file" ] ) : with file_transaction ( data , out_file ) as tx_out_file : convert_fn = CALLER_TO_BED . get ( call [ "variantcal...
def restart_agent ( self , agent_id , ** kwargs ) : '''tells the host agent running in this agency to restart the agent .'''
host_medium = self . get_medium ( 'host_agent' ) agent = host_medium . get_agent ( ) d = host_medium . get_document ( agent_id ) # This is done like this on purpose , we want to ensure that document # exists before passing it to the agent ( even though he would handle # this himself ) . d . addCallback ( lambda desc : ...
def hybrid_meco_velocity ( m1 , m2 , chi1 , chi2 , qm1 = None , qm2 = None ) : """Return the velocity of the hybrid MECO Parameters m1 : float Mass of the primary object in solar masses . m2 : float Mass of the secondary object in solar masses . chi1 : float Dimensionless spin of the primary object . ...
if qm1 is None : qm1 = 1 if qm2 is None : qm2 = 1 # Set bounds at 0.1 to skip v = 0 and at the lightring velocity chi = ( chi1 * m1 + chi2 * m2 ) / ( m1 + m2 ) vmax = kerr_lightring_velocity ( chi ) - 0.01 return minimize ( hybridEnergy , 0.2 , args = ( m1 , m2 , chi1 , chi2 , qm1 , qm2 ) , bounds = [ ( 0.1 , v...
def check_existing_vr_tag ( self ) : """Checks if version - release tag ( primary not floating tag ) exists already , and fails plugin if it does ."""
primary_images = get_primary_images ( self . workflow ) if not primary_images : return vr_image = None for image in primary_images : if '-' in image . tag : vr_image = image break if not vr_image : return should_fail = False for registry_name , registry in self . registries . items ( ) : ...
def clip_extents ( self ) : """Computes a bounding box in user coordinates covering the area inside the current clip . : return : A ` ` ( x1 , y1 , x2 , y2 ) ` ` tuple of floats : the left , top , right and bottom of the resulting extents , respectively ."""
extents = ffi . new ( 'double[4]' ) cairo . cairo_clip_extents ( self . _pointer , extents + 0 , extents + 1 , extents + 2 , extents + 3 ) self . _check_status ( ) return tuple ( extents )
def _get_view_method ( self , request ) : """Get view method ."""
if hasattr ( self , 'action' ) : return self . action if self . action else None return request . method . lower ( )
def paintEvent ( self , event ) : """Override Qt method ."""
painter = QPainter ( self ) color = QColor ( self . color ) color . setAlphaF ( .5 ) painter . setPen ( color ) offset = self . editor . document ( ) . documentMargin ( ) + self . editor . contentOffset ( ) . x ( ) for _ , line_number , block in self . editor . visible_blocks : indentation = TextBlockHelper . get_f...
def checkout ( self , path ) : """Check out file data to path . : param path : Filesystem path to check out item to . : return : True if successful ."""
if os . path . isdir ( path ) : path = os . path . join ( path , self . name ) try : log . debug ( 'Checking out %s to %s' % ( self . path , path ) ) f = open ( path , 'w' ) f . write ( self . data ( ) ) f . close ( ) return True except Exception , e : raise ItemError ( e )
def document ( self , name , file_name , ** kwargs ) : """Add Document data to Batch object . Args : name ( str ) : The name for this Group . file _ name ( str ) : The name for the attached file for this Group . date _ added ( str , kwargs ) : The date timestamp the Indicator was created . file _ content ...
group_obj = Document ( name , file_name , ** kwargs ) return self . _group ( group_obj )
def _freeze ( self , action = None ) : """Freeze this message for logging , registering it with C { action } . @ param action : The L { Action } which is the context for this message . If C { None } , the L { Action } will be deduced from the current call stack . @ return : A L { PMap } with added C { times...
if action is None : action = current_action ( ) if action is None : task_uuid = unicode ( uuid4 ( ) ) task_level = [ 1 ] else : task_uuid = action . _identification [ TASK_UUID_FIELD ] task_level = action . _nextTaskLevel ( ) . as_list ( ) timestamp = self . _timestamp ( ) new_values = { TIMESTAMP_F...
def _maybe_dt_array ( array ) : """Extract numpy array from single column data table"""
if not isinstance ( array , DataTable ) or array is None : return array if array . shape [ 1 ] > 1 : raise ValueError ( 'DataTable for label or weight cannot have multiple columns' ) # below requires new dt version # extract first column array = array . to_numpy ( ) [ : , 0 ] . astype ( 'float' ) return array
def get_objects_for_subject ( subject = None , object_category = None , relation = None , ** kwargs ) : """Convenience method : Given a subject ( e . g . gene , disease , variant ) , return all associated objects ( phenotypes , functions , interacting genes , etc )"""
searchresult = search_associations ( subject = subject , fetch_objects = True , rows = 0 , object_category = object_category , relation = relation , ** kwargs ) objs = searchresult [ 'objects' ] return objs
def load_rules ( root = 'fmn.rules' ) : """Load the big list of allowed callable rules ."""
module = __import__ ( root , fromlist = [ root . split ( '.' ) [ 0 ] ] ) hinting_helpers = fmn . lib . hinting . __dict__ . values ( ) rules = { } for name in dir ( module ) : obj = getattr ( module , name ) # Ignore non - callables . if not callable ( obj ) : continue # Ignore our decorator and...
def find ( self , x ) : """: returns : identifier of part containing x : complexity : O ( inverse _ ackerman ( n ) )"""
if self . up [ x ] == x : return x else : self . up [ x ] = self . find ( self . up [ x ] ) return self . up [ x ]
def scoped ( cls , optionable , removal_version = None , removal_hint = None ) : """Returns a dependency on this subsystem , scoped to ` optionable ` . : param removal _ version : An optional deprecation version for this scoped Subsystem dependency . : param removal _ hint : An optional hint to accompany a depr...
return SubsystemDependency ( cls , optionable . options_scope , removal_version , removal_hint )
def pix2sky_ellipse ( self , pixel , sx , sy , theta ) : """Convert an ellipse from pixel to sky coordinates . Parameters pixel : ( float , float ) The ( x , y ) coordinates of the center of the ellipse . sx , sy : float The major and minor axes ( FHWM ) of the ellipse , in pixels . theta : float The ...
ra , dec = self . pix2sky ( pixel ) x , y = pixel v_sx = [ x + sx * np . cos ( np . radians ( theta ) ) , y + sx * np . sin ( np . radians ( theta ) ) ] ra2 , dec2 = self . pix2sky ( v_sx ) major = gcd ( ra , dec , ra2 , dec2 ) pa = bear ( ra , dec , ra2 , dec2 ) v_sy = [ x + sy * np . cos ( np . radians ( theta - 90 )...
def serverInitial ( self , pkt , raddress , rport ) : """This method performs initial setup for a server context transfer , put here to refactor code out of the TftpStateServerRecvRRQ and TftpStateServerRecvWRQ classes , since their initial setup is identical . The method returns a boolean , sendoack , to ind...
options = pkt . options sendoack = False if not self . context . tidport : self . context . tidport = rport log . info ( "Setting tidport to %s" % rport ) log . debug ( "Setting default options, blksize" ) self . context . options = { 'blksize' : DEF_BLKSIZE } if options : log . debug ( "Options requested: ...
def use_federated_bin_view ( self ) : """Pass through to provider ResourceLookupSession . use _ federated _ bin _ view"""
self . _bin_view = FEDERATED # self . _ get _ provider _ session ( ' resource _ lookup _ session ' ) # To make sure the session is tracked for session in self . _get_provider_sessions ( ) : try : session . use_federated_bin_view ( ) except AttributeError : pass
def _get_unmanaged_files ( self , managed , system_all ) : '''Get the intersection between all files and managed files .'''
m_files , m_dirs , m_links = managed s_files , s_dirs , s_links = system_all return ( sorted ( list ( set ( s_files ) . difference ( m_files ) ) ) , sorted ( list ( set ( s_dirs ) . difference ( m_dirs ) ) ) , sorted ( list ( set ( s_links ) . difference ( m_links ) ) ) )
def get ( self , value ) : """Get an enumeration item for an enumeration value . : param unicode value : Enumeration value . : raise InvalidEnumItem : If ` ` value ` ` does not match any known enumeration value . : rtype : EnumItem"""
_nothing = object ( ) item = self . _values . get ( value , _nothing ) if item is _nothing : raise InvalidEnumItem ( value ) return item
def get_xmlschema ( xmlschema , mets_doc ) : """Return a ` ` class : : lxml . etree . XMLSchema ` ` instance given the path to the XMLSchema ( . xsd ) file in ` ` xmlschema ` ` and the ` ` class : : lxml . etree . _ ElementTree ` ` instance ` ` mets _ doc ` ` representing the METS file being parsed . The comp...
xsd_path = _get_file_path ( xmlschema ) xmlschema = etree . parse ( xsd_path ) schema_locations = set ( mets_doc . xpath ( "//*/@xsi:schemaLocation" , namespaces = NAMESPACES ) ) for schema_location in schema_locations : namespaces_locations = schema_location . strip ( ) . split ( ) for namespace , location in ...
def guest_reset ( self , userid ) : """reset a virtual machine : param str userid : the id of the virtual machine to be reset : returns : None"""
action = "reset guest '%s'" % userid with zvmutils . log_and_reraise_sdkbase_error ( action ) : self . _vmops . guest_reset ( userid )
def _easteregg ( app = None ) : """Like the name says . But who knows how it works ?"""
def bzzzzzzz ( gyver ) : import base64 import zlib return zlib . decompress ( base64 . b64decode ( gyver ) ) . decode ( 'ascii' ) gyver = u'\n' . join ( [ x + ( 77 - len ( x ) ) * u' ' for x in bzzzzzzz ( b''' eJyFlzuOJDkMRP06xRjymKgDJCDQStBYT8BCgK4gTwfQ2fcFs2a2FzvZk+hvlcRvRJD148efHt9m 9Xz94dRY5hGt1nrYcXx7u...
def show_lbaas_l7policy ( self , l7policy , ** _params ) : """Fetches information of a certain listener ' s L7 policy ."""
return self . get ( self . lbaas_l7policy_path % l7policy , params = _params )
def create_authors ( project_dir = os . curdir ) : """Creates the authors file , if not in a package . Returns : None Raises : RuntimeError : If the authors could not be retrieved"""
pkg_info_file = os . path . join ( project_dir , 'PKG-INFO' ) authors_file = os . path . join ( project_dir , 'AUTHORS' ) if os . path . exists ( pkg_info_file ) : return authors = get_authors ( project_dir = project_dir ) with open ( authors_file , 'wb' ) as authors_fd : authors_fd . write ( b'\n' . join ( a ....
def is_labial ( c , lang ) : """Is the character a labial"""
o = get_offset ( c , lang ) return ( o >= LABIAL_RANGE [ 0 ] and o <= LABIAL_RANGE [ 1 ] )
def unembed_samples ( samples , embedding , chain_break_method = None ) : """Return samples over the variables in the source graph . Args : samples ( iterable ) : An iterable of samples where each sample is a dict of the form { v : val , . . . } where v is a variable in the target model and val is the assoc...
if chain_break_method is None : chain_break_method = majority_vote return list ( itertools . chain ( * ( chain_break_method ( sample , embedding ) for sample in samples ) ) )
def clean_cell_meta ( self , meta ) : """Remove cell metadata that matches the default cell metadata ."""
for k , v in DEFAULT_CELL_METADATA . items ( ) : if meta . get ( k , None ) == v : meta . pop ( k , None ) return meta
def add_network_profile ( self , obj , params ) : """Add an AP profile for connecting to afterward ."""
network_id = self . _send_cmd_to_wpas ( obj [ 'name' ] , 'ADD_NETWORK' , True ) network_id = network_id . strip ( ) params . process_akm ( ) self . _send_cmd_to_wpas ( obj [ 'name' ] , 'SET_NETWORK {} ssid \"{}\"' . format ( network_id , params . ssid ) ) key_mgmt = '' if params . akm [ - 1 ] in [ AKM_TYPE_WPAPSK , AKM...
def refresh ( self ) : """Clears out the actions for this menu and then loads the files ."""
self . clear ( ) for i , filename in enumerate ( self . filenames ( ) ) : name = '%i. %s' % ( i + 1 , os . path . basename ( filename ) ) action = self . addAction ( name ) action . setData ( wrapVariant ( filename ) )