signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def main ( sleep_length = 0.1 ) : """Log to stdout using python logging in a while loop"""
log = logging . getLogger ( 'sip.examples.log_spammer' ) log . info ( 'Starting to spam log messages every %fs' , sleep_length ) counter = 0 try : while True : log . info ( 'Hello %06i (log_spammer: %s, sip logging: %s)' , counter , _version . __version__ , __version__ ) counter += 1 time . ...
def median ( array ) : """Return the median value of a list of numbers ."""
n = len ( array ) if n < 1 : return 0 elif n == 1 : return array [ 0 ] sorted_vals = sorted ( array ) midpoint = int ( n / 2 ) if n % 2 == 1 : return sorted_vals [ midpoint ] else : return ( sorted_vals [ midpoint - 1 ] + sorted_vals [ midpoint ] ) / 2.0
def _urlopen_as_json ( self , url , headers = None ) : """Shorcut for return contents as json"""
req = Request ( url , headers = headers ) return json . loads ( urlopen ( req ) . read ( ) )
def _call_validators ( self ) : """Actually run all the validations . Returns : list ( str ) : Error messages from the validators ."""
msg = [ ] msg . extend ( self . _validate_keyfile ( ) ) msg . extend ( self . _validate_dns_zone ( ) ) msg . extend ( self . _validate_retries ( ) ) msg . extend ( self . _validate_project ( ) ) return msg
def validate ( self , session ) : """Validate that the current user can be saved . : param session : SQLAlchemy session : type session : : class : ` sqlalchemy . Session ` : return : ` ` True ` ` : rtype : bool : raise : : class : ` pyshop . helpers . sqla . ModelError ` if user is not valid"""
errors = [ ] if not self . login : errors . append ( u'login is required' ) else : other = User . by_login ( session , self . login ) if other and other . id != self . id : errors . append ( u'duplicate login %s' % self . login ) if not self . password : errors . append ( u'password is required'...
def discrepancy_plot ( data , name = 'discrepancy' , report_p = True , format = 'png' , suffix = '-gof' , path = './' , fontmap = None , verbose = 1 ) : '''Generate goodness - of - fit deviate scatter plot . : Arguments : data : list List ( or list of lists for vector - valued variables ) of discrepancy value...
if verbose > 0 : print_ ( 'Plotting' , name + suffix ) if fontmap is None : fontmap = { 1 : 10 , 2 : 8 , 3 : 6 , 4 : 5 , 5 : 4 } # Generate new scatter plot figure ( ) try : x , y = transpose ( data ) except ValueError : x , y = data scatter ( x , y ) # Plot x = y line lo = nmin ( ravel ( data ) ) hi = ...
def run_details ( self , run ) : """Retrieve sequencing run details as a dictionary ."""
run_data = dict ( run = run ) req = urllib . request . Request ( "%s/nglims/api_run_details" % self . _base_url , urllib . parse . urlencode ( run_data ) ) response = urllib . request . urlopen ( req ) info = json . loads ( response . read ( ) ) if "error" in info : raise ValueError ( "Problem retrieving info: %s" ...
def get_all_monomials ( variables , extramonomials , substitutions , degree , removesubstitutions = True ) : """Return the monomials of a certain degree ."""
monomials = get_monomials ( variables , degree ) if extramonomials is not None : monomials . extend ( extramonomials ) if removesubstitutions and substitutions is not None : monomials = [ monomial for monomial in monomials if monomial not in substitutions ] monomials = [ remove_scalar_factor ( apply_substit...
def spawn_isolated_child ( self ) : """Fork or launch a new child off the target context . : returns : mitogen . core . Context of the new child ."""
return self . get_chain ( use_fork = True ) . call ( ansible_mitogen . target . spawn_isolated_child )
def from_pty ( cls , stdout , true_color = False , ansi_colors_only = None , term = None ) : """Create an Output class from a pseudo terminal . ( This will take the dimensions by reading the pseudo terminal attributes . )"""
assert stdout . isatty ( ) def get_size ( ) : rows , columns = _get_size ( stdout . fileno ( ) ) # If terminal ( incorrectly ) reports its size as 0 , pick a reasonable default . # See https : / / github . com / ipython / ipython / issues / 10071 return Size ( rows = ( rows or 24 ) , columns = ( columns...
def do_sort ( value , case_sensitive = False ) : """Sort an iterable . If the iterable is made of strings the second parameter can be used to control the case sensitiveness of the comparison which is disabled by default . . . sourcecode : : jinja { % for item in iterable | sort % } { % endfor % }"""
if not case_sensitive : def sort_func ( item ) : if isinstance ( item , basestring ) : item = item . lower ( ) return item else : sort_func = None return sorted ( seq , key = sort_func )
def p_return_statement_1 ( self , p ) : """return _ statement : RETURN SEMI | RETURN AUTOSEMI"""
p [ 0 ] = self . asttypes . Return ( ) p [ 0 ] . setpos ( p )
def get_tuids ( self , files , revision , commit = True , chunk = 50 , repo = None ) : '''Wrapper for ` _ get _ tuids ` to limit the number of annotation calls to hg and separate the calls from DB transactions . Also used to simplify ` _ get _ tuids ` . : param files : : param revision : : param commit : ...
results = [ ] revision = revision [ : 12 ] # For a single file , there is no need # to put it in an array when given . if not isinstance ( files , list ) : files = [ files ] if repo is None : repo = self . config . hg . branch for _ , new_files in jx . groupby ( files , size = chunk ) : for count , file in ...
def all_qubits ( self ) -> FrozenSet [ ops . Qid ] : """Returns the qubits acted upon by Operations in this circuit ."""
return frozenset ( q for m in self . _moments for q in m . qubits )
def sign_key ( self , keyid , default_key = None , passphrase = None ) : """sign ( an imported ) public key - keyid , with default secret key > > > import gnupg > > > gpg = gnupg . GPG ( homedir = " doctests " ) > > > key _ input = gpg . gen _ key _ input ( ) > > > key = gpg . gen _ key ( key _ input ) > ...
args = [ ] input_command = "" if passphrase : passphrase_arg = "--passphrase-fd 0" input_command = "%s\n" % passphrase args . append ( passphrase_arg ) if default_key : args . append ( str ( "--default-key %s" % default_key ) ) args . extend ( [ "--command-fd 0" , "--sign-key %s" % keyid ] ) p = self . ...
def expect_column_pair_values_to_be_in_set ( self , column_A , column_B , value_pairs_set , ignore_row_if = "both_values_are_missing" , result_format = None , include_config = False , catch_exceptions = None , meta = None ) : """Expect paired values from columns A and B to belong to a set of valid pairs . Args : ...
raise NotImplementedError
def parse_manifest ( self , fp ) : """Open manifest JSON file and build icon map Args : fp ( string or fileobject ) : Either manifest filepath to open or manifest File object . Returns : dict : Webfont icon map . Contains : * ` ` class _ name ` ` : Builded icon classname with prefix configured in mani...
# Given a string for file path to open if isinstance ( fp , string_types ) : fp = io . open ( fp , 'r' , encoding = 'utf-8' ) with fp as json_file : webfont_manifest = json . load ( json_file ) # Get the font set prefix to know the css classname icon_prefix = webfont_manifest . get ( 'preferences' ) . get ( 'fo...
def get ( self , rate_type , role , session , fields = [ ] , ** kwargs ) : '''taobao . traderates . get 搜索评价信息 搜索评价信息 , 只能获取距今180天内的评价记录'''
request = TOPRequest ( 'taobao.traderates.get' ) request [ 'rate_type' ] = rate_type request [ 'role' ] = role if not fields : tradeRate = TradeRate ( ) fields = tradeRate . fields request [ 'fields' ] = fields for k , v in kwargs . iteritems ( ) : if k not in ( 'result' , 'page_no' , 'page_size' , 'start_d...
def stop ( self , timeout = None ) : """Stop the thread ."""
logger . debug ( "ports plugin - Close thread for scan list {}" . format ( self . _stats ) ) self . _stopper . set ( )
def _process_file_continue_request ( self , request : BaseRequest ) : '''Modify the request to resume downloading file .'''
if os . path . exists ( self . _filename ) : size = os . path . getsize ( self . _filename ) request . set_continue ( size ) self . _file_continue_requested = True _logger . debug ( 'Continue file from {0}.' , size ) else : _logger . debug ( 'No file to continue.' )
def _yyyymmdd_to_year_fraction ( date ) : """Convert YYYMMDD . DD date string or float to YYYY . YYY"""
date = str ( date ) if '.' in date : date , residual = str ( date ) . split ( '.' ) residual = float ( '0.' + residual ) else : residual = 0.0 date = _datetime . datetime . strptime ( date , '%Y%m%d' ) date += _datetime . timedelta ( days = residual ) year = date . year year_start = _datetime . datetime ( y...
def language ( s ) : """Returns a ( language , confidence ) - tuple for the given string ."""
s = decode_utf8 ( s ) s = set ( w . strip ( PUNCTUATION ) for w in s . replace ( "'" , "' " ) . split ( ) ) n = float ( len ( s ) or 1 ) p = { } for xx in LANGUAGES : lexicon = _module ( xx ) . __dict__ [ "lexicon" ] p [ xx ] = sum ( 1 for w in s if w in lexicon ) / n return max ( p . items ( ) , key = lambda k...
def _check ( peers ) : '''Checks whether the input is a valid list of peers and transforms domain names into IP Addresses'''
if not isinstance ( peers , list ) : return False for peer in peers : if not isinstance ( peer , six . string_types ) : return False if not HAS_NETADDR : # if does not have this lib installed , will simply try to load what user specified # if the addresses are not correctly specified , will trow error w...
def _is_collect_cx_state_runnable ( self , proc_location ) : """Determine if collect _ connection _ state is set and can effectively run . If self . _ collect _ cx _ state is True and a custom proc _ location is provided , the system cannot run ` ss ` or ` netstat ` over a custom proc _ location : param proc ...
if self . _collect_cx_state is False : return False if proc_location != "/proc" : self . warning ( "Cannot collect connection state: currently with a custom /proc path: %s" % proc_location ) return False return True
def parseFullScan ( self , i , modifications = True ) : """parses scan info for giving a Spectrum Obj for plotting . takes significantly longer since it has to unzip / parse xml"""
scanObj = PeptideObject ( ) peptide = str ( i [ 1 ] ) pid = i [ 2 ] if modifications : sql = 'select aam.ModificationName,pam.Position,aam.DeltaMass from peptidesaminoacidmodifications pam left join aminoacidmodifications aam on (aam.AminoAcidModificationID=pam.AminoAcidModificationID) where pam.PeptideID=%s' % pid...
def filter_data ( self , min_len , max_len ) : """Preserves only samples which satisfy the following inequality : min _ len < = src sample sequence length < = max _ len AND min _ len < = tgt sample sequence length < = max _ len : param min _ len : minimum sequence length : param max _ len : maximum sequence...
logging . info ( f'Filtering data, min len: {min_len}, max len: {max_len}' ) initial_len = len ( self . src ) filtered_src = [ ] filtered_tgt = [ ] for src , tgt in zip ( self . src , self . tgt ) : if min_len <= len ( src ) <= max_len and min_len <= len ( tgt ) <= max_len : filtered_src . append ( src ) ...
def get_tab_title ( key , frame , overlay ) : """Computes a title for bokeh tabs from the key in the overlay , the element and the containing ( Nd ) Overlay ."""
if isinstance ( overlay , Overlay ) : if frame is not None : title = [ ] if frame . label : title . append ( frame . label ) if frame . group != frame . params ( 'group' ) . default : title . append ( frame . group ) else : title . append (...
def _v ( self , token , previous = None , next = None ) : """Returns a training vector for the given ( word , tag ) - tuple and its context ."""
def f ( v , s1 , s2 ) : if s2 : v [ s1 + " " + s2 ] = 1 p , n = previous , next p = ( "" , "" ) if not p else ( p [ 0 ] or "" , p [ 1 ] or "" ) n = ( "" , "" ) if not n else ( n [ 0 ] or "" , n [ 1 ] or "" ) v = { } f ( v , "b" , "b" ) # Bias . f ( v , "h" , token [ 0 ] ) # Capitalization . f ( v , "w" , to...
def InitLocCheck ( self ) : """make an interactive grid in which users can edit locations"""
# if there is a location without a name , name it ' unknown ' self . contribution . rename_item ( 'locations' , 'nan' , 'unknown' ) # propagate lat / lon values from sites table self . contribution . get_min_max_lat_lon ( ) # propagate lithologies & geologic classes from sites table self . contribution . propagate_cols...
def set_default_names ( data ) : """Sets index names to ' index ' for regular , or ' level _ x ' for Multi"""
if com . _all_not_none ( * data . index . names ) : nms = data . index . names if len ( nms ) == 1 and data . index . name == 'index' : warnings . warn ( "Index name of 'index' is not round-trippable" ) elif len ( nms ) > 1 and any ( x . startswith ( 'level_' ) for x in nms ) : warnings . wa...
def resize_state_meta ( state_m , factor , gaphas_editor = True ) : """Resize state meta data recursive what includes also LibraryStateModels meta data and its internal state _ copy"""
# print ( " START RESIZE OF STATE " , state _ m . get _ meta _ data _ editor ( for _ gaphas = gaphas _ editor ) , state _ m ) old_rel_pos = state_m . get_meta_data_editor ( for_gaphas = gaphas_editor ) [ 'rel_pos' ] # print ( " old _ rel _ pos state " , old _ rel _ pos , state _ m . core _ element ) state_m . set_meta_...
def call_in_executor ( self , func : Callable , * args , executor : Union [ Executor , str ] = None , ** kwargs ) -> Awaitable : """Call the given callable in an executor . : param func : the callable to call : param args : positional arguments to call the callable with : param executor : either an : class : ...
assert check_argument_types ( ) if isinstance ( executor , str ) : executor = self . require_resource ( Executor , executor ) return asyncio_extras . call_in_executor ( func , * args , executor = executor , ** kwargs )
def Reset ( self ) : 'Reset Axis and set default parameters for H - bridge'
spi . SPI_write_byte ( self . CS , 0xC0 ) # reset # spi . SPI _ write _ byte ( self . CS , 0x14 ) # Stall Treshold setup # spi . SPI _ write _ byte ( self . CS , 0xFF ) # spi . SPI _ write _ byte ( self . CS , 0x13 ) # Over Current Treshold setup # spi . SPI _ write _ byte ( self . CS , 0xFF ) spi . SPI_write_byte ( se...
def has_matching_etag ( remote_storage , source_storage , path , prefixed_path ) : """Compare etag of path in source storage with remote ."""
storage_etag = get_etag ( remote_storage , path , prefixed_path ) local_etag = get_file_hash ( source_storage , path ) return storage_etag == local_etag
def to_definition ( self ) : """Converts the name instance to a pyqode . core . share . Definition"""
icon = { Name . Type . Root : icons . ICON_MIMETYPE , Name . Type . Division : icons . ICON_DIVISION , Name . Type . Section : icons . ICON_SECTION , Name . Type . Variable : icons . ICON_VAR , Name . Type . Paragraph : icons . ICON_FUNC } [ self . node_type ] d = Definition ( self . name , self . line , self . column ...
def group ( args ) : """% prog group tabfile > tabfile . grouped Given a tab - delimited file , either group all elements within the file or group the elements in the value column ( s ) based on the key ( groupby ) column For example , convert this | into this a2 3 4 | a , 2,3,4,5,6 a5 6 | b , 7,8 b7 8 ...
from jcvi . utils . cbook import AutoVivification from jcvi . utils . grouper import Grouper p = OptionParser ( group . __doc__ ) p . set_sep ( ) p . add_option ( "--groupby" , default = None , type = 'int' , help = "Default column to groupby [default: %default]" ) p . add_option ( "--groupsep" , default = ',' , help =...
def _descope_flag ( self , flag , default_scope ) : """If the flag is prefixed by its scope , in the old style , extract the scope . Otherwise assume it belongs to default _ scope . returns a pair ( scope , flag ) ."""
for scope_prefix , scope_info in self . _known_scoping_prefixes : for flag_prefix in [ '--' , '--no-' ] : prefix = flag_prefix + scope_prefix if flag . startswith ( prefix ) : scope = scope_info . scope if scope_info . category == ScopeInfo . SUBSYSTEM and default_scope != GL...
def _slice_data ( self , source_area , slices , dataset ) : """Slice the data to reduce it ."""
slice_x , slice_y = slices dataset = dataset . isel ( x = slice_x , y = slice_y ) assert ( 'x' , source_area . x_size ) in dataset . sizes . items ( ) assert ( 'y' , source_area . y_size ) in dataset . sizes . items ( ) dataset . attrs [ 'area' ] = source_area return dataset
def _populate_common_request ( self , request ) : '''Populate the Request with common fields .'''
url_record = self . _item_session . url_record # Note that referrer may have already been set by the - - referer option if url_record . parent_url and not request . fields . get ( 'Referer' ) : self . _add_referrer ( request , url_record ) if self . _fetch_rule . http_login : request . username , request . pass...
def get_next_invoke_id ( self , addr ) : """Called by clients to get an unused invoke ID ."""
if _debug : StateMachineAccessPoint . _debug ( "get_next_invoke_id" ) initialID = self . nextInvokeID while 1 : invokeID = self . nextInvokeID self . nextInvokeID = ( self . nextInvokeID + 1 ) % 256 # see if we ' ve checked for them all if initialID == self . nextInvokeID : raise RuntimeErro...
def _get_targets ( self , target , include_global = True ) : """Internal iterator to split up a complete target into the possible parts it may match . For example : : > > > list ( aliases . _ get _ targets ( ' my _ app . MyModel . somefield ' ) ) [ ' ' , ' my _ app ' , ' my _ app . MyModel ' , ' my _ app . ...
target = self . _coerce_target ( target ) if include_global : yield '' if not target : return target_bits = target . split ( '.' ) for i in range ( len ( target_bits ) ) : yield '.' . join ( target_bits [ : i + 1 ] )
def _set_html2text ( self , settings ) : """Load settings for html2text ( https : / / github . com / Alir3z4 / html2text ) Warning : does not check options / values : param settings : Settings for the object ( see : https : / / github . com / Alir3z4 / html2text / blob / master / docs / usage . md ) : type ...
self . _text_maker = html2text . HTML2Text ( ) for param in settings : if not hasattr ( self . _text_maker , param ) : raise WEBParameterException ( "Setting html2text failed - unknown parameter {}" . format ( param ) ) setattr ( self . _text_maker , param , settings [ param ] )
def is_installed_extension ( name , user = None , host = None , port = None , maintenance_db = None , password = None , runas = None ) : '''Test if a specific extension is installed CLI Example : . . code - block : : bash salt ' * ' postgres . is _ installed _ extension'''
installed_ext = get_installed_extension ( name , user = user , host = host , port = port , maintenance_db = maintenance_db , password = password , runas = runas ) return bool ( installed_ext )
def find_smallest_of_three ( num1 , num2 , num3 ) : """Function to determine the smallest of three input numbers . Examples : > > > find _ smallest _ of _ three ( 10 , 20 , 0) > > > find _ smallest _ of _ three ( 19 , 15 , 18) 15 > > > find _ smallest _ of _ three ( - 10 , - 20 , - 30) -30 Args : nu...
return min ( num1 , num2 , num3 )
def scroll_constrain ( self ) : '''This keeps the scroll region within the screen region .'''
if self . scroll_row_start <= 0 : self . scroll_row_start = 1 if self . scroll_row_end > self . rows : self . scroll_row_end = self . rows
def isoformat ( self , sep = 'T' ) : """Formats the date as " % Y - % m - % d % H : % M : % S " with the sep param between the date and time portions : param set : A single character of the separator to place between the date and time : return : The formatted datetime as a unicode string in Python 3 and...
if self . microsecond == 0 : return self . strftime ( '0000-%%m-%%d%s%%H:%%M:%%S' % sep ) return self . strftime ( '0000-%%m-%%d%s%%H:%%M:%%S.%%f' % sep )
def _check_device ( self , requested_device , map_device ) : """Compare the requested device with the map device and return the map device if it differs from the requested device along with a warning ."""
type_1 = torch . device ( requested_device ) type_2 = torch . device ( map_device ) if type_1 != type_2 : warnings . warn ( 'Setting self.device = {} since the requested device ({}) ' 'is not available.' . format ( map_device , requested_device ) , DeviceWarning ) return map_device # return requested _ device i...
def load_object ( name ) : """Load object from module"""
if "." not in name : raise Exception ( 'load object need module.object' ) module_name , object_name = name . rsplit ( '.' , 1 ) if six . PY2 : module = __import__ ( module_name , globals ( ) , locals ( ) , [ utf8 ( object_name ) ] , - 1 ) else : module = __import__ ( module_name , globals ( ) , locals ( ) ,...
def RSA ( im : array , radius : int , volume_fraction : int = 1 , mode : str = 'extended' ) : r"""Generates a sphere or disk packing using Random Sequential Addition This which ensures that spheres do not overlap but does not guarantee they are tightly packed . Parameters im : ND - array The image into wh...
# Note : The 2D vs 3D splitting of this just me being lazy . . . I can ' t be # bothered to figure it out programmatically right now # TODO : Ideally the spheres should be added periodically print ( 78 * '―' ) print ( 'RSA: Adding spheres of size ' + str ( radius ) ) d2 = len ( im . shape ) == 2 mrad = 2 * radius if d2...
def market_if_touched ( self , accountID , ** kwargs ) : """Shortcut to create a MarketIfTouched Order in an Account Args : accountID : The ID of the Account kwargs : The arguments to create a MarketIfTouchedOrderRequest Returns : v20 . response . Response containing the results from submitting the requ...
return self . create ( accountID , order = MarketIfTouchedOrderRequest ( ** kwargs ) )
def _is_germline ( rec ) : """Handle somatic INFO classifications from MuTect , MuTect2 , VarDict , VarScan and Octopus ."""
if _has_somatic_flag ( rec ) : return False if _is_mutect2_somatic ( rec ) : return False ss_flag = rec . INFO . get ( "SS" ) if ss_flag is not None : if str ( ss_flag ) == "1" : return True # Octopus , assessed for potentially being Germline and not flagged SOMATIC # https : / / github . com / lunt...
def density_contourf ( self , * args , ** kwargs ) : """Estimates point density of the given linear orientation measurements ( Interpreted as poles , lines , rakes , or " raw " longitudes and latitudes based on the ` measurement ` keyword argument . ) and plots filled contours of the resulting density distrib...
lon , lat , totals , kwargs = self . _contour_helper ( args , kwargs ) return self . contourf ( lon , lat , totals , ** kwargs )
def JoinPath ( self , path_segments ) : """Joins the path segments into a path . Args : path _ segments ( list [ str ] ) : path segments . Returns : str : joined path segments prefixed with the path separator ."""
# This is an optimized way to combine the path segments into a single path # and combine multiple successive path separators to one . # Split all the path segments based on the path ( segment ) separator . path_segments = [ segment . split ( self . PATH_SEPARATOR ) for segment in path_segments ] # Flatten the sublists ...
def interpolate ( x , y , z , interp_type = 'linear' , hres = 50000 , minimum_neighbors = 3 , gamma = 0.25 , kappa_star = 5.052 , search_radius = None , rbf_func = 'linear' , rbf_smooth = 0 , boundary_coords = None ) : """Wrap interpolate _ to _ grid for deprecated interpolate function ."""
return interpolate_to_grid ( x , y , z , interp_type = interp_type , hres = hres , minimum_neighbors = minimum_neighbors , gamma = gamma , kappa_star = kappa_star , search_radius = search_radius , rbf_func = rbf_func , rbf_smooth = rbf_smooth , boundary_coords = boundary_coords )
def get_time_evolution ( self ) : """Get the function to append the time evolution of this term . Returns : function ( circuit : Circuit , t : float ) : Add gates for time evolution to ` circuit ` with time ` t `"""
term = self . simplify ( ) coeff = term . coeff if coeff . imag : raise ValueError ( "Not a real coefficient." ) ops = term . ops def append_to_circuit ( circuit , t ) : if not ops : return for op in ops : n = op . n if op . op == "X" : circuit . h [ n ] elif op ....
def from_tuple ( cls , components : tuple ) -> 'ComponentRef' : """Convert the tuple pointing to a component to a component reference . : param components : tuple of components name : return : ComponentRef"""
component_ref = ComponentRef ( name = components [ 0 ] , child = [ ] ) c = component_ref for component in components [ 1 : ] : c . child . append ( ComponentRef ( name = component , child = [ ] ) ) c = c . child [ 0 ] return component_ref
def get_environmental_configuration ( self ) : """Gets the settings that describe the environmental configuration ( supported feature set , calibrated minimum & maximum power , location & dimensions , . . . ) of the enclosure resource . Returns : Settings that describe the environmental configuration ."""
uri = '{}/environmentalConfiguration' . format ( self . data [ 'uri' ] ) return self . _helper . do_get ( uri )
def filter ( self , id ) : """Fetches information about the filter with the specified ` id ` . Returns a ` filter dict ` _ ."""
id = self . __unpack_id ( id ) url = '/api/v1/filters/{0}' . format ( str ( id ) ) return self . __api_request ( 'GET' , url )
def call ( command , working_directory = config . BASE_DIR ) : """Executes shell command in a given working _ directory . Command is a list of strings to execute as a command line . Returns a tuple of two byte strings : ( stdout , stderr )"""
LOG . info ( command ) proc = sp . Popen ( command , stdout = sp . PIPE , stderr = sp . PIPE , cwd = working_directory , shell = True ) out , err = proc . communicate ( ) return ( out , err )
def save_itemgetter ( self , obj ) : """itemgetter serializer ( needed for namedtuple support )"""
class Dummy : def __getitem__ ( self , item ) : return item items = obj ( Dummy ( ) ) if not isinstance ( items , tuple ) : items = ( items , ) return self . save_reduce ( operator . itemgetter , items )
def set_logfile ( path , instance ) : """Specify logfile path"""
global logfile logfile = os . path . normpath ( path ) + '/hfos.' + instance + '.log'
def _pip_list ( self , stdout , stderr , prefix = None ) : """Callback for ` pip _ list ` ."""
result = stdout # A dict linked = self . linked ( prefix ) pip_only = [ ] linked_names = [ self . split_canonical_name ( l ) [ 0 ] for l in linked ] for pkg in result : name = self . split_canonical_name ( pkg ) [ 0 ] if name not in linked_names : pip_only . append ( pkg ) # FIXME : NEED A MORE ROBU...
def _axes_style ( style = None , rc = None ) : """Return a parameter dict for the aesthetic style of the plots . NOTE : This is an internal method from Seaborn that is simply used to create a default aesthetic in yellowbrick . If you ' d like to use these styles then import Seaborn ! This affects things lik...
if isinstance ( style , dict ) : style_dict = style else : # Define colors here dark_gray = ".15" light_gray = ".8" # Common parameters style_dict = { "figure.facecolor" : "white" , "text.color" : dark_gray , "axes.labelcolor" : dark_gray , "legend.frameon" : False , "legend.numpoints" : 1 , "legend...
def Matches ( self , file_entry ) : """Compares the file entry against the filter . Args : file _ entry ( dfvfs . FileEntry ) : file entry to compare . Returns : bool : True if the file entry matches the filter , False if not or None if the filter does not apply ."""
location = getattr ( file_entry . path_spec , 'location' , None ) if not location : return None if '.' not in location : return False _ , _ , extension = location . rpartition ( '.' ) return extension . lower ( ) in self . _extensions
def _get_client ( ) : """Create a new client for the HNV REST API ."""
return utils . get_client ( url = CONFIG . HNV . url , username = CONFIG . HNV . username , password = CONFIG . HNV . password , allow_insecure = CONFIG . HNV . https_allow_insecure , ca_bundle = CONFIG . HNV . https_ca_bundle )
async def addFeedNodes ( self , name , items ) : '''Call a feed function and return what it returns ( typically yields Node ( ) s ) . Args : name ( str ) : The name of the feed record type . items ( list ) : A list of records of the given feed type . Returns : ( object ) : The return value from the feed f...
func = self . core . getFeedFunc ( name ) if func is None : raise s_exc . NoSuchName ( name = name ) logger . info ( f'adding feed nodes ({name}): {len(items)}' ) async for node in func ( self , items ) : yield node
def is_refreshable_url ( self , request ) : """Takes a request and returns whether it triggers a refresh examination : arg HttpRequest request : : returns : boolean"""
# Do not attempt to refresh the session if the OIDC backend is not used backend_session = request . session . get ( BACKEND_SESSION_KEY ) is_oidc_enabled = True if backend_session : auth_backend = import_string ( backend_session ) is_oidc_enabled = issubclass ( auth_backend , OIDCAuthenticationBackend ) return ...
def add_maildir ( self , maildir_path ) : """Load up a maildir and compute hash for each mail found ."""
maildir_path = self . canonical_path ( maildir_path ) logger . info ( "Opening maildir at {} ..." . format ( maildir_path ) ) # Maildir parser requires a string , not a unicode , as path . maildir = Maildir ( str ( maildir_path ) , factory = None , create = False ) # Group folders by hash . logger . info ( "{} mails fo...
def write_to_file ( self , path , filename , footer = True ) : """Class method responsible for generating a file containing the notebook object data . Parameters path : str OpenSignalsTools Root folder path ( where the notebook will be stored ) . filename : str Defines the name of the notebook file . fo...
# = = = = = Storage of Filename = = = = = self . filename = filename # = = = = = Inclusion of Footer in the Notebook = = = = = if footer is True : _generate_footer ( self . notebook , self . notebook_type ) # = = = = = Code segment for application of the OpenSignalsTools CSS style = = = = = self . notebook [ "cells...
def _init_lazy_fields ( self ) : """Member data that gets loaded or constructed on demand"""
self . gtf_path = None self . _protein_sequences = None self . _transcript_sequences = None self . _db = None self . protein_fasta_paths = None self . transcript_fasta_paths = None # only memoizing the Gene , Transcript , and Exon objects self . _genes = { } self . _transcripts = { } self . _exons = { }
def _partially_evaluate ( self , addr , simplify = False ) : """Return part of the lazy array ."""
if self . is_homogeneous : if simplify : base_val = self . base_value else : base_val = self . _homogeneous_array ( addr ) * self . base_value elif isinstance ( self . base_value , ( int , long , numpy . integer , float , bool ) ) : base_val = self . _homogeneous_array ( addr ) * self . base...
def pages ( self ) : """The aggregate pages of all the parser objects ."""
pages = [ ] for har_dict in self . har_data : har_parser = HarParser ( har_data = har_dict ) if self . page_id : for page in har_parser . pages : if page . page_id == self . page_id : pages . append ( page ) else : pages = pages + har_parser . pages return pages
def format_norm ( kwargs , current = None ) : """Format a ` ~ matplotlib . colors . Normalize ` from a set of kwargs Returns norm , kwargs the formatted ` Normalize ` instance , and the remaining keywords"""
norm = kwargs . pop ( 'norm' , current ) or 'linear' vmin = kwargs . pop ( 'vmin' , None ) vmax = kwargs . pop ( 'vmax' , None ) clim = kwargs . pop ( 'clim' , ( vmin , vmax ) ) or ( None , None ) clip = kwargs . pop ( 'clip' , None ) if norm == 'linear' : norm = colors . Normalize ( ) elif norm == 'log' : norm...
def open ( self ) : """Open the window ."""
self . _window = Window ( caption = self . caption , height = self . height , width = self . width , vsync = False , resizable = True , )
def square_root ( n , epsilon = 0.001 ) : """Return square root of n , with maximum absolute error epsilon"""
guess = n / 2 while abs ( guess * guess - n ) > epsilon : guess = ( guess + ( n / guess ) ) / 2 return guess
def __get_valid_form_data_elements ( self , soup ) : """Get all valid form input elements . Note : An element is valid when the value can be updated client - side and the element has a name attribute . Args : soup ( obj ) : The BeautifulSoup form . Returns : list ( obj ) : Soup elements ."""
elements = [ ] for element in soup . find_all ( [ "input" , "button" , "textarea" , "select" ] ) : if element . has_attr ( "name" ) : elements . append ( element ) return elements
def refresh_console ( self , console : tcod . console . Console ) -> None : """Update an Image created with : any : ` tcod . image _ from _ console ` . The console used with this function should have the same width and height as the Console given to : any : ` tcod . image _ from _ console ` . The font width a...
lib . TCOD_image_refresh_console ( self . image_c , _console ( console ) )
def _post_login_page ( self ) : """Login to Janrain ."""
# Prepare post data data = { "form" : "signInForm" , "client_id" : JANRAIN_CLIENT_ID , "redirect_uri" : "https://www.fido.ca/pages/#/" , "response_type" : "token" , "locale" : "en-US" , "userID" : self . username , "currentPassword" : self . password , } # HTTP request try : raw_res = yield from self . _session . p...
def place_bid ( self , owner_id , bid ) : """Submits a bid for this tick for current player . This is not a guarantee that it will be accepted ! If other players submit a higher bid this same tick , the bid won ' t be counted . Try again next tick if it ' s not too high ! : param int owner _ id : id of owner ...
if self . state != AuctionState . BID : raise InvalidActionError ( "Bid was attempted, but it is not currently time to submit bids." ) elif self . bid >= bid : raise InvalidActionError ( "Bid amount " + str ( bid ) + " must be greater than current bid of " + str ( self . bid ) ) elif not self . owners [ owner_i...
def fit_transform ( self , X , y , step_size = 0.1 , init_weights = None , warm_start = False ) : """Fit optimizer to X , then transforms X . See ` fit ` and ` transform ` for further explanation ."""
self . fit ( X = X , y = y , step_size = step_size , init_weights = init_weights , warm_start = warm_start ) return self . transform ( X = X )
def _ParseEntryObjectOffsets ( self , file_object , file_offset ) : """Parses entry array objects for the offset of the entry objects . Args : file _ object ( dfvfs . FileIO ) : a file - like object . file _ offset ( int ) : offset of the first entry array object relative to the start of the file - like obj...
entry_array_object = self . _ParseEntryArrayObject ( file_object , file_offset ) entry_object_offsets = list ( entry_array_object . entry_object_offsets ) while entry_array_object . next_entry_array_offset != 0 : entry_array_object = self . _ParseEntryArrayObject ( file_object , entry_array_object . next_entry_arra...
def camelcase_to_underscores ( argument ) : '''Converts a camelcase param like theNewAttribute to the equivalent python underscore variable like the _ new _ attribute'''
result = '' prev_char_title = True if not argument : return argument for index , char in enumerate ( argument ) : try : next_char_title = argument [ index + 1 ] . istitle ( ) except IndexError : next_char_title = True upper_to_lower = char . istitle ( ) and not next_char_title lower_...
def compile_bundle_entry ( self , spec , entry ) : """Handler for each entry for the bundle method of the compile process . This copies the source file or directory into the build directory ."""
modname , source , target , modpath = entry bundled_modpath = { modname : modpath } bundled_target = { modname : target } export_module_name = [ ] if isfile ( source ) : export_module_name . append ( modname ) copy_target = join ( spec [ BUILD_DIR ] , target ) if not exists ( dirname ( copy_target ) ) : ...
def _parse_metadata ( self , message ) : '''Parse incoming messages to build metadata dict Lots of ' if ' statements . It sucks , I know . Args : message ( dict ) : JSON dump of message sent from Slack Returns : Legobot . Metadata'''
# Try to handle all the fields of events we care about . metadata = Metadata ( source = self . actor_urn ) . __dict__ metadata [ 'thread_ts' ] = message . get ( 'thread_ts' ) if 'presence' in message : metadata [ 'presence' ] = message [ 'presence' ] if 'text' in message : metadata [ 'text' ] = message [ 'text'...
def summarize ( text : str , n : int , engine : str = "frequency" , tokenizer : str = "newmm" ) -> List [ str ] : """Thai text summarization : param str text : text to be summarized : param int n : number of sentences to be included in the summary : param str engine : text summarization engine : param str t...
sents = [ ] if engine == "frequency" : sents = FrequencySummarizer ( ) . summarize ( text , n , tokenizer ) else : # if engine not found , return first n sentences sents = sent_tokenize ( text ) [ : n ] return sents
def gotoNext ( self ) : """Goes to the next date based on the current mode and date ."""
scene = self . scene ( ) date = scene . currentDate ( ) # go forward a day if ( scene . currentMode ( ) == scene . Mode . Day ) : scene . setCurrentDate ( date . addDays ( 1 ) ) # go forward a week elif ( scene . currentMode ( ) == scene . Mode . Week ) : scene . setCurrentDate ( date . addDays ( 7 ) ) # go for...
def set_temperature ( self , temperature , rate , delay = 1 ) : """Performs a temperature scan . Measures until the target temperature is reached . : param measure : A callable called repeatedly until stability at target temperature is reached . : param temperature : The target temperature in kelvin . : p...
self . scan_temperature ( lambda : None , temperature , rate , delay )
def geometry ( self , geometry ) : """sets the geometry value"""
if isinstance ( geometry , AbstractGeometry ) : self . _geomObject = geometry self . _geomType = geometry . type elif arcpyFound : wkid = None wkt = None if ( hasattr ( geometry , 'spatialReference' ) and geometry . spatialReference is not None ) : if ( hasattr ( geometry . spatialReference ...
def get_inputs ( node , kwargs ) : """Helper function to get inputs"""
name = node [ "name" ] proc_nodes = kwargs [ "proc_nodes" ] index_lookup = kwargs [ "index_lookup" ] inputs = node [ "inputs" ] attrs = node . get ( "attrs" , { } ) input_nodes = [ ] for ip in inputs : input_node_id = index_lookup [ ip [ 0 ] ] input_nodes . append ( proc_nodes [ input_node_id ] . name ) return ...
def transition_run ( self , pipeline_key , blocking_slot_keys = None , fanned_out_pipelines = None , pipelines_to_run = None ) : """Marks an asynchronous or generator pipeline as running . Does nothing if the pipeline is no longer in a runnable state . Args : pipeline _ key : The db . Key of the _ PipelineRec...
def txn ( ) : pipeline_record = db . get ( pipeline_key ) if pipeline_record is None : logging . warning ( 'Pipeline ID "%s" cannot be marked as run. ' 'Does not exist.' , pipeline_key . name ( ) ) raise db . Rollback ( ) if pipeline_record . status != _PipelineRecord . WAITING : log...
def target_sdp_state ( self , state ) : """Update the target state of SDP ."""
LOG . info ( 'Setting SDP target state to %s' , state ) if self . _sdp_state . current_state == state : LOG . info ( 'Target state ignored, SDP is already "%s"!' , state ) if state == 'on' : self . set_state ( DevState . ON ) if state == 'off' : self . set_state ( DevState . OFF ) if state == 'standby' : ...
def _transform_snapshot ( raw_snapshot : str , storage : SQLiteStorage , cache : BlockHashCache , ) -> str : """Upgrades a single snapshot by adding the blockhash to it and to any pending transactions"""
snapshot = json . loads ( raw_snapshot ) block_number = int ( snapshot [ 'block_number' ] ) snapshot [ 'block_hash' ] = cache . get ( block_number ) pending_transactions = snapshot [ 'pending_transactions' ] new_pending_transactions = [ ] for transaction_data in pending_transactions : if 'raiden.transfer.events.Con...
def _exclusion_indices_for_range ( self , start_idx , end_idx ) : """Returns List of tuples of ( start , stop ) which represent the ranges of minutes which should be excluded when a market minute window is requested ."""
itree = self . _minute_exclusion_tree if itree . overlaps ( start_idx , end_idx ) : ranges = [ ] intervals = itree [ start_idx : end_idx ] for interval in intervals : ranges . append ( interval . data ) return sorted ( ranges ) else : return None
def find ( self , soup ) : '''Yield tags matching the tag criterion from a soup . There is no need to override this if you are satisfied with finding tags that match match _ criterion . Args : soup : A BeautifulSoup to search through . Yields : BeautifulSoup Tags that match the criterion .'''
for tag in soup . recursiveChildGenerator ( ) : if self . match_criterion ( tag ) : yield tag
def pretty_render ( data , format = 'text' , indent = 0 ) : """Render a dict based on a format"""
if format == 'json' : return render_json ( data ) elif format == 'html' : return render_html ( data ) elif format == 'xml' : return render_xml ( data ) else : return dict_to_plaintext ( data , indent = indent )
def make_zoho_blueprint ( client_id = None , client_secret = None , scope = None , redirect_url = None , offline = False , redirect_to = None , login_url = None , session_class = None , storage = None , reprompt_consent = False , ) : """Make a blueprint for authenticating with Zoho using OAuth 2 . This requires a...
scope = scope or [ "ZohoCRM.users.all" ] base_url = "https://www.zohoapis.com/" client = ZohoWebClient ( client_id , token_type = ZOHO_TOKEN_HEADER ) authorization_url_params = { } authorization_url_params [ "access_type" ] = "offline" if offline else "online" if reprompt_consent : authorization_url_params [ "promp...
def setup ( console = False , port = None , menu = True ) : """Setup integration Registers Pyblish for Maya plug - ins and appends an item to the File - menu Arguments : console ( bool ) : Display console with GUI port ( int , optional ) : Port from which to start looking for an available port to connect ...
if self . _has_been_setup : teardown ( ) register_plugins ( ) register_host ( ) if menu : add_to_filemenu ( ) self . _has_menu = True self . _has_been_setup = True print ( "pyblish: Loaded successfully." )
def update ( self , resource , timeout = - 1 ) : """Updates a Logical Switch . Args : resource ( dict ) : Object to update . timeout : Timeout in seconds . Wait for task completion by default . The timeout does not abort the operation in OneView , just stop waiting for its completion . Returns : dict ...
self . __set_default_values ( resource ) uri = self . _client . build_uri ( resource [ 'logicalSwitch' ] [ 'uri' ] ) return self . _client . update ( resource , uri = uri , timeout = timeout )
def pretty_json ( obj ) : """Print JSON with indentation and colours : param obj : the object to print - can be a dict or a string"""
if isinstance ( obj , string_types ) : try : obj = json . loads ( obj ) except ValueError : raise ClientException ( "`obj` is not a json string" ) json_str = json . dumps ( obj , sort_keys = True , indent = 2 ) print ( highlight ( json_str , JsonLexer ( ) , TerminalFormatter ( ) ) )
def is_insecure_platform ( ) : """Checks if the current system is missing an SSLContext object"""
v = sys . version_info if v . major == 3 : return False # Python 2 issue if v . major == 2 and v . minor == 7 and v . micro >= 9 : return False # > = 2.7.9 includes the new SSL updates try : import OpenSSL # noqa import ndg # noqa import pyasn1 # noqa except ImportError : pass return...