signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def get_sqlserver_product_version ( engine : "Engine" ) -> Tuple [ int ] : """Gets SQL Server version information . Attempted to use ` ` dialect . server _ version _ info ` ` : . . code - block : : python from sqlalchemy import create _ engine url = " mssql + pyodbc : / / USER : PASSWORD @ ODBC _ NAME " e...
assert is_sqlserver ( engine ) , ( "Only call get_sqlserver_product_version() for Microsoft SQL Server " "instances." ) sql = "SELECT CAST(SERVERPROPERTY('ProductVersion') AS VARCHAR)" rp = engine . execute ( sql ) # type : ResultProxy row = rp . fetchone ( ) dotted_version = row [ 0 ] # type : str # e . g . ' 12.0.520...
def dump_service ( self , sc ) : """Read all data blocks of a given service . : meth : ` dump _ service ` reads all data blocks from the service with service code * sc * and returns a list of strings suitable for printing . The number of strings returned does not necessarily reflect the number of data block...
def lprint ( fmt , data , index ) : ispchr = lambda x : x >= 32 and x <= 126 # noqa : E731 def print_bytes ( octets ) : return ' ' . join ( [ '%02x' % x for x in octets ] ) def print_chars ( octets ) : return '' . join ( [ chr ( x ) if ispchr ( x ) else '.' for x in octets ] ) return...
def hook_output ( module : nn . Module , detach : bool = True , grad : bool = False ) -> Hook : "Return a ` Hook ` that stores activations of ` module ` in ` self . stored `"
return Hook ( module , _hook_inner , detach = detach , is_forward = not grad )
def set_components ( self , params ) : """Set the value of exogenous model elements . Element values can be passed as keyword = value pairs in the function call . Values can be numeric type or pandas Series . Series will be interpolated by integrator . Examples > > > model . set _ components ( { ' birth _...
# It might make sense to allow the params argument to take a pandas series , where # the indices of the series are variable names . This would make it easier to # do a Pandas apply on a DataFrame of parameter values . However , this may conflict # with a pandas series being passed in as a dictionary element . for key ,...
def write_config ( filename , config , mode = "w" ) : '''use configparser to write a config object to filename'''
with open ( filename , mode ) as filey : config . write ( filey ) return filename
def _get_phi ( self , C , mag ) : """Returns the magnitude dependent intra - event standard deviation ( phi ) ( equation 15)"""
if mag < 5.5 : return C [ "phi1" ] elif mag < 5.75 : return C [ "phi1" ] + ( C [ "phi2" ] - C [ "phi1" ] ) * ( ( mag - 5.5 ) / 0.25 ) else : return C [ "phi2" ]
def combined ( cls , code , path = None , extra_args = None ) : """Compile combined - json with abi , bin , devdoc , userdoc . @ param code : literal solidity code as a string . @ param path : absolute path to solidity - file . Note : code & path are mutually exclusive ! @ param extra _ args : Either a spac...
if code and path : raise ValueError ( 'sourcecode and path are mutually exclusive.' ) if path : contracts = compile_file ( path , extra_args = extra_args ) with open ( path ) as handler : code = handler . read ( ) elif code : contracts = compile_code ( code , extra_args = extra_args ) else : ...
def get_series_by_name ( self , name ) : """Returns the first : py : class : ` . Series ` of a given name , or ` ` None ` ` . : param str name : The name to search by ."""
if not isinstance ( name , str ) : raise TypeError ( "Can only search series by str name, not '%s'" % str ( name ) ) for series in self . all_series ( ) : if series . name ( ) == name : return series
def get_content ( self ) : """performs es search and gets content objects"""
if "query" in self . query : q = self . query [ "query" ] else : q = self . query search = custom_search_model ( Content , q , field_map = { "feature-type" : "feature_type.slug" , "tag" : "tags.slug" , "content-type" : "_type" , } ) return search
def detect ( ) : """Detect available plugins and return enabled / configured stats Yields tuples of the form ( section , statsgroup ) sorted by the default StatsGroup order which maybe overriden in the config file . The ' section ' is the name of the configuration section as well as the option used to enabl...
# Load plugins and config plugins = load ( ) config = Config ( ) # Make sure that all sections have a valid plugin type defined for section in config . sections ( ) : if section == 'general' : continue try : type_ = config . item ( section , 'type' ) except ConfigError : raise Config...
def integrate_converge ( self , crit = 1e-4 , verbose = True ) : """Integrates the model until model states are converging . : param crit : exit criteria for difference of iterated solutions [ default : 0.0001] : type crit : float : param bool verbose : information whether total elapsed time should be pri...
# implemented by m - kreuzer for varname , value in self . state . items ( ) : value_old = copy . deepcopy ( value ) self . integrate_years ( 1 , verbose = False ) while np . max ( np . abs ( value_old - value ) ) > crit : value_old = copy . deepcopy ( value ) self . integrate_years ( 1 , ve...
def join ( cls , root , subkey ) : """Rebuild a full declaration name from its components . for every string x , we have ` join ( split ( x ) ) = = x ` ."""
if subkey is None : return root return enums . SPLITTER . join ( ( root , subkey ) )
def nl_family ( self , value ) : """Family setter ."""
self . bytearray [ self . _get_slicers ( 0 ) ] = bytearray ( c_uint ( value or 0 ) )
def all ( self , query , ** kwargs ) : """https : / / api . slack . com / methods / search . all"""
self . url = 'https://slack.com/api/search.all' return super ( Search , self ) . search_from_url ( query , ** kwargs )
def _parse_and_sort_accept_header ( accept_header ) : """Parse and sort the accept header items . > > > _ parse _ and _ sort _ accept _ header ( ' application / json ; q = 0.5 , text / * ' ) [ ( ' text / * ' , 1.0 ) , ( ' application / json ' , 0.5 ) ]"""
return sorted ( [ _split_into_mimetype_and_priority ( x ) for x in accept_header . split ( ',' ) ] , key = lambda x : x [ 1 ] , reverse = True )
def via ( self , * args ) : """Creates an empty error to record in the stack trace"""
error = None if len ( self . errors ) > 0 : error = self . _err ( "via" , * args ) return error
def _scons_user_error ( e ) : """Handle user errors . Print out a message and a description of the error , along with the line number and routine where it occured . The file and line number will be the deepest stack frame that is not part of SCons itself ."""
global print_stacktrace etype , value , tb = sys . exc_info ( ) if print_stacktrace : traceback . print_exception ( etype , value , tb ) filename , lineno , routine , dummy = find_deepest_user_frame ( traceback . extract_tb ( tb ) ) sys . stderr . write ( "\nscons: *** %s\n" % value ) sys . stderr . write ( 'File "...
def is_valid_coll ( self , coll ) : """Determines if the collection name for a request is valid ( exists ) : param str coll : The name of the collection to check : return : True if the collection is valid , false otherwise : rtype : bool"""
# if coll = = self . all _ coll : # return True return ( coll in self . warcserver . list_fixed_routes ( ) or coll in self . warcserver . list_dynamic_routes ( ) )
def rowgroupmap ( table , key , mapper , header = None , presorted = False , buffersize = None , tempdir = None , cache = True ) : """Group rows under the given key then apply ` mapper ` to yield zero or more output rows for each input group of rows ."""
return RowGroupMapView ( table , key , mapper , header = header , presorted = presorted , buffersize = buffersize , tempdir = tempdir , cache = cache )
def from_array ( array ) : """Deserialize a new Message from a given dictionary . : return : new Message instance . : rtype : Message"""
if array is None or not array : return None # end if assert_type_or_raise ( array , dict , parameter_name = "array" ) from . . receivable . peer import User , Chat from . . receivable . media import Animation , Audio , Contact , Document , Game , Location , MessageEntity , PhotoSize from . . receivable . media impo...
def debug_option ( f ) : """Configures - - debug option for CLI : param f : Callback Function to be passed to Click"""
def callback ( ctx , param , value ) : state = ctx . ensure_object ( Context ) state . debug = value return value return click . option ( '--debug' , expose_value = False , is_flag = True , envvar = "SAM_DEBUG" , help = 'Turn on debug logging to print debug message generated by SAM CLI.' , callback = callba...
def _delete ( self , ** kwargs ) : """wrapped with delete , override that in a subclass to customize"""
requests_params = self . _handle_requests_params ( kwargs ) delete_uri = self . _meta_data [ 'uri' ] session = self . _meta_data [ 'bigip' ] . _meta_data [ 'icr_session' ] # Check the generation for match before delete force = self . _check_force_arg ( kwargs . pop ( 'force' , True ) ) if not force : self . _check_...
def pop ( self , index = - 1 ) : """Retrieve the value at * index * , remove it from the collection , and return it ."""
if index == 0 : return self . _pop_left ( ) elif index == - 1 : return self . _pop_right ( ) else : return self . _pop_middle ( index )
def _quantize_symbol ( sym , excluded_symbols = None , offline_params = None , quantized_dtype = 'int8' ) : """Given a symbol object representing a neural network of data type FP32, quantize it into a INT8 network . Parameters sym : Symbol FP32 neural network symbol . excluded _ sym _ names : list of stri...
num_excluded_symbols = 0 if excluded_symbols is not None : assert isinstance ( excluded_symbols , list ) num_excluded_symbols = len ( excluded_symbols ) else : excluded_symbols = [ ] num_offline = 0 offline = [ ] if offline_params is not None : num_offline = len ( offline_params ) for k in offline_p...
def handle_annotation_list ( self , line : str , position : int , tokens : ParseResults ) -> ParseResults : """Handle statements like ` ` DEFINE ANNOTATION X AS LIST { " Y " , " Z " , . . . } ` ` . : raises : RedefinedAnnotationError"""
annotation = tokens [ 'name' ] self . raise_for_redefined_annotation ( line , position , annotation ) self . annotation_to_local [ annotation ] = set ( tokens [ 'values' ] ) return tokens
def convert_separable_convolution ( builder , layer , input_names , output_names , keras_layer ) : """Convert separable convolution layer from keras to coreml . Parameters keras _ layer : layer A keras layer object . builder : NeuralNetworkBuilder A neural network builder object ."""
_check_data_format ( keras_layer ) # Get input and output names input_name , output_name = ( input_names [ 0 ] , output_names [ 0 ] ) has_bias = keras_layer . use_bias # Get the weights from _ keras . weight_list = keras_layer . get_weights ( ) output_blob_shape = list ( filter ( None , keras_layer . output_shape ) ) o...
def WriteFileHeader ( self , arcname = None , compress_type = None , st = None ) : """Writes a file header ."""
if not self . _stream : raise ArchiveAlreadyClosedError ( "Attempting to write to a ZIP archive that was already closed." ) self . cur_zinfo = self . _GenerateZipInfo ( arcname = arcname , compress_type = compress_type , st = st ) self . cur_file_size = 0 self . cur_compress_size = 0 if self . cur_zinfo . compress_...
def add_service ( service , zone = None , permanent = True ) : '''Add a service for zone . If zone is omitted , default zone will be used . CLI Example : . . code - block : : bash salt ' * ' firewalld . add _ service ssh To assign a service to a specific zone : . . code - block : : bash salt ' * ' firew...
if zone : cmd = '--zone={0} --add-service={1}' . format ( zone , service ) else : cmd = '--add-service={0}' . format ( service ) if permanent : cmd += ' --permanent' return __firewall_cmd ( cmd )
def string_to_version ( verstring ) : """Return a tuple of ( epoch , version , release ) from a version string This function replaces rpmUtils . miscutils . stringToVersion , see https : / / bugzilla . redhat . com / 1364504"""
# is there an epoch ? components = verstring . split ( ':' ) if len ( components ) > 1 : epoch = components [ 0 ] else : epoch = 0 remaining = components [ : 2 ] [ 0 ] . split ( '-' ) version = remaining [ 0 ] release = remaining [ 1 ] return ( epoch , version , release )
def transformChildrenFromNative ( self , clearBehavior = True ) : """Recursively transform native children to vanilla representations ."""
for childArray in self . contents . values ( ) : for child in childArray : child = child . transformFromNative ( ) child . transformChildrenFromNative ( clearBehavior ) if clearBehavior : child . behavior = None child . parentBehavior = None
def predict ( self , pairs ) : """Predicts the learned metric between input pairs . ( For now it just calls decision function ) . Returns the learned metric value between samples in every pair . It should ideally be low for similar samples and high for dissimilar samples . Parameters pairs : array - like ...
check_is_fitted ( self , [ 'threshold_' , 'transformer_' ] ) return 2 * ( - self . decision_function ( pairs ) <= self . threshold_ ) - 1
def _compile_type ( self , schema ) : """Compile type schema : plain type matching"""
# Prepare self self . compiled_type = const . COMPILED_TYPE . TYPE self . name = get_type_name ( schema ) # Error partials err_type = self . Invalid ( _ ( u'Wrong type' ) , self . name ) # Type check function if six . PY2 and schema is basestring : # Relaxed rule for Python2 basestring typecheck = lambda v : isinst...
def grant_winsta_and_desktop ( th ) : '''Grant the token ' s user access to the current process ' s window station and desktop .'''
current_sid = win32security . GetTokenInformation ( th , win32security . TokenUser ) [ 0 ] # Add permissions for the sid to the current windows station and thread id . # This prevents windows error 0xC0000142. winsta = win32process . GetProcessWindowStation ( ) set_user_perm ( winsta , WINSTA_ALL , current_sid ) deskto...
def _read_track ( chunk ) : """Retuns a list of midi events and tempo change events"""
TEMPO , MIDI = range ( 2 ) # Deviations : The running status should be reset on non midi events , but # some files contain meta events inbetween . # TODO : Offset and time signature are not considered . tempos = [ ] events = [ ] chunk = bytearray ( chunk ) deltasum = 0 status = 0 off = 0 while off < len ( chunk ) : ...
def rg ( self ) : """Brazilian RG , return plain numbers . Check : https : / / www . ngmatematica . com / 2014/02 / como - determinar - o - digito - verificador - do . html"""
digits = self . generator . random . sample ( range ( 0 , 9 ) , 8 ) checksum = sum ( i * digits [ i - 2 ] for i in range ( 2 , 10 ) ) last_digit = 11 - ( checksum % 11 ) if last_digit == 10 : digits . append ( 'X' ) elif last_digit == 11 : digits . append ( 0 ) else : digits . append ( last_digit ) return '...
def get_margin_requirement ( self ) : """Get margin requirements for intrument ( futures only ) : Retruns : margin : dict margin requirements for instrument ( all values are ` ` None ` ` for non - futures instruments )"""
contract = self . get_contract ( ) if contract . m_secType == "FUT" : return futures . get_ib_futures ( contract . m_symbol , contract . m_exchange ) # else . . . return { "exchange" : None , "symbol" : None , "description" : None , "class" : None , "intraday_initial" : None , "intraday_maintenance" : None , "overn...
def count ( self ) : """Counts the number of rows of the main dataframe"""
try : num = len ( self . df . index ) except Exception as e : self . err ( e , "Can not count data" ) return self . ok ( "Found" , num , "rows in the dataframe" )
def unjoin_domain ( username = None , password = None , domain = None , workgroup = 'WORKGROUP' , disable = False , restart = False ) : # pylint : disable = anomalous - backslash - in - string '''Unjoin a computer from an Active Directory Domain . Requires a restart . Args : username ( str ) : Username of an ...
# pylint : enable = anomalous - backslash - in - string if six . PY2 : username = _to_unicode ( username ) password = _to_unicode ( password ) domain = _to_unicode ( domain ) status = get_domain_workgroup ( ) if 'Workgroup' in status : if status [ 'Workgroup' ] == workgroup : return 'Already joi...
def dataset_filepath ( filename , dataset_name = None , task = None , ** kwargs ) : """Get the path of the corresponding dataset file . Parameters filename : str The name of the file . dataset _ name : str , optional The name of the dataset . Used to define a sub - directory to contain all instances of ...
dataset_dir_path = dataset_dirpath ( dataset_name = dataset_name , task = task , ** kwargs ) return os . path . join ( dataset_dir_path , filename )
def notblocked ( page ) : """Determine if given url is a page that should be in sitemap ."""
for blocked in PAGES_TO_BLOCK : if blocked [ 0 ] != '*' : blocked = '*' + blocked rx = re . compile ( blocked . replace ( '*' , '[^$]*' ) ) if rx . match ( page ) : return False return True
def enable_backups ( self ) : """Enable Backups for this Instance . When enabled , we will automatically backup your Instance ' s data so that it can be restored at a later date . For more information on Instance ' s Backups service and pricing , see our ` Backups Page ` _ . . _ Backups Page : https : / / w...
self . _client . post ( "{}/backups/enable" . format ( Instance . api_endpoint ) , model = self ) self . invalidate ( ) return True
def coombs_winners ( self , profile ) : """Returns an integer list that represents all possible winners of a profile under Coombs rule . : ivar Profile profile : A Profile object that represents an election profile ."""
elecType = profile . getElecType ( ) if elecType == "soc" or elecType == "csv" : return self . coombssoc_winners ( profile ) elif elecType == "toc" : return self . coombstoc_winners ( profile ) else : print ( "ERROR: unsupported profile type" ) exit ( )
def get_all ( ) : '''Return all available boot services CLI Example : . . code - block : : bash salt ' * ' service . get _ all'''
ret = set ( ) lines = glob . glob ( '/etc/init.d/*' ) for line in lines : service = line . split ( '/etc/init.d/' ) [ 1 ] # Remove README . If it ' s an enabled service , it will be added back in . if service != 'README' : ret . add ( service ) return sorted ( ret | set ( get_enabled ( ) ) )
def copy_file ( self , filepath ) : """Returns flag which says to copy rather than link a file ."""
copy_file = False try : copy_file = self . data [ filepath ] [ 'copy' ] except KeyError : return False return copy_file
def close ( self ) : '''Releasing hardware resources .'''
try : self . dut . close ( ) except Exception : logging . warning ( 'Closing DUT was not successful' ) else : logging . debug ( 'Closed DUT' )
def cmd_link_attributes ( self , args ) : '''change optional link attributes'''
link = args [ 0 ] attributes = args [ 1 ] print ( "Setting link %s attributes (%s)" % ( link , attributes ) ) self . link_attributes ( link , attributes )
def plot_sampler ( sampler , suptitle = None , labels = None , bins = 50 , plot_samples = False , plot_hist = True , plot_chains = True , burn = 0 , chain_mask = None , temp_idx = 0 , weights = None , cutoff_weight = None , cmap = 'gray_r' , hist_color = 'k' , chain_alpha = 0.1 , points = None , covs = None , colors = ...
masked_weights = None if points is not None : points = scipy . atleast_2d ( points ) if covs is not None and len ( covs ) != len ( points ) : raise ValueError ( "If covariance matrices are provided, len(covs) must equal len(points)!" ) elif covs is None : covs = [ None , ] * len ( points ) ...
def remove_fact ( self , fact_id ) : """Remove fact from storage by it ' s ID"""
self . start_transaction ( ) fact = self . __get_fact ( fact_id ) if fact : self . __remove_fact ( fact_id ) self . facts_changed ( ) self . end_transaction ( )
def inherited_labels ( cls ) : """Return list of labels from nodes class hierarchy . : return : list"""
return [ scls . __label__ for scls in cls . mro ( ) if hasattr ( scls , '__label__' ) and not hasattr ( scls , '__abstract_node__' ) ]
def get_translated_file ( fapi , file_uri , locale , retrieval_type , include_original_strings , use_cache , cache_dir = None ) : """Returns a translated file from smartling"""
file_data = None cache_name = str ( file_uri ) + "." + str ( locale ) + "." + str ( retrieval_type ) + "." + str ( include_original_strings ) cache_file = os . path . join ( cache_dir , sha1 ( cache_name ) ) if cache_dir else None if use_cache and os . path . exists ( cache_file ) : print ( "Using cache file %s for...
def insertRow ( self , row , item , parent ) : """Insert a single item before the given row in the child items of the parent specified . : param row : the index where the rows get inserted : type row : int : param item : the item to insert . When creating the item , make sure it ' s parent is None . If not ...
item . set_model ( self ) if parent . isValid ( ) : parentitem = parent . internalPointer ( ) else : parentitem = self . _root self . beginInsertRows ( parent , row , row ) item . _parent = parentitem if parentitem : parentitem . childItems . insert ( row , item ) self . endInsertRows ( ) return True
def get_specific_nodes ( self , node , names ) : """Given a node and a sequence of strings in ` names ` , return a dictionary containing the names as keys and child ` ELEMENT _ NODEs ` , that have a ` tagName ` equal to the name ."""
nodes = [ ( x . tagName , x ) for x in node . childNodes if x . nodeType == x . ELEMENT_NODE and x . tagName in names ] return dict ( nodes )
def remove_access ( self , ** kwargs ) : # noqa : E501 """Removes the specified ids from the given dashboards ' ACL # noqa : E501 # noqa : E501 This method makes a synchronous HTTP request by default . To make an asynchronous HTTP request , please pass async _ req = True > > > thread = api . remove _ access...
kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'async_req' ) : return self . remove_access_with_http_info ( ** kwargs ) # noqa : E501 else : ( data ) = self . remove_access_with_http_info ( ** kwargs ) # noqa : E501 return data
def universe ( self ) : """Data universe available at the current time . Universe contains the data passed in when creating a Backtest . Use this data to determine strategy logic ."""
# avoid windowing every time # if calling and on same date return # cached value if self . now == self . _last_chk : return self . _funiverse else : self . _last_chk = self . now self . _funiverse = self . _universe . loc [ : self . now ] return self . _funiverse
def get_attribute ( self , obj , attribute ) : """Returns single object attribute . : param obj : requested object . : param attribute : requested attribute to query . : returns : returned value . : rtype : str"""
raw_return = self . send_command_return ( obj , attribute , '?' ) if len ( raw_return ) > 2 and raw_return [ 0 ] == '"' and raw_return [ - 1 ] == '"' : return raw_return [ 1 : - 1 ] return raw_return
def run_role ( self , name , options = None , content = None ) : """Generate a role node . options : dict key value arguments . content : content content of the directive Returns node : docutil Node Node generated by the arguments ."""
if options is None : options = { } if content is None : content = [ ] role_fn , _ = role ( name , self . language , self . node . line , self . reporter ) vec , _ = role_fn ( name , rawtext = str ( content ) , text = str ( content ) , lineno = self . node . line , inliner = self . memo . inliner , options = opt...
def set_topic_partitions ( self , * topics ) : """Set the topic / partitions to consume Optionally specify offsets to start from Accepts types : * str ( utf - 8 ) : topic name ( will consume all available partitions ) * tuple : ( topic , partition ) * dict : - { topic : partition } - { topic : [ parti...
self . _topics = [ ] self . _client . load_metadata_for_topics ( ) # Setup offsets self . _offsets = OffsetsStruct ( fetch = dict ( ) , commit = dict ( ) , highwater = dict ( ) , task_done = dict ( ) ) # Handle different topic types for arg in topics : # Topic name str - - all partitions if isinstance ( arg , ( six...
def query_starts_with ( query , prefixes ) : """Check if the query starts with any item from * prefixes * ."""
prefixes = [ prefix . lower ( ) for prefix in prefixes ] formatted_sql = sqlparse . format ( query . lower ( ) , strip_comments = True ) return bool ( formatted_sql ) and formatted_sql . split ( ) [ 0 ] in prefixes
def make_splice_junction_df ( fn , type = 'gene' ) : """Read the Gencode gtf file and make a pandas dataframe describing the splice junctions Parameters filename : str of filename Filename of the Gencode gtf file Returns df : pandas . DataFrame Dataframe of splice junctions with the following columns ...
import itertools as it import HTSeq import numpy as np # GFF _ Reader has an option for end _ included . However , I think it is # backwards . So if your gtf is end - inclusive , you want the default # ( end _ included = False ) . With this , one will NOT be subtracted from the end # coordinate . gffI = it . islice ( H...
def upstream ( self , f , n = 1 ) : """find n upstream features where upstream is determined by the strand of the query Feature f Overlapping features are not considered . f : a Feature object n : the number of features to return"""
if f . strand == - 1 : return self . right ( f , n ) return self . left ( f , n )
def combine_hex ( data ) : '''Combine list of integer values to one big integer'''
output = 0x00 for i , value in enumerate ( reversed ( data ) ) : output |= ( value << i * 8 ) return output
def getfield ( self , pkt , s ) : """If the decryption of the content did not fail with a CipherError , we begin a loop on the clear content in order to get as much messages as possible , of the type advertised in the record header . This is notably important for several TLS handshake implementations , which ...
tmp_len = self . length_from ( pkt ) lst = [ ] ret = b"" remain = s if tmp_len is not None : remain , ret = s [ : tmp_len ] , s [ tmp_len : ] if remain == b"" : if ( ( ( pkt . tls_session . tls_version or 0x0303 ) > 0x0200 ) and hasattr ( pkt , "type" ) and pkt . type == 23 ) : return ret , [ TLSApplica...
def process_app_config_section ( config , app_config ) : """Processes the app section from a configuration data dict . : param config : The config reference of the object that will hold the configuration data from the config _ data . : param app _ config : App section from a config data dict ."""
if 'addresses' in app_config : config . app [ 'addresses' ] = app_config [ 'addresses' ] if 'component' in app_config : config . app [ 'component' ] = app_config [ 'component' ] if 'data' in app_config : if 'sources' in app_config [ 'data' ] : config . app [ 'data' ] [ 'sources' ] = app_config [ 'da...
def getAllReadGroups ( self ) : """Get all read groups in a read group set"""
for dataset in self . getAllDatasets ( ) : iterator = self . _client . search_read_group_sets ( dataset_id = dataset . id ) for readGroupSet in iterator : readGroupSet = self . _client . get_read_group_set ( readGroupSet . id ) for readGroup in readGroupSet . read_groups : yield read...
def make_driveritem_deviceitem_devicename ( device_name , condition = 'is' , negate = False , preserve_case = False ) : """Create a node for DriverItem / DeviceItem / DeviceName : return : A IndicatorItem represented as an Element node"""
document = 'DriverItem' search = 'DriverItem/DeviceItem/DeviceName' content_type = 'string' content = device_name ii_node = ioc_api . make_indicatoritem_node ( condition , document , search , content_type , content , negate = negate , preserve_case = preserve_case ) return ii_node
def _setup_schema ( Base , session ) : """Create a function which adds ` _ _ marshmallow _ _ ` attribute to all signal models ."""
def create_schema_class ( m ) : if hasattr ( m , 'send_signalbus_message' ) : # Signal models should not use the SQLAlchemy session . class Meta ( object ) : model = m else : class Meta ( object ) : model = m sqla_session = session schema_class_name = '%sS...
def create_job ( self , phases , name = None , input = None ) : """CreateJob https : / / apidocs . joyent . com / manta / api . html # CreateJob"""
log . debug ( 'CreateJob' ) path = '/%s/jobs' % self . account body = { "phases" : phases } if name : body [ "name" ] = name if input : body [ "input" ] = input headers = { "Content-Type" : "application/json" } res , content = self . _request ( path , "POST" , body = json . dumps ( body ) , headers = headers ) ...
def remap_file_lines ( from_path , to_path , line_map_list ) : """Adds line _ map list to the list of association of from _ file to to to _ file"""
from_path = pyc2py ( from_path ) cache_file ( to_path ) remap_entry = file2file_remap_lines . get ( to_path ) if remap_entry : new_list = list ( remap_entry . from_to_pairs ) + list ( line_map_list ) else : new_list = line_map_list # FIXME : look for duplicates ? file2file_remap_lines [ to_path ] = RemapLineEnt...
def write_tile_if_changed ( store , tile_data , coord , format ) : """Only write tile data if different from existing . Try to read the tile data from the store first . If the existing data matches , don ' t write . Returns whether the tile was written ."""
existing_data = store . read_tile ( coord , format ) if not existing_data or not tiles_are_equal ( existing_data , tile_data , format ) : store . write_tile ( tile_data , coord , format ) return True else : return False
def from_json ( cls , json_info ) : """Build a Result instance from a json string ."""
if json_info is None : return None return ResultRecord ( trial_id = json_info [ "trial_id" ] , timesteps_total = json_info [ "timesteps_total" ] , done = json_info . get ( "done" , None ) , episode_reward_mean = json_info . get ( "episode_reward_mean" , None ) , mean_accuracy = json_info . get ( "mean_accuracy" , N...
def connect ( self , cback , subscribers = None , instance = None ) : """Add a function or a method as an handler of this signal . Any handler added can be a coroutine . : param cback : the callback ( or * handler * ) to be added to the set : returns : ` ` None ` ` or the value returned by the corresponding w...
if subscribers is None : subscribers = self . subscribers # wrapper if self . _fconnect is not None : def _connect ( cback ) : self . _connect ( subscribers , cback ) notify = partial ( self . _notify_one , instance ) if instance is not None : result = self . _fconnect ( instance , cback...
def _evaluate ( self , R , phi = 0. , t = 0. ) : """NAME : _ evaluate PURPOSE : evaluate the potential at R , phi , t INPUT : R - Galactocentric cylindrical radius phi - azimuth t - time OUTPUT : Phi ( R , phi , t ) HISTORY : 2011-03-27 - Started - Bovy ( NYU )"""
return self . _A * math . exp ( - ( t - self . _to ) ** 2. / 2. / self . _sigma2 ) / self . _alpha * math . cos ( self . _alpha * math . log ( R ) - self . _m * ( phi - self . _omegas * t - self . _gamma ) )
def add_slot_ports ( self , slot ) : """Add the ports to be added for a adapter card : param str slot : Slot name"""
slot_nb = int ( slot [ 4 ] ) # slot _ adapter = None # if slot in self . node [ ' properties ' ] : # slot _ adapter = self . node [ ' properties ' ] [ slot ] # elif self . device _ info [ ' model ' ] = = ' c7200 ' : # if self . device _ info [ ' npe ' ] = = ' npe - g2 ' : # slot _ adapter = ' C7200 - IO - GE - E ' # el...
def populate_from_trace_graph ( self , graph : TraceGraph ) -> None : """Populates this graph from the given one based on affected _ files"""
# Track which trace frames have been visited as we populate the full # traces of the graph . self . _visited_trace_frame_ids : Set [ int ] = set ( ) self . _populate_affected_issues ( graph ) if not self . _affected_issues_only : # Finds issues from the conditions and saves them . # Also saves traces that have been tri...
def update_properties ( self , new_properties ) : """Update config properties values Property name must be equal to ' Section _ option ' of config property : param new _ properties : dict with new properties values"""
[ self . _update_property_from_dict ( section , option , new_properties ) for section in self . sections ( ) for option in self . options ( section ) ]
def signed_token_generator ( private_pem , ** kwargs ) : """: param private _ pem :"""
def signed_token_generator ( request ) : request . claims = kwargs return common . generate_signed_token ( private_pem , request ) return signed_token_generator
def get_blob_hash ( self , h = hashlib . md5 ) : """get hash instance of blob content : param h : callable hash generator : type h : builtin _ function _ or _ method : rtype : _ hashlib . HASH : return : hash instance"""
assert callable ( h ) return h ( self . get_blob_data ( ) )
def role_update ( self , role_id , data , ** kwargs ) : "https : / / developer . zendesk . com / rest _ api / docs / chat / roles # update - role"
api_path = "/api/v2/roles/{role_id}" api_path = api_path . format ( role_id = role_id ) return self . call ( api_path , method = "PUT" , data = data , ** kwargs )
def _validate_monotonic ( self ) : """Validate on is _ monotonic ."""
if not self . _on . is_monotonic : formatted = self . on or 'index' raise ValueError ( "{0} must be " "monotonic" . format ( formatted ) )
def _normalize_subplot_ids ( fig ) : """Make sure a layout subplot property is initialized for every subplot that is referenced by a trace in the figure . For example , if a figure contains a ` scatterpolar ` trace with the ` subplot ` property set to ` polar3 ` , this function will make sure the figure ' s l...
layout = fig . setdefault ( 'layout' , { } ) for trace in fig . get ( 'data' , None ) : trace_type = trace . get ( 'type' , 'scatter' ) subplot_types = _trace_to_subplot . get ( trace_type , [ ] ) for subplot_type in subplot_types : subplot_prop_name = _get_subplot_prop_name ( subplot_type ) ...
def items ( self ) : """Returns a depth - first flat list of all items in the document"""
l = [ ] for e in self . data : l += e . items ( ) return l
def field_values ( self ) : """Access the field _ values : returns : twilio . rest . autopilot . v1 . assistant . field _ type . field _ value . FieldValueList : rtype : twilio . rest . autopilot . v1 . assistant . field _ type . field _ value . FieldValueList"""
if self . _field_values is None : self . _field_values = FieldValueList ( self . _version , assistant_sid = self . _solution [ 'assistant_sid' ] , field_type_sid = self . _solution [ 'sid' ] , ) return self . _field_values
def construct_url ( self ) : """Construct a full plex request URI , with ` params ` ."""
path = [ self . path ] path . extend ( [ str ( x ) for x in self . params ] ) url = self . client . base_url + '/' . join ( x for x in path if x ) query = self . kwargs . get ( 'query' ) if query : # Dict - > List if type ( query ) is dict : query = query . items ( ) # Remove items with ` None ` value ...
def _html_image ( page ) : """returns HTML img tag"""
source = _image ( page ) if not source : return alt = page . data . get ( 'label' ) or page . data . get ( 'title' ) img = "<img src=\"%s\"" % source img += " alt=\"%s\" title=\"%s\" " % ( alt , alt ) img += "align=\"right\" width=\"240\">" return img
def has_item ( self , hash_key , range_key = None , consistent_read = False ) : """Checks the table to see if the Item with the specified ` ` hash _ key ` ` exists . This may save a tiny bit of time / bandwidth over a straight : py : meth : ` get _ item ` if you have no intention to touch the data that is ret...
try : # Attempt to get the key . If it can ' t be found , it ' ll raise # an exception . self . get_item ( hash_key , range_key = range_key , # This minimizes the size of the response body . attributes_to_get = [ hash_key ] , consistent_read = consistent_read ) except dynamodb_exceptions . DynamoDBKeyNotFoundEr...
def configure ( name , host , port , auth , current ) : '''Configure is used to add various ES ports you are working on . The user can add as many es ports as the one wants , but one will remain active at one point .'''
Config = ConfigParser . ConfigParser ( ) if not os . path . exists ( os . path . dirname ( filename ) ) : try : os . makedirs ( os . path . dirname ( filename ) ) except Exception as e : click . echo ( e ) return section_name = None if ( current . lower ( ) == 'y' ) : section_name = ...
def read_rows ( self , read_position , retry = google . api_core . gapic_v1 . method . DEFAULT , timeout = google . api_core . gapic_v1 . method . DEFAULT , metadata = None , ) : """Reads rows from the table in the format prescribed by the read session . Each response contains one or more table rows , up to a max...
# Wrap the transport method to add retry and timeout logic . if "read_rows" not in self . _inner_api_calls : self . _inner_api_calls [ "read_rows" ] = google . api_core . gapic_v1 . method . wrap_method ( self . transport . read_rows , default_retry = self . _method_configs [ "ReadRows" ] . retry , default_timeout ...
def _construct_jbor ( job_id , field_name_and_maybe_index ) : ''': param job _ id : Job ID : type job _ id : string : param field _ name _ and _ maybe _ index : Field name , plus possibly " . N " where N is an array index : type field _ name _ and _ maybe _ index : string : returns : dict of JBOR'''
link = { "$dnanexus_link" : { "job" : job_id } } if '.' in field_name_and_maybe_index : split_by_dot = field_name_and_maybe_index . rsplit ( '.' , 1 ) link [ "$dnanexus_link" ] [ "field" ] = split_by_dot [ 0 ] link [ "$dnanexus_link" ] [ "index" ] = int ( split_by_dot [ 1 ] ) else : link [ "$dnanexus_li...
async def _send_sack ( self ) : """Build and send a selective acknowledgement ( SACK ) chunk ."""
gaps = [ ] gap_next = None for tsn in sorted ( self . _sack_misordered ) : pos = ( tsn - self . _last_received_tsn ) % SCTP_TSN_MODULO if tsn == gap_next : gaps [ - 1 ] [ 1 ] = pos else : gaps . append ( [ pos , pos ] ) gap_next = tsn_plus_one ( tsn ) sack = SackChunk ( ) sack . cumulati...
def focusOutEvent ( self , event ) : """Overloads the focus out event to cancel editing when the widget loses focus . : param event | < QFocusEvent >"""
super ( XNavigationEdit , self ) . focusOutEvent ( event ) self . cancelEdit ( )
def setImportDataInterface ( self , values ) : """Return the current list of import data interfaces"""
exims = self . getImportDataInterfacesList ( ) new_values = [ value for value in values if value in exims ] if len ( new_values ) < len ( values ) : logger . warn ( "Some Interfaces weren't added..." ) self . Schema ( ) . getField ( 'ImportDataInterface' ) . set ( self , new_values )
def post ( self , path = '' , retry = 0 , ** data ) : """Post an item to the Graph API . : param path : A string describing the path to the item . : param retry : An integer describing how many times the request may be retried . : param data : Graph API parameters such as ' message ' or ' source ' . See ` F...
response = self . _query ( method = 'POST' , path = path , data = data , retry = retry ) if response is False : raise FacebookError ( 'Could not post to "%s"' % path ) return response
def Parse ( self , stat , file_object , knowledge_base ) : """Parse the sshd configuration . Process each of the lines in the configuration file . Assembes an sshd _ config file into a dictionary with the configuration keyword as the key , and the configuration settings as value ( s ) . Args : stat : unus...
_ , _ = stat , knowledge_base # Clean out any residual state . self . _field_parser . Flush ( ) lines = [ l . strip ( ) for l in utils . ReadFileBytesAsUnicode ( file_object ) . splitlines ( ) ] for line in lines : # Remove comments ( will break if it includes a quoted / escaped # ) line = line . split ( "#" ) [ 0 ...
def tile_to_quadkey ( tile , level ) : """Transform tile coordinates to a quadkey"""
tile_x = tile [ 0 ] tile_y = tile [ 1 ] quadkey = "" for i in xrange ( level ) : bit = level - i digit = ord ( '0' ) mask = 1 << ( bit - 1 ) # if ( bit - 1 ) > 0 else 1 > > ( bit - 1) if ( tile_x & mask ) is not 0 : digit += 1 if ( tile_y & mask ) is not 0 : digit += 2 quadke...
def upTo ( self , key ) : """Returns the urn up to given level using URN Constants : param key : Identifier of the wished resource using URN constants : type key : int : returns : String representation of the partial URN requested : rtype : str : Example : > > > a = URN ( urn = " urn : cts : latinLit : ...
middle = [ component for component in [ self . __parsed [ "textgroup" ] , self . __parsed [ "work" ] , self . __parsed [ "version" ] ] if component is not None ] if key == URN . COMPLETE : return self . __str__ ( ) elif key == URN . NAMESPACE : return ":" . join ( [ "urn" , self . __parsed [ "urn_namespace" ] ,...
def post ( self , resource ) : """Creates a new instance of the resource . Args : resource - gophish . models . Model - The resource instance"""
response = self . api . execute ( "POST" , self . endpoint , json = ( resource . as_dict ( ) ) ) if not response . ok : raise Error . parse ( response . json ( ) ) return self . _cls . parse ( response . json ( ) )
def generate_barcodes ( nIds , codeLen = 12 ) : """Given a list of sample IDs generate unique n - base barcodes for each . Note that only 4 ^ n unique barcodes are possible ."""
def next_code ( b , c , i ) : return c [ : i ] + b + ( c [ i + 1 : ] if i < - 1 else '' ) def rand_base ( ) : return random . choice ( [ 'A' , 'T' , 'C' , 'G' ] ) def rand_seq ( n ) : return '' . join ( [ rand_base ( ) for _ in range ( n ) ] ) # homopolymer filter regex : match if 4 identical bases in a row...
def next ( self ) : """Return the next page . The page label is defined in ` ` settings . NEXT _ LABEL ` ` . Return an empty string if current page is the last ."""
if self . _page . has_next ( ) : return self . _endless_page ( self . _page . next_page_number ( ) , label = settings . NEXT_LABEL ) return ''
def run ( items ) : """Run MetaSV if we have enough supported callers , adding output to the set of calls ."""
assert len ( items ) == 1 , "Expect one input to MetaSV ensemble calling" data = items [ 0 ] work_dir = _sv_workdir ( data ) out_file = os . path . join ( work_dir , "variants.vcf.gz" ) cmd = _get_cmd ( ) + [ "--sample" , dd . get_sample_name ( data ) , "--reference" , dd . get_ref_file ( data ) , "--bam" , dd . get_al...
def flip ( self ) : """This will switch major / minor around , regardless of frequency truth . This is intended for forcing one of two populations to relate correctly to the same genotype definitions . When flipped , Ps and Qs will be backward , and the maf will no longer relate to the " minor " allele freq...
maj_count = self . maj_allele_count self . maj_allele_count = self . min_allele_count self . min_allele_count = maj_count alleles = self . alleles self . alleles = [ alleles [ 1 ] , alleles [ 0 ] ]