signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def NoSuchEntityOk ( f ) : """Decorator to remove NoSuchEntity exceptions , and raises all others ."""
def ExceptionFilter ( * args ) : try : return f ( * args ) except boto . exception . BotoServerError as e : if e . error_code == 'NoSuchEntity' : pass else : raise except : raise return False return ExceptionFilter
def save ( self ) : """modified from suvi code by vhsu"""
pri_hdu = fits . PrimaryHDU ( data = self . thmap ) # Temporal Information date_fmt = '%Y-%m-%dT%H:%M:%S.%f' date_beg = self . start_time . strftime ( date_fmt ) date_end = self . end_time . strftime ( date_fmt ) date_now = datetime . utcnow ( ) . strftime ( date_fmt ) self . set_fits_header ( "TIMESYS" , self . ref_hd...
def _export_section ( sections , pc ) : """Switch chron data to index - by - number : param dict sections : Metadata : return list _ sections : Metadata"""
logger_jsons . info ( "enter export_data: {}" . format ( pc ) ) _sections = [ ] for name , section in sections . items ( ) : # Process chron models if "model" in section : section [ "model" ] = _export_model ( section [ "model" ] ) # Process the chron measurement table if "measurementTable" in secti...
def watch_pending_transactions ( self , callback ) : '''Callback will receive one argument : the transaction object just observed This is equivalent to ` eth . filter ( ' pending ' ) `'''
self . pending_tx_watchers . append ( callback ) if len ( self . pending_tx_watchers ) == 1 : eth . filter ( 'pending' ) . watch ( self . _new_pending_tx )
def get_ngrams ( self , minimum , maximum , filter_ngrams ) : """Returns a generator supplying the n - grams ( ` minimum ` < = n < = ` maximum ` ) for this text . Each iteration of the generator supplies a tuple consisting of the size of the n - grams and a ` collections . Counter ` of the n - grams . : p...
tokens = self . get_tokens ( ) filter_pattern = self . get_filter_ngrams_pattern ( filter_ngrams ) for size in range ( minimum , maximum + 1 ) : ngrams = collections . Counter ( self . _ngrams ( tokens , size , filter_pattern ) ) yield ( size , ngrams )
def main ( ) : """Executes the given command . Returns error _ message if command is not valid . Returns : Output of the given command or error message if command is not valid ."""
try : command = sys . argv [ 1 ] except IndexError : return error_message ( ) try : module = importlib . import_module ( 'i18n.%s' % command ) module . main . args = sys . argv [ 2 : ] except ( ImportError , AttributeError ) : return error_message ( ) return module . main ( )
def dict_to_object ( source ) : """Returns an object with the key - value pairs in source as attributes ."""
target = inspectable_class . InspectableClass ( ) for k , v in source . items ( ) : setattr ( target , k , v ) return target
def offer ( self , requestType , * args ) : """public interface to the reactor . : param requestType : : param args : : return :"""
if self . _funcsByRequest . get ( requestType ) is not None : self . _workQueue . put ( ( requestType , list ( * args ) ) ) else : logger . error ( "Ignoring unknown request on reactor " + self . _name + " " + requestType )
def document ( self , wrapper ) : """Get the document root . For I { document / literal } , this is the name of the wrapper element qualified by the schema ' s target namespace . @ param wrapper : The method name . @ type wrapper : L { xsd . sxbase . SchemaObject } @ return : A root element . @ rtype : L ...
tag = wrapper [ 1 ] . name ns = wrapper [ 1 ] . namespace ( "ns0" ) return Element ( tag , ns = ns )
def check_lazy_load_wegsegment ( f ) : '''Decorator function to lazy load a : class : ` Wegsegment ` .'''
def wrapper ( * args ) : wegsegment = args [ 0 ] if ( wegsegment . _methode_id is None or wegsegment . _geometrie is None or wegsegment . _metadata is None ) : log . debug ( 'Lazy loading Wegsegment %d' , wegsegment . id ) wegsegment . check_gateway ( ) w = wegsegment . gateway . get_weg...
def mask_and_mean_loss ( input_tensor , binary_tensor , axis = None ) : """Mask a loss by using a tensor filled with 0 or 1 and average correctly . : param input _ tensor : A float tensor of shape [ batch _ size , . . . ] representing the loss / cross _ entropy : param binary _ tensor : A float tensor of shape ...
return mean_on_masked ( mask_loss ( input_tensor , binary_tensor ) , binary_tensor , axis = axis )
def simxSetObjectSelection ( clientID , objectHandles , operationMode ) : '''Please have a look at the function description / documentation in the V - REP user manual'''
c_objectHandles = ( ct . c_int * len ( objectHandles ) ) ( * objectHandles ) return c_SetObjectSelection ( clientID , c_objectHandles , len ( objectHandles ) , operationMode )
def _flatten_up_to_token ( self , token ) : """Yields all tokens up to token but excluding current ."""
if token . is_group : token = next ( token . flatten ( ) ) for t in self . _curr_stmt . flatten ( ) : if t == token : break yield t
def isvalid ( self ) : """Checks whether contents of repo are consistent with standard set ."""
gcontents = [ gf . rstrip ( '\n' ) for gf in self . repo . bake ( 'ls-files' ) ( ) ] fcontents = os . listdir ( self . repopath ) return all ( [ sf in gcontents for sf in std_files ] ) and all ( [ sf in fcontents for sf in std_files ] )
def combine ( * rnf_profiles ) : """Combine more profiles and set their maximal values . Args : * rnf _ profiles ( rnftools . rnfformat . RnfProfile ) : RNF profile ."""
for rnf_profile in rnf_profiles : self . prefix_width = max ( self . prefix_width , rnf_profile . prefix_width ) self . read_tuple_id_width = max ( self . read_tuple_id_width , rnf_profile . read_tuple_id_width ) self . genome_id_width = max ( self . genome_id_width , rnf_profile . genome_id_width ) sel...
def send_frame ( self , frame ) : '''Send a single frame . If there is no transport or we ' re not connected yet , append to the output buffer , else send immediately to the socket . This is called from within the MethodFrames .'''
if self . _closed : if self . _close_info and len ( self . _close_info [ 'reply_text' ] ) > 0 : raise ConnectionClosed ( "connection is closed: %s : %s" % ( self . _close_info [ 'reply_code' ] , self . _close_info [ 'reply_text' ] ) ) raise ConnectionClosed ( "connection is closed" ) if self . _transpor...
def _GetNextInterval ( self ) : """Returns the next Range of the file that is to be hashed . For all fingers , inspect their next expected range , and return the lowest uninterrupted range of interest . If the range is larger than BLOCK _ SIZE , truncate it . Returns : Next range of interest in a Range na...
ranges = [ x . CurrentRange ( ) for x in self . fingers ] starts = set ( [ r . start for r in ranges if r ] ) ends = set ( [ r . end for r in ranges if r ] ) if not starts : return None min_start = min ( starts ) starts . remove ( min_start ) ends |= starts min_end = min ( ends ) if min_end - min_start > self . BLO...
def date_from_isoformat ( isoformat_date ) : """Convert an ISO - 8601 date into a ` datetime . date ` object . Argument : isoformat _ date ( str ) : a date in ISO - 8601 format ( YYYY - MM - DD ) Returns : ~ datetime . date : the object corresponding to the given ISO date . Raises : ValueError : when th...
year , month , day = isoformat_date . split ( '-' ) return datetime . date ( int ( year ) , int ( month ) , int ( day ) )
def get_crimes_location ( self , location_id , date = None ) : """Get crimes at a particular snap - point location . Uses the crimes - at - location _ API call . . . _ crimes - at - location : https : / / data . police . uk / docs / method / crimes - at - location / : rtype : list : param int location _ i...
kwargs = { 'location_id' : location_id , } crimes = [ ] if date is not None : kwargs [ 'date' ] = date for c in self . service . request ( 'GET' , 'crimes-at-location' , ** kwargs ) : crimes . append ( Crime ( self , data = c ) ) return crimes
def importProteinDatabase ( filePath , proteindb = None , decoyTag = '[decoy]' , contaminationTag = '[cont]' , headerParser = None , forceId = False , cleavageRule = '[KR]' , minLength = 5 , maxLength = 40 , missedCleavage = 2 , ignoreIsoleucine = False , removeNtermM = True ) : """Generates a : class : ` ProteinDa...
proteindb = ProteinDatabase ( ) if proteindb is None else proteindb fastaRead = _readFastaFile ( filePath ) for header , sequence in fastaRead : proteinTags = list ( ) if header . startswith ( decoyTag ) : isDecoy = True header = header . replace ( decoyTag , '' ) proteinTags . append ( ...
def plural_verb ( self , text , count = None ) : """Return the plural of text , where text is a verb . If count supplied , then return text if count is one of : 1 , a , an , one , each , every , this , that otherwise return the plural . Whitespace at the start and end is preserved ."""
pre , word , post = self . partition_word ( text ) if not word : return text plural = self . postprocess ( word , self . _pl_special_verb ( word , count ) or self . _pl_general_verb ( word , count ) , ) return "{}{}{}" . format ( pre , plural , post )
def get_project_versions ( self , key , expand = None ) : """Contains a full representation of a the specified project ' s versions . : param key : : param expand : the parameters to expand : return :"""
params = { } if expand is not None : params [ 'expand' ] = expand return self . get ( 'rest/api/2/project/{}/versions' . format ( key ) , params = params )
def new_dataset ( self , * args , ** kwargs ) : """Creates a new dataset : param args : Positional args passed to the Dataset constructor . : param kwargs : Keyword args passed to the Dataset constructor . : return : : class : ` ambry . orm . Dataset ` : raises : : class : ` ambry . orm . ConflictError ` if...
ds = Dataset ( * args , ** kwargs ) try : self . session . add ( ds ) self . session . commit ( ) ds . _database = self return ds except IntegrityError as e : self . session . rollback ( ) raise ConflictError ( "Can't create dataset '{}'; one probably already exists: {} " . format ( str ( ds ) ,...
def _get_from_registry ( self ) : """Retrieves the path to the default Java installation stored in the Windows registry : return : The path found in the registry , or None"""
from . _windows import reg_keys for location in reg_keys : location = location . replace ( '\\' , '/' ) jreKey = "/proc/registry/HKEY_LOCAL_MACHINE/{}" . format ( location ) try : with open ( jreKey + "/CurrentVersion" ) as f : cv = f . read ( ) . split ( '\x00' ) versionKey = jr...
def mapred ( self , transport , inputs , query , timeout ) : """mapred ( inputs , query , timeout ) Executes a MapReduce query . . . note : : This request is automatically retried : attr : ` retries ` times if it fails due to network error . : param inputs : the input list / structure : type inputs : list...
_validate_timeout ( timeout ) return transport . mapred ( inputs , query , timeout )
def get_upregulated_genes ( self ) -> VertexSeq : """Get genes that are up - regulated . : return : Up - regulated genes ."""
up_regulated = self . graph . vs . select ( self . _is_upregulated_gene ) logger . info ( f"No. of up-regulated genes after laying on network: {len(up_regulated)}" ) return up_regulated
def __request ( self , method , endpoint , data , params = None , ** kwargs ) : """Do requests"""
if params is None : params = { } url = self . __get_url ( endpoint ) auth = None headers = { "user-agent" : "WooCommerce API Client-Python/%s" % __version__ , "accept" : "application/json" } if self . is_ssl is True and self . query_string_auth is False : auth = ( self . consumer_key , self . consumer_secret ) ...
def Database_executeSQL ( self , databaseId , query ) : """Function path : Database . executeSQL Domain : Database Method name : executeSQL Parameters : Required arguments : ' databaseId ' ( type : DatabaseId ) - > No description ' query ' ( type : string ) - > No description Returns : ' columnNames...
assert isinstance ( query , ( str , ) ) , "Argument 'query' must be of type '['str']'. Received type: '%s'" % type ( query ) subdom_funcs = self . synchronous_command ( 'Database.executeSQL' , databaseId = databaseId , query = query ) return subdom_funcs
def select_elements ( self , json_string , expr ) : """Return list of elements from _ json _ string _ , matching [ http : / / jsonselect . org / | JSONSelect ] expression . * DEPRECATED * JSON Select query language is outdated and not supported any more . Use other keywords of this library to query JSON . * A...
load_input_json = self . string_to_json ( json_string ) # parsing jsonselect match = jsonselect . match ( sel = expr , obj = load_input_json ) ret = list ( match ) return ret if ret else None
def stop ( self ) : """all links also need stop ( ) to stop their runloops"""
self . keep_listening = False # if threaded , kill threads before going down if hasattr ( self , 'join' ) : self . join ( ) self . log ( "Went down." ) return True
def __start ( self ) : """Start a new thread to process Cron"""
thread = Thread ( target = self . __loop , args = ( ) ) thread . daemon = True # daemonize thread thread . start ( ) self . __enabled = True
def get_ocv_old ( self , cycle_number = None , ocv_type = 'ocv' , dataset_number = None ) : """Find ocv data in DataSet ( voltage vs time ) . Args : cycle _ number ( int ) : find for all cycles if None . ocv _ type ( " ocv " , " ocvrlx _ up " , " ocvrlx _ down " ) : ocv - get up and down ( default ) ocvrl...
# function for getting ocv curves dataset_number = self . _validate_dataset_number ( dataset_number ) if dataset_number is None : self . _report_empty_dataset ( ) return if ocv_type in [ 'ocvrlx_up' , 'ocvrlx_down' ] : ocv = self . _get_ocv ( dataset_number = None , ocv_type = ocv_type , select_last = True ...
def profile ( message = None , verbose = False ) : """Decorator for profiling a function . TODO : Support ` @ profile ` syntax ( without parens ) . This would involve inspecting the args . In this case ` profile ` would receive a single argument , which is the function to be decorated ."""
import functools from harrison . registered_timer import RegisteredTimer # Adjust the call stack index for RegisteredTimer so the call is Timer use # is properly attributed . class DecoratorTimer ( RegisteredTimer ) : _CALLER_STACK_INDEX = 2 def wrapper ( fn ) : desc = message or fn . __name__ @ functools ....
def describe_unique_1d ( series ) : """Compute summary statistics of a unique ( ` S _ TYPE _ UNIQUE ` ) variable ( a Series ) . Parameters series : Series The variable to describe . Returns Series The description of the variable as a Series with index being stats keys ."""
return pd . Series ( [ base . S_TYPE_UNIQUE ] , index = [ 'type' ] , name = series . name )
def emit ( self , prob_min = 0.0 , prob_max = 1.0 ) : """m . emit ( , prob _ min = 0.0 , prob _ max = 1.0 ) - - Consider motif as a generative model , and have it emit a sequence"""
if not self . cumP : for logcol in self . logP : tups = [ ] for L in ACGT : p = math . pow ( 2 , logcol [ L ] ) tups . append ( ( p , L ) ) tups . sort ( ) cumu = [ ] tot = 0 for p , L in tups : tot = tot + p cumu . appe...
def cli_form ( self , * args ) : """Display a schemata ' s form definition"""
if args [ 0 ] == '*' : for schema in schemastore : self . log ( schema , ':' , schemastore [ schema ] [ 'form' ] , pretty = True ) else : self . log ( schemastore [ args [ 0 ] ] [ 'form' ] , pretty = True )
def delete_if_not_in_zsets ( self , key , member , set_list , client = None ) : """Removes ` ` key ` ` only if ` ` member ` ` is not member of any sets in the ` ` set _ list ` ` . Returns the number of removed elements ( 0 or 1 ) ."""
return self . _delete_if_not_in_zsets ( keys = [ key ] + set_list , args = [ member ] , client = client )
def getDefaultApplicationForMimeType ( self , pchMimeType , pchAppKeyBuffer , unAppKeyBufferLen ) : """return the app key that will open this mime type"""
fn = self . function_table . getDefaultApplicationForMimeType result = fn ( pchMimeType , pchAppKeyBuffer , unAppKeyBufferLen ) return result
def all_groupings ( partition ) : """Return all possible groupings of states for a particular coarse graining ( partition ) of a network . Args : partition ( tuple [ tuple ] ) : A partition of micro - elements into macro elements . Yields : tuple [ tuple [ tuple ] ] : A grouping of micro - states into m...
if not all ( partition ) : raise ValueError ( 'Each part of the partition must have at least one ' 'element.' ) micro_groupings = [ _partitions_list ( len ( part ) + 1 ) if len ( part ) > 1 else [ [ [ 0 ] , [ 1 ] ] ] for part in partition ] for grouping in itertools . product ( * micro_groupings ) : if all ( le...
def list_upgrades ( refresh = True , backtrack = 3 , ** kwargs ) : # pylint : disable = W0613 '''List all available package upgrades . refresh Whether or not to sync the portage tree before checking for upgrades . backtrack Specifies an integer number of times to backtrack if dependency calculation fails ...
if salt . utils . data . is_true ( refresh ) : refresh_db ( ) return _get_upgradable ( backtrack )
def get_publickey ( keydata ) : """Load the public key from a PEM encoded string ."""
try : key = serialization . load_pem_public_key ( keydata , backend = default_backend ( ) , ) return key except ValueError : key = serialization . load_pem_private_key ( keydata , password = None , backend = default_backend ( ) , ) key = key . public_key ( ) return key
def log_in ( self ) : """Perform the ` log _ in ` task to setup the API session for future data requests ."""
if not self . password : # Password wasn ' t give , ask for it now self . password = getpass . getpass ( 'Password: ' ) utils . pending_message ( 'Performing login...' ) login_result = self . client . login ( account = self . account , password = self . password ) if 'error' in login_result : self . handle_fail...
def get_AV_infinity ( ra , dec , frame = 'icrs' ) : """Gets the A _ V exctinction at infinity for a given line of sight . Queries the NED database . : param ra , dec : Desired coordinates , in degrees . : param frame : ( optional ) Frame of input coordinates ( e . g . , ` ` ' icrs ' , ' galactic ' ` ` )""...
coords = SkyCoord ( ra , dec , unit = 'deg' , frame = frame ) . transform_to ( 'icrs' ) rah , ram , ras = coords . ra . hms decd , decm , decs = coords . dec . dms if decd > 0 : decsign = '%2B' else : decsign = '%2D' url = 'http://ned.ipac.caltech.edu/cgi-bin/nph-calc?in_csys=Equatorial&in_equinox=J2000.0&obs_e...
def reshape_bar_plot ( df , x , y , bars ) : """Reshape data from long form to " bar plot form " . Bar plot form has x value as the index with one column for bar grouping . Table values come from y values ."""
idx = [ bars , x ] if df . duplicated ( idx ) . any ( ) : warnings . warn ( 'Duplicated index found.' ) df = df . drop_duplicates ( idx , keep = 'last' ) df = df . set_index ( idx ) [ y ] . unstack ( x ) . T return df
def get_new_command ( command ) : """Attempt to rebuild the path string by spellchecking the directories . If it fails ( i . e . no directories are a close enough match ) , then it defaults to the rules of cd _ mkdir . Change sensitivity by changing MAX _ ALLOWED _ DIFF . Default value is 0.6"""
dest = command . script_parts [ 1 ] . split ( os . sep ) if dest [ - 1 ] == '' : dest = dest [ : - 1 ] if dest [ 0 ] == '' : cwd = os . sep dest = dest [ 1 : ] elif six . PY2 : cwd = os . getcwdu ( ) else : cwd = os . getcwd ( ) for directory in dest : if directory == "." : continue ...
def find_matching ( self ) -> Dict [ TLeft , TRight ] : """Finds a matching in the bipartite graph . This is done using the Hopcroft - Karp algorithm with an implementation from the ` hopcroftkarp ` package . Returns : A dictionary where each edge of the matching is represented by a key - value pair with ...
# The directed graph is represented as a dictionary of edges # The key is the tail of all edges which are represented by the value # The value is a set of heads for the all edges originating from the tail ( key ) # In addition , the graph stores which part of the bipartite graph a node originated from # to avoid proble...
def init_file ( self , filename , lines , expected , line_offset ) : """Signal a new file ."""
self . filename = filename self . lines = lines self . expected = expected or ( ) self . line_offset = line_offset self . file_errors = 0 self . counters [ 'files' ] += 1 self . counters [ 'physical lines' ] += len ( lines )
def get_archive_format ( filename ) : """Detect filename archive format and optional compression ."""
mime , compression = util . guess_mime ( filename ) if not ( mime or compression ) : raise util . PatoolError ( "unknown archive format for file `%s'" % filename ) if mime in ArchiveMimetypes : format = ArchiveMimetypes [ mime ] else : raise util . PatoolError ( "unknown archive format for file `%s' (mime-t...
def simplify ( all_points , tilewidth , tileheight ) : """Given a list of points , return list of rects that represent them kludge : " A kludge ( or kluge ) is a workaround , a quick - and - dirty solution , a clumsy or inelegant , yet effective , solution to a problem , typically using parts that are cobbl...
def pick_rect ( points , rects ) : ox , oy = sorted ( [ ( sum ( p ) , p ) for p in points ] ) [ 0 ] [ 1 ] x = ox y = oy ex = None while 1 : x += 1 if not ( x , y ) in points : if ex is None : ex = x - 1 if ( ox , y + 1 ) in points : ...
def _update_keywords ( self , ** update_props ) : """Update operation for ISO type - specific Keywords metadata : Theme or Place"""
tree_to_update = update_props [ 'tree_to_update' ] prop = update_props [ 'prop' ] values = update_props [ 'values' ] keywords = [ ] if prop in KEYWORD_PROPS : xpath_root = self . _data_map [ '_keywords_root' ] xpath_map = self . _data_structures [ prop ] xtype = xpath_map [ 'keyword_type' ] xroot = xpat...
def mergecsv ( args ) : """% prog mergecsv * . tsv Merge a set of tsv files ."""
p = OptionParser ( mergecsv . __doc__ ) p . set_outfile ( ) opts , args = p . parse_args ( args ) if len ( args ) < 2 : sys . exit ( not p . print_help ( ) ) tsvfiles = args outfile = opts . outfile if op . exists ( outfile ) : os . remove ( outfile ) tsvfile = tsvfiles [ 0 ] fw = must_open ( opts . outfile , "...
def flatten_ ( structure ) : """Combine all leaves of a nested structure into a tuple . The nested structure can consist of any combination of tuples , lists , and dicts . Dictionary keys will be discarded but values will ordered by the sorting of the keys . Args : structure : Nested structure . Returns...
if isinstance ( structure , dict ) : if structure : structure = zip ( * sorted ( structure . items ( ) , key = lambda x : x [ 0 ] ) ) [ 1 ] else : # Zip doesn ' t work on an the items of an empty dictionary . structure = ( ) if isinstance ( structure , ( tuple , list ) ) : result = [ ] f...
def _op ( self , line , op = None , offset = 0 ) : """Returns the gate name for placing a gate on a line . : param int line : Line number . : param int op : Operation number or , by default , uses the current op count . : return : Gate name . : rtype : string"""
if op is None : op = self . op_count [ line ] return "line{}_gate{}" . format ( line , op + offset )
def get_padding_lengths ( self ) -> Dict [ str , Dict [ str , int ] ] : """Gets the maximum padding lengths from all ` ` Instances ` ` in this batch . Each ` ` Instance ` ` has multiple ` ` Fields ` ` , and each ` ` Field ` ` could have multiple things that need padding . We look at all fields in all instances ...
padding_lengths : Dict [ str , Dict [ str , int ] ] = defaultdict ( dict ) all_instance_lengths : List [ Dict [ str , Dict [ str , int ] ] ] = [ instance . get_padding_lengths ( ) for instance in self . instances ] if not all_instance_lengths : return { ** padding_lengths } all_field_lengths : Dict [ str , List [ D...
def _getAbsoluteTime ( self , start , delay ) : """Adds the delay in seconds to the start time . : param start : : param delay : : return : a datetimem for the specified point in time ."""
return start + datetime . timedelta ( days = 0 , seconds = delay )
def enabled ( self ) : """bool : ` ` True ` ` if BGP is enabled ; ` ` False ` ` if BGP is disabled ."""
namespace = 'urn:ietf:params:xml:ns:netconf:base:1.0' bgp_filter = 'rbridge-id/router/bgp' bgp_config = ET . Element ( 'get-config' , xmlns = "%s" % namespace ) source = ET . SubElement ( bgp_config , 'source' ) ET . SubElement ( source , 'running' ) ET . SubElement ( bgp_config , 'filter' , type = "xpath" , select = "...
def of_file ( self , abspath , nbytes = 0 ) : """Use default hash method to return hash value of a piece of a file Estimate processing time on : : param abspath : the absolute path to the file : param nbytes : only has first N bytes of the file . if 0 , hash all file CPU = i7-4600U 2.10GHz - 2.70GHz , RAM =...
if not os . path . exists ( abspath ) : raise FileNotFoundError ( "[Errno 2] No such file or directory: '%s'" % abspath ) m = self . default_hash_method ( ) with open ( abspath , "rb" ) as f : if nbytes : data = f . read ( nbytes ) if data : m . update ( data ) else : whi...
def addItemTag ( self , item , tag ) : """Add a tag to an individal item . tag string must be in form " user / - / label / [ tag ] " """
if self . inItemTagTransaction : # XXX : what if item ' s parent is not a feed ? if not tag in self . addTagBacklog : self . addTagBacklog [ tag ] = [ ] self . addTagBacklog [ tag ] . append ( { 'i' : item . id , 's' : item . parent . id } ) return "OK" else : return self . _modifyItemTag ( item...
def new_value ( self , key , value ) : """Create new value in data"""
data = self . model . get_data ( ) data [ key ] = value self . set_data ( data )
def recipe ( recipe ) : """Apply the given recipe to a node Sets the run _ list to the given recipe If no nodes / hostname . json file exists , it creates one"""
env . host_string = lib . get_env_host_string ( ) lib . print_header ( "Applying recipe '{0}' on node {1}" . format ( recipe , env . host_string ) ) # Create configuration and sync node data = lib . get_node ( env . host_string ) data [ "run_list" ] = [ "recipe[{0}]" . format ( recipe ) ] if not __testing__ : if en...
def feature_assert ( * feas ) : """Takes some feature patterns ( like in ` feature _ needs ` ) . Raises a fuse . FuseError if your underlying FUSE lib fails to have some of the matching features . ( Note : use a ` ` has _ foo ` ` type feature assertion only if lib support for method ` ` foo ` ` is * necessa...
fav = APIVersion ( ) for fea in feas : fn = feature_needs ( fea ) if fav < fn : raise FuseError ( "FUSE API version %d is required for feature `%s' but only %d is available" % ( fn , str ( fea ) , fav ) )
def fourier_map_2d ( uSin , angles , res , nm , lD = 0 , semi_coverage = False , coords = None , count = None , max_count = None , verbose = 0 ) : r"""2D Fourier mapping with the Fourier diffraction theorem Two - dimensional diffraction tomography reconstruction algorithm for scattering of a plane wave : math...
# TODO : # - zero - padding as for backpropagate _ 2D - However this is not # necessary as Fourier interpolation is not parallelizable with # multiprocessing and thus unattractive . Could be interesting for # specific environments without the Python GIL . # - Deal with oversampled data . Maybe issue a warning . A = ang...
def delete ( name , timeout = 90 ) : '''Delete the named service Args : name ( str ) : The name of the service to delete timeout ( int ) : The time in seconds to wait for the service to be deleted before returning . This is necessary because a service must be stopped before it can be deleted . Default i...
handle_scm = win32service . OpenSCManager ( None , None , win32service . SC_MANAGER_CONNECT ) try : handle_svc = win32service . OpenService ( handle_scm , name , win32service . SERVICE_ALL_ACCESS ) except pywintypes . error as exc : win32service . CloseServiceHandle ( handle_scm ) if exc . winerror != 1060 ...
def _compute_sparse_average_correct ( input_ , labels , per_example_weights , topk = 1 ) : """Returns the numerator and denominator of classifier accuracy ."""
labels = tf . to_int64 ( labels ) labels . get_shape ( ) . assert_is_compatible_with ( [ input_ . get_shape ( ) [ 0 ] , None ] ) if topk == 1 : predictions = tf . reshape ( tf . argmax ( input_ , 1 ) , [ - 1 , 1 ] ) in_topk = tf . reduce_any ( tf . equal ( labels , predictions ) , reduction_indices = [ 1 ] ) el...
def roundClosestValid ( val , res , decimals = None ) : """round to closest resolution"""
if decimals is None and "." in str ( res ) : decimals = len ( str ( res ) . split ( '.' ) [ 1 ] ) return round ( round ( val / res ) * res , decimals )
def find_eigen ( hint = None ) : r'''Try to find the Eigen library . If successful the include directory is returned .'''
# search with pkgconfig try : import pkgconfig if pkgconfig . installed ( 'eigen3' , '>3.0.0' ) : return pkgconfig . parse ( 'eigen3' ) [ 'include_dirs' ] [ 0 ] except : pass # manual search search_dirs = [ ] if hint is None else hint search_dirs += [ "/usr/local/include/eigen3" , "/usr/local/homebr...
def transform_e1e2 ( x , y , e1 , e2 , center_x = 0 , center_y = 0 ) : """maps the coordinates x , y with eccentricities e1 e2 into a new elliptical coordiante system : param x : : param y : : param e1: : param e2: : param center _ x : : param center _ y : : return :"""
x_shift = x - center_x y_shift = y - center_y x_ = ( 1 - e1 ) * x_shift - e2 * y_shift y_ = - e2 * x_shift + ( 1 + e1 ) * y_shift det = np . sqrt ( ( 1 - e1 ) * ( 1 + e1 ) + e2 ** 2 ) return x_ / det , y_ / det
def filter_out ( queryset , setting_name ) : """Remove unwanted results from queryset"""
kwargs = helpers . get_settings ( ) . get ( setting_name , { } ) . get ( 'FILTER_OUT' , { } ) queryset = queryset . exclude ( ** kwargs ) return queryset
def _is_at_ref_start ( self , nucmer_hit ) : '''Returns True iff the hit is " close enough " to the start of the reference sequence'''
hit_coords = nucmer_hit . ref_coords ( ) return hit_coords . start < self . ref_end_tolerance
def detectAndroidTablet ( self ) : """Return detection of an Android tablet Detects if the current device is a ( self - reported ) Android tablet . Google says these devices will have ' Android ' and NOT ' mobile ' in their user agent ."""
# First , let ' s make sure we ' re on an Android device . if not self . detectAndroid ( ) : return False # Special check for Android devices with Opera Mobile / Mini . They should NOT report here . if self . detectOperaMobile ( ) : return False # Otherwise , if it ' s Android and does NOT have ' mobile ' in it...
def _to_unicode ( instr ) : '''Converts from current users character encoding to unicode . When instr has a value of None , the return value of the function will also be None .'''
if instr is None or isinstance ( instr , six . text_type ) : return instr else : return six . text_type ( instr , 'utf8' )
def If ( self , condition , * then , ** kwargs ) : """* * If * * If ( Predicate , * Then ) Having conditionals expressions a necesity in every language , Phi includes the ` If ` expression for such a purpose . * * Arguments * * * * * Predicate * * : a predicate expression uses to determine if the ` Then ` o...
cond_f = _parse ( condition ) . _f then_f = E . Seq ( * then ) . _f else_f = utils . state_identity ast = ( cond_f , then_f , else_f ) g = _compile_if ( ast ) expr = self . __then__ ( g , ** kwargs ) expr . _ast = ast expr . _root = self return expr
def to_time_field ( formatter ) : """Returns a callable instance that will convert a string to a Time . : param formatter : String that represents data format for parsing . : return : instance of the TimeConverter ."""
class TimeConverter ( object ) : def __init__ ( self , formatter ) : self . formatter = formatter def __call__ ( self , value ) : if isinstance ( value , string_types ) : value = datetime . strptime ( value , self . formatter ) . time ( ) return value return TimeConverter ( f...
def empty_directory ( self ) : """Remove all contents of a directory Including any sub - directories and their contents"""
for child in self . walkfiles ( ) : child . remove ( ) for child in reversed ( [ d for d in self . walkdirs ( ) ] ) : if child == self or not child . isdir ( ) : continue child . rmdir ( )
def ReadBlobs ( self , blob_ids ) : """Reads given blobs ."""
result = { } for blob_id in blob_ids : result [ blob_id ] = self . blobs . get ( blob_id , None ) return result
def run_thermal_displacements ( self , t_min = 0 , t_max = 1000 , t_step = 10 , temperatures = None , direction = None , freq_min = None , freq_max = None ) : """Prepare thermal displacements calculation Parameters t _ min , t _ max , t _ step : float , optional Minimum and maximum temperatures and the interv...
if self . _dynamical_matrix is None : msg = ( "Dynamical matrix has not yet built." ) raise RuntimeError ( msg ) if self . _mesh is None : msg = ( "run_mesh has to be done." ) raise RuntimeError ( msg ) mesh_nums = self . _mesh . mesh_numbers ir_grid_points = self . _mesh . ir_grid_points if not self . ...
def get_job_config ( conf ) : """Extract handler names from job _ conf . xml"""
rval = [ ] root = elementtree . parse ( conf ) . getroot ( ) for handler in root . find ( 'handlers' ) : rval . append ( { 'service_name' : handler . attrib [ 'id' ] } ) return rval
def obj_to_dict ( cls , obj ) : """Takes a model object and converts it into a dictionary suitable for passing to the constructor ' s data attribute ."""
data = { } for field_name in cls . get_fields ( ) : try : value = getattr ( obj , field_name ) except AttributeError : # If the field doesn ' t exist on the object , fail gracefully # and don ' t include the field in the data dict at all . Fail # loudly if the field exists but produces a differe...
def finalize_options ( self ) -> None : "Get options from config files ."
self . arguments = { } # type : Dict [ str , Any ] computed_settings = from_path ( os . getcwd ( ) ) for key , value in computed_settings . items ( ) : self . arguments [ key ] = value
def setShapeClass ( self , typeID , clazz ) : """setShapeClass ( string , string ) - > None Sets the shape class of vehicles of this type ."""
self . _connection . _sendStringCmd ( tc . CMD_SET_VEHICLETYPE_VARIABLE , tc . VAR_SHAPECLASS , typeID , clazz )
def _init_edges ( self , dst_srcs_list ) : """Create all GO edges given a list of ( dst , srcs ) ."""
from goatools . gosubdag . go_paths import get_paths_goobjs , paths2edges edges_all = set ( ) goid_all = set ( ) go2obj = self . go2obj for dst , srcs in dst_srcs_list : go2obj_srcs = { } for goid in srcs : go2obj_srcs [ goid ] = go2obj [ goid ] go_paths , go_all = get_paths_goobjs ( go2obj_srcs . v...
def fit ( self , X , y , ** args ) : """The fit method is the primary entry point for the manual alpha selection visualizer . It sets the alpha param for each alpha in the alphas list on the wrapped estimator , then scores the model using the passed in X and y data set . Those scores are then aggregated and ...
self . errors = [ ] for alpha in self . alphas : self . estimator . set_params ( alpha = alpha ) scores = self . score_method ( self . estimator , X , y ) self . errors . append ( scores . mean ( ) ) # Convert errors to an ND array and draw self . errors = np . array ( self . errors ) self . draw ( ) # Alwa...
def _string_to_dictsql ( self , part ) : """Do magic matching of single words or quoted string"""
self . _logger . debug ( "parsing string: " + unicode ( part [ 0 ] ) + " of type: " + part . getName ( ) ) if part . getName ( ) == 'tag' : self . _logger . debug ( "Query part '" + part [ 0 ] + "' interpreted as tag" ) dictsql = { 'interpretation' : { 'string' : part [ 0 ] , 'interpretation' : 'tag' , 'attribu...
def _granularities ( self ) : """Returns a generator of all possible granularities based on the MIN _ GRANULARITY and MAX _ GRANULARITY settings ."""
keep = False for g in GRANULARITIES : if g == app_settings . MIN_GRANULARITY and not keep : keep = True elif g == app_settings . MAX_GRANULARITY and keep : keep = False yield g if keep : yield g
def lookup_hlr_create ( self , phonenumber , params = None ) : """Perform a new HLR lookup ."""
if params is None : params = { } return HLR ( ) . load ( self . request ( 'lookup/' + str ( phonenumber ) + '/hlr' , 'POST' , params ) )
def _get_xdata_for_function ( self , n , xdata ) : """Generates the x - data for plotting the function . Parameters Which data set we ' re using xdata Data set upon which to base this Returns float"""
# Use the xdata itself for the function if self [ 'fpoints' ] [ n ] in [ None , 0 ] : return _n . array ( xdata ) # Otherwise , generate xdata with the number of fpoints # do exponential ranging if xscale is log if self [ 'xscale' ] [ n ] == 'log' : return _n . logspace ( _n . log10 ( min ( xdata ) ) , _n . log...
def increase_posts_count ( sender , instance , ** kwargs ) : """Increases the member ' s post count after a post save . This receiver handles the update of the profile related to the user who is the poster of the forum post being created or updated ."""
if instance . poster is None : # An anonymous post is considered . No profile can be updated in # that case . return profile , dummy = ForumProfile . objects . get_or_create ( user = instance . poster ) increase_posts_count = False if instance . pk : try : old_instance = instance . __class__ . _default_...
async def connect ( self , conn_id , connection_string ) : """Connect to a device . See : meth : ` AbstractDeviceAdapter . connect ` ."""
if connection_string . startswith ( 'device/' ) : adapter_id , local_conn = self . _find_best_adapter ( connection_string , conn_id ) translate_conn = True elif connection_string . startswith ( 'adapter/' ) : adapter_str , _ , local_conn = connection_string [ 8 : ] . partition ( '/' ) adapter_id = int (...
def slices_from_global_coords ( self , slices ) : """Used for converting from mip 0 coordinates to upper mip level coordinates . This is mainly useful for debugging since the neuroglancer client displays the mip 0 coordinates for your cursor ."""
bbox = self . bbox_to_mip ( slices , 0 , self . mip ) return bbox . to_slices ( )
def set_objective_sense ( self , sense ) : """Set type of problem ( maximize or minimize ) ."""
if sense not in ( ObjectiveSense . Minimize , ObjectiveSense . Maximize ) : raise ValueError ( 'Invalid objective sense' ) self . _p . ModelSense = self . OBJ_SENSE_MAP [ sense ]
def slice ( self , start , until ) : """Takes a slice of the sequence starting at start and until but not including until . > > > seq ( [ 1 , 2 , 3 , 4 ] ) . slice ( 1 , 2) > > > seq ( [ 1 , 2 , 3 , 4 ] ) . slice ( 1 , 3) [2 , 3] : param start : starting index : param until : ending index : return : sli...
return self . _transform ( transformations . slice_t ( start , until ) )
def add_tier ( self , coro , ** kwargs ) : """Add a coroutine to the cell as a task tier . The source can be a single value or a list of either ` Tier ` types or coroutine functions already added to a ` Tier ` via ` add _ tier ` ."""
self . assertNotFinalized ( ) assert asyncio . iscoroutinefunction ( coro ) tier = self . Tier ( self , coro , ** kwargs ) self . tiers . append ( tier ) self . tiers_coro_map [ coro ] = tier return tier
def show_vcs_output_vcs_guid ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) show_vcs = ET . Element ( "show_vcs" ) config = show_vcs output = ET . SubElement ( show_vcs , "output" ) vcs_guid = ET . SubElement ( output , "vcs-guid" ) vcs_guid . text = kwargs . pop ( 'vcs_guid' ) callback = kwargs . pop ( 'callback' , self . _callback ) return callback ( config...
def print_summary ( self , decimals = 2 , ** kwargs ) : """Print summary statistics describing the fit , the coefficients , and the error bounds . Parameters decimals : int , optional ( default = 2) specify the number of decimal places to show kwargs : print additional meta data in the output ( useful to ...
# Print information about data first justify = string_justify ( 18 ) print ( self ) print ( "{} = '{}'" . format ( justify ( "duration col" ) , self . duration_col ) ) print ( "{} = '{}'" . format ( justify ( "event col" ) , self . event_col ) ) if self . weights_col : print ( "{} = '{}'" . format ( justify ( "weig...
def add ( self , num ) : """Adds num to the current value"""
try : val = self . value ( ) + num except : val = num self . set ( min ( self . imax , max ( self . imin , val ) ) )
def list_actions ( i ) : """Input : { ( repo _ uoa ) - repo UOA ( module _ uoa ) - module _ uoa , if = = " " , use kernel ( data _ uoa ) Output : { return - return code = 0 , if successful > 0 , if error ( error ) - error text if return > 0 actions - list of actions"""
o = i . get ( 'out' , '' ) ruoa = i . get ( 'repo_uoa' , '' ) muoa = i . get ( 'module_uoa' , '' ) duoa = i . get ( 'data_uoa' , '' ) if muoa != '' : if duoa != '' : muoa = duoa duoa = '' # Find path to module ' module ' to get dummies ii = { 'action' : 'load' , 'module_uoa' : cfg [ 'module_...
def load_categories ( self , max_pages = 30 ) : """Load all WordPress categories from the given site . : param max _ pages : kill counter to avoid infinite looping : return : None"""
logger . info ( "loading categories" ) # clear them all out so we don ' t get dupes if requested if self . purge_first : Category . objects . filter ( site_id = self . site_id ) . delete ( ) path = "sites/{}/categories" . format ( self . site_id ) params = { "number" : 100 } page = 1 response = self . get ( path , ...
def newline ( self , * args , ** kwargs ) : """Prints an empty line to the log . Uses the level of the last message printed unless specified otherwise with the level = kwarg ."""
levelOverride = kwargs . get ( 'level' ) or self . _lastlevel self . _log ( levelOverride , '' , 'newline' , args , kwargs )
def _get_or_create_service_key ( self ) : """Get a service key or create one if needed ."""
keys = self . service . _get_service_keys ( self . name ) for key in keys [ 'resources' ] : if key [ 'entity' ] [ 'name' ] == self . service_name : return self . service . get_service_key ( self . name , self . service_name ) self . service . create_service_key ( self . name , self . service_name ) return s...
def split_channel ( self ) : """A channel can be splitted to new channel or other existing channel . It creates subscribers list as selectable to moved ."""
if self . current . task_data . get ( 'msg' , False ) : self . show_warning_messages ( ) self . current . task_data [ 'split_operation' ] = True channel = Channel . objects . get ( self . current . task_data [ 'chosen_channels' ] [ 0 ] ) _form = SubscriberListForm ( title = _ ( u'Choose Subscribers to Migrate' ) ) ...