signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def string_build ( self , data , modname = "" , path = None ) : """Build astroid from source code string ."""
module = self . _data_build ( data , modname , path ) module . file_bytes = data . encode ( "utf-8" ) return self . _post_build ( module , "utf-8" )
def set_permissions ( obj_name , principal , permissions , access_mode = 'grant' , applies_to = None , obj_type = 'file' , reset_perms = False , protected = None ) : '''Set the permissions of an object . This can be a file , folder , registry key , printer , service , etc . . . Args : obj _ name ( str ) : T...
# Set up applies _ to defaults used by registry and file types if applies_to is None : if 'registry' in obj_type . lower ( ) : applies_to = 'this_key_subkeys' elif obj_type . lower ( ) == 'file' : applies_to = 'this_folder_subfolders_files' # If you don ' t pass ` obj _ name ` it will create a b...
def url_norm ( url , encoding = None ) : """Normalize the given URL which must be quoted . Supports unicode hostnames ( IDNA encoding ) according to RFC 3490. @ return : ( normed url , idna flag ) @ rtype : tuple of length two"""
if isinstance ( url , unicode ) : # try to decode the URL to ascii since urllib . unquote ( ) # handles non - unicode strings differently try : url = url . encode ( 'ascii' ) except UnicodeEncodeError : pass encode_unicode = True else : encode_unicode = False urlparts = list ( urlparse ....
def _build_zmat ( self , construction_table ) : """Create the Zmatrix from a construction table . Args : Construction table ( pd . DataFrame ) : Returns : Zmat : A new instance of : class : ` Zmat ` ."""
c_table = construction_table default_cols = [ 'atom' , 'b' , 'bond' , 'a' , 'angle' , 'd' , 'dihedral' ] optional_cols = list ( set ( self . columns ) - { 'atom' , 'x' , 'y' , 'z' } ) zmat_frame = pd . DataFrame ( columns = default_cols + optional_cols , dtype = 'float' , index = c_table . index ) zmat_frame . loc [ : ...
def _ensure_started ( self ) : """Marks the API as started and runs all startup handlers"""
if not self . started : async_handlers = [ startup_handler for startup_handler in self . startup_handlers if introspect . is_coroutine ( startup_handler ) ] if async_handlers : loop = asyncio . get_event_loop ( ) loop . run_until_complete ( asyncio . gather ( * [ handler ( self ) for handler in ...
def _code2pys ( self ) : """Writes code to pys file Format : < row > \t < col > \t < tab > \t < code > \n"""
for key in self . code_array : key_str = u"\t" . join ( repr ( ele ) for ele in key ) code_str = self . code_array ( key ) if code_str is not None : out_str = key_str + u"\t" + code_str + u"\n" self . pys_file . write ( out_str . encode ( "utf-8" ) )
def paths ( self ) : """Get an iter of VenvPaths within the directory ."""
contents = os . listdir ( self . path ) contents = ( os . path . join ( self . path , path ) for path in contents ) contents = ( VenvPath ( path ) for path in contents ) return contents
async def is_leader_from_status ( self ) : """Check to see if this unit is the leader . Returns True if so , and False if it is not , or if leadership does not make sense ( e . g . , there is no leader in this application . ) This method is a kluge that calls FullStatus in the ClientFacade to get its inform...
app = self . name . split ( "/" ) [ 0 ] c = client . ClientFacade . from_connection ( self . connection ) status = await c . FullStatus ( None ) # FullStatus may be more up to date than our model , and the # unit may have gone away , or we may be doing something silly , # like trying to fetch leadership for a subordina...
def enrich_by_object_type ( request , json , fun , object_type , skip_nested = False , ** kwargs ) : """Take the JSON , find its subparts having the given object part and transform them by the given function . Other key - word arguments are passed to the function . . . testsetup : : from pprint import pprint ...
if not isinstance ( object_type , list ) : object_type = [ object_type ] predicate = lambda x : 'object_type' in x and x [ 'object_type' ] in object_type return enrich_by_predicate ( request , json , fun , predicate , skip_nested = skip_nested , ** kwargs )
def change_state_id ( self , state_id = None ) : """Changes the id of the state to a new id If no state _ id is passed as parameter , a new state id is generated . : param str state _ id : The new state id of the state : return :"""
if state_id is None : state_id = state_id_generator ( used_state_ids = [ self . state_id ] ) if not self . is_root_state and not self . is_root_state_of_library : used_ids = list ( self . parent . states . keys ( ) ) + [ self . parent . state_id , self . state_id ] if state_id in used_ids : state_id...
def convert ( self , value , * args , ** kwargs ) : # pylint : disable = arguments - differ """Take a path with $ HOME variables and resolve it to full path ."""
value = os . path . expanduser ( value ) return super ( ExpandPath , self ) . convert ( value , * args , ** kwargs )
def catFiles ( filesToCat , catFile ) : """Cats a bunch of files into one file . Ensures a no more than maxCat files are concatenated at each step ."""
if len ( filesToCat ) == 0 : # We must handle this case or the cat call will hang waiting for input open ( catFile , 'w' ) . close ( ) return maxCat = 25 system ( "cat %s > %s" % ( " " . join ( filesToCat [ : maxCat ] ) , catFile ) ) filesToCat = filesToCat [ maxCat : ] while len ( filesToCat ) > 0 : system...
def _get_error_reason ( response ) : """Extract error reason from the response . It might be either the ' reason ' or the entire response"""
try : body = response . json ( ) if body and 'reason' in body : return body [ 'reason' ] except ValueError : pass return response . content
def _property ( methode , zone , key , value ) : '''internal handler for set and clear _ property methode : string either set , add , or clear zone : string name of zone key : string name of property value : string value of property'''
ret = { 'status' : True } # generate update script cfg_file = None if methode not in [ 'set' , 'clear' ] : ret [ 'status' ] = False ret [ 'message' ] = 'unkown methode {0}!' . format ( methode ) else : cfg_file = salt . utils . files . mkstemp ( ) with salt . utils . files . fpopen ( cfg_file , 'w+' , m...
def scan_posts ( self , really = True , ignore_quit = False , quiet = True ) : """Rescan the site ."""
while ( self . db . exists ( 'site:lock' ) and int ( self . db . get ( 'site:lock' ) ) != 0 ) : self . logger . info ( "Waiting for DB lock..." ) time . sleep ( 0.5 ) self . db . incr ( 'site:lock' ) self . logger . info ( "Lock acquired." ) self . logger . info ( "Scanning site..." ) self . _site . scan_posts ...
def get_engine ( engine ) : """return our implementation"""
if engine == 'auto' : engine = get_option ( 'io.parquet.engine' ) if engine == 'auto' : # try engines in this order try : return PyArrowImpl ( ) except ImportError : pass try : return FastParquetImpl ( ) except ImportError : pass raise ImportError ( "Unable to fin...
def logout ( request ) : """View to forget the user"""
request . response . headers . extend ( forget ( request ) ) return { 'redirect' : request . POST . get ( 'came_from' , '/' ) }
def _as_document ( self , partition ) : """Converts partition to document indexed by to FTS index . Args : partition ( orm . Partition ) : partition to convert . Returns : dict with structure matches to BasePartitionIndex . _ schema ."""
doc = super ( self . __class__ , self ) . _as_document ( partition ) # pass time _ coverage to the _ index _ document . doc [ 'time_coverage' ] = partition . time_coverage return doc
def compute_optional_conf ( conf_name , default_value , ** all_config ) : """Returns * conf _ name * settings if provided in * all _ config * , else returns * default _ value * . Validates * conf _ name * value if provided ."""
conf_value = all_config . get ( conf_name ) if conf_value is not None : # Validate configuration value . conf_value = get_validator ( conf_name ) ( conf_value ) else : conf_value = default_value return conf_value
def _make_nodes ( self , cwd = None ) : """Cast generated nodes to be Arcana nodes"""
for i , node in NipypeMapNode . _make_nodes ( self , cwd = cwd ) : # " Cast " NiPype node to a Arcana Node and set Arcana Node # parameters node . __class__ = self . node_cls node . _environment = self . _environment node . _versions = self . _versions node . _wall_time = self . _wall_time node . _a...
def store_report_link ( backend , user , response , * args , ** kwargs ) : '''Part of the Python Social Auth Pipeline . Stores the result service URL reported by the LMS / LTI tool consumer so that we can use it later .'''
if backend . name is 'lti' : assignment_pk = response . get ( 'assignment_pk' , None ) assignment = get_object_or_404 ( Assignment , pk = assignment_pk ) lti_result , created = LtiResult . objects . get_or_create ( assignment = assignment , user = user ) if created : logger . debug ( "LTI result...
def read_dir ( self , path ) : """Reads the given path into the tree"""
self . tree = { } self . file_count = 0 self . path = path for root , _ , filelist in os . walk ( path ) : rel = root [ len ( path ) : ] . lstrip ( '/\\' ) # empty rel , means file is in root dir if not rel : rel = ' ' for filename in filelist : filename = filename . split ( '.' ) ...
def check_url ( self ) : """Try to get URL data from queue and check it ."""
try : url_data = self . urlqueue . get ( timeout = QUEUE_POLL_INTERVALL_SECS ) if url_data is not None : try : self . check_url_data ( url_data ) finally : self . urlqueue . task_done ( url_data ) self . setName ( self . origname ) except urlqueue . Empty : pa...
def genesis_host_port ( self , genesis_txn : dict ) -> tuple : """Given a genesis transaction , return its node host and port . : param genesis _ txn : genesis transaction as dict : return : node host and port"""
txn_data = genesis_txn [ 'data' ] if self == Protocol . V_13 else genesis_txn [ 'txn' ] [ 'data' ] [ 'data' ] return ( txn_data [ 'node_ip' ] , txn_data [ 'node_port' ] )
def scalar_inc_dec ( word , valence , is_cap_diff ) : """Check if the preceding words increase , decrease , or negate / nullify the valence"""
scalar = 0.0 word_lower = word . lower ( ) if word_lower in BOOSTER_DICT : scalar = BOOSTER_DICT [ word_lower ] if valence < 0 : scalar *= - 1 # check if booster / dampener word is in ALLCAPS ( while others aren ' t ) if word . isupper ( ) and is_cap_diff : if valence > 0 : s...
def convert ( path , source_fmt , target_fmt , select = 'result:mrs' , properties = True , show_status = False , predicate_modifiers = False , color = False , pretty_print = False , indent = None ) : """Convert between various DELPH - IN Semantics representations . Args : path ( str , file ) : filename , testsu...
if source_fmt . startswith ( 'eds' ) and not target_fmt . startswith ( 'eds' ) : raise ValueError ( 'Conversion from EDS to non-EDS currently not supported.' ) if indent : pretty_print = True indent = 4 if indent is True else safe_int ( indent ) if len ( tsql . inspect_query ( 'select ' + select ) [ 'projec...
def get_figure ( new_fig = True , subplot = '111' , params = None ) : """Function to be used for viewing - plotting , to initialize the matplotlib figure - axes . Args : new _ fig ( bool ) : Defines if a new figure will be created , if false current figure is used subplot ( tuple or matplolib subplot specif...
_get_plt ( ) if new_fig : fig = plt . figure ( ) else : fig = plt . gcf ( ) params = dict_if_none ( params ) if isinstance ( subplot , ( tuple , list ) ) : ax = fig . add_subplot ( * subplot , ** params ) else : ax = fig . add_subplot ( subplot , ** params ) return fig , ax
def _get_name_info ( name_index , name_list ) : """Helper to get optional details about named references Returns the dereferenced name as both value and repr if the name list is defined . Otherwise returns the name index and its repr ( ) ."""
argval = name_index if ( name_list is not None # PyPY seems to " optimize " out constant names , # so we need for that : and name_index < len ( name_list ) ) : argval = name_list [ name_index ] argrepr = argval else : argrepr = repr ( argval ) return argval , argrepr
def Ignore ( self , target , dependency ) : """Ignore a dependency ."""
tlist = self . arg2nodes ( target , self . fs . Entry ) dlist = self . arg2nodes ( dependency , self . fs . Entry ) for t in tlist : t . add_ignore ( dlist ) return tlist
def crop ( self , left , right ) : """Remove given seconds from either end of time series Parameters left : float Number of seconds of data to remove from the left of the time series . right : float Number of seconds of data to remove from the right of the time series . Returns cropped : pycbc . types...
if left + right > self . duration : raise ValueError ( 'Cannot crop more data than we have' ) s = int ( left * self . sample_rate ) e = len ( self ) - int ( right * self . sample_rate ) return self [ s : e ]
def thanks ( self , answer , thanks = True ) : """感谢或取消感谢回答 : param Answer answer : 要感谢或取消感谢的回答 : param thanks : True - - > 感谢 , False - - > 取消感谢 : return : 成功返回True , 失败返回False : rtype : bool"""
from . answer import Answer if isinstance ( answer , Answer ) is False : raise ValueError ( 'argument answer need to be Zhihu.Answer object.' ) if answer . author . url == self . url : return False data = { '_xsrf' : answer . xsrf , 'aid' : answer . aid } res = self . _session . post ( Thanks_Url if thanks else...
def extract_ctcp ( self , spin , nick , user , host , target , msg ) : """it is used to extract ctcp requests into pieces ."""
# The ctcp delimiter token . DELIM = '\001' if not msg . startswith ( DELIM ) or not msg . endswith ( DELIM ) : return ctcp_args = msg . strip ( DELIM ) . split ( ' ' ) spawn ( spin , ctcp_args [ 0 ] , ( nick , user , host , target , msg ) , * ctcp_args [ 1 : ] )
def ExportModelOperationsMixin ( model_name ) : """Returns a mixin for models to export counters for lifecycle operations . Usage : class User ( ExportModelOperationsMixin ( ' user ' ) , Model ) :"""
# Force create the labels for this model in the counters . This # is not necessary but it avoids gaps in the aggregated data . model_inserts . labels ( model_name ) model_updates . labels ( model_name ) model_deletes . labels ( model_name ) class Mixin ( object ) : def _do_insert ( self , * args , ** kwargs ) : ...
def _compute_deletions ( self ) : """If there are fewer than self . _ proc _ limit possible deletion sets , compute all subprocessors obtained by deleting a minimal subset of qubits ."""
M , N , L , edgelist = self . M , self . N , self . L , self . _edgelist if 2 ** len ( self . _evil ) <= self . _proc_limit : deletions = self . _compute_all_deletions ( ) self . _processors = [ self . _subprocessor ( d ) for d in deletions ] else : self . _processors = None
def savePattern ( self ) : """Save internal RAM pattern to flash"""
if ( self . dev == None ) : return '' buf = [ REPORT_ID , ord ( 'W' ) , 0xBE , 0xEF , 0xCA , 0xFE , 0 , 0 , 0 ] return self . write ( buf ) ;
def stop ( self ) : """Called to stop the reveiver thread ."""
self . _stop_thread . set ( ) # f you want to close the connection in a timely fashion , # call shutdown ( ) before close ( ) . with self . _lock : # Receive thread might use the socket self . receive_socket . shutdown ( socket . SHUT_RDWR ) self . receive_socket . close ( ) self . send_socket . shutdown ( sock...
def spawn ( self , actor , aid = None , ** params ) : '''Spawn a new actor from ` ` actor ` ` .'''
aid = aid or create_aid ( ) future = actor . send ( 'arbiter' , 'spawn' , aid = aid , ** params ) return actor_proxy_future ( aid , future )
def hold_time ( self , datetime = None ) : """持仓时间 Keyword Arguments : datetime { [ type ] } - - [ description ] ( default : { None } )"""
def weights ( x ) : if sum ( x [ 'amount' ] ) != 0 : return pd . Timestamp ( self . datetime ) - pd . to_datetime ( x . datetime . max ( ) ) else : return np . nan if datetime is None : return self . history_table . set_index ( 'datetime' , drop = False ) . sort_index ( ) . groupby ( 'code' ...
def get_vlan_brief_output_has_more ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) get_vlan_brief = ET . Element ( "get_vlan_brief" ) config = get_vlan_brief output = ET . SubElement ( get_vlan_brief , "output" ) has_more = ET . SubElement ( output , "has-more" ) has_more . text = kwargs . pop ( 'has_more' ) callback = kwargs . pop ( 'callback' , self . _callback ) ...
def set_time_offset ( self , offset , is_utc ) : """Temporarily set the current time offset ."""
is_utc = bool ( is_utc ) self . clock_manager . time_offset = offset self . clock_manager . is_utc = is_utc return [ Error . NO_ERROR ]
def capakey_rest_gateway_request ( url , headers = { } , params = { } ) : '''Utility function that helps making requests to the CAPAKEY REST service . : param string url : URL to request . : param dict headers : Headers to send with the URL . : param dict params : Parameters to send with the URL . : returns...
try : res = requests . get ( url , headers = headers , params = params ) res . raise_for_status ( ) return res except requests . ConnectionError as ce : raise GatewayRuntimeException ( 'Could not execute request due to connection problems:\n%s' % repr ( ce ) , ce ) except requests . HTTPError as he : ...
def concat ( self , other , strict = False ) : """Concats two metadata objects together . Parameters other : Meta Meta object to be concatenated strict : bool if True , ensure there are no duplicate variable names Notes Uses units and name label of self if other is different Returns Meta Concate...
mdata = self . copy ( ) # checks if strict : for key in other . keys ( ) : if key in mdata : raise RuntimeError ( 'Duplicated keys (variable names) ' + 'across Meta objects in keys().' ) for key in other . keys_nD ( ) : if key in mdata : raise RuntimeError ( 'Duplicated k...
def build ( self , polygons ) : """Build a BSP tree out of ` polygons ` . When called on an existing tree , the new polygons are filtered down to the bottom of the tree and become new nodes there . Each set of polygons is partitioned using the first polygon ( no heuristic is used to pick a good split ) ."""
if len ( polygons ) == 0 : return if not self . plane : self . plane = polygons [ 0 ] . plane . clone ( ) # add polygon to this node self . polygons . append ( polygons [ 0 ] ) front = [ ] back = [ ] # split all other polygons using the first polygon ' s plane for poly in polygons [ 1 : ] : # coplanar front and...
def logWrite ( self , string ) : """Only write text to the log file , do not print"""
logFile = open ( self . logFile , 'at' ) logFile . write ( string + '\n' ) logFile . close ( )
def sleep ( seconds , ** kwargs ) : '''same as time . sleep ( seconds ) but prints out where it was called before sleeping and then again after finishing sleeping I just find this really handy for debugging sometimes since - - 2017-4-27 : param seconds : float | int , how many seconds to sleep'''
if seconds <= 0.0 : raise ValueError ( "Invalid seconds {}" . format ( seconds ) ) with Reflect . context ( ** kwargs ) as r : instance = V_CLASS ( r , stream , ** kwargs ) instance . writeline ( "Sleeping {} second{} at {}" . format ( seconds , "s" if seconds != 1.0 else "" , instance . path_value ( ) ) ) ...
def register ( self , event , callback , selector = None ) : """Resister an event that you want to monitor . : param event : Name of the event to monitor : param callback : Callback function for when the event is received ( Params : event , interface ) . : param selector : ` ( Optional ) ` CSS selector for th...
self . processor . register ( event , callback , selector )
def update_category ( uid , post_data ) : '''Update the category of the post . : param uid : The ID of the post . Extra info would get by requests .'''
# deprecated # catid = kwargs [ ' catid ' ] if MCategory . get _ by _ uid ( kwargs . get ( ' catid ' ) ) else None # post _ data = self . get _ post _ data ( ) if 'gcat0' in post_data : pass else : return False # Used to update MPost2Category , to keep order . the_cats_arr = [ ] # Used to update post extinfo . ...
def _size_map ( size ) : '''Map Bcache ' s size strings to real bytes'''
try : # I know , I know , EAFP . # But everything else is reason for None if not isinstance ( size , int ) : if re . search ( r'[Kk]' , size ) : size = 1024 * float ( re . sub ( r'[Kk]' , '' , size ) ) elif re . search ( r'[Mm]' , size ) : size = 1024 ** 2 * float ( re . sub ...
def timemeter ( msg = None ) : """Timer meter Use this annotation method can calculate the execute time . : param msg : custom message output : return : fn values"""
def _time_meter ( fn ) : @ functools . wraps ( fn ) def _wrapper ( * args , ** kwargs ) : mark = timeit . default_timer ( ) result = fn ( * args , ** kwargs ) cost = timeit . default_timer ( ) - mark if msg : logger . info ( msg , cost ) else : log...
def render_svg ( self , render_id , words , arcs ) : """Render SVG . render _ id ( int ) : Unique ID , typically index of document . words ( list ) : Individual words and their tags . arcs ( list ) : Individual arcs and their start , end , direction and label . RETURNS ( unicode ) : Rendered SVG markup ."""
self . levels = self . get_levels ( arcs ) self . highest_level = len ( self . levels ) self . offset_y = self . distance / 2 * self . highest_level + self . arrow_stroke self . width = self . offset_x + len ( words ) * self . distance self . height = self . offset_y + 3 * self . word_spacing self . id = render_id word...
def convert_to_foldable ( input_filename : str , output_filename : str , slice_horiz : int , slice_vert : int , overwrite : bool = False , longedge : bool = False , latex_paper_size : str = LATEX_PAPER_SIZE_A4 ) -> bool : """Runs a chain of tasks to convert a PDF to a useful booklet PDF ."""
if not os . path . isfile ( input_filename ) : log . warning ( "Input file does not exist or is not a file" ) return False if not overwrite and os . path . isfile ( output_filename ) : log . error ( "Output file exists; not authorized to overwrite (use " "--overwrite if you are sure)" ) return False log...
def iter_predict ( self , X , include_init = False ) : """Returns the predictions for ` ` X ` ` at every stage of the boosting procedure . Args : X ( array - like or sparse matrix of shape ( n _ samples , n _ features ) : The input samples . Sparse matrices are accepted only if they are supported by the weak ...
utils . validation . check_is_fitted ( self , 'init_estimator_' ) X = utils . check_array ( X , accept_sparse = [ 'csr' , 'csc' ] , dtype = None , force_all_finite = False ) y_pred = self . init_estimator_ . predict ( X ) # The user decides if the initial prediction should be included or not if include_init : yield...
def download_from_github ( fname , path ) : """Download database from GitHub : param fname : file name with extension ( ' . zip ' ) of the target item : type fname : str : param path : path to save unzipped files : type path : str : return : database folder : rtype : folder"""
base_url = 'https://github.com/ornlneutronimaging/ImagingReso/blob/master/ImagingReso/reference_data/' # Add GitHub junk to the file name for downloading . f = fname + '?raw=true' url = base_url + f block_size = 16384 req = urlopen ( url ) # Get file size from header if sys . version_info [ 0 ] < 3 : file_size = in...
def transform ( self , X , y = None , sample_weight = None ) : '''Transforms the time series data into segments ( temporal tensor ) Note this transformation changes the number of samples in the data If y and sample _ weight are provided , they are transformed to align to the new samples Parameters X : array...
check_ts_data ( X , y ) Xt , Xc = get_ts_data_parts ( X ) yt = y swt = sample_weight N = len ( Xt ) # number of time series if Xt [ 0 ] . ndim > 1 : Xt = np . array ( [ sliding_tensor ( Xt [ i ] , self . width , self . _step , self . order ) for i in np . arange ( N ) ] ) else : Xt = np . array ( [ sliding_wind...
def simxQuery ( clientID , signalName , signalValue , retSignalName , timeOutInMs ) : '''Please have a look at the function description / documentation in the V - REP user manual'''
retSignalLength = ct . c_int ( ) ; retSignalValue = ct . POINTER ( ct . c_ubyte ) ( ) sigV = signalValue if sys . version_info [ 0 ] == 3 : if type ( signalName ) is str : signalName = signalName . encode ( 'utf-8' ) if type ( retSignalName ) is str : retSignalName = retSignalName . encode ( 'ut...
def select_t ( self , t = None , out = bool ) : """Return a time index array Return a boolean or integer index array , hereafter called ' ind ' The array refers to the reference time vector self . ddataRef [ ' t ' ] Parameters t : None / float / np . ndarray / list / tuple The time values to be selected :...
assert out in [ bool , int ] ind = _select_ind ( t , self . _ddataRef [ 't' ] , self . _ddataRef [ 'nt' ] ) if out is int : ind = ind . nonzero ( ) [ 0 ] return ind
def aic ( eval_data , predictions , scores , learner ) : '''Return Akaike information criterion ( AIC ) scores for the given ` learner ` producing the given ` scores ` ( log likelihoods in base e ) : aic = 2 * learner . num _ params - 2 * sum ( log _ 2 ( exp ( scores ) ) ) The result is a list * one element l...
return ( - 2.0 * np . array ( scores ) / np . log ( 2.0 ) ) . tolist ( ) + [ 2.0 * float ( learner . num_params ) ]
def start_udp_server ( self , ip , port , name = None , timeout = None , protocol = None , family = 'ipv4' ) : """Starts a new UDP server to given ` ip ` and ` port ` . Server can be given a ` name ` , default ` timeout ` and a ` protocol ` . ` family ` can be either ipv4 ( default ) or ipv6. Examples : | S...
self . _start_server ( UDPServer , ip , port , name , timeout , protocol , family )
def regression ( ) : """Run regression testing - lint and then run all tests ."""
# HACK : Start using hitchbuildpy to get around this . Command ( "touch" , DIR . project . joinpath ( "pathquery" , "__init__.py" ) . abspath ( ) ) . run ( ) storybook = _storybook ( { } ) . only_uninherited ( ) # storybook . with _ params ( * * { " python version " : " 2.7.10 " } ) \ # . ordered _ by _ name ( ) . play...
def bias_ratio ( self , position = False ) : """判斷乖離 : param bool positive _ or _ negative : 正乖離 為 True , 負乖離 為 False"""
return self . data . ma_bias_ratio_pivot ( self . data . ma_bias_ratio ( 3 , 6 ) , position = position )
def get_minimal_inconsistent_cores ( instance , nmodels = 0 , exclude = [ ] ) : '''[ compute _ mic ( instance , nmodels , exclude ) ] returns a list containing [ nmodels ] TermSet objects representing subset minimal inconsistent cores of the system described by the TermSet [ instance ] . The list [ exclude ] sh...
inputs = get_reductions ( instance ) prg = [ dyn_mic_prg , inputs . to_file ( ) , instance . to_file ( ) , exclude_sol ( exclude ) ] options = '--heuristic=Vmtf ' + str ( nmodels ) solver = GringoClasp ( clasp_options = options ) models = solver . run ( prg , collapseTerms = True , collapseAtoms = False ) os . unlink (...
def command ( self , ns , raw , ** kw ) : """Executes command . { " op " : " c " , " ns " : " testdb . $ cmd " , " o " : { " drop " : " fs . files " }"""
try : dbname = raw [ 'ns' ] . split ( '.' , 1 ) [ 0 ] self . dest [ dbname ] . command ( raw [ 'o' ] , check = True ) except OperationFailure , e : logging . warning ( e )
def del_collection ( self , service_name , collection_name , base_class = None ) : """Deletes a collection for a given service . Fails silently if no collection is found in the cache . : param service _ name : The service a given ` ` Collection ` ` talks to . Ex . ` ` sqs ` ` , ` ` sns ` ` , ` ` dynamodb ` ` ...
# Unlike ` ` get _ collection ` ` , this should be fire & forget . # We don ' t really care , as long as it ' s not in the cache any longer . try : classpath = self . build_classpath ( base_class ) opts = self . services [ service_name ] [ 'collections' ] [ collection_name ] del opts [ classpath ] except Ke...
def _generate_base_namespace_module ( self , api , namespace ) : """Creates a module for the namespace . All data types and routes are represented as Python classes ."""
self . cur_namespace = namespace generate_module_header ( self ) if namespace . doc is not None : self . emit ( '"""' ) self . emit_raw ( namespace . doc ) self . emit ( '"""' ) self . emit ( ) self . emit_raw ( validators_import ) # Generate import statements for all referenced namespaces . self . _gen...
def start_running ( self ) : """Start running the Runner ."""
self . comp . warm_up ( ) self . check_runner ( ) self . running = True
def abs_energy ( x ) : """Returns the absolute energy of the time series which is the sum over the squared values . . math : : E = \\ sum _ { i = 1 , \ ldots , n } x _ i ^ 2 : param x : the time series to calculate the feature of : type x : numpy . ndarray : return : the value of this feature : return t...
if not isinstance ( x , ( np . ndarray , pd . Series ) ) : x = np . asarray ( x ) return np . dot ( x , x )
def get_engine ( name ) : """get an engine from string ( engine class without Engine )"""
name = name . capitalize ( ) + 'Engine' if name in globals ( ) : return globals ( ) [ name ] raise KeyError ( "engine '%s' does not exist" % name )
def process_status ( self , helper , sess , check ) : """get the snmp value , check the status and update the helper"""
if check == 'ntp_current_state' : ntp_status_int = helper . get_snmp_value ( sess , helper , self . oids [ 'oid_ntp_current_state_int' ] ) result = self . check_ntp_status ( ntp_status_int ) elif check == 'gps_mode' : gps_status_int = helper . get_snmp_value ( sess , helper , self . oids [ 'oid_gps_mode_int...
def clear_cache ( self ) : '''Completely clear cache'''
errors = [ ] for rdir in ( self . cache_root , self . file_list_cachedir ) : if os . path . exists ( rdir ) : try : shutil . rmtree ( rdir ) except OSError as exc : errors . append ( 'Unable to delete {0}: {1}' . format ( rdir , exc ) ) return errors
def _build_indexes ( self ) : """Build indexes from data for fast filtering of data . Building indexes of data when possible . This is only supported when dealing with a List of Dictionaries with String values ."""
if isinstance ( self . _data , list ) : for d in self . _data : if not isinstance ( d , dict ) : err = u'Cannot build index for non Dict type.' self . _tcex . log . error ( err ) raise RuntimeError ( err ) data_obj = DataObj ( d ) self . _master_index . se...
def aggplot ( df , projection = None , hue = None , by = None , geometry = None , nmax = None , nmin = None , nsig = 0 , agg = np . mean , cmap = 'viridis' , vmin = None , vmax = None , legend = True , legend_kwargs = None , extent = None , figsize = ( 8 , 6 ) , ax = None , ** kwargs ) : """Self - aggregating quadt...
fig = _init_figure ( ax , figsize ) # Set up projection . if projection : projection = projection . load ( df , { 'central_longitude' : lambda df : np . mean ( np . array ( [ p . x for p in df . geometry . centroid ] ) ) , 'central_latitude' : lambda df : np . mean ( np . array ( [ p . y for p in df . geometry . ce...
def logoff_session ( session_id ) : '''Initiate the logoff of a session . . . versionadded : : 2016.11.0 : param session _ id : The numeric Id of the session . : return : A boolean representing whether the logoff succeeded . CLI Example : . . code - block : : bash salt ' * ' rdp . logoff _ session sessi...
try : win32ts . WTSLogoffSession ( win32ts . WTS_CURRENT_SERVER_HANDLE , session_id , True ) except PyWinError as error : _LOG . error ( 'Error calling WTSLogoffSession: %s' , error ) return False return True
def _add_include_arg ( arg_parser ) : """Adds optional repeatable include parameter to a parser . : param arg _ parser : ArgumentParser parser to add this argument to ."""
arg_parser . add_argument ( "--include" , metavar = 'Path' , action = 'append' , type = to_unicode , dest = 'include_paths' , help = "Specifies a single path to include. This argument can be repeated." , default = [ ] )
def add_file ( self , path ) : """Add a resource file or library file to the database"""
libdoc = LibraryDocumentation ( path ) if len ( libdoc . keywords ) > 0 : if libdoc . doc . startswith ( "Documentation for resource file" ) : # bah ! The file doesn ' t have an file - level documentation # and libdoc substitutes some placeholder text . libdoc . doc = "" collection_id = self . add_c...
def allow_implicit_stop ( gen_func ) : """Fix the backwards - incompatible PEP - 0479 gotcha / bug https : / / www . python . org / dev / peps / pep - 0479"""
@ functools . wraps ( gen_func ) def wrapper ( * args , ** kwargs ) : with warnings . catch_warnings ( ) : for cls in [ DeprecationWarning , PendingDeprecationWarning ] : warnings . filterwarnings ( action = "ignore" , message = ".* raised StopIteration" , category = cls , ) try : ...
def setType ( self , personID , typeID ) : """setType ( string , string ) - > None Sets the id of the type for the named person ."""
self . _connection . _sendStringCmd ( tc . CMD_SET_PERSON_VARIABLE , tc . VAR_TYPE , personID , typeID )
def get_attrdict ( self ) -> OrderedNamespace : """Returns what looks like a plain object with the values of the SQLAlchemy ORM object ."""
# noinspection PyUnresolvedReferences columns = self . __table__ . columns . keys ( ) values = ( getattr ( self , x ) for x in columns ) zipped = zip ( columns , values ) return OrderedNamespace ( zipped )
def get ( self , groupName , default = None ) : """Returns the contents of the named group . * * groupName * * is a : ref : ` type - string ` , and the returned values will either be : ref : ` type - immutable - list ` of group contents or ` ` None ` ` if no group was found . : : > > > font . groups [ " myG...
return super ( BaseGroups , self ) . get ( groupName , default )
def on_error ( func , path , exc_info ) : # pylint : disable = unused - argument """Error handler for ` ` shutil . rmtree ` ` . If the error is due to an access error ( read only file ) it attempts to add write permission and then retries . If the error is for another reason it re - raises the error . Usage...
if not os . access ( path , os . W_OK ) : # Is the error an access error ? os . chmod ( path , stat . S_IWUSR ) func ( path ) else : raise
def register_result ( self , job , skip_sanity_checks = False ) : """function to register the result of a job This function is called from HB _ master , don ' t call this from your script ."""
if self . is_finished : raise RuntimeError ( "This HB iteration is finished, you can't register more results!" ) config_id = job . id config = job . kwargs [ 'config' ] budget = job . kwargs [ 'budget' ] timestamps = job . timestamps result = job . result exception = job . exception d = self . data [ config_id ] if...
def jacobi ( n , alpha , beta , standardization , symbolic = False ) : """Generate the recurrence coefficients a _ k , b _ k , c _ k in P _ { k + 1 } ( x ) = ( a _ k x - b _ k ) * P _ { k } ( x ) - c _ k P _ { k - 1 } ( x ) for the Jacobi polynomials which are orthogonal on [ - 1 , 1] with respect to the weig...
gamma = sympy . gamma if symbolic else lambda x : scipy . special . gamma ( float ( x ) ) def rational ( x , y ) : # < https : / / github . com / sympy / sympy / pull / 13670 > return ( sympy . Rational ( x , y ) if all ( [ isinstance ( val , int ) for val in [ x , y ] ] ) else x / y ) frac = rational if symbolic e...
def list ( self , search = False , ** kwargs ) : """Returns a list of : class : ` Message ` objects and a pager dict . : Example : messages , pager = client . messages . list ( ) : param bool search : If True then search messages using ` ids ` , ` sessionId ` , and / or ` query ` . Default = False : param i...
kwargs [ "search" ] = search return self . get_instances ( kwargs )
def _write_vxr ( self , f , numEntries = None ) : '''Creates a VXR at the end of the file . Returns byte location of the VXR The First , Last , and Offset fields will need to be filled in later'''
f . seek ( 0 , 2 ) byte_loc = f . tell ( ) section_type = CDF . VXR_ nextVXR = 0 if ( numEntries == None ) : nEntries = CDF . NUM_VXR_ENTRIES else : nEntries = int ( numEntries ) block_size = CDF . VXR_BASE_SIZE64 + ( 4 + 4 + 8 ) * nEntries nUsedEntries = 0 firsts = [ - 1 ] * nEntries lasts = [ - 1 ] * nEntries...
def belu ( x ) : """Bipolar ELU as in https : / / arxiv . org / abs / 1709.04054."""
x_shape = shape_list ( x ) x1 , x2 = tf . split ( tf . reshape ( x , x_shape [ : - 1 ] + [ - 1 , 2 ] ) , 2 , axis = - 1 ) y1 = tf . nn . elu ( x1 ) y2 = - tf . nn . elu ( - x2 ) return tf . reshape ( tf . concat ( [ y1 , y2 ] , axis = - 1 ) , x_shape )
def compile_date ( self ) : """Returns a string specifying the date and time at which the DLL was translated . Args : self ( JLink ) : the ` ` JLink ` ` instance Returns : Datetime string ."""
result = self . _dll . JLINKARM_GetCompileDateTime ( ) return ctypes . cast ( result , ctypes . c_char_p ) . value . decode ( )
def daily_returns ( self ) : """[ float ] 当前最新一天的日收益"""
if self . _static_unit_net_value == 0 : return np . nan return 0 if self . _static_unit_net_value == 0 else self . unit_net_value / self . _static_unit_net_value - 1
def write_function_cmdline ( self , job ) : '''Write a series of commandline variables to be concatenated together eventually and either called with subprocess . Popen ( ) or with apiDockerCall ( ) if a docker image is called for . : param job : A list such that : ( job priority # , job ID # , Job Skeleton ...
fn_section = '\n' cmd_array = [ ] if 'raw_commandline' in self . tasks_dictionary [ job ] : for cmd in self . tasks_dictionary [ job ] [ 'raw_commandline' ] : if not cmd . startswith ( "r'''" ) : cmd = 'str({i} if not isinstance({i}, tuple) else process_and_read_file({i}, tempDir, fileStore)).st...
def _wait_for_completion ( conn , wait_timeout , server_id ) : '''Poll request status until resource is provisioned .'''
wait_timeout = time . time ( ) + wait_timeout while wait_timeout > time . time ( ) : time . sleep ( 5 ) server = conn . get_server ( server_id ) server_state = server [ 'status' ] [ 'state' ] . lower ( ) if server_state == "powered_on" : return elif server_state == 'failed' : raise E...
def QA_SU_save_option_commodity_min ( client = DATABASE , ui_log = None , ui_progress = None ) : ''': param client : : return :'''
# 测试中发现 , 一起回去 , 容易出现错误 , 每次获取一个品种后 , 更换服务ip继续获取 ? _save_option_commodity_cu_min ( client = client , ui_log = ui_log , ui_progress = ui_progress ) _save_option_commodity_sr_min ( client = client , ui_log = ui_log , ui_progress = ui_progress ) _save_option_commodity_m_min ( client = client , ui_log = ui_log , ui_progres...
def create_job ( self , emails ) : """Create a new bulk verification job for the list of emails . : param list emails : Email addresses to verify . : return : A Job object ."""
resp = self . _call ( endpoint = 'bulk' , data = { 'input_location' : '1' , 'input' : '\n' . join ( emails ) } ) return Job ( resp [ 'job_id' ] )
def ADR ( self , params ) : """ADR Ra , [ PC , # imm10_4] ADR Ra , label Load the address of label or the PC offset into Ra Ra must be a low register"""
# TODO may need to rethink how I do PC , may need to be byte alligned # TODO This is wrong as each address is a word , not a byte . The filled value with its location ( Do we want that , or the value at that location [ Decompiled instruction ] ) try : Ra , Rb , Rc = self . get_three_parameters ( self . THREE_PARAME...
def logical_and ( f1 , f2 ) : # function factory '''Logical and from functions . Parameters f1 , f2 : function Function that takes array and returns true or false for each item in array . Returns Function Examples filter _ func = logical _ and ( is _ data _ record , is _ data _ from _ channel ( 4 ) ) ...
def f_and ( arr ) : return np . logical_and ( f1 ( arr ) , f2 ( arr ) ) f_and . __name__ = f1 . __name__ + "_and_" + f2 . __name__ return f_and
def pad_sequence_to_length ( sequence : List , desired_length : int , default_value : Callable [ [ ] , Any ] = lambda : 0 , padding_on_right : bool = True ) -> List : """Take a list of objects and pads it to the desired length , returning the padded list . The original list is not modified . Parameters sequen...
# Truncates the sequence to the desired length . if padding_on_right : padded_sequence = sequence [ : desired_length ] else : padded_sequence = sequence [ - desired_length : ] # Continues to pad with default _ value ( ) until we reach the desired length . for _ in range ( desired_length - len ( padded_sequence ...
def copy_ami_to_new_name ( self , ami_id , new_name , source_region = 'us-east-1' ) : """Copies an AMI from the default region and name to the desired name and region : param ami _ id : ami id to copy : param new _ name : name of the new ami to create : param source _ region : the source region of the ami to ...
new_image_ids = [ ] for region in self . aws_regions : copy_img_cmd = "aws ec2 copy-image --source-image-id {} --profile {} --source-region {} --region {} --name {}" . format ( ami_id , self . aws_project , source_region , region , new_name ) res = subprocess . check_output ( shlex . split ( copy_img_cmd ) ) ...
def get_mol ( chebi_id ) : '''Returns mol'''
chebi_id_regexp = '^\\d+\\,' + str ( chebi_id ) + '\\,.*' mol_file_end_regexp = '\",mol,\\dD' this_structure = [ ] filename = get_file ( 'structures.csv.gz' ) with io . open ( filename , 'r' , encoding = 'cp1252' ) as textfile : in_chebi_id = False next ( textfile ) for line in textfile : if in_cheb...
def _ScanNode ( self , scan_context , scan_node , auto_recurse = True ) : """Scans a node for supported formats . Args : scan _ context ( SourceScannerContext ) : source scanner context . scan _ node ( SourceScanNode ) : source scan node . auto _ recurse ( Optional [ bool ] ) : True if the scan should autom...
if not scan_context : raise ValueError ( 'Invalid scan context.' ) if not scan_node : raise ValueError ( 'Invalid scan node.' ) scan_path_spec = scan_node . path_spec system_level_file_entry = None if scan_node . IsSystemLevel ( ) : system_level_file_entry = resolver . Resolver . OpenFileEntry ( scan_node ....
def GetCellValueNoFail ( self , column ) : """get a cell , if it does not exist fail note that column at row START AT 1 same as excel"""
cell = GetCellValue ( self , column ) if cell == None : raise ValueError ( "cell %d does not exist" % ( column , ) ) return cell
def _call_config ( self , method , * args , ** kwargs ) : """Call the configuration at the given method which must take a section name as first argument"""
return getattr ( self . _config , method ) ( self . _section_name , * args , ** kwargs )
def getCatIds ( self , catNms = [ ] , supNms = [ ] , catIds = [ ] ) : """filtering parameters . default skips that filter . : param catNms ( str array ) : get cats for given cat names : param supNms ( str array ) : get cats for given supercategory names : param catIds ( int array ) : get cats for given cat id...
catNms = catNms if _isArrayLike ( catNms ) else [ catNms ] supNms = supNms if _isArrayLike ( supNms ) else [ supNms ] catIds = catIds if _isArrayLike ( catIds ) else [ catIds ] if len ( catNms ) == len ( supNms ) == len ( catIds ) == 0 : cats = self . dataset [ 'categories' ] else : cats = self . dataset [ 'cat...
def _gen_back ( self ) : '''Return a list of loaded roster backends'''
back = set ( ) if self . backends : for backend in self . backends : fun = '{0}.targets' . format ( backend ) if fun in self . rosters : back . add ( backend ) return back return sorted ( back )