signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def min_heapify ( arr , start , simulation , iteration ) : """Min heapify helper for min _ heap _ sort"""
# Offset last _ parent by the start ( last _ parent calculated as if start index was 0) # All array accesses need to be offset by start end = len ( arr ) - 1 last_parent = ( end - start - 1 ) // 2 # Iterate from last parent to first for parent in range ( last_parent , - 1 , - 1 ) : current_parent = parent # Ite...
def _viz_prototype ( self , vis_fn ) : '''Outputs a function which will log the arguments to Visdom in an appropriate way . Args : vis _ fn : A function , such as self . vis . image'''
def _viz_logger ( * args , ** kwargs ) : self . win = vis_fn ( * args , win = self . win , env = self . env , opts = self . opts , ** kwargs ) return _viz_logger
def send_email ( self , ** kwargs ) : """Sends an email using Mandrill ' s API . Returns a Requests : class : ` Response ` object . At a minimum kwargs must contain the keys to , from _ email , and text . Everything passed as kwargs except for the keywords ' key ' , ' async ' , and ' ip _ pool ' will be sen...
endpoint = self . messages_endpoint data = { 'async' : kwargs . pop ( 'async' , False ) , 'ip_pool' : kwargs . pop ( 'ip_pool' , '' ) , 'key' : kwargs . pop ( 'key' , self . api_key ) , } if not data . get ( 'key' , None ) : raise ValueError ( 'No Mandrill API key has been configured' ) # Sending a template through...
def update_bundle ( self , href = None , name = None , notify_url = None , version = None , external_id = None ) : """Update a bundle . Note that only the ' name ' and ' notify _ url ' can be update . ' href ' the relative href to the bundle . May not be None . ' name ' the name of the bundle . May be None . ...
# Argument error checking . assert href is not None assert version is None or isinstance ( version , int ) # Prepare the data we ' re going to include in our bundle update . data = None fields = { } if name is not None : fields [ 'name' ] = name if notify_url is not None : fields [ 'notify_url' ] = notify_url i...
def _validate_format ( req ) : '''Validate jsonrpc compliance of a jsonrpc - dict . req - the request as a jsonrpc - dict raises SLOJSONRPCError on validation error'''
# check for all required keys for key in SLOJSONRPC . _min_keys : if not key in req : logging . debug ( 'JSONRPC: Fmt Error: Need key "%s"' % key ) raise SLOJSONRPCError ( - 32600 ) # check all keys if allowed for key in req . keys ( ) : if not key in SLOJSONRPC . _allowed_keys : logging...
def ephemeral ( cls ) : """Creates a new ephemeral key constructed using a raw 32 - byte string from urandom . Ephemeral keys are used once for each encryption task and are then discarded ; they are not intended for long - term or repeat use ."""
private_key = nacl . public . PrivateKey ( os . urandom ( 32 ) ) return cls ( private_key . public_key , private_key )
def require_paragraph ( self ) : """Create a new paragraph unless the currently - active container is already a paragraph ."""
if self . _containers and _is_paragraph ( self . _containers [ - 1 ] ) : return False else : self . start_paragraph ( ) return True
def ifadd ( self , iff , addr ) : """Add an interface ' iff ' with provided address into routing table . Ex : ifadd ( ' eth0 ' , ' 2001 : bd8 : cafe : 1 : : 1/64 ' ) will add following entry into # noqa : E501 Scapy6 internal routing table : Destination Next Hop iface Def src @ Metric 2001 : bd8 : cafe : 1 ...
addr , plen = ( addr . split ( "/" ) + [ "128" ] ) [ : 2 ] addr = in6_ptop ( addr ) plen = int ( plen ) naddr = inet_pton ( socket . AF_INET6 , addr ) nmask = in6_cidr2mask ( plen ) prefix = inet_ntop ( socket . AF_INET6 , in6_and ( nmask , naddr ) ) self . invalidate_cache ( ) self . routes . append ( ( prefix , plen ...
def src_paths_changed ( self ) : """See base class docstring ."""
# Get the diff dictionary diff_dict = self . _git_diff ( ) # Return the changed file paths ( dict keys ) # in alphabetical order return sorted ( diff_dict . keys ( ) , key = lambda x : x . lower ( ) )
def reader ( self ) : from ambry . orm . exc import NotFoundError from fs . errors import ResourceNotFoundError """The reader for the datafile"""
try : return self . datafile . reader except ResourceNotFoundError : raise NotFoundError ( "Failed to find partition file, '{}' " . format ( self . datafile . path ) )
def constraints_stmt ( stmt , env = None ) : """Since a statement may define new names or return an expression , the constraints that result are in a ConstrainedEnv mapping names to types , with constraints , and maybe having a return type ( which is a constrained type )"""
env = env or { } if isinstance ( stmt , ast . FunctionDef ) : arg_env = fn_env ( stmt . args ) body_env = extended_env ( env , arg_env ) constraints = [ ] return_type = None # TODO : should be fresh and constrained ? for body_stmt in stmt . body : cs = constraints_stmt ( body_stmt , env ...
def add_doc_to_update ( self , action , update_spec , action_buffer_index ) : """Prepare document for update based on Elasticsearch response . Set flag if document needs to be retrieved from Elasticsearch"""
doc = { "_index" : action [ "_index" ] , "_type" : action [ "_type" ] , "_id" : action [ "_id" ] , } # If get _ from _ ES = = True - > get document ' s source from Elasticsearch get_from_ES = self . should_get_id ( action ) self . doc_to_update . append ( ( doc , update_spec , action_buffer_index , get_from_ES ) )
def split ( X , Y , question ) : """Partitions a dataset . For each row in the dataset , check if it matches the question . If so , add it to ' true rows ' , otherwise , add it to ' false rows ' ."""
true_X , false_X = [ ] , [ ] true_Y , false_Y = [ ] , [ ] for x , y in zip ( X , Y ) : if question . match ( x ) : true_X . append ( x ) true_Y . append ( y ) else : false_X . append ( x ) false_Y . append ( y ) return ( np . array ( true_X ) , np . array ( false_X ) , np . array...
def viz_json ( net , dendro = True , links = False ) : '''make the dictionary for the clustergram . js visualization'''
from . import calc_clust import numpy as np all_dist = calc_clust . group_cutoffs ( ) for inst_rc in net . dat [ 'nodes' ] : inst_keys = net . dat [ 'node_info' ] [ inst_rc ] all_cats = [ x for x in inst_keys if 'cat-' in x ] for i in range ( len ( net . dat [ 'nodes' ] [ inst_rc ] ) ) : inst_dict =...
def autodiscover ( path = None , plugin_prefix = 'intake_' ) : """Scan for Intake plugin packages and return a dict of plugins . This function searches path ( or sys . path ) for packages with names that start with plugin _ prefix . Those modules will be imported and scanned for subclasses of intake . source ...
plugins = { } for importer , name , ispkg in pkgutil . iter_modules ( path = path ) : if name . startswith ( plugin_prefix ) : t = time . time ( ) new_plugins = load_plugins_from_module ( name ) for plugin_name , plugin in new_plugins . items ( ) : if plugin_name in plugins : ...
def readMangleFile ( infile , lon , lat , index = None ) : """DEPRECATED : 2018-05-04 Mangle must be set up on your system . The index argument is a temporary file naming convention to avoid file conflicts . Coordinates must be given in the native coordinate system of the Mangle file ."""
msg = "'mask.readMangleFile': ADW 2018-05-05" DeprecationWarning ( msg ) if index is None : index = np . random . randint ( 0 , 1.e10 ) coordinate_file = 'temp_coordinate_%010i.dat' % ( index ) maglim_file = 'temp_maglim_%010i.dat' % ( index ) writer = open ( coordinate_file , 'w' ) for ii in range ( 0 , len ( lon ...
def update ( self ) : """Update this range"""
if not self . _track_changes : return True # there ' s nothing to update data = self . to_api_data ( restrict_keys = self . _track_changes ) response = self . session . patch ( self . build_url ( '' ) , data = data ) if not response : return False data = response . json ( ) for field in self . _track_changes : ...
def download_url ( url , dir_name = '.' , save_name = None , store_directory = None , messages = True , suffix = '' ) : """Download a file from a url and save it to disk ."""
if sys . version_info >= ( 3 , 0 ) : from urllib . parse import quote from urllib . request import urlopen from urllib . error import HTTPError , URLError else : from urllib2 import quote from urllib2 import urlopen from urllib2 import URLError as HTTPError i = url . rfind ( '/' ) file = url [ i...
def __setup_tool_config ( self , conf ) : """Setups toolbox object and authorization mechanism based on supplied toolbox _ path ."""
tool_config_files = conf . get ( "tool_config_files" , None ) if not tool_config_files : # For compatibity with Galaxy , allow tool _ config _ file # option name . tool_config_files = conf . get ( "tool_config_file" , None ) toolbox = None if tool_config_files : toolbox = ToolBox ( tool_config_files ) else : ...
def get_value_len ( value ) : '''Get length of ` ` value ` ` . If ` ` value ` ` ( eg , iterator ) has no len ( ) , convert it to list first . return both length and converted value .'''
try : Nvalue = len ( value ) except TypeError : # convert iterator / generator to list value = list ( value ) Nvalue = len ( value ) return Nvalue , value
def zip ( * args , ** kwargs ) : """Returns a list of tuples , where the i - th tuple contains the i - th element from each of the argument sequences or iterables ( or default if too short ) ."""
args = [ list ( iterable ) for iterable in args ] n = max ( map ( len , args ) ) v = kwargs . get ( "default" , None ) return _zip ( * [ i + [ v ] * ( n - len ( i ) ) for i in args ] )
def flatten_list ( lobj ) : """Recursively flattens a list . : param lobj : List to flatten : type lobj : list : rtype : list For example : > > > import pmisc > > > pmisc . flatten _ list ( [ 1 , [ 2 , 3 , [ 4 , 5 , 6 ] ] , 7 ] ) [1 , 2 , 3 , 4 , 5 , 6 , 7]"""
ret = [ ] for item in lobj : if isinstance ( item , list ) : for sub_item in flatten_list ( item ) : ret . append ( sub_item ) else : ret . append ( item ) return ret
def get_prep_value ( self , value ) : """Perform preliminary non - db specific value checks and conversions ."""
if value : if not isinstance ( value , PhoneNumber ) : value = to_python ( value ) if value . is_valid ( ) : format_string = getattr ( settings , "PHONENUMBER_DB_FORMAT" , "E164" ) fmt = PhoneNumber . format_map [ format_string ] value = value . format_as ( fmt ) else : ...
def colored ( cls , color , message ) : """Small function to wrap a string around a color Args : color ( str ) : name of the color to wrap the string with , must be one of the class properties message ( str ) : String to wrap with the color Returns : str : the colored string"""
return getattr ( cls , color . upper ( ) ) + message + cls . DEFAULT
def run_optimization ( self ) : """Run the optimization , call run _ one _ step with suitable placeholders . Returns : True if certificate is found False otherwise"""
penalty_val = self . params [ 'init_penalty' ] # Don ' t use smoothing initially - very inaccurate for large dimension self . smooth_on = False smooth_val = 0 learning_rate_val = self . params [ 'init_learning_rate' ] self . current_outer_step = 1 while self . current_outer_step <= self . params [ 'outer_num_steps' ] :...
def _publish_response ( self , slug , message ) : """Publish a response message for a device Args : slug ( string ) : The device slug that we are publishing on behalf of message ( dict ) : A set of key value pairs that are used to create the message that is sent ."""
resp_topic = self . topics . gateway_topic ( slug , 'data/response' ) self . _logger . debug ( "Publishing response message: (topic=%s) (message=%s)" , resp_topic , message ) self . client . publish ( resp_topic , message )
def measure_fps ( self , window = 1 , callback = '%1.1f FPS' ) : """Measure the current FPS Sets the update window , connects the draw event to update _ fps and sets the callback function . Parameters window : float The time - window ( in seconds ) to calculate FPS . Default 1.0. callback : function | s...
# Connect update _ fps function to draw self . events . draw . disconnect ( self . _update_fps ) if callback : if isinstance ( callback , string_types ) : callback_str = callback # because callback gets overwritten def callback ( x ) : print ( callback_str % x ) self . _fps_w...
def close ( self ) : """Closes the handle opened by open ( ) . The remapped function is WinDivertClose : : BOOL WinDivertClose ( _ _ in HANDLE handle For more info on the C call visit : http : / / reqrypt . org / windivert - doc . html # divert _ close"""
if not self . is_open : raise RuntimeError ( "WinDivert handle is not open." ) windivert_dll . WinDivertClose ( self . _handle ) self . _handle = None
def load_collection_from_stream ( resource , stream , content_type ) : """Creates a new collection for the registered resource and calls ` load _ into _ collection _ from _ stream ` with it ."""
coll = create_staging_collection ( resource ) load_into_collection_from_stream ( coll , stream , content_type ) return coll
def delete ( self ) : """Extend to the delete the session from storage"""
self . clear ( ) if os . path . isfile ( self . _filename ) : os . unlink ( self . _filename ) else : LOGGER . debug ( 'Session file did not exist: %s' , self . _filename )
def write_to_textfile ( path , registry ) : """Write metrics to the given path . This is intended for use with the Node exporter textfile collector . The path must end in . prom for the textfile collector to process it ."""
tmppath = '%s.%s.%s' % ( path , os . getpid ( ) , threading . current_thread ( ) . ident ) with open ( tmppath , 'wb' ) as f : f . write ( generate_latest ( registry ) ) # rename ( 2 ) is atomic . os . rename ( tmppath , path )
def write_headers ( self , observations , sys_header ) : """Writes the header part of the astrom file so that only the source data has to be filled in ."""
if self . _header_written : raise AstromFormatError ( "Astrom file already has headers." ) self . _write_observation_list ( observations ) self . _write_observation_headers ( observations ) self . _write_sys_header ( sys_header ) self . _write_source_header ( ) self . _header_written = True
def _set_red_profile_ecn ( self , v , load = False ) : """Setter method for red _ profile _ ecn , mapped from YANG variable / qos / ecn / red _ profile / red _ profile _ ecn ( container ) If this variable is read - only ( config : false ) in the source YANG file , then _ set _ red _ profile _ ecn is considered ...
if hasattr ( v , "_utype" ) : v = v . _utype ( v ) try : t = YANGDynClass ( v , base = red_profile_ecn . red_profile_ecn , is_container = 'container' , presence = False , yang_name = "red-profile-ecn" , rest_name = "ecn" , parent = self , path_helper = self . _path_helper , extmethods = self . _extmethods , reg...
def get_token ( self , user_id ) : """Get user token Checks if a custom token implementation is registered and uses that . Otherwise falls back to default token implementation . Returns a string token on success . : param user _ id : int , user id : return : str"""
if not self . jwt_implementation : return self . default_token_implementation ( user_id ) try : implementation = import_string ( self . jwt_implementation ) except ImportError : msg = 'Failed to import custom JWT implementation. ' msg += 'Check that configured module exists [{}]' raise x . Configura...
def semantic_similarity ( go_id1 , go_id2 , godag , branch_dist = None ) : '''Finds the semantic similarity ( inverse of the semantic distance ) between two GO terms .'''
dist = semantic_distance ( go_id1 , go_id2 , godag , branch_dist ) if dist is not None : return 1.0 / float ( dist )
def getReffs ( self , level = 1 , subreference = None ) -> CtsReferenceSet : """Reference available at a given level : param level : Depth required . If not set , should retrieve first encountered level ( 1 based ) . 0 retrieves inside a range : param subreference : Subreference ( optional ) : returns : Lis...
level += self . depth if not subreference : subreference = self . reference return self . textObject . getValidReff ( level , reference = subreference )
def visualize_model ( onnx_model , open_browser = True , dest = "index.html" ) : """Creates a graph visualization of an ONNX protobuf model . It creates a SVG graph with * d3 . js * and stores it into a file . : param model : ONNX model ( protobuf object ) : param open _ browser : opens the browser : param ...
graph = onnx_model . graph model_info = "Model produced by: " + onnx_model . producer_name + " version(" + onnx_model . producer_version + ")" html_str = """ <!doctype html> <meta charset="utf-8"> <title>ONNX Visualization</title> <script src="https://d3js.org/d3.v3.min.js"></script> <link rel="styl...
def weather ( searchterm ) : """Get the weather for a place given by searchterm Returns a title and a list of forecasts . The title describes the location for the forecast ( i . e . " Portland , ME USA " ) The list of forecasts is a list of dictionaries in slack attachment fields format ( see https : / / ap...
unit = "si" if os . environ . get ( "WEATHER_CELSIUS" ) else "us" geo = requests . get ( "https://api.mapbox.com/geocoding/v5/mapbox.places/{}.json?limit=1&access_token={}" . format ( quote ( searchterm . encode ( "utf8" ) ) , MAPBOX_API_TOKEN ) ) . json ( ) citystate = geo [ "features" ] [ 0 ] [ "place_name" ] lon , l...
def to_array ( self , itaper , normalization = '4pi' , csphase = 1 ) : """Return the spherical harmonic coefficients of taper i as a numpy array . Usage coeffs = x . to _ array ( itaper , [ normalization , csphase ] ) Returns coeffs : ndarray , shape ( 2 , lwin + 1 , lwin + 11) 3 - D numpy ndarray of th...
if type ( normalization ) != str : raise ValueError ( 'normalization must be a string. ' + 'Input type was {:s}' . format ( str ( type ( normalization ) ) ) ) if normalization . lower ( ) not in ( '4pi' , 'ortho' , 'schmidt' ) : raise ValueError ( "normalization must be '4pi', 'ortho' " + "or 'schmidt'. Provide...
def _select_next_server ( self ) : """Looks up in the server pool for an available server and attempts to connect ."""
# Continue trying to connect until there is an available server # or bail in case there are no more available servers . while True : if len ( self . _server_pool ) == 0 : self . _current_server = None raise ErrNoServers now = time . time ( ) s = self . _server_pool . pop ( 0 ) if self . ...
def inspect ( self , nids = None , wslice = None , ** kwargs ) : """Inspect the tasks ( SCF iterations , Structural relaxation . . . ) and produces matplotlib plots . Args : nids : List of node identifiers . wslice : Slice object used to select works . kwargs : keyword arguments passed to ` task . inspect...
figs = [ ] for task in self . select_tasks ( nids = nids , wslice = wslice ) : if hasattr ( task , "inspect" ) : fig = task . inspect ( ** kwargs ) if fig is None : cprint ( "Cannot inspect Task %s" % task , color = "blue" ) else : figs . append ( fig ) else : ...
def addEdgeToGraph ( parentNodeName , childNodeName , graphFileHandle , colour = "black" , length = "10" , weight = "1" , dir = "none" , label = "" , style = "" ) : """Links two nodes in the graph together ."""
graphFileHandle . write ( 'edge[color=%s,len=%s,weight=%s,dir=%s,label="%s",style=%s];\n' % ( colour , length , weight , dir , label , style ) ) graphFileHandle . write ( "%s -- %s;\n" % ( parentNodeName , childNodeName ) )
def get_sessionmaker ( sqlalchemy_url , engine = None ) : """Create session with database to work in"""
if engine is None : engine = create_engine ( sqlalchemy_url ) return sessionmaker ( bind = engine )
def count ( self ) : """Returns the number of bits set to True in the bit string . Usage : assert BitString ( ' 00110 ' ) . count ( ) = = 2 Arguments : None Return : An int , the number of bits with value 1."""
result = 0 bits = self . _bits while bits : result += bits % 2 bits >>= 1 return result
def split_adhoc_filters_into_base_filters ( fd ) : """Mutates form data to restructure the adhoc filters in the form of the four base filters , ` where ` , ` having ` , ` filters ` , and ` having _ filters ` which represent free form where sql , free form having sql , structured where clauses and structured h...
adhoc_filters = fd . get ( 'adhoc_filters' ) if isinstance ( adhoc_filters , list ) : simple_where_filters = [ ] simple_having_filters = [ ] sql_where_filters = [ ] sql_having_filters = [ ] for adhoc_filter in adhoc_filters : expression_type = adhoc_filter . get ( 'expressionType' ) ...
async def addNodes ( self , nodedefs ) : '''Quickly add / modify a list of nodes from node definition tuples . This API is the simplest / fastest way to add nodes , set node props , and add tags to nodes remotely . Args : nodedefs ( list ) : A list of node definition tuples . See below . A node definition...
async with await self . snap ( ) as snap : snap . strict = False async for node in snap . addNodes ( nodedefs ) : yield node
def limits ( self , x1 , x2 , y1 , y2 ) : """Set the coordinate boundaries of plot"""
import math self . x1 = x1 self . x2 = x2 self . y1 = y1 self . y2 = y2 self . xscale = ( self . cx2 - self . cx1 ) / ( self . x2 - self . x1 ) self . yscale = ( self . cy2 - self . cy1 ) / ( self . y2 - self . y1 ) ra1 = self . x1 ra2 = self . x2 dec1 = self . y1 dec2 = self . y2 ( sx1 , sy2 ) = self . p2c ( ( ra1 , d...
def template ( page = None , layout = None , ** kwargs ) : """Decorator to change the view template and layout . It works on both View class and view methods on class only $ layout is applied , everything else will be passed to the kwargs Using as first argument , it will be the layout . : first arg or $ ...
pkey = "_template_extends__" def decorator ( f ) : if inspect . isclass ( f ) : layout_ = layout or page extends = kwargs . pop ( "extends" , None ) if extends and hasattr ( extends , pkey ) : items = getattr ( extends , pkey ) . items ( ) if "layout" in items : ...
def monthly ( usaf , year , field = 'GHI (W/m^2)' ) : """monthly insolation"""
m = [ ] lastm = 1 usafdata = Data ( usaf , year ) t = 0 for r in usafdata : r [ 'GHI (W/m^2)' ] = r [ 'Glo Mod (Wh/m^2)' ] r [ 'DHI (W/m^2)' ] = r [ 'Dif Mod (Wh/m^2)' ] r [ 'DNI (W/m^2)' ] = r [ 'Dir Mod (Wh/m^2)' ] if r [ 'datetime' ] . month != lastm : m . append ( t / 1000. ) t = 0 ...
def remove_setting ( self , section , name , save = False ) : '''remove a setting from the global config'''
configfile = get_configfile ( ) return _remove_setting ( section , name , configfile , save )
def angular_power_spectrum ( self ) : """Returns the angular power spectrum for the set of coefficients . That is , we compute c _ n = sum cnm * conj ( cnm ) m = - n Returns : power _ spectrum ( numpy . array , dtype = double ) spectrum as a function of n ."""
# Added this routine as a result of my discussions with Ajinkya Nene # https : / / github . com / anene list_of_modes = self . _reshape_m_vecs ( ) Nmodes = len ( list_of_modes ) angular_power = np . zeros ( Nmodes , dtype = np . double ) for n in range ( 0 , Nmodes ) : mode = np . array ( list_of_modes [ n ] , dtyp...
def load ( yaml_string , schema = None , label = u"<unicode string>" ) : """Parse the first YAML document in a string and produce corresponding YAML object ."""
return generic_load ( yaml_string , schema = schema , label = label )
def time_from_hhmmssmmm ( string , decimal_separator = "." ) : """Parse the given ` ` HH : MM : SS . mmm ` ` string and return a time value . : param string string : the string to be parsed : param string decimal _ separator : the decimal separator to be used : rtype : : class : ` ~ aeneas . exacttiming . Tim...
if decimal_separator == "," : pattern = HHMMSS_MMM_PATTERN_COMMA else : pattern = HHMMSS_MMM_PATTERN v_length = TimeValue ( "0.000" ) try : match = pattern . search ( string ) if match is not None : v_h = int ( match . group ( 1 ) ) v_m = int ( match . group ( 2 ) ) v_s = int ( m...
def pack_nibbles ( nibbles ) : """pack nibbles to binary : param nibbles : a nibbles sequence . may have a terminator"""
if nibbles [ - 1 ] == NIBBLE_TERMINATOR : flags = 2 nibbles = nibbles [ : - 1 ] else : flags = 0 oddlen = len ( nibbles ) % 2 flags |= oddlen # set lowest bit if odd number of nibbles if oddlen : nibbles = [ flags ] + nibbles else : nibbles = [ flags , 0 ] + nibbles o = b'' for i in range ( 0 , len ...
def close ( self ) -> Awaitable [ None ] : """Close all ongoing DNS calls ."""
for ev in self . _throttle_dns_events . values ( ) : ev . cancel ( ) return super ( ) . close ( )
def errors ( self ) : """Computes and returns the error and standard deviation of the filter at this time step . Returns error : np . array size 1xorder + 1 std : np . array size 1xorder + 1"""
n = self . n dt = self . dt order = self . _order sigma = self . sigma error = np . zeros ( order + 1 ) std = np . zeros ( order + 1 ) if n == 0 : return ( error , std ) if order == 0 : error [ 0 ] = sigma / sqrt ( n ) std [ 0 ] = sigma / sqrt ( n ) elif order == 1 : if n > 1 : error [ 0 ] = sig...
def cloud_init ( names , host = None , quiet = False , ** kwargs ) : '''Wrapper for using lxc . init in saltcloud compatibility mode names Name of the containers , supports a single name or a comma delimited list of names . host Minion to start the container on . Required . path path to the container ...
if quiet : log . warning ( "'quiet' argument is being deprecated. Please migrate to --quiet" ) return __salt__ [ 'lxc.init' ] ( names = names , host = host , saltcloud_mode = True , quiet = quiet , ** kwargs )
def centers_of_labels ( labels ) : '''Return the i , j coordinates of the centers of a labels matrix The result returned is an 2 x n numpy array where n is the number of the label minus one , result [ 0 , x ] is the i coordinate of the center and result [ x , 1 ] is the j coordinate of the center . You can ...
max_labels = np . max ( labels ) if max_labels == 0 : return np . zeros ( ( 2 , 0 ) , int ) result = scind . center_of_mass ( np . ones ( labels . shape ) , labels , np . arange ( max_labels ) + 1 ) result = np . array ( result ) if result . ndim == 1 : result . shape = ( 2 , 1 ) return result return result...
def do_training ( num_epoch , optimizer , kvstore , learning_rate , model_prefix , decay ) : """Perform CapsNet training"""
summary_writer = SummaryWriter ( args . tblog_dir ) lr_scheduler = SimpleLRScheduler ( learning_rate ) optimizer_params = { 'lr_scheduler' : lr_scheduler } module . init_params ( ) module . init_optimizer ( kvstore = kvstore , optimizer = optimizer , optimizer_params = optimizer_params ) n_epoch = 0 while True : if...
def log_to_console ( status = True , level = None ) : """Log events to the console . Args : status ( bool , Optional , Default = True ) whether logging to console should be turned on ( True ) or off ( False ) level ( string , Optional , Default = None ) : level of logging ; whichever level is chosen all h...
if status : if level is not None : logger . setLevel ( level ) console_handler = logging . StreamHandler ( ) # create formatter formatter = logging . Formatter ( '%(levelname)s-%(name)s: %(message)s' ) # add formatter to handler console_handler . setFormatter ( formatter ) logger . a...
def _process_changes ( self , newRev , branch ) : """Read changes since last change . - Read list of commit hashes . - Extract details from each commit . - Add changes to database ."""
# initial run , don ' t parse all history if not self . lastRev : return rebuild = False if newRev in self . lastRev . values ( ) : if self . buildPushesWithNoCommits : existingRev = self . lastRev . get ( branch ) if existingRev is None : # This branch was completely unknown , rebuild ...
def get_config_env_key ( k : str ) -> str : """Returns a scrubbed environment variable key , PULUMI _ CONFIG _ < k > , that can be used for setting explicit varaibles . This is unlike PULUMI _ CONFIG which is just a JSON - serialized bag ."""
env_key = '' for c in k : if c == '_' or 'A' <= c <= 'Z' or '0' <= c <= '9' : env_key += c elif 'a' <= c <= 'z' : env_key += c . upper ( ) else : env_key += '_' return 'PULUMI_CONFIG_%s' % env_key
def _execute_model ( self , feed_dict , out_dict ) : """Executes model . : param feed _ dict : Input dictionary mapping nodes to input data . : param out _ dict : Output dictionary mapping names to nodes . : return : Dictionary mapping names to input data ."""
network_out = self . sess . run ( list ( out_dict . values ( ) ) , feed_dict = feed_dict ) run_out = dict ( zip ( list ( out_dict . keys ( ) ) , network_out ) ) return run_out
def fourier_ratios ( phase_shifted_coeffs ) : r"""Returns the : math : ` R _ { j1 } ` and : math : ` \ phi _ { j1 } ` values for the given phase - shifted coefficients . . . math : : R _ { j1 } = A _ j / A _ 1 . . math : : \ phi _ { j1 } = \ phi _ j - j \ phi _ 1 * * Parameters * * phase _ shifted _ c...
n_coeff = phase_shifted_coeffs . size # n _ coeff = 2 * degree + 1 = > degree = ( n _ coeff - 1 ) / 2 degree = ( n_coeff - 1 ) / 2 amplitudes = phase_shifted_coeffs [ 1 : : 2 ] phases = phase_shifted_coeffs [ 2 : : 2 ] # there are degree - 1 amplitude ratios , and degree - 1 phase deltas , # so altogether there are 2 *...
def reset_time_estimate ( self , ** kwargs ) : """Resets estimated time for the object to 0 seconds . Args : * * kwargs : Extra options to send to the server ( e . g . sudo ) Raises : GitlabAuthenticationError : If authentication is not correct GitlabTimeTrackingError : If the time tracking update cannot ...
path = '%s/%s/reset_time_estimate' % ( self . manager . path , self . get_id ( ) ) return self . manager . gitlab . http_post ( path , ** kwargs )
def get_worker ( self , * queues ) : """Returns an RQ worker instance for the given queue names , e . g . : : configured _ worker = rq . get _ worker ( ) default _ worker = rq . get _ worker ( ' default ' ) default _ low _ worker = rq . get _ worker ( ' default ' , ' low ' ) : param \\ * queues : Names of q...
if not queues : queues = self . queues queues = [ self . get_queue ( name ) for name in queues ] worker_cls = import_attribute ( self . worker_class ) worker = worker_cls ( queues , connection = self . connection , job_class = self . job_class , queue_class = self . queue_class , ) for exception_handler in self . _...
def reverseComplement ( seq ) : '''Helper function for generating reverse - complements'''
revComp = '' complement = { 'A' : 'T' , 'C' : 'G' , 'G' : 'C' , 'T' : 'A' , 'N' : 'N' , '$' : '$' } for c in reversed ( seq ) : revComp += complement [ c ] return revComp
def get_layout_settings ( self ) : """Return the layout state for this splitter and its children . Record the current state , including file names and current line numbers , of the splitter panels . Returns : A dictionary containing keys { hexstate , sizes , splitsettings } . hexstate : String of saveStat...
splitsettings = [ ] for editorstack , orientation in self . iter_editorstacks ( ) : clines = [ ] cfname = '' # XXX - this overrides value from the loop to always be False ? orientation = False if hasattr ( editorstack , 'data' ) : clines = [ finfo . editor . get_cursor_line_number ( ) for fi...
def session ( self ) : """This is a session between the consumer ( your website ) and the provider ( e . g . Twitter ) . It is * not * a session between a user of your website and your website . : return :"""
return self . session_class ( client_key = self . client_key , client_secret = self . client_secret , signature_method = self . signature_method , signature_type = self . signature_type , rsa_key = self . rsa_key , client_class = self . client_class , force_include_body = self . force_include_body , blueprint = self , ...
def _broadcast_shapes ( s1 , s2 ) : """Given array shapes ` s1 ` and ` s2 ` , compute the shape of the array that would result from broadcasting them together ."""
n1 = len ( s1 ) n2 = len ( s2 ) n = max ( n1 , n2 ) res = [ 1 ] * n for i in range ( n ) : if i >= n1 : c1 = 1 else : c1 = s1 [ n1 - 1 - i ] if i >= n2 : c2 = 1 else : c2 = s2 [ n2 - 1 - i ] if c1 == 1 : rc = c2 elif c2 == 1 or c1 == c2 : rc = c1 ...
def build_strain_specific_models ( self , save_models = False ) : """Using the orthologous genes matrix , create and modify the strain specific models based on if orthologous genes exist . Also store the sequences directly in the reference GEM - PRO protein sequence attribute for the strains ."""
if len ( self . df_orthology_matrix ) == 0 : raise RuntimeError ( 'Empty orthology matrix' ) # Create an emptied copy of the reference GEM - PRO for strain_gempro in tqdm ( self . strains ) : log . debug ( '{}: building strain specific model' . format ( strain_gempro . id ) ) # For each genome , load the me...
def _new_level ( self , depth ) : """Create a new level and header and connect signals : param depth : the depth level : type depth : int : returns : None : rtype : None : raises : None"""
l = self . create_level ( depth ) h = self . create_header ( depth ) self . add_lvl_to_ui ( l , h ) l . new_root . connect ( partial ( self . set_root , depth + 1 ) ) self . _levels . append ( l )
def proto_value_for_feature ( example , feature_name ) : """Get the value of a feature from Example regardless of feature type ."""
feature = get_example_features ( example ) [ feature_name ] if feature is None : raise ValueError ( 'Feature {} is not on example proto.' . format ( feature_name ) ) feature_type = feature . WhichOneof ( 'kind' ) if feature_type is None : raise ValueError ( 'Feature {} on example proto has no declared type.' . ...
def iterdata ( fd , close_fd = True , ** opts ) : '''Iterate through the data provided by a file like object . Optional parameters may be used to control how the data is deserialized . Examples : The following example show use of the iterdata function . : : with open ( ' foo . csv ' , ' rb ' ) as fd : f...
fmt = opts . get ( 'format' , 'lines' ) fopts = fmtopts . get ( fmt , { } ) # set default options for format for opt , val in fopts . items ( ) : opts . setdefault ( opt , val ) ncod = opts . get ( 'encoding' ) if ncod is not None : fd = codecs . getreader ( ncod ) ( fd ) fmtr = fmtyielders . get ( fmt ) if fmt...
def get_updates ( self , ** kwargs ) : '''Get parameter update expressions for performing optimization . Keyword arguments can be applied here to set any of the global optimizer attributes . Yields updates : ( parameter , expression ) tuples A sequence of parameter updates to be applied during optimizatio...
self . _prepare ( ** kwargs ) for param , grad in self . _differentiate ( ) : for var , update in self . _get_updates_for ( param , grad ) : # For auxiliary variables , updates are meant to replace the # existing variable value . if var != param : yield var , update continue ...
def putNamedChild ( self , res ) : """putNamedChild takes either an instance of hendrix . contrib . NamedResource or any resource . Resource with a " namespace " attribute as a means of allowing application level control of resource namespacing . if a child is already found at an existing path , resources w...
try : EmptyResource = resource . Resource namespace = res . namespace parts = namespace . strip ( '/' ) . split ( '/' ) # initialise parent and children parent = self children = self . children # loop through all of the path parts except for the last one for name in parts [ : - 1 ] : ...
def objects_delete ( self , bucket , key ) : """Deletes the specified object . Args : bucket : the name of the bucket . key : the key of the object within the bucket . Raises : Exception if there is an error performing the operation ."""
url = Api . _ENDPOINT + ( Api . _OBJECT_PATH % ( bucket , Api . _escape_key ( key ) ) ) datalab . utils . Http . request ( url , method = 'DELETE' , credentials = self . _credentials , raw_response = True )
def parse_cmd_arguments ( ) : """Parse command line arguments ."""
parser = argparse . ArgumentParser ( ) parser . add_argument ( 'file' , type = str , help = 'Filename to be staticfied' ) parser . add_argument ( '--static-endpoint' , help = 'Static endpoint which is "static" by default' ) parser . add_argument ( '--add-tags' , type = str , help = 'Additional tags to staticfy' ) parse...
def make_vis_T ( model , objective_f , param_f = None , optimizer = None , transforms = None , relu_gradient_override = False ) : """Even more flexible optimization - base feature vis . This function is the inner core of render _ vis ( ) , and can be used when render _ vis ( ) isn ' t flexible enough . Unfortun...
# pylint : disable = unused - variable t_image = make_t_image ( param_f ) objective_f = objectives . as_objective ( objective_f ) transform_f = make_transform_f ( transforms ) optimizer = make_optimizer ( optimizer , [ ] ) global_step = tf . train . get_or_create_global_step ( ) init_global_step = tf . variables_initia...
def _temp_bool_prop ( propname , doc = "" , default = False ) : """Creates a property that uses the : class : ` _ TempBool ` class Parameters propname : str The attribute name to use . The _ TempBool instance will be stored in the ` ` ' _ ' + propname ` ` attribute of the corresponding instance doc : str ...
def getx ( self ) : if getattr ( self , '_' + propname , None ) is not None : return getattr ( self , '_' + propname ) else : setattr ( self , '_' + propname , _TempBool ( default ) ) return getattr ( self , '_' + propname ) def setx ( self , value ) : getattr ( self , propname ) . value...
def _process_mappings ( self , limit = None ) : """This function imports linkage mappings of various entities to genetic locations in cM or cR . Entities include sequence variants , BAC ends , cDNA , ESTs , genes , PAC ends , RAPDs , SNPs , SSLPs , and STSs . Status : NEEDS REVIEW : param limit : : retu...
LOG . info ( "Processing chromosome mappings" ) if self . test_mode : graph = self . testgraph else : graph = self . graph line_counter = 0 model = Model ( graph ) geno = Genotype ( graph ) raw = '/' . join ( ( self . rawdir , self . files [ 'mappings' ] [ 'file' ] ) ) taxon_num = '7955' taxon_id = 'NCBITaxon:'...
def get_regular_properties ( self , _type , * args , ** kwargs ) : """Make table with properties by schema _ id : param str _ type : : rtype : str"""
if not SchemaObjects . contains ( _type ) : return _type schema = SchemaObjects . get ( _type ) if schema . schema_type == SchemaTypes . DEFINITION and not kwargs . get ( 'definition' ) : return '' head = """.. csv-table:: :delim: | :header: "Name", "Required", "Type", "Format", "Properties", "Descripti...
def to_manager ( sdf , columns , index ) : """create and return the block manager from a dataframe of series , columns , index"""
# from BlockManager perspective axes = [ ensure_index ( columns ) , ensure_index ( index ) ] return create_block_manager_from_arrays ( [ sdf [ c ] for c in columns ] , columns , axes )
def fill ( self , text ) : """Set the text value of each matched element to ` text ` . Example usage : . . code : : python # Set the text of the first element matched by the query to " Foo " q . first . fill ( ' Foo ' ) Args : text ( str ) : The text used to fill the element ( usually a text field or te...
def _fill ( elem ) : # pylint : disable = missing - docstring elem . clear ( ) elem . send_keys ( text ) self . map ( _fill , u'fill({!r})' . format ( text ) ) . execute ( )
def write_question ( self , question ) : """Writes a question to the packet"""
self . write_name ( question . name ) self . write_short ( question . type ) self . write_short ( question . clazz )
def get_cleaned_data_for_step ( self , step ) : """Returns the cleaned data for a given ` step ` . Before returning the cleaned data , the stored values are being revalidated through the form . If the data doesn ' t validate , None will be returned ."""
if step in self . form_list : form_obj = self . get_form ( step = step , data = self . storage . get_step_data ( step ) , files = self . storage . get_step_files ( step ) ) if form_obj . is_valid ( ) : return form_obj . cleaned_data return None
def loads ( s , model = None , parser = None ) : """Deserialize s ( a str ) to a Python object ."""
with StringIO ( s ) as f : return load ( f , model = model , parser = parser )
def encode ( self , obj ) : """Returns ` ` obj ` ` serialized as JSON formatted bytes . Raises ~ ipfsapi . exceptions . EncodingError Parameters obj : str | list | dict | int JSON serializable Python object Returns bytes"""
try : result = json . dumps ( obj , sort_keys = True , indent = None , separators = ( ',' , ':' ) , ensure_ascii = False ) if isinstance ( result , six . text_type ) : return result . encode ( "utf-8" ) else : return result except ( UnicodeEncodeError , TypeError ) as error : raise excep...
def set_portfast_type ( self , name , value = 'normal' ) : """Configures the portfast value for the specified interface Args : name ( string ) : The interface identifier to configure . The name must be the full interface name ( eg Ethernet1 , not Et1 ) . value ( string ) : The value to configure the portfas...
if value not in [ 'network' , 'edge' , 'normal' , None ] : raise ValueError ( 'invalid portfast type value specified' ) cmds = [ 'spanning-tree portfast %s' % value ] if value == 'edge' : cmds . append ( 'spanning-tree portfast auto' ) return self . configure_interface ( name , cmds )
def register_tc_plugins ( self , plugin_name , plugin_class ) : """Loads a plugin as a dictionary and attaches needed parts to correct areas for testing parts . : param plugin _ name : Name of the plugins : param plugin _ class : PluginBase : return : Nothing"""
if plugin_name in self . registered_plugins : raise PluginException ( "Plugin {} already registered! Duplicate " "plugins?" . format ( plugin_name ) ) self . logger . debug ( "Registering plugin %s" , plugin_name ) plugin_class . init ( bench = self . bench ) if plugin_class . get_bench_api ( ) is not None : re...
def combinations_with_replacement ( iterable , r ) : """This function acts as a replacement for the itertools . combinations _ with _ replacement function . The original does not replace items that come earlier in the provided iterator ."""
stk = [ [ i , ] for i in iterable ] pop = stk . pop while len ( stk ) > 0 : top = pop ( ) if len ( top ) == r : yield tuple ( top ) else : stk . extend ( top + [ i ] for i in iterable )
def _extend_blocks ( extend_node , blocks , context ) : """Extends the dictionary ` blocks ` with * new * blocks in the parent node ( recursive ) : param extend _ node : The ` ` { % extends . . % } ` ` node object . : type extend _ node : ExtendsNode : param blocks : dict of all block names found in the templ...
try : # This needs a fresh parent context , or it will detection recursion in Django 1.9 + , # and thus skip the base template , which is already loaded . parent = extend_node . get_parent ( _get_extend_context ( context ) ) except TemplateSyntaxError : if _is_variable_extends ( extend_node ) : # we don ' t sup...
def add_filter ( ds , patterns ) : """Add a filter or list of filters to a datasource . A filter is a simple string , and it matches if it is contained anywhere within a line . Args : ds ( @ datasource component ) : The datasource to filter patterns ( str , [ str ] ) : A string , list of strings , or set of...
if not plugins . is_datasource ( ds ) : raise Exception ( "Filters are applicable only to datasources." ) delegate = dr . get_delegate ( ds ) if delegate . raw : raise Exception ( "Filters aren't applicable to raw datasources." ) if not delegate . filterable : raise Exception ( "Filters aren't applicable to...
def initial_classification ( self , obresult , target_is_sky = False ) : """Classify input frames ,"""
# lists of targets and sky frames with obresult . frames [ 0 ] . open ( ) as baseimg : # Initial checks has_bpm_ext = 'BPM' in baseimg self . logger . debug ( 'images have BPM extension: %s' , has_bpm_ext ) images_info = [ ] for f in obresult . frames : with f . open ( ) as img : # Getting some metadata fro...
def RequestPacket ( self ) : """Create a ready - to - transmit authentication request packet . Return a RADIUS packet which can be directly transmitted to a RADIUS server . : return : raw packet : rtype : string"""
attr = self . _PktEncodeAttributes ( ) if self . authenticator is None : self . authenticator = self . CreateAuthenticator ( ) if self . id is None : self . id = self . CreateID ( ) header = struct . pack ( '!BBH16s' , self . code , self . id , ( 20 + len ( attr ) ) , self . authenticator ) return header + attr
def check_dirs ( ) : """Check the directories if they exist . : raises FileExistsError : if a file exists but is not a directory"""
dirs = [ MAIN_DIR , TEMP_DIR , DOWNLOAD_DIR , SAVESTAT_DIR ] for directory in dirs : if directory . exists ( ) and not directory . is_dir ( ) : raise FileExistsError ( str ( directory . resolve ( ) ) + " cannot be used as a directory." )
def _install_requirements ( path ) : """Install a blueprint ' s requirements . txt"""
locations = [ os . path . join ( path , "_blueprint" ) , os . path . join ( path , "_base" ) , path ] success = True for location in locations : try : with open ( os . path . join ( location , "requirements.txt" ) ) : puts ( "\nRequirements file found at {0}" . format ( os . path . join ( locati...
def preview ( self ) : """Returns an HTML preview for a Scheduled Tweet ."""
if self . id : resource = self . PREVIEW resource = resource . format ( account_id = self . account . id , id = self . id ) response = Request ( self . account . client , 'get' , resource ) . perform ( ) return response . body [ 'data' ]
def get_element_by_path ( tree , path_and_name , namespace ) : # type : ( _ Element , str , str ) - > typing . Union [ _ Element , None ] """Find sub - element of given path with given short name ."""
global xml_element_cache namespace_map = { 'A' : namespace [ 1 : - 1 ] } base_path , element_name = path_and_name . rsplit ( '/' , 1 ) if base_path in xml_element_cache : base_element = xml_element_cache [ base_path ] else : base_xpath = ar_path_to_x_path ( base_path ) elems = tree . xpath ( base_xpath , na...
def flushmany ( self ) : """Send a potentially huge number of pending signals over the message bus . This method assumes that the number of pending signals might be huge , so that they might not fit into memory . However , ` SignalBus . flushmany ` is not very smart in handling concurrent senders . It is mo...
models_to_flush = self . get_signal_models ( ) try : return sum ( self . _flushmany_signals ( model ) for model in models_to_flush ) finally : self . signal_session . remove ( )