signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def parse ( args = None ) : """Defines how to parse CLI arguments for the DomainTools API"""
parser = argparse . ArgumentParser ( description = 'The DomainTools CLI API Client' ) parser . add_argument ( '-u' , '--username' , dest = 'user' , default = '' , help = 'API Username' ) parser . add_argument ( '-k' , '--key' , dest = 'key' , default = '' , help = 'API Key' ) parser . add_argument ( '-c' , '--credfile'...
def get_all_subclasses ( typ , recursive : bool = True , _memo = None ) -> Sequence [ Type [ Any ] ] : """Returns all subclasses , and supports generic types . It is recursive by default See discussion at https : / / github . com / Stewori / pytypes / issues / 31 : param typ : : param recursive : a boolean in...
_memo = _memo or set ( ) # if we have collected the subclasses for this already , return if typ in _memo : return [ ] # else remember that we have collected them , and collect them _memo . add ( typ ) if is_generic_type ( typ ) : # We now use get _ origin ( ) to also find all the concrete subclasses in case the des...
def when ( self , key ) : """Specify context , i . e . condition that must be met . Arguments : key ( str ) : Name of the context whose value you want to query . Returns : Context :"""
ctx = Context ( key , self ) self . context . append ( ctx ) return ctx
def _run ( self ) : """Do the APM lumping ."""
# print ( " Doing APM Clustering . . . " ) # Start looping for maxIter times n_macrostates = 1 # initialized as 1 because no macrostate exist in loop 0 metaQ = - 1.0 prevQ = - 1.0 global_maxQ = - 1.0 local_maxQ = - 1.0 for iter in range ( self . max_iter ) : self . __max_state = - 1 self . __micro_stack = [ ] ...
def read_certificates ( glob_path ) : '''Returns a dict containing details of a all certificates matching a glob glob _ path : A path to certificates to be read and returned . CLI Example : . . code - block : : bash salt ' * ' x509 . read _ certificates " / etc / pki / * . crt "'''
ret = { } for path in glob . glob ( glob_path ) : if os . path . isfile ( path ) : try : ret [ path ] = read_certificate ( certificate = path ) except ValueError as err : log . debug ( 'Unable to read certificate %s: %s' , path , err ) return ret
def convdicts ( ) : """Access a set of example learned convolutional dictionaries . Returns cdd : dict A dict associating description strings with dictionaries represented as ndarrays Examples Print the dict keys to obtain the identifiers of the available dictionaries > > > from sporco import util ...
pth = os . path . join ( os . path . dirname ( __file__ ) , 'data' , 'convdict.npz' ) npz = np . load ( pth ) cdd = { } for k in list ( npz . keys ( ) ) : cdd [ k ] = npz [ k ] return cdd
def compose ( * fs : Any ) -> Callable : """Compose functions from left to right . e . g . compose ( f , g ) ( x ) = f ( g ( x ) )"""
return foldl1 ( lambda f , g : lambda * x : f ( g ( * x ) ) , fs )
def get_tx_fee_per_byte ( bitcoind_opts = None , config_path = None , bitcoind_client = None ) : """Get the tx fee per byte from the underlying blockchain Return the fee on success Return None on error"""
if bitcoind_client is None : bitcoind_client = get_bitcoind_client ( bitcoind_opts = bitcoind_opts , config_path = config_path ) try : # try to confirm in 2-3 blocks try : fee_info = bitcoind_client . estimatesmartfee ( 2 ) if 'errors' in fee_info and len ( fee_info [ 'errors' ] ) > 0 : ...
def attach ( cls , training_job_name , sagemaker_session = None , model_channel_name = 'model' ) : """Attach to an existing training job . Create an Estimator bound to an existing training job , each subclass is responsible to implement ` ` _ prepare _ init _ params _ from _ job _ description ( ) ` ` as this me...
sagemaker_session = sagemaker_session or Session ( ) job_details = sagemaker_session . sagemaker_client . describe_training_job ( TrainingJobName = training_job_name ) init_params = cls . _prepare_init_params_from_job_description ( job_details , model_channel_name ) estimator = cls ( sagemaker_session = sagemaker_sessi...
def create_parser ( self , prog_name , subcommand ) : """Override the base create _ parser ( ) method to add this command ' s custom options in Django 1.7 and below ."""
if not self . use_argparse : self . __class__ . option_list = TestCommand . option_list + self . custom_options parser = super ( Command , self ) . create_parser ( prog_name , subcommand ) return parser
def g_to_n ( self , g_interval ) : """convert a genomic ( g . ) interval to a transcript cDNA ( n . ) interval"""
grs , gre = g_interval . start . base - 1 - self . gc_offset , g_interval . end . base - 1 - self . gc_offset # frs , fre = ( f ) orward ( r ) na ( s ) tart & ( e ) nd ; forward w . r . t . genome frs , frs_offset , frs_cigar = self . _map ( from_pos = self . ref_pos , to_pos = self . tgt_pos , pos = grs , base = "star...
def POST ( self , courseid , taskid , isLTI ) : """POST a new submission"""
username = self . user_manager . session_username ( ) course = self . course_factory . get_course ( courseid ) if not self . user_manager . course_is_open_to_user ( course , username , isLTI ) : return self . template_helper . get_renderer ( ) . course_unavailable ( ) task = course . get_task ( taskid ) if not self...
def copy_and_replace ( file_in , file_out , mapping , ** kwargs ) : '''Copy a file and replace some placeholders with new values .'''
separator = '@@' if 'separator' in kwargs : separator = kwargs [ 'separator' ] file_in = open ( file_in , 'r' ) file_out = open ( file_out , 'w' ) s = file_in . read ( ) for find , replace in mapping : find = separator + find + separator print ( u'Replacing {0} with {1}' . format ( find , replace ) ) s ...
def transform ( self , sequences , mode = 'clip' ) : """Transform a list of sequences to internal indexing Recall that ` sequences ` can be arbitrary labels , whereas ` ` transmat _ ` ` and ` ` countsmat _ ` ` are indexed with integers between 0 and ` ` n _ states - 1 ` ` . This methods maps a set of sequence...
if mode not in [ 'clip' , 'fill' ] : raise ValueError ( 'mode must be one of ["clip", "fill"]: %s' % mode ) sequences = list_of_1d ( sequences ) result = [ ] for y in sequences : if mode == 'fill' : result . append ( self . partial_transform ( y , mode ) ) elif mode == 'clip' : result . exte...
def cmd_show ( docid ) : """Arguments : < doc _ id > Show document information ( but not its content , see ' dump ' ) . See ' search ' for the document id . Possible JSON replies : " status " : " error " , " exception " : " yyy " , " reason " : " xxxx " , " args " : " ( xxxx , ) " " status " : " ok " , ...
dsearch = get_docsearch ( ) doc = dsearch . get ( docid ) r = { 'type' : str ( type ( doc ) ) , 'nb_pages' : doc . nb_pages , 'labels' : [ l . name for l in doc . labels ] , 'first_line' : _get_first_line ( doc ) , 'pages' : [ ] } for page in doc . pages : nb_lines = 0 nb_words = 0 for line in page . boxes ...
def exists ( name , delimiter = DEFAULT_TARGET_DELIM ) : '''Ensure that a grain is set name The grain name delimiter A delimiter different from the default can be provided . Check whether a grain exists . Does not attempt to check or set the value .'''
name = re . sub ( delimiter , DEFAULT_TARGET_DELIM , name ) ret = { 'name' : name , 'changes' : { } , 'result' : True , 'comment' : 'Grain exists' } _non_existent = object ( ) existing = __salt__ [ 'grains.get' ] ( name , _non_existent ) if existing is _non_existent : ret [ 'result' ] = False ret [ 'comment' ] ...
def ticket_macro_apply ( self , ticket_id , id , ** kwargs ) : "https : / / developer . zendesk . com / rest _ api / docs / core / macros # show - ticket - after - changes"
api_path = "/api/v2/tickets/{ticket_id}/macros/{id}/apply.json" api_path = api_path . format ( ticket_id = ticket_id , id = id ) return self . call ( api_path , ** kwargs )
def call ( self , * args , ** kwargs ) : """Delegates to ` subprocess . check _ call ` ."""
args , kwargs = self . __process__ ( * args , ** kwargs ) return check_call ( args , ** kwargs )
def read_pandas ( self , format = 'table' , ** kwargs ) : """Read using : mod : ` pandas ` . The function ` ` pandas . read _ FORMAT ` ` is called where ` ` FORMAT ` ` is set from the argument * format * . * kwargs * are passed to this function . Supported formats likely include ` ` clipboard ` ` , ` ` csv ` ...
import pandas reader = getattr ( pandas , 'read_' + format , None ) if not callable ( reader ) : raise PKError ( 'unrecognized Pandas format %r: no function pandas.read_%s' , format , format ) with self . open ( 'rb' ) as f : return reader ( f , ** kwargs )
def in_base ( self , base ) : """Return value in ` ` base ` ` . : returns : Radix in ` ` base ` ` : rtype : Radix : raises ConvertError : if ` ` base ` ` is less than 2"""
if base == self . base : return copy . deepcopy ( self ) ( result , _ ) = Radices . from_rational ( self . as_rational ( ) , base ) return result
def project_interval_forward ( self , c_interval ) : """project c _ interval on the source transcript to the destination transcript : param c _ interval : an : class : ` hgvs . interval . Interval ` object on the source transcript : returns : c _ interval : an : class : ` hgvs . interval . Interval ` object o...
return self . dst_tm . g_to_c ( self . src_tm . c_to_g ( c_interval ) )
def tokens_to_indices ( self , tokens : List [ Token ] , vocabulary : Vocabulary , index_name : str ) -> Dict [ str , List [ TokenType ] ] : """Takes a list of tokens and converts them to one or more sets of indices . This could be just an ID for each token from the vocabulary . Or it could split each token int...
raise NotImplementedError
def f_dc_power ( effective_irradiance , cell_temp , module ) : """Calculate DC power using Sandia Performance model : param effective _ irradiance : effective irradiance [ suns ] : param cell _ temp : PV cell temperature [ degC ] : param module : PV module dictionary or pandas data frame : returns : i _ sc ...
dc = pvlib . pvsystem . sapm ( effective_irradiance , cell_temp , module ) fields = ( 'i_sc' , 'i_mp' , 'v_oc' , 'v_mp' , 'p_mp' ) return tuple ( dc [ field ] for field in fields )
def visit_Dict ( self , node : AST , dfltChaining : bool = True ) -> str : """Return dict representation of ` node ` s elements ."""
items = ( ': ' . join ( ( self . visit ( key ) , self . visit ( value ) ) ) for key , value in zip ( node . keys , node . values ) ) return f"{{{', '.join(items)}}}"
def enable_memcache ( source = None , release = None , package = None ) : """Determine if memcache should be enabled on the local unit @ param release : release of OpenStack currently deployed @ param package : package to derive OpenStack version deployed @ returns boolean Whether memcache should be enabled""...
_release = None if release : _release = release else : _release = os_release ( package , base = 'icehouse' ) if not _release : _release = get_os_codename_install_source ( source ) return CompareOpenStackReleases ( _release ) >= 'mitaka'
def write_transport ( self , data ) : """Write data to media transport . The data is encoded using the SBC codec and RTP encapsulated before being written to the transport file descriptor . : param array { byte } data : Payload data to encode , encapsulate and send ."""
if ( 'w' not in self . access_type ) : raise BTIncompatibleTransportAccessType return self . codec . encode ( self . fd , self . write_mtu , data )
def child_task ( self ) : '''child process - this holds all the GUI elements'''
from MAVProxy . modules . lib import mp_util import wx_processguard from wx_loader import wx from wxsettings_ui import SettingsDlg mp_util . child_close_fds ( ) app = wx . App ( False ) dlg = SettingsDlg ( self . settings ) dlg . parent_pipe = self . parent_pipe dlg . ShowModal ( ) dlg . Destroy ( )
def intermediary_to_dot ( tables , relationships , output ) : """Save the intermediary representation to dot format ."""
dot_file = _intermediary_to_dot ( tables , relationships ) with open ( output , "w" ) as file_out : file_out . write ( dot_file )
async def disconnect ( self , sid , namespace = None ) : """Disconnect a client . The only difference with the : func : ` socketio . Server . disconnect ` method is that when the ` ` namespace ` ` argument is not given the namespace associated with the class is used . Note : this method is a coroutine ."""
return await self . server . disconnect ( sid , namespace = namespace or self . namespace )
def destroy_cloudwatch_log_event ( app = '' , env = 'dev' , region = '' ) : """Destroy Cloudwatch log event . Args : app ( str ) : Spinnaker Application name . env ( str ) : Deployment environment . region ( str ) : AWS region . Returns : bool : True upon successful completion ."""
session = boto3 . Session ( profile_name = env , region_name = region ) cloudwatch_client = session . client ( 'logs' ) # FIXME : see below # TODO : Log group name is required , where do we get it if it is not in application - master - env . json ? cloudwatch_client . delete_subscription_filter ( logGroupName = '/aws/l...
def _lscmp ( a , b ) : '''Compares two strings in a cryptographically save way : Runtime is not affected by length of common prefix .'''
return not sum ( 0 if x == y else 1 for x , y in zip ( a , b ) ) and len ( a ) == len ( b )
def _to_patches ( self , X ) : """Reshapes input to patches of the size of classifier ' s receptive field . For example : input X shape : [ n _ samples , n _ pixels _ y , n _ pixels _ x , n _ bands ] output : [ n _ samples * n _ pixels _ y / receptive _ field _ y * n _ pixels _ x / receptive _ field _ x , r...
window = self . patch_size asteps = self . patch_size if len ( X . shape ) == 4 : window += ( 0 , ) asteps += ( 1 , ) image_view = rolling_window ( X , window , asteps ) new_shape = image_view . shape return image_view , new_shape
def pst_from_io_files ( tpl_files , in_files , ins_files , out_files , pst_filename = None ) : """generate a Pst instance from the model io files . If ' inschek ' is available ( either in the current directory or registered with the system variables ) and the model output files are available , then the observ...
par_names = set ( ) if not isinstance ( tpl_files , list ) : tpl_files = [ tpl_files ] if not isinstance ( in_files , list ) : in_files = [ in_files ] assert len ( in_files ) == len ( tpl_files ) , "len(in_files) != len(tpl_files)" for tpl_file in tpl_files : assert os . path . exists ( tpl_file ) , "templa...
def _select_ps ( p ) : # There are more generic ways of doing this but profiling # revealed that selecting these points is one of the slow # things that is easy to change . This is about 11 times # faster than the generic algorithm it is replacing . # it is possible that different break points could yield # better esti...
if p >= .99 : return .990 , .995 , .999 elif p >= .975 : return .975 , .990 , .995 elif p >= .95 : return .950 , .975 , .990 elif p >= .9125 : return .900 , .950 , .975 elif p >= .875 : return .850 , .900 , .950 elif p >= .825 : return .800 , .850 , .900 elif p >= .7625 : return .750 , .800 ...
def _parse_area ( self , area_xml ) : """Parses an Area tag , which is effectively a room , depending on how the Lutron controller programming was done ."""
area = Area ( self . _lutron , name = area_xml . get ( 'Name' ) , integration_id = int ( area_xml . get ( 'IntegrationID' ) ) , occupancy_group_id = area_xml . get ( 'OccupancyGroupAssignedToID' ) ) for output_xml in area_xml . find ( 'Outputs' ) : output = self . _parse_output ( output_xml ) area . add_output ...
def get_tree_info ( decision_tree , feature_names = None , ** export_graphviz_kwargs ) : # type : ( . . . ) - > TreeInfo """Convert DecisionTreeClassifier or DecisionTreeRegressor to an inspectable object ."""
return TreeInfo ( criterion = decision_tree . criterion , tree = _get_root_node_info ( decision_tree , feature_names ) , graphviz = tree2dot ( decision_tree , feature_names = feature_names , ** export_graphviz_kwargs ) , is_classification = isinstance ( decision_tree , ClassifierMixin ) , )
def cfmakeraw ( tflags ) : """Given a list returned by : py : func : ` termios . tcgetattr ` , return a list modified in a manner similar to the ` cfmakeraw ( ) ` C library function , but additionally disabling local echo ."""
# BSD : https : / / github . com / freebsd / freebsd / blob / master / lib / libc / gen / termios . c # L162 # Linux : https : / / github . com / lattera / glibc / blob / master / termios / cfmakeraw . c # L20 iflag , oflag , cflag , lflag , ispeed , ospeed , cc = tflags iflag &= ~ flags ( 'IMAXBEL IXOFF INPCK BRKINT P...
def add_dipole_gwb ( psr , dist = 1 , ngw = 1000 , seed = None , flow = 1e-8 , fhigh = 1e-5 , gwAmp = 1e-20 , alpha = - 0.66 , logspacing = True , dipoleamps = None , dipoledir = None , dipolemag = None ) : """Add a stochastic background from inspiraling binaries distributed according to a pure dipole distributio...
gwb = GWB ( ngw , seed , flow , fhigh , gwAmp , alpha , logspacing , dipoleamps , dipoledir , dipolemag ) gwb . add_gwb ( psr , dist ) return gwb
def email ( random = random , * args , ** kwargs ) : """Return an e - mail address > > > mock _ random . seed ( 0) > > > email ( random = mock _ random ) ' onion @ bag - of - heroic - chimps . sexy ' > > > email ( random = mock _ random ) ' agatha - incrediblebritches - spam @ amazingbritches . click ' ...
if 'name' in kwargs and kwargs [ 'name' ] : words = kwargs [ 'name' ] else : words = random . choice ( [ noun ( random = random ) , name ( random = random ) , name ( random = random ) + "+spam" , ] ) return _slugify ( words ) + "@" + domain ( random = random )
def clean_existing ( self , value ) : """Clean the data and return an existing document with its fields updated based on the cleaned values ."""
existing_pk = value [ self . pk_field ] try : obj = self . fetch_existing ( existing_pk ) except ReferenceNotFoundError : raise ValidationError ( 'Object does not exist.' ) orig_data = self . get_orig_data_from_existing ( obj ) # Clean the data ( passing the new data dict and the original data to # the schema )...
def role_create ( name , profile = None , ** connection_args ) : '''Create a named role . CLI Example : . . code - block : : bash salt ' * ' keystone . role _ create admin'''
kstone = auth ( profile , ** connection_args ) if 'Error' not in role_get ( name = name , profile = profile , ** connection_args ) : return { 'Error' : 'Role "{0}" already exists' . format ( name ) } kstone . roles . create ( name ) return role_get ( name = name , profile = profile , ** connection_args )
def tx_verify ( cls , verified_block_txids , tx ) : """Given the block ' s verified block txids , verify that a transaction is legit . @ tx must be a dict with the following fields : * locktime : int * version : int * vin : list of dicts with : * vout : int , * hash : hex str * sequence : int ( option...
tx_hash = cls . tx_hash ( tx ) return tx_hash in verified_block_txids
def get_path ( self , key , rel_to_cwd = False , rel_to_conf = False ) : """Retrieve a path from the config , resolving it against the invokation directory or the configuration file directory , depending on whether it was passed through the command - line or the configuration file . Args : key : str , the...
if key in self . __cli : path = self . __cli [ key ] from_conf = False else : path = self . __config . get ( key ) from_conf = True if not isinstance ( path , str ) : return None res = self . __abspath ( path , from_conf ) if rel_to_cwd : return os . path . relpath ( res , self . __invoke_dir ) ...
def robust_backtrack ( self ) : """Estimate step size L by computing a linesearch that guarantees that F < = Q according to the robust FISTA backtracking strategy in : cite : ` florea - 2017 - robust ` . This also updates all the supporting variables ."""
self . L *= self . L_gamma_d maxiter = self . L_maxiter iterBTrack = 0 linesearch = 1 self . store_Yprev ( ) while linesearch and iterBTrack < maxiter : t = float ( 1. + np . sqrt ( 1. + 4. * self . L * self . Tk ) ) / ( 2. * self . L ) T = self . Tk + t y = ( self . Tk * self . var_xprv ( ) + t * self . ZZ...
def items ( self ) : """Loads the items this Installation refers to ."""
for id in self . _items : yield self . store . getItemByID ( int ( id ) )
def get_children ( self ) : """Get the child nodes below this node . : returns : The children . : rtype : iterable ( NodeNG )"""
for field in self . _astroid_fields : attr = getattr ( self , field ) if attr is None : continue if isinstance ( attr , ( list , tuple ) ) : yield from attr else : yield attr
def _get_vcf_breakends ( hydra_file , genome_2bit , options = None ) : """Parse BEDPE input , yielding VCF ready breakends ."""
if options is None : options = { } for features in group_hydra_breakends ( hydra_parser ( hydra_file , options ) ) : if len ( features ) == 1 and is_deletion ( features [ 0 ] , options ) : yield build_vcf_deletion ( features [ 0 ] , genome_2bit ) elif len ( features ) == 1 and is_tandem_dup ( featur...
def get_new_profile_template ( self ) : """Retrieves the profile template for a given server profile . Returns : dict : Server profile template ."""
uri = '{}/new-profile-template' . format ( self . data [ "uri" ] ) return self . _helper . do_get ( uri )
def clean_df ( df , fill_nan = True , drop_empty_columns = True ) : """Clean a pandas dataframe by : 1 . Filling empty values with Nan 2 . Dropping columns with all empty values Args : df : Pandas DataFrame fill _ nan ( bool ) : If any empty values ( strings , None , etc ) should be replaced with NaN dr...
if fill_nan : df = df . fillna ( value = np . nan ) if drop_empty_columns : df = df . dropna ( axis = 1 , how = 'all' ) return df . sort_index ( )
def runfile ( filename , args = None , wdir = None , namespace = None , post_mortem = False ) : """Run filename args : command line arguments ( string ) wdir : working directory post _ mortem : boolean , whether to enter post - mortem mode on error"""
try : filename = filename . decode ( 'utf-8' ) except ( UnicodeError , TypeError , AttributeError ) : # UnicodeError , TypeError - - > eventually raised in Python 2 # AttributeError - - > systematically raised in Python 3 pass if __umr__ . enabled : __umr__ . run ( ) if args is not None and not isinstance (...
def distinct_counts ( self ) : """Return counts for each distinct haplotype ."""
# hash the haplotypes k = [ hash ( self . values [ : , i ] . tobytes ( ) ) for i in range ( self . shape [ 1 ] ) ] # count and sort # noinspection PyArgumentList counts = sorted ( collections . Counter ( k ) . values ( ) , reverse = True ) return np . asarray ( counts )
def delete_worksheet ( self , worksheet_id ) : """Deletes a worksheet by it ' s id"""
url = self . build_url ( self . _endpoints . get ( 'get_worksheet' ) . format ( id = quote ( worksheet_id ) ) ) return bool ( self . session . delete ( url ) )
def process_key_dict ( self , key , d , level ) : """Process key value dicts e . g . METADATA " key " " value " """
# add any composite level comments comments = d . get ( "__comments__" , { } ) lines = [ ] self . _add_type_comment ( level , comments , lines ) lines += [ self . add_start_line ( key , level ) ] lines += self . process_dict ( d , level , comments ) lines . append ( self . add_end_line ( level , 1 , key ) ) return line...
def get_tgt ( self , temperature = None , structure = None , quad = None ) : """Gets the thermodynamic Gruneisen tensor ( TGT ) by via an integration of the GGT weighted by the directional heat capacity . See refs : R . N . Thurston and K . Brugger , Phys . Rev . 113 , A1604 ( 1964 ) . K . Brugger Phys . ...
if temperature and not structure : raise ValueError ( "If using temperature input, you must also " "include structure" ) quad = quad if quad else DEFAULT_QUAD points = quad [ 'points' ] weights = quad [ 'weights' ] num , denom , c = np . zeros ( ( 3 , 3 ) ) , 0 , 1 for p , w in zip ( points , weights ) : gk = E...
def find_guests ( names , path = None ) : '''Return a dict of hosts and named guests path path to the container parent default : / var / lib / lxc ( system default ) . . versionadded : : 2015.8.0'''
ret = { } names = names . split ( ',' ) for data in _list_iter ( path = path ) : host , stat = next ( six . iteritems ( data ) ) for state in stat : for name in stat [ state ] : if name in names : if host in ret : ret [ host ] . append ( name ) ...
def get_activities_for_objective ( self , objective_id ) : """Gets the activities for the given objective . In plenary mode , the returned list contains all of the activities mapped to the objective ` ` Id ` ` or an error results if an Id in the supplied list is not found or inaccessible . Otherwise , inacc...
# Implemented from template for # osid . learning . ActivityLookupSession . get _ activities _ for _ objective _ template # NOTE : This implementation currently ignores plenary view collection = JSONClientValidated ( 'learning' , collection = 'Activity' , runtime = self . _runtime ) result = collection . find ( dict ( ...
def get_full_order_book ( self , symbol ) : """Get a list of all bids and asks aggregated by price for a symbol . This call is generally used by professional traders because it uses more server resources and traffic , and Kucoin has strict access frequency control . https : / / docs . kucoin . com / # get - f...
data = { 'symbol' : symbol } return self . _get ( 'market/orderbook/level2' , False , data = data )
def form_query ( query_type , query ) : """Returns a multi match query"""
fields = [ field + "^" + str ( SEARCH_BOOSTS [ field ] ) if field in SEARCH_BOOSTS else field for field in SEARCH_FIELDS ] return Q ( "multi_match" , fields = fields , query = query , type = query_type )
def flush ( self , safe = None ) : '''Perform all database operations currently in the queue'''
result = None for index , op in enumerate ( self . queue ) : try : result = op . execute ( ) except : self . clear_queue ( ) self . clear_cache ( ) raise self . clear_queue ( ) return result
def quat2mat ( quaternion ) : """Converts given quaternion ( x , y , z , w ) to matrix . Args : quaternion : vec4 float angles Returns : 3x3 rotation matrix"""
q = np . array ( quaternion , dtype = np . float32 , copy = True ) [ [ 3 , 0 , 1 , 2 ] ] n = np . dot ( q , q ) if n < EPS : return np . identity ( 3 ) q *= math . sqrt ( 2.0 / n ) q = np . outer ( q , q ) return np . array ( [ [ 1.0 - q [ 2 , 2 ] - q [ 3 , 3 ] , q [ 1 , 2 ] - q [ 3 , 0 ] , q [ 1 , 3 ] + q [ 2 , 0 ...
def _print_bar ( self ) : '''Print a progress bar .'''
self . _print ( '[' ) for position in range ( self . _bar_width ) : position_fraction = position / ( self . _bar_width - 1 ) position_bytes = position_fraction * self . max_value if position_bytes < ( self . continue_value or 0 ) : self . _print ( '+' ) elif position_bytes <= ( self . continue_v...
def create_cities_csv ( filename = "places2k.txt" , output = "cities.csv" ) : """Takes the places2k . txt from USPS and creates a simple file of all cities ."""
with open ( filename , 'r' ) as city_file : with open ( output , 'w' ) as out : for line in city_file : # Drop Puerto Rico ( just looking for the 50 states ) if line [ 0 : 2 ] == "PR" : continue # Per census . gov , characters 9-72 are the name of the city or plac...
def _get_lang ( self , * args , ** kwargs ) : """Let users select language"""
if "lang" in kwargs : if kwargs [ "lang" ] in self . _available_languages : self . lang = kwargs [ "lang" ]
def change_time ( filename , newtime ) : """Change the time of a process or group of processes by writing a new time to the time file ."""
with open ( filename , "w" ) as faketimetxt_handle : faketimetxt_handle . write ( "@" + newtime . strftime ( "%Y-%m-%d %H:%M:%S" ) )
def key_pair_from_ed25519_key ( hex_private_key ) : """Generate base58 encode public - private key pair from a hex encoded private key"""
priv_key = crypto . Ed25519SigningKey ( bytes . fromhex ( hex_private_key ) [ : 32 ] , encoding = 'bytes' ) public_key = priv_key . get_verifying_key ( ) return CryptoKeypair ( private_key = priv_key . encode ( encoding = 'base58' ) . decode ( 'utf-8' ) , public_key = public_key . encode ( encoding = 'base58' ) . decod...
def __writeDocstring ( self ) : """Runs eternally , dumping out docstring line batches as they get fed in . Replaces original batches of docstring lines with modified versions fed in via send ."""
while True : firstLineNum , lastLineNum , lines = ( yield ) newDocstringLen = lastLineNum - firstLineNum + 1 while len ( lines ) < newDocstringLen : lines . append ( '' ) # Substitute the new block of lines for the original block of lines . self . docLines [ firstLineNum : lastLineNum + 1 ] ...
def erase_in_line ( self , how = 0 , private = False ) : """Erase a line in a specific way . Character attributes are set to cursor attributes . : param int how : defines the way the line should be erased in : * ` ` 0 ` ` - - Erases from cursor to end of line , including cursor position . * ` ` 1 ` ` - - ...
self . dirty . add ( self . cursor . y ) if how == 0 : interval = range ( self . cursor . x , self . columns ) elif how == 1 : interval = range ( self . cursor . x + 1 ) elif how == 2 : interval = range ( self . columns ) line = self . buffer [ self . cursor . y ] for x in interval : line [ x ] = self ....
def singlehtml_sidebars ( app ) : """When using a ` ` singlehtml ` ` builder , replace the ` ` html _ sidebars ` ` config with ` ` singlehtml _ sidebars ` ` . This can be used to change what sidebars are rendered for the single page called ` ` " index " ` ` by the builder ."""
if app . config . singlehtml_sidebars is not None and isinstance ( app . builder , SingleFileHTMLBuilder ) : app . config . html_sidebars = app . config . singlehtml_sidebars
def create ( self , name = None , description = None ) : """Creates a new , empty dataset . Parameters name : str , optional The name of the dataset . description : str , optional The description of the dataset . Returns request . Response The response contains the properties of a new dataset as a J...
uri = URITemplate ( self . baseuri + '/{owner}' ) . expand ( owner = self . username ) return self . session . post ( uri , json = self . _attribs ( name , description ) )
def headloss_exp_general ( Vel , KMinor ) : """Return the minor head loss due to expansion in the general case . This equation applies to both laminar and turbulent flows ."""
# Checking input validity ut . check_range ( [ Vel , ">0" , "Velocity" ] , [ KMinor , '>=0' , 'K minor' ] ) return KMinor * Vel ** 2 / ( 2 * gravity . magnitude )
def lag_matrix ( blk , max_lag = None ) : """Finds the lag matrix for a given 1 - D block sequence . Parameters blk : An iterable with well - defined length . Don ' t use this function with Stream objects ! max _ lag : The size of the result , the lags you ' d need . Defaults to ` ` len ( blk ) - 1 ` ` ...
if max_lag is None : max_lag = len ( blk ) - 1 elif max_lag >= len ( blk ) : raise ValueError ( "Block length should be higher than order" ) return [ [ sum ( blk [ n - i ] * blk [ n - j ] for n in xrange ( max_lag , len ( blk ) ) ) for i in xrange ( max_lag + 1 ) ] for j in xrange ( max_lag + 1 ) ]
def main ( argv = sys . argv ) : # type : ( List [ str ] ) - > int """Parse and check the command line arguments ."""
parser = optparse . OptionParser ( usage = """\ usage: %prog [options] -o <output_path> <module_path> [exclude_pattern, ...] Look recursively in <module_path> for Python modules and packages and create one reST file with automodule directives per package in the <output_path>. The <exclude_pattern>s can be file and/or...
def set_dict_item ( dct , name_string , set_to ) : """Sets dictionary item identified by name _ string to set _ to . name _ string is the indentifier generated using flatten _ dict . Maintains the type of the orginal object in dct and tries to convert set _ to to that type ."""
key_strings = str ( name_string ) . split ( '-->' ) d = dct for ks in key_strings [ : - 1 ] : d = d [ ks ] item_type = type ( d [ key_strings [ - 1 ] ] ) d [ key_strings [ - 1 ] ] = item_type ( set_to )
def get_encounter_list_for_patient ( self , patient_id ) : """invokes TouchWorksMagicConstants . ACTION _ GET _ ENCOUNTER _ LIST _ FOR _ PATIENT action : return : JSON response"""
magic = self . _magic_json ( action = TouchWorksMagicConstants . ACTION_GET_ENCOUNTER_LIST_FOR_PATIENT , app_name = self . _app_name , token = self . _token . token , patient_id = patient_id ) response = self . _http_request ( TouchWorksEndPoints . MAGIC_JSON , data = magic ) result = self . _get_results_or_raise_if_ma...
def prettify ( self , depth = 0 , separator = " " , last = True , pre = False , inline = False ) : """Same as : meth : ` toString ` , but returns prettified element with content . Note : This method is partially broken , and can sometimes create unexpected results . Returns : str : Prettified string ."""
output = "" if self . getTagName ( ) != "" and self . tagToString ( ) . strip ( ) == "" : return "" # if not inside < pre > and not inline , shift tag to the right if not pre and not inline : output += ( depth * separator ) # for < pre > set ' pre ' flag if self . getTagName ( ) . lower ( ) == "pre" and self . ...
def get_values ( text ) : """Accept a string such as BACKGROUNDCOLOR [ r ] [ g ] [ b ] and return [ ' r ' , ' g ' , ' b ' ]"""
res = re . findall ( r"\[(.*?)\]" , text ) values = [ ] for r in res : if "|" in r : params = r . split ( "|" ) for p in params : values . append ( p ) else : values . append ( r ) values = [ str ( v . lower ( ) ) for v in values ] return values
def dataset_dirpath ( dataset_name = None , task = None , ** kwargs ) : """Get the path of the corresponding dataset file . Parameters dataset _ name : str , optional The name of the dataset . Used to define a sub - directory to contain all instances of the dataset . If not given , a dataset - agnostic dire...
dataset_dir_path = data_dirpath ( task = task , ** kwargs ) if dataset_name : dataset_dir_name = _snail_case ( dataset_name ) dataset_dir_path = os . path . join ( dataset_dir_path , dataset_dir_name ) os . makedirs ( dataset_dir_path , exist_ok = True ) return dataset_dir_path
def head ( self , lines = 10 ) : """Return the top lines of the file ."""
self . seek ( 0 ) for i in range ( lines ) : if not self . seek_line_forward ( ) : break end_pos = self . file . tell ( ) self . seek ( 0 ) data = self . file . read ( end_pos - 1 ) if data : return self . splitlines ( data ) else : return [ ]
def inject_default_call ( self , high ) : '''Sets . call function to a state , if not there . : param high : : return :'''
for chunk in high : state = high [ chunk ] if not isinstance ( state , collections . Mapping ) : continue for state_ref in state : needs_default = True if not isinstance ( state [ state_ref ] , list ) : continue for argset in state [ state_ref ] : if i...
def one ( cls , filter = None , ** kwargs ) : """Return the first document matching the filter"""
from mongoframes . queries import Condition , Group , to_refs # Flatten the projection kwargs [ 'projection' ] , references , subs = cls . _flatten_projection ( kwargs . get ( 'projection' , cls . _default_projection ) ) # Find the document if isinstance ( filter , ( Condition , Group ) ) : filter = filter . to_dic...
def shift ( self , periods = 1 , freq = None , axis = 'major' ) : """Shift index by desired number of periods with an optional time freq . The shifted data will not include the dropped periods and the shifted axis will be smaller than the original . This is different from the behavior of DataFrame . shift ( )...
if freq : return self . tshift ( periods , freq , axis = axis ) return super ( ) . slice_shift ( periods , axis = axis )
def get_extension_license_data ( self , extension_id ) : """GetExtensionLicenseData . [ Preview API ] : param str extension _ id : : rtype : : class : ` < ExtensionLicenseData > < azure . devops . v5_0 . licensing . models . ExtensionLicenseData > `"""
route_values = { } if extension_id is not None : route_values [ 'extensionId' ] = self . _serialize . url ( 'extension_id' , extension_id , 'str' ) response = self . _send ( http_method = 'GET' , location_id = '004a420a-7bef-4b7f-8a50-22975d2067cc' , version = '5.0-preview.1' , route_values = route_values ) return ...
def rekey ( self , key , nonce = None , recovery_key = False ) : """Enter a single recovery key share to progress the rekey of the Vault . If the threshold number of recovery key shares is reached , Vault will complete the rekey . Otherwise , this API must be called multiple times until that threshold is met . ...
params = { 'key' : key , } if nonce is not None : params [ 'nonce' ] = nonce api_path = '/v1/sys/rekey/update' if recovery_key : api_path = '/v1/sys/rekey-recovery-key/update' response = self . _adapter . put ( url = api_path , json = params , ) return response . json ( )
def hash ( self ) : """Create a unique hash for what is currently playing . The hash is based on title , artist , album and total time . It should always be the same for the same content , but it is not guaranteed ."""
base = '{0}{1}{2}{3}' . format ( self . title , self . artist , self . album , self . total_time ) return hashlib . sha256 ( base . encode ( 'utf-8' ) ) . hexdigest ( )
def is_addable ( self , device , automount = True ) : """Check if device can be added with ` ` auto _ add ` ` ."""
if not self . is_automount ( device , automount ) : return False if device . is_filesystem : return not device . is_mounted if device . is_crypto : return self . _prompt and not device . is_unlocked if device . is_partition_table : return any ( self . is_addable ( dev ) for dev in self . get_all_handlea...
def main ( args = None ) : """Main function for usage of psyplot from the command line This function creates a parser that parses command lines to the : func : ` make _ plot ` functions or ( if the ` ` psyplot _ gui ` ` module is present , to the : func : ` psyplot _ gui . start _ app ` function ) Returns ...
try : from psyplot_gui import get_parser as _get_parser except ImportError : logger . debug ( 'Failed to import gui' , exc_info = True ) parser = get_parser ( create = False ) parser . update_arg ( 'output' , required = True ) parser . create_arguments ( ) parser . parse2func ( args ) else : ...
def unregistercls ( self , schemacls = None , data_types = None ) : """Unregister schema class or associated data _ types . : param type schemacls : sub class of Schema . : param list data _ types : data _ types to unregister ."""
return _REGISTRY . unregistercls ( schemacls = schemacls , data_types = data_types )
def _use_private_key ( self , client_certchain_file : str , client_key_file : str , client_key_type : OpenSslFileTypeEnum , client_key_password : str ) -> None : """The certificate chain file must be in PEM format . Private method because it should be set via the constructor ."""
# Ensure the files exist with open ( client_certchain_file ) : pass with open ( client_key_file ) : pass self . _ssl_ctx . use_certificate_chain_file ( client_certchain_file ) self . _ssl_ctx . set_private_key_password ( client_key_password ) try : self . _ssl_ctx . use_PrivateKey_file ( client_key_file , c...
def smooth_frames ( self , sigtype = 'physical' ) : """Convert expanded signals with different samples / frame into a uniform numpy array . Input parameters - sigtype ( default = ' physical ' ) : Specifies whether to mooth the e _ p _ signal field ( ' physical ' ) , or the e _ d _ signal field ( ' digital...
spf = self . samps_per_frame [ : ] for ch in range ( len ( spf ) ) : if spf [ ch ] is None : spf [ ch ] = 1 # Total samples per frame tspf = sum ( spf ) if sigtype == 'physical' : n_sig = len ( self . e_p_signal ) sig_len = int ( len ( self . e_p_signal [ 0 ] ) / spf [ 0 ] ) signal = np . zeros ...
def _htmlify_text ( self , s ) : """Make text HTML - friendly ."""
colored = self . _handle_ansi_color_codes ( html . escape ( s ) ) return linkify ( self . _buildroot , colored , self . _linkify_memo ) . replace ( '\n' , '</br>' )
def list ( self ) : """Get a list of staged ( in - progress ) imports . : return : : class : ` imports . Import < imports . Import > ` list"""
schema = ImportSchema ( ) resp = self . service . list ( self . base ) return self . service . decode ( schema , resp , many = True )
def altitudes ( self ) : '''A list of the altitudes of each vertex [ AltA , AltB , AltC ] , list of floats . An altitude is the shortest distance from a vertex to the side opposite of it .'''
a = self . area * 2 return [ a / self . a , a / self . b , a / self . c ]
def _get_metadata ( field , expr , metadata_expr , no_metadata_rule ) : """Find the correct metadata expression for the expression . Parameters field : { ' deltas ' , ' checkpoints ' } The kind of metadata expr to lookup . expr : Expr The baseline expression . metadata _ expr : Expr , ' auto ' , or None...
if isinstance ( metadata_expr , bz . Expr ) or metadata_expr is None : return metadata_expr try : return expr . _child [ '_' . join ( ( ( expr . _name or '' ) , field ) ) ] except ( ValueError , AttributeError ) : if no_metadata_rule == 'raise' : raise ValueError ( "no %s table could be reflected fo...
def add_footpoint_and_equatorial_drifts ( inst , equ_mer_scalar = 'equ_mer_drifts_scalar' , equ_zonal_scalar = 'equ_zon_drifts_scalar' , north_mer_scalar = 'north_footpoint_mer_drifts_scalar' , north_zon_scalar = 'north_footpoint_zon_drifts_scalar' , south_mer_scalar = 'south_footpoint_mer_drifts_scalar' , south_zon_sc...
inst [ 'equ_mer_drift' ] = { 'data' : inst [ equ_mer_scalar ] * inst [ mer_drift ] , 'units' : 'm/s' , 'long_name' : 'Equatorial meridional ion velocity' , 'notes' : ( 'Velocity along meridional direction, perpendicular ' 'to field and within meridional plane, scaled to ' 'magnetic equator. Positive is up at magnetic e...
def escape_code_start ( source , ext , language = 'python' ) : """Escape code start with ' # '"""
parser = StringParser ( language ) for pos , line in enumerate ( source ) : if not parser . is_quoted ( ) and is_escaped_code_start ( line , ext ) : source [ pos ] = _SCRIPT_EXTENSIONS . get ( ext , { } ) . get ( 'comment' , '#' ) + ' ' + line parser . read_line ( line ) return source
def indexbox ( msg = "Shall I continue?" , title = " " , choices = ( "Yes" , "No" ) , image = None , default_choice = 'Yes' , cancel_choice = 'No' ) : """Display a buttonbox with the specified choices . : param str msg : the msg to be displayed : param str title : the window title : param list choices : a lis...
reply = bb . buttonbox ( msg = msg , title = title , choices = choices , image = image , default_choice = default_choice , cancel_choice = cancel_choice ) if reply is None : return None for i , choice in enumerate ( choices ) : if reply == choice : return i msg = ( "There is a program logic error in the...
def _descriptiveIdentifier ( contactType ) : """Get a descriptive identifier for C { contactType } , taking into account the fact that it might not have implemented the C { descriptiveIdentifier } method . @ type contactType : L { IContactType } provider . @ rtype : C { unicode }"""
descriptiveIdentifierMethod = getattr ( contactType , 'descriptiveIdentifier' , None ) if descriptiveIdentifierMethod is not None : return descriptiveIdentifierMethod ( ) warn ( "IContactType now has the 'descriptiveIdentifier'" " method, %s did not implement it" % ( contactType . __class__ , ) , category = Pending...
def _update_justification ( self , justification ) : """Updates horizontal text justification button Parameters justification : String in [ " left " , " center " , " right " ] \t Switches button to untoggled if False and toggled if True"""
states = { "left" : 2 , "center" : 0 , "right" : 1 } self . justify_tb . state = states [ justification ] self . justify_tb . toggle ( None ) self . justify_tb . Refresh ( )
def describe_topic_rule ( ruleName , region = None , key = None , keyid = None , profile = None ) : '''Given a topic rule name describe its properties . Returns a dictionary of interesting properties . CLI Example : . . code - block : : bash salt myminion boto _ iot . describe _ topic _ rule myrule'''
try : conn = _get_conn ( region = region , key = key , keyid = keyid , profile = profile ) rule = conn . get_topic_rule ( ruleName = ruleName ) if rule and 'rule' in rule : rule = rule [ 'rule' ] keys = ( 'ruleName' , 'sql' , 'description' , 'actions' , 'ruleDisabled' ) return { 'rul...
def depth_october_average_ground_temperature ( self , value = None ) : """Corresponds to IDD Field ` depth _ october _ average _ ground _ temperature ` Args : value ( float ) : value for IDD Field ` depth _ october _ average _ ground _ temperature ` Unit : C if ` value ` is None it will not be checked again...
if value is not None : try : value = float ( value ) except ValueError : raise ValueError ( 'value {} need to be of type float ' 'for field `depth_october_average_ground_temperature`' . format ( value ) ) self . _depth_october_average_ground_temperature = value