signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def importSNPs ( packageFile ) : """The big wrapper , this function should detect the SNP type by the package manifest and then launch the corresponding function . Here ' s an example of a SNP manifest file for Casava SNPs : : [ package _ infos ] description = Casava SNPs for testing purposes maintainer = T...
printf ( "Importing polymorphism set: %s... (This may take a while)" % packageFile ) isDir = False if not os . path . isdir ( packageFile ) : packageDir = _decompressPackage ( packageFile ) else : isDir = True packageDir = packageFile fpMan = os . path . normpath ( packageDir + '/manifest.ini' ) if not os ....
def access_token_response ( self , token , message_id = None ) : """Access token response structure . Success if token is set , otherwise ( None , empty string ) give error response . If message _ id is set then an extra messageId attribute is set in the response to handle postMessage ( ) responses ."""
if ( token ) : data = { "accessToken" : token , "expiresIn" : self . access_token_lifetime } if ( message_id ) : data [ 'messageId' ] = message_id else : data = { "error" : "client_unauthorized" , "description" : "No authorization details received" } return data
def run ( self ) : '''Start a Master Worker'''
salt . utils . process . appendproctitle ( self . name ) self . clear_funcs = ClearFuncs ( self . opts , self . key , ) self . aes_funcs = AESFuncs ( self . opts ) salt . utils . crypt . reinit_crypto ( ) self . __bind ( )
def human_duration ( duration_seconds : float ) -> str : """Convert a duration in seconds into a human friendly string ."""
if duration_seconds < 0.001 : return '0 ms' if duration_seconds < 1 : return '{} ms' . format ( int ( duration_seconds * 1000 ) ) return '{} s' . format ( int ( duration_seconds ) )
def setup_logging ( self ) : """Configure the logging framework ."""
if self . config . debug : util . setup_logging ( level = logging . DEBUG ) util . activate_debug_shell_on_signal ( ) else : util . setup_logging ( level = logging . INFO )
def read_proxy ( fl ) : """Read a file to create a proxy record instance"""
outcore = ProxyRecord ( data = pd . read_csv ( fl , sep = r'\s*\,\s*' , index_col = None , engine = 'python' ) ) return outcore
def clean ( self ) : '''Either staffCategory or staffMember must be filled in , but not both .'''
if not self . staffCategory and not self . staffMember : raise ValidationError ( _ ( 'Either staff category or staff member must be specified.' ) ) if self . staffCategory and self . staffMember : raise ValidationError ( _ ( 'Specify either a staff category or a staff member, not both.' ) )
def _run_events ( self , tag , stage = None ) : """Run tests marked with a particular tag and stage"""
self . _run_event_methods ( tag , stage ) self . _run_tests ( tag , stage )
def update_fitness ( objective_function , particle ) : """Calculates and updates the fitness and best _ fitness of a particle . Fitness is calculated using the ' problem . fitness ' function . Args : problem : The optimization problem encapsulating the fitness function and optimization type . particle : c...
fitness = objective_function ( particle . position ) best_fitness = particle . best_fitness cmp = comparator ( fitness ) if best_fitness is None or cmp ( fitness , best_fitness ) : best_position = particle . position return particle . _replace ( fitness = fitness , best_fitness = fitness , best_position = best_...
def lsb_release ( self , loglevel = logging . DEBUG ) : """Get distro information from lsb _ release ."""
# v the space is intentional , to avoid polluting bash history . shutit = self . shutit d = { } self . send ( ShutItSendSpec ( self , send = ' command lsb_release -a' , check_exit = False , echo = False , loglevel = loglevel , ignore_background = True ) ) res = shutit . match_string ( self . pexpect_child . before , r'...
def inverse_kinematic_optimization ( chain , target_frame , starting_nodes_angles , regularization_parameter = None , max_iter = None ) : """Computes the inverse kinematic on the specified target with an optimization method Parameters chain : ikpy . chain . Chain The chain used for the Inverse kinematics . ...
# Only get the position target = target_frame [ : 3 , 3 ] if starting_nodes_angles is None : raise ValueError ( "starting_nodes_angles must be specified" ) # Compute squared distance to target def optimize_target ( x ) : # y = np . append ( starting _ nodes _ angles [ : chain . first _ active _ joint ] , x ) y ...
def translate ( obj , vec , ** kwargs ) : """Translates curves , surface or volumes by the input vector . Keyword Arguments : * ` ` inplace ` ` : if False , operation applied to a copy of the object . * Default : False * : param obj : input geometry : type obj : abstract . SplineGeometry or multi . Abstract...
# Input validity checks if not vec or not isinstance ( vec , ( tuple , list ) ) : raise GeomdlException ( "The input must be a list or a tuple" ) # Input validity checks if len ( vec ) != obj . dimension : raise GeomdlException ( "The input vector must have " + str ( obj . dimension ) + " components" ) # Keywor...
def save ( self , name , data , location = 'local' , kind = 'json' ) : """Save a dictionary in a JSON file within the cache directory ."""
file_ext = '.json' if kind == 'json' else '.pkl' path = self . _get_path ( name , location , file_ext = file_ext ) _ensure_dir_exists ( op . dirname ( path ) ) logger . debug ( "Save data to `%s`." , path ) if kind == 'json' : _save_json ( path , data ) else : _save_pickle ( path , data )
def format_key_from_backend ( self , key ) : """Strip the configured prefix from a key retrieved from the backend before passing it on to other pghoard code and presenting it to the user ."""
if not self . prefix : return key if not key . startswith ( self . prefix ) : raise StorageError ( "Key {!r} does not start with expected prefix {!r}" . format ( key , self . prefix ) ) return key [ len ( self . prefix ) : ]
def decode_json ( cls , dct ) : '''Custom JSON decoder for Events . Can be used as the ` ` object _ hook ` ` argument of ` ` json . load ` ` or ` ` json . loads ` ` . Args : dct ( dict ) : a JSON dictionary to decode The dictionary should have keys ` ` event _ name ` ` and ` ` event _ values ` ` Raises ...
if not ( 'event_name' in dct and 'event_values' in dct ) : return dct event_name = dct [ 'event_name' ] if event_name not in _CONCRETE_EVENT_CLASSES : raise ValueError ( "Could not find appropriate Event class for event_name: %r" % event_name ) event_values = dct [ 'event_values' ] model_id = event_values . pop...
def _send_to_destination ( self , destination , header , payload , transport_kwargs , add_path_step = True ) : """Helper function to send a message to a specific recipe destination ."""
if header : header = header . copy ( ) header [ "workflows-recipe" ] = True else : header = { "workflows-recipe" : True } dest_kwargs = transport_kwargs . copy ( ) if ( "transport-delay" in self . recipe [ destination ] and "delay" not in transport_kwargs ) : dest_kwargs [ "delay" ] = self . recipe [ de...
async def packages ( self , package_state : Union [ int , str ] = '' , show_archived : bool = False ) -> list : """Get the list of packages associated with the account ."""
packages_resp = await self . _request ( 'post' , API_URL_BUYER , json = { 'version' : '1.0' , 'method' : 'GetTrackInfoList' , 'param' : { 'IsArchived' : show_archived , 'Item' : '' , 'Page' : 1 , 'PerPage' : 40 , 'PackageState' : package_state , 'Sequence' : '0' } , 'sourcetype' : 0 } ) _LOGGER . debug ( 'Packages resp...
def list_milestones ( page_size = 200 , page_index = 0 , q = "" , sort = "" ) : """List all ProductMilestones"""
data = list_milestones_raw ( page_size , page_index , sort , q ) if data : return utils . format_json_list ( data )
def backward_committor_sensitivity ( T , A , B , index ) : """calculate the sensitivity matrix for index of the backward committor from A to B given transition matrix T . Parameters T : numpy . ndarray shape = ( n , n ) Transition matrix A : array like List of integer state labels for set A B : array li...
# This is really ugly to compute . The problem is , that changes in T induce changes in # the stationary distribution and so we need to add this influence , too # I implemented something which is correct , but don ' t ask me about the derivation n = len ( T ) trT = numpy . transpose ( T ) one = numpy . ones ( n ) eq = ...
def _idle_loop ( self ) : """This is used to exec the idle function in a safe context and a separate thread"""
while not self . _stop_update_flag : time . sleep ( self . update_interval ) with self . update_lock : try : self . idle ( ) except : self . _log . error ( "exception in App.idle method" , exc_info = True ) if self . _need_update_flag : try : ...
def read_dirs ( path , folder ) : '''Fetches name of all files in path in long form , and labels associated by extrapolation of directory names .'''
lbls , fnames , all_lbls = [ ] , [ ] , [ ] full_path = os . path . join ( path , folder ) for lbl in sorted ( os . listdir ( full_path ) ) : if lbl not in ( '.ipynb_checkpoints' , '.DS_Store' ) : all_lbls . append ( lbl ) for fname in os . listdir ( os . path . join ( full_path , lbl ) ) : ...
def greenhall_sw ( t , alpha ) : """Eqn ( 7 ) from Greenhall2004"""
alpha = int ( alpha ) if alpha == 2 : return - np . abs ( t ) elif alpha == 1 : if t == 0 : return 0 else : return pow ( t , 2 ) * np . log ( np . abs ( t ) ) elif alpha == 0 : return np . abs ( pow ( t , 3 ) ) elif alpha == - 1 : if t == 0 : return 0 else : retur...
def blacklist ( db , term = None ) : """List the blacklisted entities available in the registry . The function will return the list of blacklisted entities . If term parameter is set , it will only return the information about the entities which match that term . When the given term does not match with any ...
mbs = [ ] with db . connect ( ) as session : if term : mbs = session . query ( MatchingBlacklist ) . filter ( MatchingBlacklist . excluded . like ( '%' + term + '%' ) ) . order_by ( MatchingBlacklist . excluded ) . all ( ) if not mbs : raise NotFoundError ( entity = term ) else : ...
def _to_scientific_tuple ( number ) : r"""Return mantissa and exponent of a number expressed in scientific notation . Full precision is maintained if the number is represented as a string . : param number : Number : type number : integer , float or string : rtype : Tuple whose first item is the mantissa ( *...
# pylint : disable = W0632 if isinstance ( number , bool ) or ( not isinstance ( number , ( int , float , str ) ) ) : raise RuntimeError ( "Argument `number` is not valid" ) convert = not isinstance ( number , str ) # Detect zero and return , simplifies subsequent algorithm if ( convert and ( not number ) ) or ( ( ...
def find_min_required ( path ) : """Inspect terraform files and find minimum version ."""
found_min_required = '' for filename in glob . glob ( os . path . join ( path , '*.tf' ) ) : with open ( filename , 'r' ) as stream : tf_config = hcl . load ( stream ) if tf_config . get ( 'terraform' , { } ) . get ( 'required_version' ) : found_min_required = tf_config . get ( 'terrafor...
def upgrade ( reboot = False , at_time = None ) : '''Upgrade the kernel and optionally reboot the system . reboot : False Request a reboot if a new kernel is available . at _ time : immediate Schedule the reboot at some point in the future . This argument is ignored if ` ` reboot = False ` ` . See : py ...
result = __salt__ [ 'pkg.upgrade' ] ( name = _package_name ( ) ) _needs_reboot = needs_reboot ( ) ret = { 'upgrades' : result , 'active' : active ( ) , 'latest_installed' : latest_installed ( ) , 'reboot_requested' : reboot , 'reboot_required' : _needs_reboot } if reboot and _needs_reboot : log . warning ( 'Rebooti...
def from_geom ( geom ) : """Create and return a position object for the geom Parameters geom : geom An instantiated geom object . Returns out : position A position object Raises : class : ` PlotnineError ` if unable to create a ` position ` ."""
name = geom . params [ 'position' ] if issubclass ( type ( name ) , position ) : return name if isinstance ( name , type ) and issubclass ( name , position ) : klass = name elif is_string ( name ) : if not name . startswith ( 'position_' ) : name = 'position_{}' . format ( name ) klass = Registr...
def set_unspents ( self , unspents ) : """Set the unspent inputs for a transaction . : param unspents : a list of : class : ` TxOut ` ( or the subclass : class : ` Spendable ` ) objects corresponding to the : class : ` TxIn ` objects for this transaction ( same number of items in each list )"""
if len ( unspents ) != len ( self . txs_in ) : raise ValueError ( "wrong number of unspents" ) self . unspents = unspents
def compute_l_from_MCMC ( self , X , n = 0 , sampler = None , flat_trace = None , burn = 0 , thin = 1 , ** kwargs ) : """Compute desired quantities from MCMC samples of the hyperparameter posterior . The return will be a list with a number of rows equal to the number of hyperparameter samples . The columns will...
if flat_trace is None : if sampler is None : sampler = self . sample_hyperparameter_posterior ( burn = burn , ** kwargs ) # If we create the sampler , we need to make sure we clean up # its pool : try : sampler . pool . close ( ) except AttributeError : # This wil...
def register_binary_type ( content_type , dumper , loader ) : """Register handling for a binary content type . : param str content _ type : content type to register the hooks for : param dumper : called to decode bytes into a dictionary . Calling convention : ` ` dumper ( obj _ dict ) - > bytes ` ` . : para...
content_type = headers . parse_content_type ( content_type ) content_type . parameters . clear ( ) key = str ( content_type ) _content_types [ key ] = content_type handler = _content_handlers . setdefault ( key , _ContentHandler ( key ) ) handler . dict_to_bytes = dumper handler . bytes_to_dict = loader
def opensignals_hierarchy ( root = None , update = False , clone = False ) : """Brief Function that generates the OpenSignalsTools Notebooks File Hierarchy programatically . Description OpenSignalsTools Notebooks folder obey to a predefined hierarchy that allows to run the code of online available notebooks...
if root is None : root = os . getcwd ( ) categories = list ( NOTEBOOK_KEYS . keys ( ) ) # = = = = = Creation of the main directory = = = = = current_dir = root + "/biosignalsnotebooks_environment" if not os . path . isdir ( current_dir ) : os . makedirs ( current_dir ) # = = = = = Copy of ' images ' ' styles ' ...
def make_directory_writable ( dirname ) : """Makes directory readable and writable by everybody . Args : dirname : name of the directory Returns : True if operation was successfull If you run something inside Docker container and it writes files , then these files will be written as root user with restr...
retval = shell_call ( [ 'docker' , 'run' , '-v' , '{0}:/output_dir' . format ( dirname ) , 'busybox:1.27.2' , 'chmod' , '-R' , 'a+rwx' , '/output_dir' ] ) if not retval : logging . error ( 'Failed to change permissions on directory: %s' , dirname ) return retval
def servers_with_roles ( self , roles , env = None , match_all = False ) : """Get servers with the given roles . If env is given , then the environment must match as well . If match _ all is True , then only return servers who have all of the given roles . Otherwise , return servers that have one or more of the...
result = [ ] roles = set ( roles ) for instance in self . server_details ( ) : instroles = set ( instance [ 'roles' ] ) envmatches = ( env is None ) or ( instance [ 'environment' ] == env ) if envmatches and match_all and roles <= instroles : result . append ( instance ) elif envmatches and not ...
def dtraj_T100K_dt10_n ( self , divides ) : """100K frames trajectory at timestep 10 , arbitrary n - state discretization ."""
disc = np . zeros ( 100 , dtype = int ) divides = np . concatenate ( [ divides , [ 100 ] ] ) for i in range ( len ( divides ) - 1 ) : disc [ divides [ i ] : divides [ i + 1 ] ] = i + 1 return disc [ self . dtraj_T100K_dt10 ]
def ecef2geodetic_old ( x : float , y : float , z : float , ell : Ellipsoid = None , deg : bool = True ) -> Tuple [ float , float , float ] : """convert ECEF ( meters ) to geodetic coordinates input x , y , z [ meters ] target ECEF location [ 0 , Infinity ) ell reference ellipsoid deg degrees input / output...
if ell is None : ell = Ellipsoid ( ) ea = ell . a eb = ell . b rad = hypot ( x , y ) # Constant required for Latitude equation rho = arctan2 ( eb * z , ea * rad ) # Constant required for latitude equation c = ( ea ** 2 - eb ** 2 ) / hypot ( ea * rad , eb * z ) # Starter for the Newtons Iteration Method vnew = arcta...
def get_repo_version ( url ) : """Get the current version on GitHub ` url ` looks like ' https : / / raw . githubusercontent . com / aquatix / ns - notifications / master / VERSION '"""
response = requests . get ( url ) if response . status_code == 404 : return None else : return response . text . replace ( '\n' , '' )
def get_bucket_files ( glob_pattern , base_dir , force = False , pattern_slice = slice ( None ) ) : """Helper function to download files from Google Cloud Storage . Args : glob _ pattern ( str or list ) : Glob pattern string or series of patterns used to search for on Google Cloud Storage . The pattern should...
if gcsfs is None : raise RuntimeError ( "Missing 'gcsfs' dependency for GCS download." ) if not os . path . isdir ( base_dir ) : # it is the caller ' s responsibility to make this raise OSError ( "Directory does not exist: {}" . format ( base_dir ) ) if isinstance ( glob_pattern , str ) : glob_pattern = [ g...
def filelist ( jottapath , JFS ) : """Get a set ( ) of files from a jottapath ( a folder )"""
log . debug ( "filelist %r" , jottapath ) try : jf = JFS . getObject ( jottapath ) except JFSNotFoundError : return set ( ) # folder does not exist , so pretend it is an empty folder if not isinstance ( jf , JFSFolder ) : return False return set ( [ f . name for f in jf . files ( ) if not f . is_deleted...
def gp_background ( ) : """plot background methods and S / B vs energy"""
inDir , outDir = getWorkDirs ( ) data , REBIN = OrderedDict ( ) , None titles = [ 'SE_{+-}' , 'SE@^{corr}_{/Symbol \\261\\261}' , 'ME@^{N}_{+-}' ] Apm = OrderedDict ( [ ( '19' , 0.026668 ) , ( '27' , 0.026554 ) , ( '39' , 0.026816 ) , ( '62' , 0.026726 ) ] ) fake = np . array ( [ [ - 1 , 1 , 0 , 0 , 0 ] ] ) lines = { '...
def access_key_id ( ecs_access_key_id ) : """Display / set / update the ECS access key id ."""
if not ecs_access_key_id : click . secho ( dtool_config . utils . get_ecs_access_key_id ( CONFIG_PATH ) ) else : click . secho ( dtool_config . utils . set_ecs_access_key_id ( CONFIG_PATH , ecs_access_key_id ) )
def query ( wosclient , wos_query , xml_query = None , count = 5 , offset = 1 , limit = 100 ) : """Query Web of Science and XML query results with multiple requests ."""
results = [ single ( wosclient , wos_query , xml_query , min ( limit , count - x + 1 ) , x ) for x in range ( offset , count + 1 , limit ) ] if xml_query : return [ el for res in results for el in res ] else : pattern = _re . compile ( r'^<\?xml.*?\n<records>\n|\n</records>$.*' ) return ( '<?xml version="1....
def _handle_binary_op ( self , node , scope , ctxt , stream ) : """TODO : Docstring for _ handle _ binary _ op . : node : TODO : scope : TODO : ctxt : TODO : stream : TODO : returns : TODO"""
self . _dlog ( "handling binary operation {}" . format ( node . op ) ) switch = { "+" : lambda x , y : x + y , "-" : lambda x , y : x - y , "*" : lambda x , y : x * y , "/" : lambda x , y : x / y , "|" : lambda x , y : x | y , "^" : lambda x , y : x ^ y , "&" : lambda x , y : x & y , "%" : lambda x , y : x % y , ">" : ...
def get_ipv6_neighbors_table ( self ) : """Get IPv6 neighbors table information . Return a list of dictionaries having the following set of keys : * interface ( string ) * mac ( string ) * ip ( string ) * age ( float ) in seconds * state ( string ) For example : : ' interface ' : ' MgmtEth0 / RSP0 /...
ipv6_neighbors_table = [ ] command = "show ipv6 neighbors" output = self . _send_command ( command ) ipv6_neighbors = "" fields = re . split ( r"^IPv6\s+Address.*Interface$" , output , flags = ( re . M | re . I ) ) if len ( fields ) == 2 : ipv6_neighbors = fields [ 1 ] . strip ( ) for entry in ipv6_neighbors . spli...
def publish ( self , cart , env = None ) : """` cart ` - Release cart to publish in json format Publish a release cart in JSON format to the pre - release environment ."""
juicer . utils . Log . log_debug ( "Initializing publish of cart '%s'" % cart . cart_name ) if not env : env = self . _defaults [ 'start_in' ] cart_id = juicer . utils . upload_cart ( cart , env ) juicer . utils . Log . log_debug ( '%s uploaded with an id of %s' % ( cart . cart_name , cart_id ) ) return True
def jsonify ( self , data : Any , code : Union [ int , Tuple [ int , str , str ] ] = HTTPStatus . OK , headers : Optional [ Dict [ str , str ] ] = None , ) : """Convenience method to return json responses . : param data : The python data to jsonify . : param code : The HTTP status code to return . : param hea...
return jsonify ( data ) , code , headers or { }
def codemirror_settings_update ( configs , parameters , on = None , names = None ) : """Return a new dictionnary of configs updated with given parameters . You may use ` ` on ` ` and ` ` names ` ` arguments to select config or filter out some configs from returned dict . Arguments : configs ( dict ) : Dicti...
# Deep copy of given config output = copy . deepcopy ( configs ) # Optionnaly filtering config from given names if names : output = { k : output [ k ] for k in names } # Select every config if selectors is empty if not on : on = output . keys ( ) for k in on : output [ k ] . update ( parameters ) return out...
def makefifo ( self , tarinfo , targetpath ) : """Make a fifo called targetpath ."""
if hasattr ( os , "mkfifo" ) : os . mkfifo ( targetpath ) else : raise ExtractError ( "fifo not supported by system" )
def _process_phenotypicseries ( self , limit ) : """Creates classes from the OMIM phenotypic series list . These are grouping classes to hook the more granular OMIM diseases . # TEC what does ' hook ' mean here ? : param limit : : return :"""
if self . test_mode : graph = self . testgraph else : graph = self . graph LOG . info ( "getting phenotypic series titles" ) model = Model ( graph ) line_counter = 0 src_key = 'phenotypicSeries' col = self . files [ src_key ] [ 'columns' ] raw = '/' . join ( ( self . rawdir , self . files [ src_key ] [ 'file' ]...
def new_block ( self ) : """create a new sub block to the current block and return it . the sub block is added to the current block ."""
child = Block ( self , py3_wrapper = self . py3_wrapper ) self . add ( child ) return child
def parse ( text ) : """Parses the dependency schema from a given string ( typically a container stdout log )"""
found = re . findall ( r'(?<=BEGIN_DEPENDENCIES_SCHEMA_OUTPUT>).*(?=<END_DEPENDENCIES_SCHEMA_OUTPUT)' , text ) dependency_results = [ ] for match in found : data = json . loads ( match ) validate ( data ) # will throw ValidationError if invalid dependency_results += data [ 'dependencies' ] # we don ' t ...
def find_last_true ( sorted_list , true_criterion ) : """Suppose we have a list of item [ item1 , item2 , . . . , itemN ] . : type array : list : param array : an iterable object that support inex : param x : a comparable value If we do a mapping : : > > > def true _ criterion ( item ) : . . . return it...
# exam first item , if not true , then impossible to find result if not true_criterion ( sorted_list [ 0 ] ) : raise ValueError # exam last item , if true , it is the one . if true_criterion ( sorted_list [ - 1 ] ) : return sorted_list [ - 1 ] lower , upper = 0 , len ( sorted_list ) - 1 index = int ( ( lower + ...
def _send_event_task ( args ) : """Actually sends the MixPanel event . Runs in a uwsgi worker process ."""
endpoint = args [ 'endpoint' ] json_message = args [ 'json_message' ] _consumer_impl . send ( endpoint , json_message )
def _calculate_position ( self , at_line = None , at_position = None , at_point = None ) : """Calculate a global point position ` QPoint ( x , y ) ` , for a given line , local cursor position , or local point ."""
# Check that no option or only one option is given : if [ at_line , at_position , at_point ] . count ( None ) < 2 : raise Exception ( 'Provide no argument or only one argument!' ) # Saving cursor position : if at_position is None : at_position = self . get_position ( 'cursor' ) # FIXME : What id this used for ?...
def configure_error_handlers ( app ) : """Configure application error handlers"""
def render_error ( error ) : return ( render_template ( 'errors/%s.html' % error . code , title = error_messages [ error . code ] , code = error . code ) , error . code ) for ( errcode , title ) in error_messages . iteritems ( ) : app . errorhandler ( errcode ) ( render_error )
def k_bn ( self , n , Re ) : """returns normalisation of the sersic profile such that Re is the half light radius given n _ sersic slope"""
bn = self . b_n ( n ) k = bn * Re ** ( - 1. / n ) return k , bn
def start ( self ) : """Start HTML output ."""
today = time . time ( ) yesterday = today - 86400 tomorrow = today + 86400 today = time . localtime ( today ) yesterday = time . localtime ( yesterday ) tomorrow = time . localtime ( tomorrow ) fn = self . fnFromDate ( today ) if os . path . exists ( fn ) : out . warn ( 'HTML output file %r already exists' % fn ) ...
def consistency_check ( self ) : """Checks the network for consistency , including bus definitions and impedances . Prints warnings if anything is potentially inconsistent . Examples > > > network . consistency _ check ( )"""
for c in self . iterate_components ( self . one_port_components ) : missing = c . df . index [ ~ c . df . bus . isin ( self . buses . index ) ] if len ( missing ) > 0 : logger . warning ( "The following %s have buses which are not defined:\n%s" , c . list_name , missing ) for c in self . iterate_compone...
def from_dataframe ( cls , name , df , indices , primary_key = None ) : """Infer table metadata from a DataFrame"""
# ordered list ( column _ name , column _ type ) pairs column_types = [ ] # which columns have nullable values nullable = set ( ) # tag cached database by dataframe ' s number of rows and columns for column_name in df . columns : values = df [ column_name ] if values . isnull ( ) . any ( ) : nullable . ...
def create_dump ( ) : """Create the grammar for the ' dump ' statement"""
dump = upkey ( "dump" ) . setResultsName ( "action" ) return ( dump + upkey ( "schema" ) + Optional ( Group ( delimitedList ( table ) ) . setResultsName ( "tables" ) ) )
def _normalize_options ( self , options ) : """Generator of 2 - tuples ( option - key , option - value ) . When options spec is a list , generate a 2 - tuples per list item . : param options : dict { option : value } returns : iterator ( option - key , option - value ) - option names lower cased and prepe...
for key , value in list ( options . items ( ) ) : if '--' in key : normalized_key = self . _normalize_arg ( key ) else : normalized_key = '--%s' % self . _normalize_arg ( key ) if isinstance ( value , ( list , tuple ) ) : for opt_val in value : yield ( normalized_key , op...
def map_run ( path = None , opts = None , ** kwargs ) : '''Execute a salt cloud map file'''
client = _get_client ( ) if isinstance ( opts , dict ) : client . opts . update ( opts ) info = client . map_run ( path , ** salt . utils . args . clean_kwargs ( ** kwargs ) ) return info
def cleanUpPparse ( outputpath , rawfilename , mgf = False ) : """Delete temporary files generated by pparse , including the filetypes " . csv " , " . ms1 " , " . ms2 " , " . xtract " , the files " pParsePlusLog . txt " and " pParse . para " and optionally also the " . mgf " file generated by pParse . . . war...
extensions = [ 'csv' , 'ms1' , 'ms2' , 'xtract' ] filename , fileext = os . path . splitext ( os . path . basename ( rawfilename ) ) additionalFiles = [ aux . joinpath ( outputpath , 'pParsePlusLog.txt' ) , aux . joinpath ( outputpath , filename + '.pparse.para' ) , ] for ext in extensions : filepath = aux . joinpa...
def add_override ( self , partname , content_type ) : """Add a child ` ` < Override > ` ` element with attributes set to parameter values ."""
return self . _add_override ( partName = partname , contentType = content_type )
def set_cursor ( self , value ) : """Changes the grid cursor cell . Parameters value : 2 - tuple or 3 - tuple of String \t row , col , tab or row , col for target cursor position"""
shape = self . grid . code_array . shape if len ( value ) == 3 : self . grid . _last_selected_cell = row , col , tab = value if row < 0 or col < 0 or tab < 0 or row >= shape [ 0 ] or col >= shape [ 1 ] or tab >= shape [ 2 ] : raise ValueError ( "Cell {value} outside of {shape}" . format ( value = value ...
def _parse_error ( self , error ) : """Parses a single GLSL error and extracts the linenr and description Other GLIR implementations may omit this ."""
error = str ( error ) # Nvidia # 0(7 ) : error C1008 : undefined variable " MV " m = re . match ( r'(\d+)\((\d+)\)\s*:\s(.*)' , error ) if m : return int ( m . group ( 2 ) ) , m . group ( 3 ) # ATI / Intel # ERROR : 0:131 : ' { ' : syntax error parse error m = re . match ( r'ERROR:\s(\d+):(\d+):\s(.*)' , error ) if...
def _split_section_and_key ( key ) : """Return a tuple with config section and key ."""
parts = key . split ( '.' ) if len ( parts ) > 1 : return 'renku "{0}"' . format ( parts [ 0 ] ) , '.' . join ( parts [ 1 : ] ) return 'renku' , key
def pexpireat ( self , key , timestamp ) : """Set expire timestamp on key , timestamp in milliseconds . : raises TypeError : if timeout is not int"""
if not isinstance ( timestamp , int ) : raise TypeError ( "timestamp argument must be int, not {!r}" . format ( timestamp ) ) fut = self . execute ( b'PEXPIREAT' , key , timestamp ) return wait_convert ( fut , bool )
def in_navitem ( self , resources , nav_href ) : """Given href of nav item , determine if resource is in it"""
# The navhref might end with ' / index ' so remove it if so if nav_href . endswith ( '/index' ) : nav_href = nav_href [ : - 6 ] return self . docname . startswith ( nav_href )
def validate ( self , message , schema_name ) : """Validate a message given a schema . Args : message ( dict ) : Loaded JSON of pulled message from Google PubSub . schema _ name ( str ) : Name of schema to validate ` ` message ` ` against . ` ` schema _ name ` ` will be used to look up schema from : py ...
err = None try : jsonschema . validate ( message , self . schemas [ schema_name ] ) except KeyError : msg = ( f'Schema "{schema_name}" was not found (available: ' f'{", ".join(self.schemas.keys())})' ) err = { 'msg' : msg } except jsonschema . ValidationError as e : msg = ( f'Given message was not valid...
def guess_feature_type ( nc , variable ) : '''Returns a string describing the feature type for this variable : param netCDF4 . Dataset nc : An open netCDF dataset : param str variable : name of the variable to check'''
if is_point ( nc , variable ) : return 'point' if is_timeseries ( nc , variable ) : return 'timeseries' if is_multi_timeseries_orthogonal ( nc , variable ) : return 'multi-timeseries-orthogonal' if is_multi_timeseries_incomplete ( nc , variable ) : return 'multi-timeseries-incomplete' if is_cf_trajector...
def resolveport ( self , definitions ) : """Resolve port _ type reference . @ param definitions : A definitions object . @ type definitions : L { Definitions }"""
ref = qualify ( self . type , self . root , definitions . tns ) port_type = definitions . port_types . get ( ref ) if port_type is None : raise Exception ( "portType '%s', not-found" % self . type ) else : self . type = port_type
def value2rgba ( x : float , cmap : Callable = cm . RdYlGn , alpha_mult : float = 1.0 ) -> Tuple : "Convert a value ` x ` from 0 to 1 ( inclusive ) to an RGBA tuple according to ` cmap ` times transparency ` alpha _ mult ` ."
c = cmap ( x ) rgb = ( np . array ( c [ : - 1 ] ) * 255 ) . astype ( int ) a = c [ - 1 ] * alpha_mult return tuple ( rgb . tolist ( ) + [ a ] )
def has_legend ( self , bool_value ) : """Add , remove , or leave alone the ` ` < c : legend > ` ` child element depending on current state and * bool _ value * . If * bool _ value * is | True | and no ` ` < c : legend > ` ` element is present , a new default element is added . When | False | , any existing l...
if bool ( bool_value ) is False : self . _remove_legend ( ) else : if self . legend is None : self . _add_legend ( )
def validate_introspect_request ( self , request ) : """Ensure the request is valid . The protected resource calls the introspection endpoint using an HTTP POST request with parameters sent as " application / x - www - form - urlencoded " . token REQUIRED . The string value of the token . token _ type _ h...
self . _raise_on_missing_token ( request ) self . _raise_on_invalid_client ( request ) self . _raise_on_unsupported_token ( request )
def asm ( args ) : """% prog asm asmfile Extract FASTA sequences from asm reads ."""
p = OptionParser ( asm . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( p . print_help ( ) ) asmfile , = args prefix = asmfile . rsplit ( "." , 1 ) [ 0 ] ctgfastafile = prefix + ".ctg.fasta" scffastafile = prefix + ".scf.fasta" fp = open ( asmfile ) ctgfw = open ( ctgfastafile ,...
def get_html ( self ) : """Bibliographic entry in html format ."""
# Author links au_link = ( '<a href="https://www.scopus.com/authid/detail.url' '?origin=AuthorProfile&authorId={0}">{1}</a>' ) if len ( self . authors ) > 1 : authors = u', ' . join ( [ au_link . format ( a . auid , a . given_name + ' ' + a . surname ) for a in self . authors [ 0 : - 1 ] ] ) authors += ( u' and...
def parse ( self ) : """Executes the registered parsers to parse input configurations ."""
self . _config = _Config ( ) self . _setDefaults ( ) for parser in self . parsers : for key , value in parser . parse ( self , self . _config ) . items ( ) : key = self . _sanitizeName ( key ) if key not in self . configs : raise UnknownConfigurationException ( key ) if value is ...
def error_keys_not_found ( self , keys ) : """Check if the requested keys are found in the dict . : param keys : keys to be looked for"""
try : log . error ( "Filename: {0}" . format ( self [ 'meta' ] [ 'location' ] ) ) except : log . error ( "Filename: {0}" . format ( self [ 'location' ] ) ) log . error ( "Key '{0}' does not exist" . format ( '.' . join ( keys ) ) ) indent = "" last_index = len ( keys ) - 1 for i , k in enumerate ( keys ) : ...
def reply_regexp ( self , user , regexp ) : """Prepares a trigger for the regular expression engine . : param str user : The user ID invoking a reply . : param str regexp : The original trigger text to be turned into a regexp . : return regexp : The final regexp object ."""
if regexp in self . master . _regexc [ "trigger" ] : # Already compiled this one ! return self . master . _regexc [ "trigger" ] [ regexp ] # If the trigger is simply ' * ' then the * there needs to become ( . * ? ) # to match the blank string too . regexp = re . sub ( RE . zero_star , r'<zerowidthstar>' , regexp ) ...
def _set_lsp_frr_priority ( self , v , load = False ) : """Setter method for lsp _ frr _ priority , mapped from YANG variable / mpls _ config / router / mpls / mpls _ cmds _ holder / lsp / lsp _ frr / lsp _ frr _ priority ( container ) If this variable is read - only ( config : false ) in the source YANG file ,...
if hasattr ( v , "_utype" ) : v = v . _utype ( v ) try : t = YANGDynClass ( v , base = lsp_frr_priority . lsp_frr_priority , is_container = 'container' , presence = False , yang_name = "lsp-frr-priority" , rest_name = "priority" , parent = self , path_helper = self . _path_helper , extmethods = self . _extmetho...
def format_top ( counter , top = 3 ) : """Format a top ."""
items = islice ( reversed ( sorted ( counter . iteritems ( ) , key = lambda x : x [ 1 ] ) ) , 0 , top ) return u'; ' . join ( u'{g} ({nb})' . format ( g = g , nb = nb ) for g , nb in items )
def add_rec_new ( self , k , val ) : """Recursively add a new value and its children to me , and assign a variable to it . Args : k ( str ) : The name of the variable to assign . val ( LispVal ) : The value to be added and assigned . Returns : LispVal : The added value ."""
self . rec_new ( val ) self [ k ] = val return val
def set_start_location ( self , new_location ) : # type : ( int ) - > None '''A method to set the location of the start of the partition . Parameters : new _ location - The new extent the UDF partition should start at . Returns : Nothing .'''
if not self . _initialized : raise pycdlibexception . PyCdlibInternalError ( 'UDF Partition Volume Descriptor not initialized' ) self . part_start_location = new_location
def _ensure_running ( name , no_start = False , path = None ) : '''If the container is not currently running , start it . This function returns the state that the container was in before changing path path to the container parent directory default : / var / lib / lxc ( system ) . . versionadded : : 2015.8...
_ensure_exists ( name , path = path ) pre = state ( name , path = path ) if pre == 'running' : # This will be a no - op but running the function will give us a pretty # return dict . return start ( name , path = path ) elif pre == 'stopped' : if no_start : raise CommandExecutionError ( 'Container \'{0}\...
def rerun ( version = "3.7.0" ) : """Rerun last example code block with specified version of python ."""
from commandlib import Command Command ( DIR . gen . joinpath ( "py{0}" . format ( version ) , "bin" , "python" ) ) ( DIR . gen . joinpath ( "state" , "examplepythoncode.py" ) ) . in_dir ( DIR . gen . joinpath ( "state" ) ) . run ( )
def nucleotide_linkage ( residues ) : """Support for DNA / RNA ligands by finding missing covalent linkages to stitch DNA / RNA together ."""
nuc_covalent = [ ] # Basic support for RNA / DNA as ligand # nucleotides = [ 'A' , 'C' , 'T' , 'G' , 'U' , 'DA' , 'DC' , 'DT' , 'DG' , 'DU' ] dna_rna = { } # Dictionary of DNA / RNA residues by chain covlinkage = namedtuple ( "covlinkage" , "id1 chain1 pos1 conf1 id2 chain2 pos2 conf2" ) # Create missing covlinkage ent...
def AddNewSignature ( self , pattern , offset = None ) : """Adds a signature . Args : pattern ( bytes ) : pattern of the signature . offset ( int ) : offset of the signature . None is used to indicate the signature has no offset . A positive offset is relative from the start of the data a negative offset ...
self . signatures . append ( Signature ( pattern , offset = offset ) )
def get_all_tags_of_reminder ( self , reminder_id ) : """Get all tags of reminder This will iterate over all pages until it gets all elements . So if the rate limit exceeded it will throw an Exception and you will get nothing : param reminder _ id : the reminder id : return : list"""
return self . _iterate_through_pages ( get_function = self . get_tags_of_reminder_per_page , resource = REMINDER_TAGS , ** { 'reminder_id' : reminder_id } )
def condition_yaw ( heading , relative = False ) : """Send MAV _ CMD _ CONDITION _ YAW message to point vehicle at a specified heading ( in degrees ) . This method sets an absolute heading by default , but you can set the ` relative ` parameter to ` True ` to set yaw relative to the current yaw heading . By d...
if relative : is_relative = 1 # yaw relative to direction of travel else : is_relative = 0 # yaw is an absolute angle # create the CONDITION _ YAW command using command _ long _ encode ( ) msg = vehicle . message_factory . command_long_encode ( 0 , 0 , # target system , target component mavutil . mavlin...
def get_events ( self , from_ = None , to = None ) : """Query a slice of the events . Events are always returned in the order the were added . It also queries older event archives until it finds the event UUIDs necessary . Parameters : from _ - - if not None , return only events added after the event with...
if from_ : frombatchno = self . _find_batch_containing_event ( from_ ) if frombatchno is None : msg = 'from_={0}' . format ( from_ ) raise EventStore . EventKeyDoesNotExistError ( msg ) else : frombatchno = 0 if to : tobatchno = self . _find_batch_containing_event ( to ) if tobatchno...
def send ( self , topic , kmsg ) : """Send the message into the given topic : param str topic : a kafka topic : param ksr . transport . Message kmsg : Message to serialize : return : Execution result : rtype : kser . result . Result"""
try : self . client . do_request ( method = "POST" , params = dict ( format = "raw" ) , path = "/topic/{}" . format ( topic ) , data = kmsg . MARSHMALLOW_SCHEMA . dump ( kmsg ) ) result = Result ( uuid = kmsg . uuid , stdout = "Message sent: {} ({})" . format ( kmsg . uuid , kmsg . entrypoint ) ) except Excepti...
def _create_one ( self , ctx ) : """Creates an instance to be saved when a model is created ."""
assert isinstance ( ctx , ResourceQueryContext ) fields = dict_pick ( ctx . data , self . _model_columns ) model = self . model_cls ( ** fields ) return model
def _respawn ( self ) : """Pick a random location for the star making sure it does not overwrite an existing piece of text ."""
self . _cycle = randint ( 0 , len ( self . _star_chars ) ) ( height , width ) = self . _screen . dimensions while True : self . _x = randint ( 0 , width - 1 ) self . _y = self . _screen . start_line + randint ( 0 , height - 1 ) if self . _screen . get_from ( self . _x , self . _y ) [ 0 ] == 32 : bre...
def isotopePattern ( sum_formula , threshold = 1e-4 , rel_threshold = True , desired_prob = None ) : """Calculates isotopic peaks for a sum formula . : param sum _ formula : text representation of an atomic composition : type sum _ formula : str : param threshold : minimum peak abundance : type threshold : ...
assert threshold >= 0 and threshold < 1 assert desired_prob is None or ( desired_prob > 0 and desired_prob <= 1 ) if desired_prob : s = ims . spectrum_new_from_sf ( sum_formula . encode ( 'ascii' ) , desired_prob ) else : s = ims . spectrum_new_from_sf_thr ( sum_formula . encode ( 'ascii' ) , threshold , rel_th...
def build_extension ( extensions : Sequence [ ExtensionHeader ] ) -> str : """Unparse a ` ` Sec - WebSocket - Extensions ` ` header . This is the reverse of : func : ` parse _ extension ` ."""
return ", " . join ( build_extension_item ( name , parameters ) for name , parameters in extensions )
def configBorderRouter ( self , P_Prefix , P_stable = 1 , P_default = 1 , P_slaac_preferred = 0 , P_Dhcp = 0 , P_preference = 0 , P_on_mesh = 1 , P_nd_dns = 0 ) : """configure the border router with a given prefix entry parameters Args : P _ Prefix : IPv6 prefix that is available on the Thread Network P _ sta...
print '%s call configBorderRouter' % self . port prefix = self . __convertIp6PrefixStringToIp6Address ( str ( P_Prefix ) ) print prefix try : parameter = '' if P_slaac_preferred == 1 : parameter += ' -a -f' if P_stable == 1 : parameter += ' -s' if P_default == 1 : parameter += ' ...
def sentence ( random = random , * args , ** kwargs ) : """Return a whole sentence > > > mock _ random . seed ( 0) > > > sentence ( random = mock _ random ) " Agatha Incrediblebritches can ' t wait to smell two chimps in Boatbencheston . " > > > mock _ random . seed ( 2) > > > sentence ( random = mock _ r...
if 'name' in kwargs and kwargs [ 'name' ] : nm = kwargs ( name ) elif random . choice ( [ True , False , False ] ) : nm = name ( capitalize = True , random = random ) else : nm = random . choice ( people ) def type_one ( ) : return "{name} will {verb} {thing}." . format ( name = nm , verb = verb ( rando...
def _execute_connector ( connector_command , top_level_argument , * file_contents , listing = None ) : """Executes a connector by executing the given connector _ command . The content of args will be the content of the files handed to the connector cli . : param connector _ command : The connector command to ex...
# create temp _ files for every file _ content temp_files = [ ] for file_content in file_contents : if file_content is None : continue tmp_file = tempfile . NamedTemporaryFile ( 'w' ) json . dump ( file_content , tmp_file ) tmp_file . flush ( ) temp_files . append ( tmp_file ) tmp_listing_fi...
def compute_payload_block_hash ( this ) : """Compute hash of each payload block . Used to prevent payload corruption and tampering ."""
return hmac . new ( hashlib . sha512 ( struct . pack ( '<Q' , this . _index ) + hashlib . sha512 ( this . _ . _ . header . value . dynamic_header . master_seed . data + this . _ . transformed_key + b'\x01' ) . digest ( ) ) . digest ( ) , struct . pack ( '<Q' , this . _index ) + struct . pack ( '<I' , len ( this . block...
async def shutdown ( self , container , force = False ) : '''Shutdown all connections . Exclusive connections created by get _ connection will shutdown after release ( )'''
p = self . _connpool self . _connpool = [ ] self . _shutdown = True if self . _defaultconn : p . append ( self . _defaultconn ) self . _defaultconn = None if self . _subscribeconn : p . append ( self . _subscribeconn ) self . _subscribeconn = None await container . execute_all ( [ self . _shutdown_conn ...