signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def _redis_connection_settings ( self ) : """Return a dictionary of redis connection settings ."""
return { config . HOST : self . settings . get ( config . HOST , self . _REDIS_HOST ) , config . PORT : self . settings . get ( config . PORT , self . _REDIS_PORT ) , 'selected_db' : self . settings . get ( config . DB , self . _REDIS_DB ) }
def save_plot ( axes = "gca" , path = None ) : """Saves the figure in my own ascii format"""
global line_attributes # choose a path to save to if path == None : path = _s . dialogs . Save ( "*.plot" , default_directory = "save_plot_default_directory" ) if path == "" : print ( "aborted." ) return if not path . split ( "." ) [ - 1 ] == "plot" : path = path + ".plot" f = file ( path , "w" ) # if n...
def _write ( self , ret ) : """This function needs to correspond to this : https : / / github . com / saltstack / salt / blob / develop / salt / returners / redis _ return . py # L88"""
self . redis . set ( '{0}:{1}' . format ( ret [ 'id' ] , ret [ 'jid' ] ) , json . dumps ( ret ) ) self . redis . lpush ( '{0}:{1}' . format ( ret [ 'id' ] , ret [ 'fun' ] ) , ret [ 'jid' ] ) self . redis . sadd ( 'minions' , ret [ 'id' ] ) self . redis . sadd ( 'jids' , ret [ 'jid' ] )
def requestTimedOut ( self , reply ) : """Trap the timeout . In Async mode requestTimedOut is called after replyFinished"""
# adapt http _ call _ result basing on receiving qgs timer timout signal self . exception_class = RequestsExceptionTimeout self . http_call_result . exception = RequestsExceptionTimeout ( "Timeout error" )
def prepare_date ( data , schema ) : """Converts datetime . date to int timestamp"""
if isinstance ( data , datetime . date ) : return data . toordinal ( ) - DAYS_SHIFT else : return data
def add_icon_widget ( self , ref , x = 1 , y = 1 , name = "heart" ) : """Add Icon Widget"""
if ref not in self . widgets : widget = IconWidget ( screen = self , ref = ref , x = x , y = y , name = name ) self . widgets [ ref ] = widget return self . widgets [ ref ]
def make_anchor_id ( self ) : """Return string to use as URL anchor for this comment ."""
result = re . sub ( '[^a-zA-Z0-9_]' , '_' , self . user + '_' + self . timestamp ) return result
def _is_current ( self , file_path , zip_path ) : """Return True if the file _ path is current for this zip _ path"""
timestamp , size = self . _get_date_and_size ( self . zipinfo [ zip_path ] ) if not os . path . isfile ( file_path ) : return False stat = os . stat ( file_path ) if stat . st_size != size or stat . st_mtime != timestamp : return False # check that the contents match zip_contents = self . loader . get_data ( zi...
def isa ( cls , protocol ) : """Does the type ' cls ' participate in the ' protocol ' ?"""
if not isinstance ( cls , type ) : raise TypeError ( "First argument to isa must be a type. Got %s." % repr ( cls ) ) if not isinstance ( protocol , type ) : raise TypeError ( ( "Second argument to isa must be a type or a Protocol. " "Got an instance of %r." ) % type ( protocol ) ) return issubclass ( cls , pro...
def make_multisig_segwit_wallet ( m , n ) : """Create a bundle of information that can be used to generate an m - of - n multisig witness script ."""
pks = [ ] for i in xrange ( 0 , n ) : pk = BitcoinPrivateKey ( compressed = True ) . to_wif ( ) pks . append ( pk ) return make_multisig_segwit_info ( m , pks )
def build_help_html ( ) : """Build the help HTML using the shared resources ."""
remove_from_help = [ "not-in-help" , "copyright" ] if sys . platform in [ "win32" , "cygwin" ] : remove_from_help . extend ( [ "osx" , "linux" ] ) elif sys . platform == "darwin" : remove_from_help . extend ( [ "linux" , "windows" , "linux-windows" ] ) else : remove_from_help . extend ( [ "osx" , "windows" ...
def get_tasklogger ( name = "TaskLogger" ) : """Get a TaskLogger object Parameters logger : str , optional ( default : " TaskLogger " ) Unique name of the logger to retrieve Returns logger : TaskLogger"""
try : return logging . getLogger ( name ) . tasklogger except AttributeError : return logger . TaskLogger ( name )
def get_directors ( self ) : """Return all directors for this company"""
directors = Director . objects . filter ( company = self , is_current = True ) . select_related ( 'person' ) return directors
def from_diff ( diff , options = None , cwd = None ) : """Create a Radius object from a diff rather than a reposistory ."""
return RadiusFromDiff ( diff = diff , options = options , cwd = cwd )
def get_existing_path ( path , topmost_path = None ) : """Get the longest parent path in ` path ` that exists . If ` path ` exists , it is returned . Args : path ( str ) : Path to test topmost _ path ( str ) : Do not test this path or above Returns : str : Existing path , or None if no path was found ."...
prev_path = None if topmost_path : topmost_path = os . path . normpath ( topmost_path ) while True : if os . path . exists ( path ) : return path path = os . path . dirname ( path ) if path == prev_path : return None if topmost_path and os . path . normpath ( path ) == topmost_path :...
def candidate_foundation ( candidate_type , candidate_transport , base_address ) : """See RFC 5245 - 4.1.1.3 . Computing Foundations"""
key = '%s|%s|%s' % ( candidate_type , candidate_transport , base_address ) return hashlib . md5 ( key . encode ( 'ascii' ) ) . hexdigest ( )
def stack ( self , k = 5 , stratify = False , shuffle = True , seed = 100 , full_test = True , add_diff = False ) : """Stacks sequence of models . Parameters k : int , default 5 Number of folds . stratify : bool , default False shuffle : bool , default True seed : int , default 100 full _ test : bool ...
result_train = [ ] result_test = [ ] y = None for model in self . models : result = model . stack ( k = k , stratify = stratify , shuffle = shuffle , seed = seed , full_test = full_test ) train_df = pd . DataFrame ( result . X_train , columns = generate_columns ( result . X_train , model . name ) ) test_df ...
async def _on_rpc_command ( self , event ) : """Received an RPC command that we should execute ."""
payload = event [ 'payload' ] rpc_id = payload [ 'rpc_id' ] tag = payload [ 'response_uuid' ] args = payload [ 'payload' ] result = 'success' response = b'' if self . _rpc_dispatcher is None or not self . _rpc_dispatcher . has_rpc ( rpc_id ) : result = 'rpc_not_found' else : try : response = self . _rpc...
def prettyPrintPacket ( pkt ) : """not done"""
s = 'packet ID: {} instr: {} len: {}' . format ( pkt [ 4 ] , pkt [ 7 ] , int ( ( pkt [ 6 ] << 8 ) + pkt [ 5 ] ) ) if len ( s ) > 10 : params = pkt [ 8 : - 2 ] s += ' params: {}' . format ( params ) return s
def format_op_row ( ipFile , totLines , totWords , uniqueWords ) : """Format the output row with stats"""
txt = os . path . basename ( ipFile ) . ljust ( 36 ) + ' ' txt += str ( totLines ) . rjust ( 7 ) + ' ' txt += str ( totWords ) . rjust ( 7 ) + ' ' txt += str ( len ( uniqueWords ) ) . rjust ( 7 ) + ' ' return txt
def readline ( self , size = None ) : """Read a single line from rfile buffer and return it . Args : size ( int ) : minimum amount of data to read Returns : bytes : One line from rfile ."""
if size is not None : data = self . rfile . readline ( size ) self . bytes_read += len ( data ) self . _check_length ( ) return data # User didn ' t specify a size . . . # We read the line in chunks to make sure it ' s not a 100MB line ! res = [ ] while True : data = self . rfile . readline ( 256 ) ...
def remove_resource ( self , path ) : """Helper function to remove resources . : param path : the path for the unwanted resource : rtype : the removed object"""
path = path . strip ( "/" ) paths = path . split ( "/" ) actual_path = "" i = 0 for p in paths : i += 1 actual_path += "/" + p try : res = self . root [ actual_path ] except KeyError : res = None if res is not None : del ( self . root [ actual_path ] ) return res
def order_of_magnitude_str ( num , base = 10.0 , prefix_list = None , exponent_list = None , suffix = '' , prefix = None ) : """TODO : Rewrite byte _ str to use this func Returns : str"""
abs_num = abs ( num ) # Find the right magnidue for prefix_ , exponent in zip ( prefix_list , exponent_list ) : # Let user request the prefix requested = False if prefix is not None : if prefix != prefix_ : continue requested = True # Otherwise find the best prefix magnitude ...
def _do_perspective_warp ( c : FlowField , targ_pts : Points , invert = False ) : "Apply warp to ` targ _ pts ` from ` _ orig _ pts ` to ` c ` ` FlowField ` ."
if invert : return _apply_perspective ( c , _find_coeffs ( targ_pts , _orig_pts ) ) return _apply_perspective ( c , _find_coeffs ( _orig_pts , targ_pts ) )
def _get_sd ( file_descr ) : """Get streamdescriptor matching file _ descr fileno . : param file _ descr : file object : return : StreamDescriptor or None"""
for stream_descr in NonBlockingStreamReader . _streams : if file_descr == stream_descr . stream . fileno ( ) : return stream_descr return None
def _get_matchable_segments ( segments ) : """Performs a depth - first search of the segment tree to get all matchable segments ."""
for subsegment in segments : if isinstance ( subsegment , Token ) : break # No tokens allowed next to segments if isinstance ( subsegment , Segment ) : if isinstance ( subsegment , MatchableSegment ) : yield subsegment for matchable_subsegment in _get_matchable_segmen...
def import_subview ( self , idx , subview ) : """Add the given subview to the corpus . Args : idx ( str ) : An idx that is unique in the corpus for identifying the subview . If already a subview exists with the given id it will be overridden . subview ( Subview ) : The subview to add ."""
subview . corpus = self self . _subviews [ idx ] = subview
def p_ExtendedAttributeNamedArgList ( p ) : """ExtendedAttributeNamedArgList : IDENTIFIER " = " IDENTIFIER " ( " ArgumentList " ) " """
p [ 0 ] = model . ExtendedAttribute ( name = p [ 1 ] , value = model . ExtendedAttributeValue ( name = p [ 3 ] , arguments = p [ 5 ] ) )
def _delete_chars ( self , value ) : """Deletes the specified number of charachters ."""
value = int ( value ) if value <= 0 : value = 1 for i in range ( value ) : self . _cursor . deleteChar ( ) self . _text_edit . setTextCursor ( self . _cursor ) self . _last_cursor_pos = self . _cursor . position ( )
def publish_page ( page , languages ) : """Publish a CMS page in all given languages ."""
for language_code , lang_name in iter_languages ( languages ) : url = page . get_absolute_url ( ) if page . publisher_is_draft : page . publish ( language_code ) log . info ( 'page "%s" published in %s: %s' , page , lang_name , url ) else : log . info ( 'published page "%s" already e...
def create ( self , data ) : """Create a new component"""
response = self . http . post ( str ( self ) , json = data , auth = self . auth ) response . raise_for_status ( ) return response . json ( )
def check_nonparametric_sources ( fname , smodel , investigation_time ) : """: param fname : full path to a source model file : param smodel : source model object : param investigation _ time : investigation _ time to compare with in the case of nonparametric sources : returns : the nonparametric so...
# NonParametricSeismicSources np = [ src for sg in smodel . src_groups for src in sg if hasattr ( src , 'data' ) ] if np and smodel . investigation_time != investigation_time : raise ValueError ( 'The source model %s contains an investigation_time ' 'of %s, while the job.ini has %s' % ( fname , smodel . investigati...
def apply_dict_of_variables_vfunc ( func , * args , signature , join = 'inner' , fill_value = None ) : """Apply a variable level function over dicts of DataArray , DataArray , Variable and ndarray objects ."""
args = [ _as_variables_or_variable ( arg ) for arg in args ] names = join_dict_keys ( args , how = join ) grouped_by_name = collect_dict_values ( args , names , fill_value ) result_vars = OrderedDict ( ) for name , variable_args in zip ( names , grouped_by_name ) : result_vars [ name ] = func ( * variable_args ) if...
def get_top_live_games ( self , partner = '' , ** kwargs ) : """Returns a dictionary that includes top MMR live games : param partner : ( int , optional ) : return : dictionary of prize pools , see : doc : ` responses < / responses > `"""
if 'partner' not in kwargs : kwargs [ 'partner' ] = partner url = self . __build_url ( urls . GET_TOP_LIVE_GAME , ** kwargs ) req = self . executor ( url ) if self . logger : self . logger . info ( 'URL: {0}' . format ( url ) ) if not self . __check_http_err ( req . status_code ) : return response . build (...
def clear ( self ) : """Clears the dict ."""
self . __values . clear ( ) self . __access_keys = [ ] self . __modified_times . clear ( )
def load_scripts ( self ) : """opens file dialog to load scripts into gui"""
# update scripts so that current settings do not get lost for index in range ( self . tree_scripts . topLevelItemCount ( ) ) : script_item = self . tree_scripts . topLevelItem ( index ) self . update_script_from_item ( script_item ) dialog = LoadDialog ( elements_type = "scripts" , elements_old = self . scripts...
def connect ( self , dests = [ ] , name = None , id = '' , props = { } ) : '''Connect this port to other DataPorts . After the connection has been made , a delayed reparse of the connections for this and the destination port will be triggered . @ param dests A list of the destination Port objects . Must be pr...
# Data ports can only connect to opposite data ports with self . _mutex : new_props = props . copy ( ) ptypes = [ d . porttype for d in dests ] if self . porttype == 'DataInPort' : if 'DataOutPort' not in ptypes : raise exceptions . WrongPortTypeError if self . porttype == 'DataOutPo...
def control_valve_choke_P_l ( Psat , Pc , FL , P1 = None , P2 = None , disp = True ) : r'''Calculates either the upstream or downstream pressure at which choked flow though a liquid control valve occurs , given either a set upstream or downstream pressure . Implements an analytical solution of the needed equa...
FF = FF_critical_pressure_ratio_l ( Psat = Psat , Pc = Pc ) Pmin_absolute = FF * Psat if P2 is None : ans = P2 = FF * FL * FL * Psat - FL * FL * P1 + P1 elif P1 is None : ans = P1 = ( FF * FL * FL * Psat - P2 ) / ( FL * FL - 1.0 ) else : raise Exception ( 'Either P1 or P2 needs to be specified' ) if P2 > P1...
def quality ( self , key ) : """Returns the quality of the key . . . versionadded : : 0.6 In previous versions you had to use the item - lookup syntax ( eg : ` ` obj [ key ] ` ` instead of ` ` obj . quality ( key ) ` ` )"""
for item , quality in self : if self . _value_matches ( key , item ) : return quality return 0
def compile ( schema , pointer , context , scope = None ) : """Compiles schema with ` JSON Schema ` _ draft - 04. : param schema : obj to compile : type schema : Mapping : param pointer : uri of the schema : type pointer : Pointer , str : param context : context of this schema : type context : Context ...
schm = deepcopy ( schema ) scope = urljoin ( scope or str ( pointer ) , schm . pop ( 'id' , None ) ) if '$ref' in schema : return ReferenceValidator ( urljoin ( scope , schema [ '$ref' ] ) , context ) attrs = { } if 'additionalItems' in schm : subpointer = pointer_join ( pointer , 'additionalItems' ) attrs ...
def reference_handler ( self , iobject , fact , attr_info , add_fact_kargs ) : """Handler for facts that contain a reference to a fact . As shown below in the handler list , this handler is called when a attribute with key ' @ idref ' on the fact ' s node is detected - - this attribute signifies that this fac...
logger . debug ( "XXX Found reference with %s" % attr_info ) if 'idref' in attr_info : ref_key = 'idref' ( namespace , namespace_uri , uid ) = self . split_qname ( attr_info [ ref_key ] ) elif fact [ 'attribute' ] and fact [ 'attribute' ] == 'phase_id' : if fact [ 'term' ] == '' : return True el...
def _get_attachment_data ( self , id , filename ) : """Retrieve the contents of a specific attachment ( identified by filename ) ."""
uri = '/' . join ( [ self . base_url , self . name , id , 'Attachments' , filename ] ) return uri , { } , 'get' , None , None , False
def coordination_geometry_symmetry_measures_sepplane_optim ( self , coordination_geometry , points_perfect = None , nb_set = None , optimization = None ) : """Returns the symmetry measures of a given coordination _ geometry for a set of permutations depending on the permutation setup . Depending on the parameters...
csms = [ ] permutations = [ ] algos = [ ] local2perfect_maps = [ ] perfect2local_maps = [ ] for algo in coordination_geometry . algorithms : if algo . algorithm_type == SEPARATION_PLANE : cgsm = self . coordination_geometry_symmetry_measures_separation_plane_optim ( coordination_geometry , algo , points_per...
def make_empty_table ( row_count , column_count ) : """Make an empty table Parameters row _ count : int The number of rows in the new table column _ count : int The number of columns in the new table Returns table : list of lists of str Each cell will be an empty str ( ' ' )"""
table = [ ] while row_count > 0 : row = [ ] for column in range ( column_count ) : row . append ( '' ) table . append ( row ) row_count -= 1 return table
def output ( self ) : """Return a 20 - byte hash corresponding to this script ( or None if not applicable ) ."""
hash160 = self . _script_info . get ( "hash160" , None ) if hash160 : yield ( "hash160" , b2h ( hash160 ) , None ) address = self . address ( ) yield ( "address" , address , "%s address" % self . _network . network_name ) yield ( "%s_address" % self . _network . symbol , address , "legacy" )
def state_args ( id_ , state , high ) : '''Return a set of the arguments passed to the named state'''
args = set ( ) if id_ not in high : return args if state not in high [ id_ ] : return args for item in high [ id_ ] [ state ] : if not isinstance ( item , dict ) : continue if len ( item ) != 1 : continue args . add ( next ( iter ( item ) ) ) return args
def _resolve_index ( self , mixed ) : """Find the index based on various strategies for a node , probably an input or output of chain . Supported inputs are indexes , node values or names ."""
if mixed is None : return None if type ( mixed ) is int or mixed in self . edges : return mixed if isinstance ( mixed , str ) and mixed in self . named : return self . named [ mixed ] if mixed in self . nodes : return self . nodes . index ( mixed ) raise ValueError ( "Cannot find node matching {!r}." . ...
def finetune_classification_cnn ( config ) : """Main function ."""
# read params dataset = config [ 'dataset' ] x_names = config [ 'x_names' ] y_name = config [ 'y_name' ] model_dir = config [ 'model_dir' ] debug = config [ 'debug' ] num_classes = None if 'num_classes' in config . keys ( ) : num_classes = config [ 'num_classes' ] batch_size = config [ 'training' ] [ 'batch_size' ]...
def omega ( self , structure , n , u ) : """Finds directional frequency contribution to the heat capacity from direction and polarization Args : structure ( Structure ) : Structure to be used in directional heat capacity determination n ( 3x1 array - like ) : direction for Cv determination u ( 3x1 array...
l0 = np . dot ( np . sum ( structure . lattice . matrix , axis = 0 ) , n ) l0 *= 1e-10 # in A weight = float ( structure . composition . weight ) * 1.66054e-27 # in kg vol = structure . volume * 1e-30 # in m ^ 3 vel = ( 1e9 * self [ 0 ] . einsum_sequence ( [ n , u , n , u ] ) / ( weight / vol ) ) ** 0.5 return vel / l0
def dump_part ( part , total_segments = None ) : """' part ' may be the hash _ key if we are dumping just a few hash _ keys - else it will be the segment number"""
try : connection = Connection ( host = config [ 'host' ] , region = config [ 'region' ] ) filename = "." . join ( [ config [ 'table_name' ] , str ( part ) , "dump" ] ) if config [ 'compress' ] : opener = gzip . GzipFile filename += ".gz" else : opener = open dumper = BatchDum...
def show_human ( ) : """Curses terminal with standard outputs"""
form = 'RAW' units = 'raw' data_window = curses . newwin ( 19 , 39 , 0 , 0 ) sat_window = curses . newwin ( 14 , 39 , 0 , 40 ) device_window = curses . newwin ( 6 , 39 , 13 , 40 ) packet_window = curses . newwin ( 7 , 79 , 19 , 0 ) for new_data in gpsd_socket : if new_data : data_stream . unpack ( new_data ...
def viewinfo ( self , postinfo ) : '''In infor .'''
self . redirect_kind ( postinfo ) if DB_CFG [ 'kind' ] == 's' : cat_enum1 = [ ] else : ext_catid = postinfo . extinfo [ 'def_cat_uid' ] if 'def_cat_uid' in postinfo . extinfo else '' ext_catid2 = postinfo . extinfo [ 'def_cat_uid' ] if 'def_cat_uid' in postinfo . extinfo else None cat_enum1 = MCategory ...
def _parse_trigger ( self , trigger_clause ) : """Parse a named event or explicit stream trigger into a TriggerDefinition ."""
cond = trigger_clause [ 0 ] named_event = None explicit_stream = None explicit_trigger = None # Identifier parse tree is Group ( Identifier ) if cond . getName ( ) == 'identifier' : named_event = cond [ 0 ] elif cond . getName ( ) == 'stream_trigger' : trigger_type = cond [ 0 ] stream = cond [ 1 ] oper ...
def mouseMoveEvent ( self , event ) : """Handle the mouse move event for a drag operation ."""
self . declaration . mouse_move_event ( event ) super ( QtGraphicsView , self ) . mouseMoveEvent ( event )
def inverse ( self ) : """return index array that maps unique values back to original space . unique [ inverse ] = = keys"""
inv = np . empty ( self . size , np . int ) inv [ self . sorter ] = self . sorted_group_rank_per_key return inv
def gateway_by_type ( self , type = None , on_network = None ) : # @ ReservedAssignment """Return gateways for the specified node . You can also specify type to find only gateways of a specific type . Valid types are : bgp _ peering , netlink , ospfv2 _ area . : param RoutingNode self : the routing node to ch...
gateways = route_level ( self , 'gateway' ) if not type : for gw in gateways : yield gw else : for node in gateways : # TODO : Change to type = = node . related _ element _ type when # only supporting SMC > = 6.4 if type == node . routing_node_element . typeof : # If the parent is level inte...
def _populate_profile_from_attributes ( self , profile ) : """Populate the given profile object from AUTH _ LDAP _ PROFILE _ ATTR _ MAP . Returns True if the profile was modified ."""
save_profile = False for field , attr in self . settings . PROFILE_ATTR_MAP . items ( ) : try : # user _ attrs is a hash of lists of attribute values setattr ( profile , field , self . attrs [ attr ] [ 0 ] ) save_profile = True except Exception : logger . warning ( "%s does not have a va...
def add ( self , key , value ) : """Add an entry to a list preference Add ` value ` to the list of entries for the ` key ` preference ."""
if not key in self . prefs : self . prefs [ key ] = [ ] self . prefs [ key ] . append ( value )
def upload_file ( self , session , output , serverdir ) : """Upload a file to koji : return : str , pathname on server"""
name = output . metadata [ 'filename' ] self . log . debug ( "uploading %r to %r as %r" , output . file . name , serverdir , name ) kwargs = { } if self . blocksize is not None : kwargs [ 'blocksize' ] = self . blocksize self . log . debug ( "using blocksize %d" , self . blocksize ) upload_logger = KojiUploadLo...
def encrypt_and_hash ( self , plaintext : bytes ) -> bytes : """Sets ciphertext = EncryptWithAd ( h , plaintext ) , calls MixHash ( ciphertext ) , and returns ciphertext . Note that if k is empty , the EncryptWithAd ( ) call will set ciphertext equal to plaintext . : param plaintext : bytes sequence : return ...
ciphertext = self . cipher_state . encrypt_with_ad ( self . h , plaintext ) self . mix_hash ( ciphertext ) return ciphertext
def generate_statistics_subparser ( subparsers ) : """Adds a sub - command parser to ` subparsers ` to generate statistics from a set of results ."""
parser = subparsers . add_parser ( 'stats' , description = constants . STATISTICS_DESCRIPTION , formatter_class = ParagraphFormatter , help = constants . STATISTICS_HELP ) parser . set_defaults ( func = generate_statistics ) utils . add_common_arguments ( parser ) utils . add_corpus_arguments ( parser ) parser . add_ar...
def get_interpolated_value ( self , energy , integrated = False ) : """Returns the COHP for a particular energy . Args : energy : Energy to return the COHP value for ."""
inter = { } for spin in self . cohp : if not integrated : inter [ spin ] = get_linear_interpolated_value ( self . energies , self . cohp [ spin ] , energy ) elif self . icohp is not None : inter [ spin ] = get_linear_interpolated_value ( self . energies , self . icohp [ spin ] , energy ) els...
def get_middleware ( exclude = ( ) , append = ( ) , current = { 'middleware' : MIDDLEWARE_CLASSES } ) : """Returns MIDDLEWARE _ CLASSES without the middlewares listed in exclude and with the middlewares listed in append . The use of a mutable dict is intentional , in order to preserve the state of the MIDDLEW...
current [ 'middleware' ] = tuple ( [ m for m in current [ 'middleware' ] if m not in exclude ] ) + tuple ( append ) return current [ 'middleware' ]
def which_api_version ( self , api_call ) : """Return QualysGuard API version for api _ call specified ."""
# Leverage patterns of calls to API methods . if api_call . endswith ( '.php' ) : # API v1. return 1 elif api_call . startswith ( 'api/2.0/' ) : # API v2. return 2 elif '/am/' in api_call : # Asset Management API . return 'am' elif '/was/' in api_call : # WAS API . return 'was' return False
def is_transaction_signer_authorized ( self , transactions , state_root , from_state ) : """Check the transaction signing key against the allowed transactor permissions . The roles being checked are the following , from first to last : " transactor . transaction _ signer . < TP _ Name > " " transactor . tra...
role = None if role is None : role = self . _cache . get_role ( "transactor.transaction_signer" , state_root , from_state ) if role is None : role = self . _cache . get_role ( "transactor" , state_root , from_state ) if role is None : policy_name = "default" else : policy_name = role . policy_name polic...
def to_datetime ( t ) : """Convert 6 - part time tuple into datetime object ."""
if t is None : return None # extract values year , mon , day , h , m , s = t # assume the values are valid try : return datetime ( year , mon , day , h , m , s ) except ValueError : pass # sanitize invalid values mday = ( 0 , 31 , 29 , 31 , 30 , 31 , 30 , 31 , 31 , 30 , 31 , 30 , 31 ) if mon < 1 : mon =...
def save ( self , * args , ** kwargs ) : """Kicks off celery task to re - save associated special coverages to percolator : param args : inline arguments ( optional ) : param kwargs : keyword arguments : return : ` bulbs . campaigns . Campaign `"""
campaign = super ( Campaign , self ) . save ( * args , ** kwargs ) save_campaign_special_coverage_percolator . delay ( self . tunic_campaign_id ) return campaign
def tenant_get ( tenant_id = None , name = None , profile = None , ** connection_args ) : '''Return a specific tenants ( keystone tenant - get ) CLI Examples : . . code - block : : bash salt ' * ' keystone . tenant _ get c965f79c4f864eaaa9c3b41904e67082 salt ' * ' keystone . tenant _ get tenant _ id = c965f...
kstone = auth ( profile , ** connection_args ) ret = { } if name : for tenant in getattr ( kstone , _TENANTS , None ) . list ( ) : if tenant . name == name : tenant_id = tenant . id break if not tenant_id : return { 'Error' : 'Unable to resolve tenant id' } tenant = getattr ( kst...
def dense_to_deeper_block ( dense_layer , weighted = True ) : '''deeper dense layer .'''
units = dense_layer . units weight = np . eye ( units ) bias = np . zeros ( units ) new_dense_layer = StubDense ( units , units ) if weighted : new_dense_layer . set_weights ( ( add_noise ( weight , np . array ( [ 0 , 1 ] ) ) , add_noise ( bias , np . array ( [ 0 , 1 ] ) ) ) ) return [ StubReLU ( ) , new_dense_laye...
def kindpath ( self , kind ) : """Returns a path to the resources for a given input kind . : param ` kind ` : The kind of input : - " ad " : Active Directory - " monitor " : Files and directories - " registry " : Windows Registry - " script " : Scripts - " splunktcp " : TCP , processed - " tcp " : TCP...
if kind in self . kinds : return UrlEncoded ( kind , skip_encode = True ) # Special cases elif kind == 'tcp' : return UrlEncoded ( 'tcp/raw' , skip_encode = True ) elif kind == 'splunktcp' : return UrlEncoded ( 'tcp/cooked' , skip_encode = True ) else : raise ValueError ( "No such kind on server: %s" % ...
def compile_with_symbol ( self , func , theano_args = None , owner = None ) : '''Compile the function with theano symbols'''
if theano_args is None : theano_args = [ ] # initialize the shared buffers upc = UpdateCollector ( ) # get the output symbols and other Theano options theano_ret = func ( * theano_args ) if owner is None else func ( owner , * theano_args ) # integrate the information of updates , givens and the other options out = ...
def get_orthology_matrix ( self , pid_cutoff = None , bitscore_cutoff = None , evalue_cutoff = None , filter_condition = 'OR' , remove_strains_with_no_orthology = True , remove_strains_with_no_differences = False , remove_genes_not_in_base_model = True ) : """Create the orthology matrix by finding best bidirectiona...
# TODO : document and test other cutoffs # Get the path to the reference genome r_file = self . reference_gempro . genome_path bbh_files = { } log . info ( 'Running bidirectional BLAST and finding best bidirectional hits (BBH)...' ) for strain_gempro in tqdm ( self . strains ) : g_file = strain_gempro . genome_path...
def format_units ( self , value , unit = "B" , optimal = 5 , auto = True , si = False ) : """Takes a value and formats it for user output , we can choose the unit to use eg B , MiB , kbits / second . This is mainly for use with bytes / bits it converts the value into a human readable form . It has various add...
UNITS = "KMGTPEZY" DECIMAL_SIZE = 1000 BINARY_SIZE = 1024 CUTOFF = 1000 can_round = False if unit : # try to guess the unit . Do we have a known prefix too it ? if unit [ 0 ] . upper ( ) in UNITS : index = UNITS . index ( unit [ 0 ] . upper ( ) ) + 1 post = unit [ 1 : ] si = len ( unit ) > 1...
def _init_metadata ( self ) : """stub"""
self . _attempts_metadata = { 'element_id' : Id ( self . my_osid_object_form . _authority , self . my_osid_object_form . _namespace , 'attempts' ) , 'element_label' : 'Attempts' , 'instructions' : 'Max number of student attempts' , 'required' : False , 'read_only' : False , 'linked' : False , 'array' : False , 'default...
def validate_proxy_ticket ( service , ticket , pgturl = None ) : """Validate a proxy ticket string . Return a 4 - tuple containing a ` ` ProxyTicket ` ` , an optional ` ` ProxyGrantingTicket ` ` and a list of proxies through which authentication proceeded , or a ` ` ValidationError ` ` if ticket validation fa...
logger . debug ( "Proxy validation request received for %s" % ticket ) pt = ProxyTicket . objects . validate_ticket ( ticket , service ) attributes = get_attributes ( pt . user , pt . service ) # Build a list of all services that proxied authentication , # in reverse order of which they were traversed proxies = [ pt . ...
def predict_and_score ( self , eval_instances , random = False , verbosity = 0 ) : '''Return most likely outputs and scores for the particular set of outputs given in ` eval _ instances ` , as a tuple . Return value should be equivalent to the default implementation of return ( self . predict ( eval _ instanc...
if hasattr ( self , '_using_default_separate' ) and self . _using_default_separate : raise NotImplementedError self . _using_default_combined = True return ( self . predict ( eval_instances , random = random , verbosity = verbosity ) , self . score ( eval_instances , verbosity = verbosity ) )
def get_num_names ( include_expired = False , proxy = None , hostport = None ) : """Get the number of names , optionally counting the expired ones Return { ' error ' : . . . } on failure"""
assert proxy or hostport , 'Need proxy or hostport' if proxy is None : proxy = connect_hostport ( hostport ) schema = { 'type' : 'object' , 'properties' : { 'count' : { 'type' : 'integer' , 'minimum' : 0 , } , } , 'required' : [ 'count' , ] , } count_schema = json_response_schema ( schema ) resp = { } try : if ...
def BinaryRoche ( r , D , q , F , Omega = 0.0 ) : r"""Computes a value of the asynchronous , eccentric Roche potential . If : envvar : ` Omega ` is passed , it computes the difference . The asynchronous , eccentric Roche potential is given by [ Wilson1979 ] _ . . math : : \ Omega = \ frac { 1 } { \ sqrt { x...
return 1.0 / sqrt ( r [ 0 ] * r [ 0 ] + r [ 1 ] * r [ 1 ] + r [ 2 ] * r [ 2 ] ) + q * ( 1.0 / sqrt ( ( r [ 0 ] - D ) * ( r [ 0 ] - D ) + r [ 1 ] * r [ 1 ] + r [ 2 ] * r [ 2 ] ) - r [ 0 ] / D / D ) + 0.5 * F * F * ( 1 + q ) * ( r [ 0 ] * r [ 0 ] + r [ 1 ] * r [ 1 ] ) - Omega
def pair_tree_creator ( meta_id ) : """Splits string into a pairtree path ."""
chunks = [ ] for x in range ( 0 , len ( meta_id ) ) : if x % 2 : continue if ( len ( meta_id ) - 1 ) == x : chunk = meta_id [ x ] else : chunk = meta_id [ x : x + 2 ] chunks . append ( chunk ) return os . sep + os . sep . join ( chunks ) + os . sep
def gff ( args ) : """% prog gff btabfile Convert btab file generated by AAT to gff3 format ."""
from jcvi . utils . range import range_minmax from jcvi . formats . gff import valid_gff_parent_child , valid_gff_type p = OptionParser ( gff . __doc__ ) p . add_option ( "--source" , default = None , help = "Specify GFF source." + " By default, it picks algorithm used to generate btab file." + " [default: %default]" )...
def load_frontends ( config , callback , internal_attributes ) : """Load all frontend modules specified in the config : type config : satosa . satosa _ config . SATOSAConfig : type callback : ( satosa . context . Context , satosa . internal . InternalData ) - > satosa . response . Response : type internal _...
frontend_modules = _load_plugins ( config . get ( "CUSTOM_PLUGIN_MODULE_PATHS" ) , config [ "FRONTEND_MODULES" ] , frontend_filter , config [ "BASE" ] , internal_attributes , callback ) logger . info ( "Setup frontends: %s" % [ frontend . name for frontend in frontend_modules ] ) return frontend_modules
def shuffle_step ( entries , step ) : '''Shuffle the step'''
answer = [ ] for i in range ( 0 , len ( entries ) , step ) : sub = entries [ i : i + step ] shuffle ( sub ) answer += sub return answer
def download_file ( self , remote_filename , local_filename = None ) : """Download file from github . Args : remote _ filename ( str ) : The name of the file as defined in git repository . local _ filename ( str , optional ) : Defaults to None . The name of the file as it should be be written to local files...
status = 'Failed' if local_filename is None : local_filename = remote_filename if not self . args . force and os . access ( local_filename , os . F_OK ) : if not self . _confirm_overwrite ( local_filename ) : self . _print_results ( local_filename , 'Skipped' ) return url = '{}{}' . format ( sel...
def force_update ( self ) : """Forces an update of the module ."""
if self . disabled or self . terminated or not self . enabled : return # clear cached _ until for each method to allow update for meth in self . methods : self . methods [ meth ] [ "cached_until" ] = time ( ) if self . config [ "debug" ] : self . _py3_wrapper . log ( "clearing cache for method {}" ....
def version_parser ( version_string ) : """: param version _ string : The version tag as returned by the registry / hub API : return : A tuple with the parsed version / an exception when the version format is unknown / incorrect"""
version , commit , branch = version_string . split ( '-' , 3 ) # Remove the " v " version_number = version [ 1 : ] version_number = int ( version_number ) return Version ( version_number , commit , branch )
def superclasses ( self , inherited = False ) : """Iterate over the superclasses of the class . This function is the Python equivalent of the CLIPS class - superclasses command ."""
data = clips . data . DataObject ( self . _env ) lib . EnvClassSuperclasses ( self . _env , self . _cls , data . byref , int ( inherited ) ) for klass in classes ( self . _env , data . value ) : yield klass
def section_tortuosity ( neurites , neurite_type = NeuriteType . all ) : '''section tortuosities in a collection of neurites'''
return map_sections ( sectionfunc . section_tortuosity , neurites , neurite_type = neurite_type )
def reset_namespace ( self ) : """Resets the namespace by removing all names defined by the user"""
self . shellwidget . reset_namespace ( warning = self . reset_warning , message = True )
def valid_result ( self , r ) : '''Check if the result is valid A result is invalid if : - All its source paths belong to the source path filtered - Or a similar result was reported and saved during a previous run'''
source_mapping_elements = [ elem [ 'source_mapping' ] [ 'filename_absolute' ] for elem in r [ 'elements' ] if 'source_mapping' in elem ] if r [ 'elements' ] and all ( ( any ( path in src_mapping for path in self . _paths_to_filter ) for src_mapping in source_mapping_elements ) ) : return False return not r [ 'descr...
def build_list_result ( results , xml ) : """构建带翻页的列表 : param results : 已获取的数据列表 : param xml : 原始页面xml : return : { ' results ' : list , ' count ' : int , ' next _ start ' : int | None } 如果count与results长度不同 , 则有更多 如果next _ start不为None , 则可以到下一页"""
xml_count = xml . xpath ( '//div[@class="paginator"]/span[@class="count"]/text()' ) xml_next = xml . xpath ( '//div[@class="paginator"]/span[@class="next"]/a/@href' ) count = int ( re . search ( r'\d+' , xml_count [ 0 ] ) . group ( ) ) if xml_count else len ( results ) next_start = int ( re . search ( r'start=(\d+)' , ...
def _update_likelihood_model ( self , inst , partition_parameters , tree ) : """Set parameters of likelihood model - inst - using values in dictionary - partition _ parameters - , and - tree -"""
# Build transition matrix from dict model = partition_parameters [ 'model' ] freqs = partition_parameters . get ( 'frequencies' ) if model == 'LG' : subs_model = phylo_utils . models . LG ( freqs ) elif model == 'WAG' : subs_model = phylo_utils . models . WAG ( freqs ) elif model == 'GTR' : rates = partitio...
def _get_value_from_config ( self , section , name ) : """Loads the default from the config . Returns _ no _ value if it doesn ' t exist"""
conf = configuration . get_config ( ) try : value = conf . get ( section , name ) except ( NoSectionError , NoOptionError , KeyError ) : return _no_value return self . parse ( value )
def calc_inuh_v1 ( self ) : """Calculate the unit hydrograph input . Required derived parameters : | RelLandArea | Required flux sequences : | Q0 | | Q1 | Calculated flux sequence : | InUH | Basic equation : : math : ` InUH = Q0 + Q1 ` Example : The unit hydrographs receives base flow from the...
der = self . parameters . derived . fastaccess flu = self . sequences . fluxes . fastaccess flu . inuh = der . rellandarea * flu . q0 + flu . q1
def flags ( self , index ) : """Override Qt method"""
if not index . isValid ( ) : return Qt . ItemIsEnabled column = index . column ( ) if column in [ 0 , 1 , 2 , 3 ] : return Qt . ItemFlags ( Qt . ItemIsEnabled ) else : return Qt . ItemFlags ( Qt . NoItemFlags )
def _get_build_command ( self , mkdocs_site_path : Path ) -> str : '''Generate ` ` mkdocs build ` ` command to build the site . : param mkdocs _ site _ path : Path to the output directory for the site'''
components = [ self . _mkdocs_config . get ( 'mkdocs_path' , 'mkdocs' ) ] components . append ( 'build' ) components . append ( f'-d "{self._escape_control_characters(str(mkdocs_site_path))}"' ) command = ' ' . join ( components ) self . logger . debug ( f'Build command: {command}' ) return command
def clean ( self ) : '''Verify that the user and staffMember are not mismatched . Location can only be specified if user and staffMember are not .'''
if self . staffMember and self . staffMember . userAccount and self . user and not self . staffMember . userAccount == self . user : raise ValidationError ( _ ( 'Transaction party user does not match staff member user.' ) ) if self . location and ( self . user or self . staffMember ) : raise ValidationError ( _...
def pericenter ( self , return_times = False , func = np . mean , interp_kwargs = None , minimize_kwargs = None , approximate = False ) : """Estimate the pericenter ( s ) of the orbit by identifying local minima in the spherical radius and interpolating between timesteps near the minima . By default , this re...
if return_times and func is not None : raise ValueError ( "Cannot return times if reducing pericenters " "using an input function. Pass `func=None` if " "you want to return all individual pericenters " "and times." ) if func is None : reduce = False func = lambda x : x else : reduce = True # time must i...
def scatter_group ( ax , key , imask , adata , Y , projection = '2d' , size = 3 , alpha = None ) : """Scatter of group using representation of data Y ."""
mask = adata . obs [ key ] . cat . categories [ imask ] == adata . obs [ key ] . values color = adata . uns [ key + '_colors' ] [ imask ] if not isinstance ( color [ 0 ] , str ) : from matplotlib . colors import rgb2hex color = rgb2hex ( adata . uns [ key + '_colors' ] [ imask ] ) if not is_color_like ( color )...
def items_differ ( jsonitems , dbitems , subfield_dict ) : """check whether or not jsonitems and dbitems differ"""
# short circuit common cases if len ( jsonitems ) == len ( dbitems ) == 0 : # both are empty return False elif len ( jsonitems ) != len ( dbitems ) : # if lengths differ , they ' re definitely different return True original_jsonitems = jsonitems jsonitems = copy . deepcopy ( jsonitems ) keys = jsonitems [ 0 ] ....
def read_msbuild_xml ( path , values = { } ) : """Reads the MS Build XML file at the path and returns its contents . Keyword arguments : values - - The map to append the contents to ( default { } )"""
# Attempt to read the file contents try : document = parse ( path ) except Exception as e : logging . exception ( 'Could not read MS Build XML file at %s' , path ) return values # Convert the XML to JSON format logging . info ( 'Processing MS Build XML file at %s' , path ) # Get the rule node rule = documen...