signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def terminate ( self , signal_chain = KILL_CHAIN , kill_wait = KILL_WAIT_SEC , purge = True ) : """Ensure a process is terminated by sending a chain of kill signals ( SIGTERM , SIGKILL ) ."""
alive = self . is_alive ( ) if alive : logger . debug ( 'terminating {}' . format ( self . _name ) ) for signal_type in signal_chain : pid = self . pid try : logger . debug ( 'sending signal {} to pid {}' . format ( signal_type , pid ) ) self . _kill ( signal_type ) ...
def get_sub_electrodes ( self , adjacent_only = True ) : """If this electrode contains multiple voltage steps , then it is possible to use only a subset of the voltage steps to define other electrodes . For example , an LiTiO2 electrode might contain three subelectrodes : [ LiTiO2 - - > TiO2 , LiTiO2 - - > Li...
if adjacent_only : return [ self . __class__ ( self . _vpairs [ i : i + 1 ] , self . _working_ion_entry , self . _composition ) for i in range ( len ( self . _vpairs ) ) ] sub_electrodes = [ ] for i in range ( len ( self . _vpairs ) ) : for j in range ( i , len ( self . _vpairs ) ) : sub_electrodes . ap...
def run_kernel ( self , func , gpu_args , threads , grid ) : """runs the CUDA kernel passed as ' func ' : param func : A PyCuda kernel compiled for this specific kernel configuration : type func : pycuda . driver . Function : param gpu _ args : A list of arguments to the kernel , order should match the orde...
func ( * gpu_args , block = threads , grid = grid , texrefs = self . texrefs )
async def dist ( self , mesg ) : '''Distribute an existing event tuple . Args : mesg ( ( str , dict ) ) : An event tuple . Example : await base . dist ( ( ' foo ' , { ' bar ' : ' baz ' } ) )'''
if self . isfini : return ( ) ret = [ ] for func in self . _syn_funcs . get ( mesg [ 0 ] , ( ) ) : try : ret . append ( await s_coro . ornot ( func , mesg ) ) except asyncio . CancelledError : raise except Exception : logger . exception ( 'base %s error with mesg %s' , self , mes...
def get_torrent_download_limit ( self , infohash_list ) : """Get download speed limit of the supplied torrents . : param infohash _ list : Single or list ( ) of infohashes ."""
data = self . _process_infohash_list ( infohash_list ) return self . _post ( 'command/getTorrentsDlLimit' , data = data )
def get_event_data ( self , section , time_in_seconds = False ) : """Get the template or complement event data . : param section : Either template , complement , or both . : param time _ in _ seconds : Return the start and length fields in seconds , rather than samples . : return : The event dataset for the...
if section not in [ 'template' , 'complement' , 'both' ] : raise Exception ( 'Unrecognized section: {} Expected: "template", "complement" or "both"' . format ( section ) ) results = self . get_results ( ) if results is None : return None , None if section is 'both' else None if section == 'both' : sections ...
def documents_upload ( ctx , max_threads , files ) : """Upload a document file ( of any type ) to One Codex"""
if len ( files ) == 0 : click . echo ( ctx . get_help ( ) ) return files = list ( files ) bar = click . progressbar ( length = sum ( [ _file_size ( x ) for x in files ] ) , label = "Uploading... " ) run_via_threadpool ( ctx . obj [ "API" ] . Documents . upload , files , { "progressbar" : bar } , max_threads = m...
def instruction_DEC_register ( self , opcode , register ) : """Decrement accumulator"""
a = register . value r = self . DEC ( a ) # log . debug ( " $ % x DEC % s value $ % x - 1 = $ % x " % ( # self . program _ counter , # register . name , a , r register . set ( r )
def _Open ( self , path_spec = None , mode = 'rb' ) : """Opens the file - like object defined by path specification . Args : path _ spec ( PathSpec ) : path specification . mode ( Optional [ str ] ) : file access mode . Raises : AccessError : if the access to open the file was denied . IOError : if the ...
if not path_spec : raise ValueError ( 'Missing path specification.' ) if path_spec . HasParent ( ) : raise errors . PathSpecError ( 'Unsupported path specification with parent.' ) location = getattr ( path_spec , 'location' , None ) if location is None : raise errors . PathSpecError ( 'Path specification mi...
def subvol_snapshot ( self , source , destination , read_only = False ) : """Take a snapshot : param source : source path of subvol : param destination : destination path of snapshot : param read _ only : Set read - only on the snapshot : return :"""
args = { "source" : source , "destination" : destination , "read_only" : read_only , } self . _subvol_snapshot_chk . check ( args ) self . _client . sync ( 'btrfs.subvol_snapshot' , args )
def close ( self ) : """Subprocess cleanup ."""
# Give time to flush data if debug was on if self . debug : time . sleep ( 10 ) # Terminate workers for host in self . workers : host . close ( ) # Terminate the brokers for broker in self . brokers : try : broker . close ( ) except AttributeError : # Broker was not started ( probably mislaunche...
def map_statistic ( self , plot ) : """Mapping aesthetics to computed statistics"""
data = self . data if not len ( data ) : return type ( data ) ( ) # Assemble aesthetics from layer , plot and stat mappings aesthetics = deepcopy ( self . mapping ) if self . inherit_aes : aesthetics = defaults ( aesthetics , plot . mapping ) aesthetics = defaults ( aesthetics , self . stat . DEFAULT_AES ) # Th...
def trigger_show_by_id ( self , id , ** kwargs ) : "https : / / developer . zendesk . com / rest _ api / docs / core / triggers # getting - triggers"
api_path = "/api/v2/triggers/{id}.json" api_path = api_path . format ( id = id ) return self . call ( api_path , ** kwargs )
def marker_gene_overlap ( adata : AnnData , reference_markers : Union [ Dict [ str , set ] , Dict [ str , list ] ] , * , key : str = 'rank_genes_groups' , method : Optional [ str ] = 'overlap_count' , normalize : Union [ str , None ] = None , top_n_markers : Optional [ int ] = None , adj_pval_threshold : Optional [ flo...
# Test user inputs if inplace : raise NotImplementedError ( 'Writing Pandas dataframes to h5ad is ' 'currently under development.\n' 'Please use `inplace=False`.' ) if key not in adata . uns : raise ValueError ( 'Could not find marker gene data. ' 'Please run `sc.tl.rank_genes_groups()` first.' ) avail_methods ...
def rhombohedral ( a : float , alpha : float ) : """Convenience constructor for a rhombohedral lattice . Args : a ( float ) : * a * lattice parameter of the rhombohedral cell . alpha ( float ) : Angle for the rhombohedral lattice in degrees . Returns : Rhombohedral lattice of dimensions a x a x a ."""
return Lattice . from_parameters ( a , a , a , alpha , alpha , alpha )
def bin2hex ( fin , fout , offset = 0 ) : """Simple bin - to - hex convertor . @ return 0 if all OK @ param fin input bin file ( filename or file - like object ) @ param fout output hex file ( filename or file - like object ) @ param offset starting address offset for loading bin"""
h = IntelHex ( ) try : h . loadbin ( fin , offset ) except IOError : e = sys . exc_info ( ) [ 1 ] # current exception txt = 'ERROR: unable to load bin file:' , str ( e ) print ( txt ) return 1 try : h . tofile ( fout , format = 'hex' ) except IOError : e = sys . exc_info ( ) [ 1 ] # ...
def attributes ( self ) : """Returns a list of attributes"""
overridden_attrs = self . _attributes sortmap = { "neutral" : 1 , "positive" : 2 , "negative" : 3 } sortedattrs = list ( overridden_attrs . values ( ) ) sortedattrs . sort ( key = operator . itemgetter ( "defindex" ) ) sortedattrs . sort ( key = lambda t : sortmap . get ( t . get ( "effect_type" , "neutral" ) , 99 ) ) ...
def post ( self , page , payload , parms = None ) : '''Posts a string payload to the server - used to make new Redmine items . Returns an JSON string or error .'''
if self . readonlytest : print 'Redmine read only test: Pretending to create: ' + page return payload else : return self . open ( page , parms , payload )
def trigger_staged_cg_hook ( self , name , g , * args , ** kwargs ) : """Calls a three - staged hook : 1 . ` ` " pre _ " + name ` ` 2 . ` ` " in _ " + name ` ` 3 . ` ` " post _ " + name ` `"""
print_hooks = self . _print_hooks # TODO : document name lookup business # TODO : refactor this context stuff , its confusing hook_name = "pre_" + name printed_name = hook_name if print_hooks else None self . trigger_cg_hook ( hook_name , g , printed_name , * args , ** kwargs ) # TODO : avoid copies hook_name = "in_" +...
def xrandr ( self ) : """This is the main py3status method , it will orchestrate what ' s being displayed on the bar ."""
self . layout = self . _get_layout ( ) self . _set_available_combinations ( ) self . _choose_what_to_display ( ) if len ( self . available_combinations ) < 2 and self . hide_if_single_combination : full_text = self . py3 . safe_format ( self . format , { "output" : "" } ) else : if self . fixed_width is True : ...
def run_edisgo_pool ( ding0_file_list , run_args_opt , workers = mp . cpu_count ( ) , worker_lifetime = 1 ) : """Use python multiprocessing toolbox for parallelization Several grids are analyzed in parallel . Parameters ding0 _ file _ list : list Ding0 grid data file names run _ args _ opt : list eDisGo...
def collect_pool_results ( result ) : results . append ( result ) results = [ ] pool = mp . Pool ( workers , maxtasksperchild = worker_lifetime ) for file in ding0_file_list : edisgo_args = [ file ] + run_args_opt pool . apply_async ( func = run_edisgo_twice , args = ( edisgo_args , ) , callback = collect_p...
def directory_remove ( self , path ) : """Removes a guest directory if empty . Symbolic links in the final component will not be followed , instead an not - a - directory error is reported . in path of type str Path to the directory that should be removed . Guest path style ."""
if not isinstance ( path , basestring ) : raise TypeError ( "path can only be an instance of type basestring" ) self . _call ( "directoryRemove" , in_p = [ path ] )
def mkpartfs ( device , part_type , fs_type , start , end ) : '''Make a < part _ type > partition with a new filesystem of < fs _ type > , beginning at < start > and ending at < end > ( by default in megabytes ) . < part _ type > should be one of " primary " , " logical " , or " extended " . < fs _ type > mus...
_validate_device ( device ) if part_type not in set ( [ 'primary' , 'logical' , 'extended' ] ) : raise CommandExecutionError ( 'Invalid part_type passed to partition.mkpartfs' ) if not _is_fstype ( fs_type ) : raise CommandExecutionError ( 'Invalid fs_type passed to partition.mkpartfs' ) _validate_partition_bou...
def check_model ( self ) : """Check the model for various errors . This method checks for the following errors . In the same time also updates the cardinalities of all the random variables . * Checks if clique potentials are defined for all the cliques or not . * Check for running intersection property is n...
if not nx . is_connected ( self ) : raise ValueError ( 'The Junction Tree defined is not fully connected.' ) return super ( JunctionTree , self ) . check_model ( )
def _check_dir ( self ) : """Makes sure that the working directory for the wrapper modules exists ."""
from os import path , mkdir if not path . isdir ( self . dirpath ) : mkdir ( self . dirpath ) # Copy the ftypes . py module shipped with fortpy to the local directory . ftypes = path . join ( get_fortpy_templates ( ) , "ftypes.py" ) from shutil import copy copy ( ftypes , self . dirpath ) # Crea...
def _write2 ( self , data , multithread = True , ** kwargs ) : ''': param data : Data to be written : type data : str or mmap object : param multithread : If True , sends multiple write requests asynchronously : type multithread : boolean Writes the data * data * to the file . . . note : : Writing to re...
if not USING_PYTHON2 : assert ( isinstance ( data , bytes ) ) self . _ensure_write_bufsize ( ** kwargs ) def write_request ( data_for_write_req ) : if multithread : self . _async_upload_part_request ( data_for_write_req , index = self . _cur_part , ** kwargs ) else : self . upload_part ( dat...
def discard ( self , key ) : """Banana banana"""
if key in self . map : key , prev , nxt = self . map . pop ( key ) prev [ 2 ] = nxt nxt [ 1 ] = prev
def millRule ( self , aLvlNow , pLvlNow , MPCnow , TranShkNow , EmpNow , t_age , LorenzBool , ManyStatsBool ) : '''The millRule for this class simply calls the method calcStats .'''
self . calcStats ( aLvlNow , pLvlNow , MPCnow , TranShkNow , EmpNow , t_age , LorenzBool , ManyStatsBool ) if self . AggShockBool : return self . calcRandW ( aLvlNow , pLvlNow ) else : # These variables are tracked but not created in no - agg - shocks specifications self . MaggNow = 0.0 self . AaggNow = 0.0
def to_jd ( year , month , day ) : '''Determine Julian day from Persian date'''
if year >= 0 : y = 474 else : y = 473 epbase = year - y epyear = 474 + ( epbase % 2820 ) if month <= 7 : m = ( month - 1 ) * 31 else : m = ( month - 1 ) * 30 + 6 return day + m + trunc ( ( ( epyear * 682 ) - 110 ) / 2816 ) + ( epyear - 1 ) * 365 + trunc ( epbase / 2820 ) * 1029983 + ( EPOCH - 1 )
def send_chat_messages ( self , messages ) : """Useful for logging messages into the replay ."""
self . _parallel . run ( ( c . chat , message ) for c , message in zip ( self . _controllers , messages ) )
async def deserialize ( data : dict ) : """Create the object from a previously serialized object . : param data : The output of the " serialize " call Example : source _ id = ' foobar123' name = ' Address Schema ' version = ' 1.0' attrs = [ ' address ' , ' city ' , ' state ' ] payment _ handle = 0 s...
try : # Todo : Find better way to access attr _ names . Potential for issues . schema = await Schema . _deserialize ( "vcx_schema_deserialize" , json . dumps ( data ) , data [ 'data' ] [ 'source_id' ] , data [ 'data' ] [ 'name' ] , data [ 'data' ] [ 'version' ] , data [ 'data' ] [ 'data' ] ) schema . schema_id ...
def version_jar ( self ) : """Special case of version ( ) when the executable is a JAR file ."""
cmd = config . get_command ( 'java' ) cmd . append ( '-jar' ) cmd += self . cmd self . version ( cmd = cmd , path = self . cmd [ 0 ] )
def trigger ( self , event : str , ** kwargs : Any ) -> None : """Trigger all handlers for an event to ( asynchronously ) execute"""
event = event . upper ( ) for func in self . _event_handlers [ event ] : self . loop . create_task ( func ( ** kwargs ) ) # This will unblock anyone that is awaiting on the next loop update , # while still ensuring the next ` await client . wait ( event ) ` doesn ' t # immediately fire . async_event = self . _event...
def _get_all_filtered_channels ( self , topics_without_signature ) : """get all filtered chanels from blockchain logs"""
mpe_address = self . get_mpe_address ( ) event_signature = self . ident . w3 . sha3 ( text = "ChannelOpen(uint256,uint256,address,address,address,bytes32,uint256,uint256)" ) . hex ( ) topics = [ event_signature ] + topics_without_signature logs = self . ident . w3 . eth . getLogs ( { "fromBlock" : self . args . from_bl...
def _next_image_partname ( self , ext ) : """The next available image partname , starting from ` ` / word / media / image1 . { ext } ` ` where unused numbers are reused . The partname is unique by number , without regard to the extension . * ext * does not include the leading period ."""
def image_partname ( n ) : return PackURI ( '/word/media/image%d.%s' % ( n , ext ) ) used_numbers = [ image_part . partname . idx for image_part in self ] for n in range ( 1 , len ( self ) + 1 ) : if n not in used_numbers : return image_partname ( n ) return image_partname ( len ( self ) + 1 )
def get_first_view ( self , fmt = 'json' ) : """Get a first view model as dict : return :"""
url = self . __url + 'views/first' return self . session . get ( url ) . json ( )
def insert ( self , index , value ) : '''Insert a node in - place . It is highly suggested that you do not use this method . Use assoc instead'''
newnode = LookupTreeNode ( index , value ) level = 0 node = self . root while True : ind = _getbits ( newnode . index , level ) level += 1 child = node . children [ ind ] if child is None or child . index == newnode . index : if child : assert child . value == newnode . value ...
def get_toolbar_buttons ( self ) : """Return toolbar buttons list ."""
buttons = [ ] # Code to add the stop button if self . stop_button is None : self . stop_button = create_toolbutton ( self , text = _ ( "Stop" ) , icon = self . stop_icon , tip = _ ( "Stop the current command" ) ) self . disable_stop_button ( ) # set click event handler self . stop_button . clicked . con...
def flatten_and_batch_shift_indices ( indices : torch . Tensor , sequence_length : int ) -> torch . Tensor : """This is a subroutine for : func : ` ~ batched _ index _ select ` . The given ` ` indices ` ` of size ` ` ( batch _ size , d _ 1 , . . . , d _ n ) ` ` indexes into dimension 2 of a target tensor , which ...
# Shape : ( batch _ size ) offsets = get_range_vector ( indices . size ( 0 ) , get_device_of ( indices ) ) * sequence_length for _ in range ( len ( indices . size ( ) ) - 1 ) : offsets = offsets . unsqueeze ( 1 ) # Shape : ( batch _ size , d _ 1 , . . . , d _ n ) offset_indices = indices + offsets # Shape : ( batch...
def to_neo4j ( graph , neo_connection , use_tqdm = False ) : """Upload a BEL graph to a Neo4j graph database using : mod : ` py2neo ` . : param pybel . BELGraph graph : A BEL Graph : param neo _ connection : A : mod : ` py2neo ` connection object . Refer to the ` py2neo documentation < http : / / py2neo . org...
import py2neo if isinstance ( neo_connection , str ) : neo_connection = py2neo . Graph ( neo_connection ) tx = neo_connection . begin ( ) node_map = { } nodes = list ( graph ) if use_tqdm : nodes = tqdm ( nodes , desc = 'nodes' ) for node in nodes : if NAMESPACE not in node or VARIANTS in node or MEMBERS in...
def SerializeExclusiveData ( self , writer ) : """Serialize object . Args : writer ( neo . IO . BinaryWriter ) :"""
writer . WriteVarBytes ( self . Script ) if self . Version >= 1 : writer . WriteFixed8 ( self . Gas )
def search_song ( self , song_name , quiet = False , limit = 9 ) : """Search song by song name . : params song _ name : song name . : params quiet : automatically select the best one . : params limit : song count returned by weapi . : return : a Song object ."""
result = self . search ( song_name , search_type = 1 , limit = limit ) if result [ 'result' ] [ 'songCount' ] <= 0 : LOG . warning ( 'Song %s not existed!' , song_name ) raise SearchNotFound ( 'Song {} not existed.' . format ( song_name ) ) else : songs = result [ 'result' ] [ 'songs' ] if quiet : ...
def _set_detail ( self , v , load = False ) : """Setter method for detail , mapped from YANG variable / openflow _ state / detail ( container ) If this variable is read - only ( config : false ) in the source YANG file , then _ set _ detail is considered as a private method . Backends looking to populate this...
if hasattr ( v , "_utype" ) : v = v . _utype ( v ) try : t = YANGDynClass ( v , base = detail . detail , is_container = 'container' , presence = False , yang_name = "detail" , rest_name = "detail" , parent = self , path_helper = self . _path_helper , extmethods = self . _extmethods , register_paths = True , ext...
def execute ( self ) : """Execute the search and return an instance of ` ` Response ` ` wrapping all the data ."""
es = connections . get_connection ( self . _using ) self . _response = self . _response_class ( self , es . update_by_query ( index = self . _index , body = self . to_dict ( ) , ** self . _params ) ) return self . _response
def update ( self , defaults = values . unset ) : """Update the DefaultsInstance : param dict defaults : A JSON string that describes the default task links . : returns : Updated DefaultsInstance : rtype : twilio . rest . autopilot . v1 . assistant . defaults . DefaultsInstance"""
data = values . of ( { 'Defaults' : serialize . object ( defaults ) , } ) payload = self . _version . update ( 'POST' , self . _uri , data = data , ) return DefaultsInstance ( self . _version , payload , assistant_sid = self . _solution [ 'assistant_sid' ] , )
def help_center_section_subscription_show ( self , section_id , id , locale = None , ** kwargs ) : "https : / / developer . zendesk . com / rest _ api / docs / help _ center / subscriptions # show - section - subscription"
api_path = "/api/v2/help_center/sections/{section_id}/subscriptions/{id}.json" api_path = api_path . format ( section_id = section_id , id = id ) if locale : api_opt_path = "/api/v2/help_center/{locale}/sections/{section_id}/subscriptions/{id}.json" api_path = api_opt_path . format ( section_id = section_id , i...
def _set_path ( self , v , load = False ) : """Setter method for path , mapped from YANG variable / mpls _ config / router / mpls / mpls _ cmds _ holder / path ( list ) If this variable is read - only ( config : false ) in the source YANG file , then _ set _ path is considered as a private method . Backends l...
if hasattr ( v , "_utype" ) : v = v . _utype ( v ) try : t = YANGDynClass ( v , base = YANGListType ( "path_name" , path . path , yang_name = "path" , rest_name = "path" , parent = self , is_container = 'list' , user_ordered = False , path_helper = self . _path_helper , yang_keys = 'path-name' , extensions = { ...
def _create_event_listeners ( self ) : """Create and bind the event listeners ."""
LOG . debug ( "Create the event listeners." ) for event_type , callback in self . _event_callback_pairs : LOG . debug ( "Create listener for %r event" , event_type ) listener = self . _utils . get_vnic_event_listener ( event_type ) eventlet . spawn_n ( listener , callback )
def project_process ( index , start , end ) : """Compute the metrics for the project process section of the enriched github issues index . Returns a dictionary containing " bmi _ metrics " , " time _ to _ close _ metrics " , " time _ to _ close _ review _ metrics " and patchsets _ metrics as the keys and th...
results = { "bmi_metrics" : [ BMI ( index , start , end ) ] , "time_to_close_metrics" : [ DaysToCloseAverage ( index , start , end ) , DaysToCloseMedian ( index , start , end ) ] , "time_to_close_review_metrics" : [ ] , "patchsets_metrics" : [ ] } return results
def _parse_welcome ( client , command , actor , args ) : """Parse a WELCOME and update user state , then dispatch a WELCOME event ."""
_ , _ , hostmask = args . rpartition ( ' ' ) client . user . update_from_hostmask ( hostmask ) client . dispatch_event ( "WELCOME" , hostmask )
def det_refpoint ( self , angle ) : """Return the detector reference point position at ` ` angle ` ` . For an angle ` ` phi ` ` , the detector position is given by : : det _ ref ( phi ) = translation + rot _ matrix ( phi ) * ( det _ rad * src _ to _ det _ init ) where ` ` src _ to _ det _ init ` ` is the in...
squeeze_out = ( np . shape ( angle ) == ( ) ) angle = np . array ( angle , dtype = float , copy = False , ndmin = 1 ) # Initial vector from the rotation center to the detector . It can be # computed this way since source and detector are at maximum distance , # i . e . the connecting line passes the origin . center_to_...
def agent ( ) : """Run the agent , connecting to a ( remote ) host started independently ."""
agent_module , agent_name = FLAGS . agent . rsplit ( "." , 1 ) agent_cls = getattr ( importlib . import_module ( agent_module ) , agent_name ) logging . info ( "Starting agent:" ) with lan_sc2_env . LanSC2Env ( host = FLAGS . host , config_port = FLAGS . config_port , race = sc2_env . Race [ FLAGS . agent_race ] , step...
def setup ( cli ) : """Everything to make skypipe ready to use"""
if not cli . global_config . loaded : setup_dotcloud_account ( cli ) discover_satellite ( cli ) cli . success ( "Skypipe is ready for action" )
def urljoin ( netloc , port , ssl ) : """Basically the counter - part of : func : ` urlsplit ` ."""
rv = ( "https" if ssl else "http" ) + "://" + netloc if ssl and port != 443 or not ssl and port != 80 : rv += ":%i" % port return rv
def get_dir ( self , scope , class_ ) : """Return the callable function from appdirs , but with the result wrapped in self . path _ class"""
prop_name = '{scope}_{class_}_dir' . format ( ** locals ( ) ) value = getattr ( self . wrapper , prop_name ) MultiPath = Multi . for_class ( self . path_class ) return MultiPath . detect ( value )
def create_hook ( self , auth , repo_name , hook_type , config , events = None , organization = None , active = False ) : """Creates a new hook , and returns the created hook . : param auth . Authentication auth : authentication object , must be admin - level : param str repo _ name : the name of the repo for w...
if events is None : events = [ "push" ] # default value is mutable , so assign inside body data = { "type" : hook_type , "config" : config , "events" : events , "active" : active } url = "/repos/{o}/{r}/hooks" . format ( o = organization , r = repo_name ) if organization is not None else "/repos/{r}/hooks" . format...
def update_context ( self , context , update_mask = None , retry = google . api_core . gapic_v1 . method . DEFAULT , timeout = google . api_core . gapic_v1 . method . DEFAULT , metadata = None ) : """Updates the specified context . Example : > > > import dialogflow _ v2 > > > client = dialogflow _ v2 . Contex...
# Wrap the transport method to add retry and timeout logic . if 'update_context' not in self . _inner_api_calls : self . _inner_api_calls [ 'update_context' ] = google . api_core . gapic_v1 . method . wrap_method ( self . transport . update_context , default_retry = self . _method_configs [ 'UpdateContext' ] . retr...
def export ( self ) : """Serializes to JSON ."""
fields = [ 'id' , 'host' , 'port' , 'user' ] out = { } for field in fields : out [ field ] = getattr ( self , field , None ) out [ 'mountOptions' ] = self . mount_opts out [ 'mountPoint' ] = self . mount_point out [ 'beforeMount' ] = self . cmd_before_mount out [ 'authType' ] = self . auth_method out [ 'sshKey' ] =...
def printAllElements ( self ) : """print out all modeled elements"""
cnt = 1 print ( "{id:<3s}: {name:<12s} {type:<10s} {classname:<10s}" . format ( id = 'ID' , name = 'Name' , type = 'Type' , classname = 'Class Name' ) ) for e in self . _lattice_eleobjlist : print ( "{cnt:>03d}: {name:<12s} {type:<10s} {classname:<10s}" . format ( cnt = cnt , name = e . name , type = e . typename ,...
def on_finish ( self ) : """Invoked once the request has been finished . Increment a counter created in the format : package [ . module ] . Class . METHOD . STATUS tornado . web . RequestHandler . GET . 200"""
super ( StatsdMixin , self ) . on_finish ( ) key = '%s.%s.%s.%s' % ( self . __module__ , self . __class__ . __name__ , self . request . method , self . _status_code ) LOGGER . info ( 'Processing %s' , key ) self . statsd_incr ( key ) self . statsd_add_timing ( key , self . request . request_time ( ) * 1000 )
def summary_status ( call , data ) : """Retrieve status in regions of interest , along with heterogeneity metrics . Provides output with overall purity and ploidy , along with region specific calls ."""
out_file = None if call . get ( "vrn_file" ) and os . path . exists ( call . get ( "vrn_file" ) ) : out_file = os . path . join ( os . path . dirname ( call [ "vrn_file" ] ) , "%s-%s-lohsummary.yaml" % ( dd . get_sample_name ( data ) , call [ "variantcaller" ] ) ) if not utils . file_uptodate ( out_file , call ...
def _config_logic ( napalm_device , loaded_result , test = False , debug = False , replace = False , commit_config = True , loaded_config = None , commit_in = None , commit_at = None , revert_in = None , revert_at = None , commit_jid = None , ** kwargs ) : '''Builds the config logic for ` load _ config ` and ` load...
# As the Salt logic is built around independent events # when it comes to configuration changes in the # candidate DB on the network devices , we need to # make sure we ' re using the same session . # Hence , we need to pass the same object around . # the napalm _ device object is inherited from # the load _ config or ...
def removeRandomLenPadding ( str , blocksize = AES_blocksize ) : 'ISO 10126 Padding ( withdrawn , 2007 ) : Remove Padding with random bytes + last byte equal to the number of padding bytes'
pad_len = ord ( str [ - 1 ] ) # last byte contains number of padding bytes assert pad_len < blocksize , 'padding error' assert pad_len < len ( str ) , 'padding error' return str [ : - pad_len ]
def _add_debugging_fields ( gelf_dict , record ) : """Add debugging fields to the given ` ` gelf _ dict ` ` : param gelf _ dict : dictionary representation of a GELF log . : type gelf _ dict : dict : param record : : class : ` logging . LogRecord ` to extract debugging fields from to insert into the given `...
gelf_dict . update ( { 'file' : record . pathname , 'line' : record . lineno , '_function' : record . funcName , '_pid' : record . process , '_thread_name' : record . threadName , } ) # record . processName was added in Python 2.6.2 pn = getattr ( record , 'processName' , None ) if pn is not None : gelf_dict [ '_pr...
def default_login_checker ( user ) : """user must be a dictionary here default is checking username / password if login is ok returns True else False : param user : dict { ' username ' : ' ' , ' password ' : ' ' }"""
username = user . get ( 'username' ) password = user . get ( 'password' ) the_username = os . environ . get ( 'SIMPLELOGIN_USERNAME' , current_app . config . get ( 'SIMPLELOGIN_USERNAME' , 'admin' ) ) the_password = os . environ . get ( 'SIMPLELOGIN_PASSWORD' , current_app . config . get ( 'SIMPLELOGIN_PASSWORD' , 'sec...
def from_bytes ( cls , xbytes : bytes ) -> 'BlsEntity' : """Creates and Bls entity from bytes representation . : param xbytes : Bytes representation of Bls entity : return : BLS entity intance"""
logger = logging . getLogger ( __name__ ) logger . debug ( "BlsEntity::from_bytes: >>>" ) c_instance = c_void_p ( ) do_call ( cls . from_bytes_handler , xbytes , len ( xbytes ) , byref ( c_instance ) ) res = cls ( c_instance ) logger . debug ( "BlsEntity::from_bytes: <<< res: %r" , res ) return res
def get_child_vault_ids ( self , vault_id ) : """Gets the child ` ` Ids ` ` of the given vault . arg : vault _ id ( osid . id . Id ) : the ` ` Id ` ` to query return : ( osid . id . IdList ) - the children of the vault raise : NotFound - ` ` vault _ id ` ` is not found raise : NullArgument - ` ` vault _ id ...
# Implemented from template for # osid . resource . BinHierarchySession . get _ child _ bin _ ids if self . _catalog_session is not None : return self . _catalog_session . get_child_catalog_ids ( catalog_id = vault_id ) return self . _hierarchy_session . get_children ( id_ = vault_id )
def decode ( self , name ) : """Translate a target name into its integer code . > > > planets . decode ( ' Venus ' ) 299 Raises ` ` ValueError ` ` if you supply an unknown name , or ` ` KeyError ` ` if the target is missing from this kernel . You can supply an integer code if you already have one and just...
if isinstance ( name , int ) : code = name else : name = name . upper ( ) code = _targets . get ( name ) if code is None : raise ValueError ( 'unknown SPICE target {0!r}' . format ( name ) ) if code not in self . codes : targets = ', ' . join ( _format_code_and_name ( c ) for c in self . cod...
def ServiceWorker_deliverPushMessage ( self , origin , registrationId , data ) : """Function path : ServiceWorker . deliverPushMessage Domain : ServiceWorker Method name : deliverPushMessage Parameters : Required arguments : ' origin ' ( type : string ) - > No description ' registrationId ' ( type : str...
assert isinstance ( origin , ( str , ) ) , "Argument 'origin' must be of type '['str']'. Received type: '%s'" % type ( origin ) assert isinstance ( registrationId , ( str , ) ) , "Argument 'registrationId' must be of type '['str']'. Received type: '%s'" % type ( registrationId ) assert isinstance ( data , ( str , ) ) ,...
def ipython_only ( option ) : """Mark that an option should only be exposed in IPython . Parameters option : decorator A click . option decorator . Returns ipython _ only _ dec : decorator A decorator that correctly applies the argument even when not using IPython mode ."""
if __IPYTHON__ : return option argname = extract_option_object ( option ) . name def d ( f ) : @ wraps ( f ) def _ ( * args , ** kwargs ) : kwargs [ argname ] = None return f ( * args , ** kwargs ) return _ return d
def make_nn_descent ( dist , dist_args ) : """Create a numba accelerated version of nearest neighbor descent specialised for the given distance metric and metric arguments . Numba doesn ' t support higher order functions directly , but we can instead JIT compile the version of NN - descent for any given metri...
@ numba . njit ( parallel = True ) def nn_descent ( data , n_neighbors , rng_state , max_candidates = 50 , n_iters = 10 , delta = 0.001 , rho = 0.5 , rp_tree_init = True , leaf_array = None , verbose = False , ) : n_vertices = data . shape [ 0 ] current_graph = make_heap ( data . shape [ 0 ] , n_neighbors ) ...
def train ( self , ds ) : """Run training step : solve for best - fit spectral model"""
if self . useErrors : self . coeffs , self . scatters , self . new_tr_labels , self . chisqs , self . pivots , self . scales = _train_model_new ( ds ) else : self . coeffs , self . scatters , self . chisqs , self . pivots , self . scales = _train_model ( ds )
def is_in_schedule_mode ( self ) : """Returns True if base _ station is currently on a scheduled mode ."""
resource = "schedule" mode_event = self . publish_and_get_event ( resource ) if mode_event and mode_event . get ( "resource" , None ) == "schedule" : properties = mode_event . get ( 'properties' ) return properties . get ( "active" , False ) return False
def distance_tt_point ( a , b ) : """Euclidean distance between two ( tracktotrip ) points Args : a ( : obj : ` Point ` ) b ( : obj : ` Point ` ) Returns : float"""
return math . sqrt ( ( b . lat - a . lat ) ** 2 + ( b . lon - a . lon ) ** 2 )
def _prepare_encryption_table ( ) : """Prepare encryption table for MPQ hash function ."""
seed = 0x00100001 crypt_table = { } for i in range ( 256 ) : index = i for j in range ( 5 ) : seed = ( seed * 125 + 3 ) % 0x2AAAAB temp1 = ( seed & 0xFFFF ) << 0x10 seed = ( seed * 125 + 3 ) % 0x2AAAAB temp2 = ( seed & 0xFFFF ) crypt_table [ index ] = ( temp1 | temp2 ) ...
def _last_commit ( self ) : """Retrieve the most recent commit message ( with ` ` svn log - l1 ` ` ) Returns : tuple : ( datestr , ( revno , user , None , desc ) ) $ svn log - l1 r25701 | bhendrix | 2010-08-02 12:14:25 - 0500 ( Mon , 02 Aug 2010 ) | 1 line added selection range traits to make it possible ...
cmd = [ 'svn' , 'log' '-l1' ] op = self . sh ( cmd , shell = False ) data , rest = op . split ( '\n' , 2 ) [ 1 : ] revno , user , datestr , lc = data . split ( ' | ' , 3 ) desc = '\n' . join ( rest . split ( '\n' ) [ 1 : - 2 ] ) revno = revno [ 1 : ] # lc = long ( lc . rstrip ( ' line ' ) ) return datestr , ( revno , u...
def start ( self ) : """Initiate the session by starting to execute the command with the peer . : return : The : attr : ` ~ . xso . Command . first _ payload ` of the response This sends an empty command IQ request with the : attr : ` ~ . ActionType . EXECUTE ` action . The : attr : ` status ` , : attr : ` ...
if self . _response is not None : raise RuntimeError ( "command execution already started" ) request = aioxmpp . IQ ( type_ = aioxmpp . IQType . SET , to = self . _peer_jid , payload = adhoc_xso . Command ( self . _command_name ) , ) self . _response = yield from self . _stream . send_iq_and_wait_for_reply ( reques...
def validate_parameters ( self ) : """Validate that the parameters are correctly specified ."""
for p in self . params : if p not in self . known_params : raise errors . UnknownParameter ( p , self . known_params )
def p_flatten ( self , obj , ** kwargs ) : """Flatten a list of lists of lists . . . of strings into a string This is usually used as the action for sequence expressions : . . code - block : : my _ rule < - ' a ' . ' c ' { p _ flatten } With the input " abc " and no action , this rule returns [ ' a ' , ' b ...
if isinstance ( obj , six . string_types ) : return obj result = "" for i in obj : result += self . p_flatten ( i ) return result
def open_sciobj_file_by_path ( abs_path , write = False ) : """Open a SciObj file for read or write . If opened for write , create any missing directories . For a SciObj stored in the default SciObj store , the path includes the PID hash based directory levels . This is the only method in GMN that opens SciOb...
if write : d1_common . utils . filesystem . create_missing_directories_for_file ( abs_path ) return open ( abs_path , 'wb' if write else 'rb' )
def apply_T1 ( word ) : '''There is a syllable boundary in front of every CV - sequence .'''
# split consonants and vowels : ' balloon ' - > [ ' b ' , ' a ' , ' ll ' , ' oo ' , ' n ' ] WORD = [ w for w in re . split ( '([ieAyOauo]+)' , word ) if w ] count = 0 for i , v in enumerate ( WORD ) : if i == 0 and is_consonant ( v [ 0 ] ) : continue elif is_consonant ( v [ 0 ] ) and i + 1 != len ( WORD...
def assign ( self , ** kwargs ) : r"""Assign new columns to a DataFrame . Returns a new object with all original columns in addition to new ones . Existing columns that are re - assigned will be overwritten . Parameters * * kwargs : dict of { str : callable or Series } The column names are keywords . If t...
data = self . copy ( ) # > = 3.6 preserve order of kwargs if PY36 : for k , v in kwargs . items ( ) : data [ k ] = com . apply_if_callable ( v , data ) else : # < = 3.5 : do all calculations first . . . results = OrderedDict ( ) for k , v in kwargs . items ( ) : results [ k ] = com . apply_i...
async def variant ( self , elem = None , elem_type = None , params = None ) : """Loads / dumps variant type : param elem : : param elem _ type : : param params : : return :"""
elem_type = elem_type if elem_type else elem . __class__ version = await self . version ( elem_type , params , elem = elem ) if self . is_tracked ( ) : return self . get_tracked ( ) if hasattr ( elem_type , 'boost_serialize' ) : elem = elem_type ( ) if elem is None else elem self . pop_track ( ) return ...
def parse_document ( xmlcontent ) : """Parse document with content . Content is placed in file ' document . xml ' ."""
document = etree . fromstring ( xmlcontent ) body = document . xpath ( './/w:body' , namespaces = NAMESPACES ) [ 0 ] document = doc . Document ( ) for elem in body : if elem . tag == _name ( '{{{w}}}p' ) : document . elements . append ( parse_paragraph ( document , elem ) ) if elem . tag == _name ( '{{{...
def exists ( self , document_or_id = None , session = None , ** kwargs ) : """Check if a file exists in this instance of : class : ` GridFS ` . The file to check for can be specified by the value of its ` ` _ id ` ` key , or by passing in a query document . A query document can be passed in as dictionary , or...
if kwargs : f = self . __files . find_one ( kwargs , [ "_id" ] , session = session ) else : f = self . __files . find_one ( document_or_id , [ "_id" ] , session = session ) return f is not None
def set_menu_separator ( self , img ) : """Sets the menu separator . Must be called before adding entries to the menu"""
if img : self . menu_separator_tag = '<img src="{}" alt="/" />' . format ( self . _rel ( img ) ) else : self . menu_separator_tag = None
def imagetransformer_base_12l_8h_big ( ) : """big 1d model for conditional image generation ."""
hparams = imagetransformer_sep_channels_8l_8h ( ) hparams . filter_size = 1024 hparams . num_decoder_layers = 12 hparams . batch_size = 1 hparams . hidden_size = 512 hparams . learning_rate_warmup_steps = 4000 hparams . sampling_method = "random" hparams . beam_size = 1 hparams . block_width = 256 return hparams
def log_subtract ( loga , logb ) : r"""Numerically stable method for avoiding overflow errors when calculating : math : ` \ log ( a - b ) ` , given : math : ` \ log ( a ) ` , : math : ` \ log ( a ) ` and that : math : ` a > b ` . See https : / / hips . seas . harvard . edu / blog / 2013/01/09 / computing - lo...
return loga + np . log ( 1 - np . exp ( logb - loga ) )
def per_version_data ( self ) : """Return download data by version . : return : dict of cache data ; keys are datetime objects , values are dict of version ( str ) to count ( int ) : rtype : dict"""
ret = { } for cache_date in self . cache_dates : data = self . _cache_get ( cache_date ) if len ( data [ 'by_version' ] ) == 0 : data [ 'by_version' ] = { 'other' : 0 } ret [ cache_date ] = data [ 'by_version' ] return ret
def history ( self , currency , since = 0 , until = 9999999999 , limit = 500 , wallet = 'exchange' ) : """View you balance ledger entries : param currency : currency to look for : param since : Optional . Return only the history after this timestamp . : param until : Optional . Return only the history before ...
payload = { "request" : "/v1/history" , "nonce" : self . _nonce , "currency" : currency , "since" : since , "until" : until , "limit" : limit , "wallet" : wallet } signed_payload = self . _sign_payload ( payload ) r = requests . post ( self . URL + "/history" , headers = signed_payload , verify = True ) json_resp = r ....
def simulated_annealing ( problem , schedule = _exp_schedule , iterations_limit = 0 , viewer = None ) : '''Simulated annealing . schedule is the scheduling function that decides the chance to choose worst nodes depending on the time . If iterations _ limit is specified , the algorithm will end after that nu...
return _local_search ( problem , _create_simulated_annealing_expander ( schedule ) , iterations_limit = iterations_limit , fringe_size = 1 , stop_when_no_better = iterations_limit == 0 , viewer = viewer )
def convert_to_process_params_dict ( opt ) : """Takes the namespace object ( opt ) from the multi - detector interface and returns a dictionary of command line options that will be handled correctly by the register _ to _ process _ params ligolw function ."""
opt = copy . deepcopy ( opt ) for arg , val in vars ( opt ) . items ( ) : if isinstance ( val , DictWithDefaultReturn ) : new_val = [ ] for key in val . keys ( ) : if isinstance ( val [ key ] , list ) : for item in val [ key ] : if item is not None : ...
def query ( self , query ) : """Sends a query to the Riemann server > > > client . query ( ' true ' ) : returns : A list of event dictionaries taken from the response : raises Exception : if used with a : py : class : ` . UDPTransport `"""
if isinstance ( self . transport , riemann_client . transport . UDPTransport ) : raise Exception ( 'Cannot query the Riemann server over UDP' ) response = self . send_query ( query ) return [ self . create_dict ( e ) for e in response . events ]
def _remove_buffers ( state ) : """Return ( state _ without _ buffers , buffer _ paths , buffers ) for binary message parts A binary message part is a memoryview , bytearray , or python 3 bytes object . As an example : > > > state = { ' plain ' : [ 0 , ' text ' ] , ' x ' : { ' ar ' : memoryview ( ar1 ) } , ' ...
buffer_paths , buffers = [ ] , [ ] state = _separate_buffers ( state , [ ] , buffer_paths , buffers ) return state , buffer_paths , buffers
def display ( self ) : """dump operation"""
print ( "{}" . format ( self ) ) for task in self . tasks : print ( " - {}" . format ( task ) )
def convert_ensembl_to_entrez ( self , ensembl ) : """Convert Ensembl Id to Entrez Gene Id"""
if 'ENST' in ensembl : pass else : raise ( IndexError ) # Submit resquest to NCBI eutils / Gene database server = "http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?" + self . options + "&db=gene&term={0}" . format ( ensembl ) r = requests . get ( server , headers = { "Content-Type" : "text/xml" } ) if ...
def loop ( self ) : """The actual infinite loop for this transformation ."""
logger . debug ( "Node loop starts for {!r}." . format ( self ) ) while self . should_loop : try : self . step ( ) except InactiveReadableError : break logger . debug ( "Node loop ends for {!r}." . format ( self ) )
def attention_lm_moe_memory_efficient ( ) : """Memory - efficient version ."""
hparams = attention_lm_moe_large ( ) hparams . diet_experts = True hparams . layer_preprocess_sequence = "n" hparams . layer_postprocess_sequence = "da" hparams . layer_prepostprocess_dropout = 0.0 hparams . memory_efficient_ffn = True hparams . attention_type = AttentionType . MEMORY_EFFICIENT hparams . num_heads = 8 ...
def _get_preprocessed ( self , data ) : """Returns : ( DeveloperPackage , new _ data ) 2 - tuple IFF the preprocess function changed the package ; otherwise None ."""
from rez . serialise import process_python_objects from rez . utils . data_utils import get_dict_diff_str from copy import deepcopy with add_sys_paths ( config . package_definition_build_python_paths ) : preprocess_func = getattr ( self , "preprocess" , None ) if preprocess_func : print_info ( "Applying...
def _remove_persistent_module ( mod , comment ) : '''Remove module from loader . conf . If comment is true only comment line where module is .'''
if not mod or mod not in mod_list ( True ) : return set ( ) if comment : __salt__ [ 'file.comment' ] ( _LOADER_CONF , _MODULE_RE . format ( mod ) ) else : __salt__ [ 'file.sed' ] ( _LOADER_CONF , _MODULE_RE . format ( mod ) , '' ) return set ( [ mod ] )