signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def _fetch_one ( self , request : Request ) -> Tuple [ bool , float ] : '''Process one of the loop iteration . Coroutine . Returns : If True , stop processing any future requests .'''
_logger . info ( _ ( 'Fetching ‘{url}’.' ) , url = request . url ) response = None try : response = yield from self . _web_client_session . start ( ) self . _item_session . response = response action = self . _result_rule . handle_pre_response ( self . _item_session ) if action in ( Actions . RETRY , Ac...
def export_input_zip ( ekey , dstore ) : """Export the data in the ` input _ zip ` dataset as a . zip file"""
dest = dstore . export_path ( 'input.zip' ) nbytes = dstore . get_attr ( 'input/zip' , 'nbytes' ) zbytes = dstore [ 'input/zip' ] . value # when reading input _ zip some terminating null bytes are truncated ( for # unknown reasons ) therefore they must be restored zbytes += b'\x00' * ( nbytes - len ( zbytes ) ) open ( ...
def flatten_nested_hash ( hash_table ) : """Flatten nested dictionary for GET / POST / DELETE API request"""
def flatten ( hash_table , brackets = True ) : f = { } for key , value in hash_table . items ( ) : _key = '[' + str ( key ) + ']' if brackets else str ( key ) if isinstance ( value , dict ) : for k , v in flatten ( value ) . items ( ) : f [ _key + k ] = v elif...
def move_inside ( self , parent_id ) : """Moving one node of tree inside another For example see : * : mod : ` sqlalchemy _ mptt . tests . cases . move _ node . test _ move _ inside _ function ` * : mod : ` sqlalchemy _ mptt . tests . cases . move _ node . test _ move _ inside _ to _ the _ same _ parent _ fun...
# noqa session = Session . object_session ( self ) self . parent_id = parent_id self . mptt_move_inside = parent_id session . add ( self )
def targets_format ( self , value ) : """Setter for * * self . _ _ targets _ format * * attribute . : param value : Attribute value . : type value : unicode"""
if value is not None : assert type ( value ) is unicode , "'{0}' attribute: '{1}' type is not 'unicode'!" . format ( "targets_format" , value ) assert os . path . exists ( value ) , "'{0}' attribute: '{1}' file doesn't exists!" . format ( "targets_format" , value ) self . __targets_format = value
def generate_proxy ( prefix , base_url = '' , verify_ssl = True , middleware = None , append_middleware = None , cert = None , timeout = None ) : """Generate a ProxyClass based view that uses the passed base _ url ."""
middleware = list ( middleware or HttpProxy . proxy_middleware ) middleware += list ( append_middleware or [ ] ) return type ( 'ProxyClass' , ( HttpProxy , ) , { 'base_url' : base_url , 'reverse_urls' : [ ( prefix , base_url ) ] , 'verify_ssl' : verify_ssl , 'proxy_middleware' : middleware , 'cert' : cert , 'timeout' :...
def check_update ( ) : """Return the following values : ( False , errmsg ) - online version could not be determined ( True , None ) - user has newest version ( True , ( version , url string ) ) - update available ( True , ( version , None ) ) - current version is newer than online version"""
version , value = get_online_version ( ) if version is None : # value is an error message return False , value if version == CurrentVersion : # user has newest version return True , None if is_newer_version ( version ) : # value is an URL linking to the update package return True , ( version , value ) # use...
def getargspec ( func ) : """Variation of inspect . getargspec that works for more functions . This function works for Cythonized , non - cpdef functions , which expose argspec information but are not accepted by getargspec . It also works for Python 3 functions that use annotations , which are simply ignored...
if inspect . ismethod ( func ) : func = func . __func__ # Cythonized functions have a . _ _ code _ _ , but don ' t pass inspect . isfunction ( ) try : code = func . __code__ except AttributeError : raise TypeError ( "{!r} is not a Python function" . format ( func ) ) if hasattr ( code , "co_kwonlyargcount" ...
def _create_eval_metric_composite ( metric_names : List [ str ] ) -> mx . metric . CompositeEvalMetric : """Creates a composite EvalMetric given a list of metric names ."""
metrics = [ EarlyStoppingTrainer . _create_eval_metric ( metric_name ) for metric_name in metric_names ] return mx . metric . create ( metrics )
def highlight_min ( self , subset = None , color = 'yellow' , axis = 0 ) : """Highlight the minimum by shading the background . Parameters subset : IndexSlice , default None a valid slice for ` ` data ` ` to limit the style application to . color : str , default ' yellow ' axis : { 0 or ' index ' , 1 or '...
return self . _highlight_handler ( subset = subset , color = color , axis = axis , max_ = False )
def all_solidity_variables_read ( self ) : """recursive version of solidity _ read"""
if self . _all_solidity_variables_read is None : self . _all_solidity_variables_read = self . _explore_functions ( lambda x : x . solidity_variables_read ) return self . _all_solidity_variables_read
def stub ( ) : """Just some left over code"""
form = cgi . FieldStorage ( ) userid = form [ 'userid' ] . value password = form [ 'passwd' ] . value group = form [ 'group' ] . value
def resource_filename_mod_dist ( module_name , dist ) : """Given a module name and a distribution , attempt to resolve the actual path to the module ."""
try : return pkg_resources . resource_filename ( dist . as_requirement ( ) , join ( * module_name . split ( '.' ) ) ) except pkg_resources . DistributionNotFound : logger . warning ( "distribution '%s' not found, falling back to resolution using " "module_name '%s'" , dist , module_name , ) return pkg_resou...
def destroy_vm_by_uuid ( self , si , vm_uuid , vm_path , logger ) : """destroy the given vm : param si : pyvmomi ' ServiceInstance ' : param vm _ uuid : str uuid of the vm to destroyed : param vm _ path : str path to the vm that will be destroyed : param logger :"""
if vm_uuid is not None : vm = self . find_by_uuid ( si , vm_uuid , vm_path ) if vm : return self . destroy_vm ( vm , logger ) # return ' vm not found ' # for apply the same Interface as for ' destroy _ vm _ by _ name ' raise ValueError ( 'vm not found' )
def plot_acc_pry_depth ( A_g_lf , A_g_hf , pry_deg , depths , glide_mask = None ) : '''Plot the acceleration with the pitch , roll , and heading Args A _ g _ lf : ndarray Low - pass filtered calibration accelerometer signal A _ g _ hf : ndarray High - pass filtered calibration accelerometer signal pry _...
import numpy fig , ( ax1 , ax2 , ax3 ) = plt . subplots ( 3 , 1 , sharex = True ) ax1 . title . set_text ( 'acceleromter' ) ax1 . plot ( range ( len ( A_g_lf ) ) , A_g_lf , color = _colors [ 0 ] ) ax1 . title . set_text ( 'PRH' ) ax2 . plot ( range ( len ( pry_deg ) ) , pry_deg , color = _colors [ 1 ] ) ax3 . title . s...
def error ( self , err = None ) : """Update the circuit breaker with an error event ."""
if self . state == 'half-open' : self . test_fail_count = min ( self . test_fail_count + 1 , 16 ) self . errors . append ( self . clock ( ) ) if len ( self . errors ) > self . maxfail : time = self . clock ( ) - self . errors . pop ( 0 ) if time < self . time_unit : if time == 0 : time =...
def import_from_string ( path , slient = True ) : """根据给定的对象路径 , 动态加载对象 。"""
names = path . split ( "." ) for i in range ( len ( names ) , 0 , - 1 ) : p1 = "." . join ( names [ 0 : i ] ) module = import_module ( p1 ) if module : p2 = "." . join ( names [ i : ] ) if p2 : return select ( module , p2 , slient = slient ) else : return modu...
def validate_value ( self , value ) : """Validate value is an acceptable type during set _ python operation"""
if self . readonly : raise ValidationError ( self . record , "Cannot set readonly field '{}'" . format ( self . name ) ) if value not in ( None , self . _unset ) : if self . supported_types and not isinstance ( value , tuple ( self . supported_types ) ) : raise ValidationError ( self . record , "Field '...
def _iter_files ( self , mod_name ) : '''Iterate over all file _ mapping files in order of closeness to mod _ name'''
# do we have an exact match ? if mod_name in self . file_mapping : yield mod_name # do we have a partial match ? for k in self . file_mapping : if mod_name in k : yield k # anyone else ? Bueller ? for k in self . file_mapping : if mod_name not in k : yield k
def mergecopy ( src , dest ) : """copy2 , but only if the destination isn ' t up to date"""
if os . path . exists ( dest ) and os . stat ( dest ) . st_mtime >= os . stat ( src ) . st_mtime : return copy2 ( src , dest )
def parse_colnames ( colnames , coords = None ) : """Convert colnames input into list of column numbers ."""
cols = [ ] if not isinstance ( colnames , list ) : colnames = colnames . split ( ',' ) # parse column names from coords file and match to input values if coords is not None and fileutil . isFits ( coords ) [ 0 ] : # Open FITS file with table ftab = fits . open ( coords , memmap = False ) # determine which e...
def run_guest ( ) : """A sample for quickly deploy and start a virtual guest ."""
# user input the properties of guest , image and network . _user_input_properties ( ) # run a guest . _run_guest ( GUEST_USERID , IMAGE_PATH , IMAGE_OS_VERSION , GUEST_PROFILE , GUEST_VCPUS , GUEST_MEMORY , NETWORK_INFO , VSWITCH_NAME , DISKS_LIST )
def PerfectSquare_metric ( bpmn_graph ) : """Returns the value of the Perfect Square metric ( " Given a set of element types ranked in decreasing order of the number of their instances , the PSM is the ( unique ) largest number such that the top p types occur ( together ) at least p2 times . " ) for the...
all_types_count = Counter ( [ node [ 1 ] [ 'type' ] for node in bpmn_graph . get_nodes ( ) if node [ 1 ] [ 'type' ] ] ) sorted_counts = [ count for _ , count in all_types_count . most_common ( ) ] potential_perfect_square = min ( len ( sorted_counts ) , int ( sqrt ( sum ( sorted_counts ) ) ) ) for i in range ( potentia...
def _cleaned ( _pipeline_objects ) : """Return standardized pipeline objects to be used for comparing Remove year , month , and day components of the startDateTime so that data pipelines with the same time of day but different days are considered equal ."""
pipeline_objects = copy . deepcopy ( _pipeline_objects ) for pipeline_object in pipeline_objects : if pipeline_object [ 'id' ] == 'DefaultSchedule' : for field_object in pipeline_object [ 'fields' ] : if field_object [ 'key' ] == 'startDateTime' : start_date_time_string = field_o...
def autodiscover ( self , message ) : """This function simply returns the server version number as a response to the client . Args : message ( dict ) : A dictionary of the autodiscover message from the client . Returns : A JSON string of the " OHAI Client " server response with the server ' s version ...
# Check to see if the client ' s version is the same as our own . if message [ "version" ] in self . allowed_versions : logger . debug ( "<%s> Client version matches server " "version." % message [ "cuuid" ] ) response = serialize_data ( { "method" : "OHAI Client" , "version" : self . version , "server_name" : ...
def _add_conntrack_stats_metrics ( self , conntrack_path , tags ) : """Parse the output of conntrack - S Add the parsed metrics"""
try : output , _ , _ = get_subprocess_output ( [ "sudo" , conntrack_path , "-S" ] , self . log ) # conntrack - S sample : # cpu = 0 found = 27644 invalid = 19060 ignore = 485633411 insert = 0 insert _ failed = 1 \ # drop = 1 early _ drop = 0 error = 0 search _ restart = 39936711 # cpu = 1 found = 21...
def spawn_container ( addr , env_cls = Environment , mgr_cls = EnvManager , set_seed = True , * args , ** kwargs ) : """Spawn a new environment in a given address as a coroutine . Arguments and keyword arguments are passed down to the created environment at initialization time . If ` setproctitle < https : / ...
# Try setting the process name to easily recognize the spawned # environments with ' ps - x ' or ' top ' try : import setproctitle as spt title = 'creamas: {}({})' . format ( env_cls . __class__ . __name__ , _get_base_url ( addr ) ) spt . setproctitle ( title ) except : pass if set_seed : _set_rando...
def get_device_info ( self ) -> dict : '''Queries Temp - Deck for it ' s build version , model , and serial number returns : dict Where keys are the strings ' version ' , ' model ' , and ' serial ' , and each value is a string identifier ' serial ' : ' 1aa11bb22 ' , ' model ' : ' 1aa11bb22 ' , ' version...
try : return self . _recursive_get_info ( DEFAULT_COMMAND_RETRIES ) except ( MagDeckError , SerialException , SerialNoResponse ) as e : return { 'error' : str ( e ) }
def get_output ( src ) : """parse lines looking for commands"""
output = '' lines = open ( src . path , 'rU' ) . readlines ( ) for line in lines : m = re . match ( config . import_regex , line ) if m : include_path = os . path . abspath ( src . dir + '/' + m . group ( 'script' ) ) ; if include_path not in config . sources : script = Script ( incl...
def write ( self , message ) : """( coroutine ) Write a single message into the pipe ."""
if self . done_f . done ( ) : raise BrokenPipeError try : yield From ( write_message_to_pipe ( self . pipe_instance . pipe_handle , message ) ) except BrokenPipeError : self . done_f . set_result ( None ) raise
def degrees ( radians = 0 , arcminutes = 0 , arcseconds = 0 ) : """TODO docs ."""
deg = 0. if radians : deg = math . degrees ( radians ) if arcminutes : deg += arcminutes / arcmin ( degrees = 1. ) if arcseconds : deg += arcseconds / arcsec ( degrees = 1. ) return deg
def decompile ( ast , indentation = 4 , line_length = 100 , starting_indentation = 0 ) : """Decompiles an AST into Python code . Arguments : - ast : code to decompile , using AST objects as generated by the standard library ast module - indentation : indentation level of lines - line _ length : if lines bec...
decompiler = Decompiler ( indentation = indentation , line_length = line_length , starting_indentation = starting_indentation , ) return decompiler . run ( ast )
def fit_transform ( self , input_df , normalize = True ) : """Convert the dataframe to a matrix ( numpy ndarray ) Args : input _ df ( dataframe ) : The dataframe to convert normalize ( bool ) : Boolean flag to normalize numeric columns ( default = True )"""
# Shallow copy the dataframe ( we ' ll be making changes to some columns ) _df = input_df . copy ( deep = False ) # Set class variables that will be used both now and later for transform self . normalize = normalize # Convert columns that are probably categorical self . convert_to_categorical ( _df ) # First check for ...
def neighbors ( self , n , t = None ) : """Return a list of the nodes connected to the node n at time t . Parameters n : node A node in the graph t : snapshot id ( default = None ) If None will be returned the neighbors of the node on the flattened graph . Returns nlist : list A list of nodes that a...
try : if t is None : return list ( self . _adj [ n ] ) else : return [ i for i in self . _adj [ n ] if self . __presence_test ( n , i , t ) ] except KeyError : raise nx . NetworkXError ( "The node %s is not in the graph." % ( n , ) )
def _discover_port ( self ) : """This is a private utility method . This method attempts to discover the com port that the arduino is connected to . : returns : Detected Comport"""
# if MAC get list of ports if sys . platform . startswith ( 'darwin' ) : locations = glob . glob ( '/dev/tty.[usb*]*' ) locations = glob . glob ( '/dev/tty.[wchusb*]*' ) + locations locations . append ( 'end' ) # for everyone else , here is a list of possible ports else : locations = [ '/dev/ttyACM0' , ...
def node_neighbors ( node_id ) : """Send a GET request to the node table . This calls the neighbours method of the node making the request and returns a list of descriptions of the nodes ( even if there is only one ) . Required arguments : participant _ id , node _ id Optional arguments : type , connectio...
exp = Experiment ( session ) # get the parameters node_type = request_parameter ( parameter = "node_type" , parameter_type = "known_class" , default = models . Node ) connection = request_parameter ( parameter = "connection" , default = "to" ) failed = request_parameter ( parameter = "failed" , parameter_type = "bool" ...
def copy ( self , source_path , destination_path , threads = DEFAULT_THREADS , start_time = None , end_time = None , part_size = DEFAULT_PART_SIZE , ** kwargs ) : """Copy object ( s ) from one S3 location to another . Works for individual keys or entire directories . When files are larger than ` part _ size ` , m...
# don ' t allow threads to be less than 3 threads = 3 if threads < 3 else threads if self . isdir ( source_path ) : return self . _copy_dir ( source_path , destination_path , threads = threads , start_time = start_time , end_time = end_time , part_size = part_size , ** kwargs ) # If the file isn ' t a directory jus...
def execute_code_block ( elem , doc ) : """Executes a code block by passing it to the executor . Args : elem The AST element . doc The document . Returns : The output of the command ."""
command = select_executor ( elem , doc ) . split ( ' ' ) code = elem . text if 'plt' in elem . attributes or 'plt' in elem . classes : code = save_plot ( code , elem ) command . append ( code ) if 'args' in elem . attributes : for arg in elem . attributes [ 'args' ] . split ( ) : command . append ( arg ...
def get_next_objective_banks ( self , n = None ) : """Gets the next set of ObjectiveBank elements in this list which must be less than or equal to the return from available ( ) . arg : n ( cardinal ) : the number of ObjectiveBank elements requested which must be less than or equal to available ( ) return ...
if n > self . available ( ) : # ! ! ! This is not quite as specified ( see method docs ) ! ! ! raise IllegalState ( 'not enough elements available in this list' ) else : next_list = [ ] x = 0 while x < n : try : next_list . append ( next ( self ) ) except Exception : # Need t...
def monitor_dir ( args ) : """displaying the changed files"""
def show_fp ( fp ) : args [ 'MDFILE' ] = fp pretty = run_args ( args ) print pretty print "(%s)" % col ( fp , L ) cmd = args . get ( 'change_cmd' ) if cmd : run_changed_file_cmd ( cmd , fp = fp , pretty = pretty ) ftree = { } d = args . get ( '-M' ) # was a change command given ? d += ':...
def parse ( self , data ) : # type : ( bytes ) - > None '''A method to parse an ISO9660 Path Table Record out of a string . Parameters : data - The string to parse . Returns : Nothing .'''
( self . len_di , self . xattr_length , self . extent_location , self . parent_directory_num ) = struct . unpack_from ( self . FMT , data [ : 8 ] , 0 ) if self . len_di % 2 != 0 : self . directory_identifier = data [ 8 : - 1 ] else : self . directory_identifier = data [ 8 : ] self . dirrecord = None self . _ini...
def config ( self , ** kwargs ) : """Configure resources of the widget . To get the list of options for this widget , call the method : meth : ` ~ Balloon . keys ` . See : meth : ` ~ Balloon . _ _ init _ _ ` for a description of the widget specific option ."""
self . __headertext = kwargs . pop ( "headertext" , self . __headertext ) self . __text = kwargs . pop ( "text" , self . __text ) self . __width = kwargs . pop ( "width" , self . __width ) self . _timeout = kwargs . pop ( "timeout" , self . _timeout ) self . __background = kwargs . pop ( "background" , self . __backgro...
def regularrun ( shell , prompt_template = "default" , aliases = None , envvars = None , extra_commands = None , speed = 1 , test_mode = False , commentecho = False , ) : """Allow user to run their own live commands until CTRL - Z is pressed again ."""
loop_again = True command_string = regulartype ( prompt_template ) if command_string == TAB : loop_again = False return loop_again run_command ( command_string , shell , aliases = aliases , envvars = envvars , extra_commands = extra_commands , test_mode = test_mode , ) return loop_again
def distorted_inputs ( dataset , batch_size = None , num_preprocess_threads = None ) : """Generate batches of distorted versions of ImageNet images . Use this function as the inputs for training a network . Distorting images provides a useful technique for augmenting the data set during training in order to m...
if not batch_size : batch_size = FLAGS . batch_size # Force all input processing onto CPU in order to reserve the GPU for # the forward inference and back - propagation . with tf . device ( '/cpu:0' ) : images , labels = batch_inputs ( dataset , batch_size , train = True , num_preprocess_threads = num_preproces...
def create_new_folder ( self , current_path , title , subtitle , is_package ) : """Create new folder"""
if current_path is None : current_path = '' if osp . isfile ( current_path ) : current_path = osp . dirname ( current_path ) name , valid = QInputDialog . getText ( self , title , subtitle , QLineEdit . Normal , "" ) if valid : dirname = osp . join ( current_path , to_text_string ( name ) ) try : ...
def _gcs_delete ( args , _ ) : """Delete one or more buckets or objects ."""
objects = _expand_list ( args [ 'bucket' ] ) objects . extend ( _expand_list ( args [ 'object' ] ) ) errs = [ ] for obj in objects : try : bucket , key = google . datalab . storage . _bucket . parse_name ( obj ) if bucket and key : gcs_object = google . datalab . storage . Object ( bucke...
def get_block_name ( self , index ) : """Returns the string name of the block at the given index"""
meta = self . GetMetaData ( index ) if meta is not None : return meta . Get ( vtk . vtkCompositeDataSet . NAME ( ) ) return None
def string_pieces ( s , maxlen = 1024 ) : """Takes a ( unicode ) string and yields pieces of it that are at most ` maxlen ` characters , trying to break it at punctuation / whitespace . This is an important step before using a tokenizer with a maximum buffer size ."""
if not s : return i = 0 while True : j = i + maxlen if j >= len ( s ) : yield s [ i : ] return # Using " j - 1 " keeps boundary characters with the left chunk while unicodedata . category ( s [ j - 1 ] ) not in BOUNDARY_CATEGORIES : j -= 1 if j == i : # No boundary av...
def verify ( self , flag_values ) : """Verifies that constraint is satisfied . flags library calls this method to verify Validator ' s constraint . Args : flag _ values : flags . FlagValues , the FlagValues instance to get flags from . Raises : Error : Raised if constraint is not satisfied ."""
param = self . _get_input_to_checker_function ( flag_values ) if not self . checker ( param ) : raise _exceptions . ValidationError ( self . message )
def buffer_open ( self , buf ) : """register and focus new : class : ` ~ alot . buffers . Buffer ` ."""
# call pre _ buffer _ open hook prehook = settings . get_hook ( 'pre_buffer_open' ) if prehook is not None : prehook ( ui = self , dbm = self . dbman , buf = buf ) if self . current_buffer is not None : offset = settings . get ( 'bufferclose_focus_offset' ) * - 1 currentindex = self . buffers . index ( self...
def set_arc ( self , arc ) : """Set the ACK retry count for radio communication"""
_send_vendor_setup ( self . handle , SET_RADIO_ARC , arc , 0 , ( ) ) self . arc = arc
def get_uv_tan ( c ) : """Get tangent plane basis vectors on the unit sphere at the given spherical coordinates ."""
l = c . spherical . lon b = c . spherical . lat p = np . array ( [ - np . sin ( l ) , np . cos ( l ) , np . zeros_like ( l . value ) ] ) . T q = np . array ( [ - np . cos ( l ) * np . sin ( b ) , - np . sin ( l ) * np . sin ( b ) , np . cos ( b ) ] ) . T return np . stack ( ( p , q ) , axis = - 1 )
def replace_route ( DryRun = None , RouteTableId = None , DestinationCidrBlock = None , GatewayId = None , DestinationIpv6CidrBlock = None , EgressOnlyInternetGatewayId = None , InstanceId = None , NetworkInterfaceId = None , VpcPeeringConnectionId = None , NatGatewayId = None ) : """Replaces an existing route with...
pass
def parse_ssh_config ( lines ) : '''Parses lines from the SSH config to create roster targets . : param lines : Individual lines from the ssh config file : return : Dictionary of targets in similar style to the flat roster'''
# transform the list of individual lines into a list of sublists where each # sublist represents a single Host definition hosts = [ ] for line in lines : line = salt . utils . stringutils . to_unicode ( line ) if not line or line . startswith ( '#' ) : continue elif line . startswith ( 'Host ' ) : ...
def parse_report ( self , buf ) : """Parse a buffer containing a HID report ."""
dpad = buf [ 5 ] % 16 return DS4Report ( # Left analog stick buf [ 1 ] , buf [ 2 ] , # Right analog stick buf [ 3 ] , buf [ 4 ] , # L2 and R2 analog buf [ 8 ] , buf [ 9 ] , # DPad up , down , left , right ( dpad in ( 0 , 1 , 7 ) ) , ( dpad in ( 3 , 4 , 5 ) ) , ( dpad in ( 5 , 6 , 7 ) ) , ( dpad in ( 1 , 2 , 3 ) ) , # B...
def dump_pytorch_graph ( graph ) : """List all the nodes in a PyTorch graph ."""
f = "{:25} {:40} {} -> {}" print ( f . format ( "kind" , "scopeName" , "inputs" , "outputs" ) ) for node in graph . nodes ( ) : print ( f . format ( node . kind ( ) , node . scopeName ( ) , [ i . unique ( ) for i in node . inputs ( ) ] , [ i . unique ( ) for i in node . outputs ( ) ] ) )
async def destroy ( self , destroy_all_models = False ) : """Destroy this controller . : param bool destroy _ all _ models : Destroy all hosted models in the controller ."""
controller_facade = client . ControllerFacade . from_connection ( self . connection ( ) ) return await controller_facade . DestroyController ( destroy_all_models )
def over ( self , window ) : """Define a windowing column . : param window : a : class : ` WindowSpec ` : return : a Column > > > from pyspark . sql import Window > > > window = Window . partitionBy ( " name " ) . orderBy ( " age " ) . rowsBetween ( - 1 , 1) > > > from pyspark . sql . functions import ran...
from pyspark . sql . window import WindowSpec if not isinstance ( window , WindowSpec ) : raise TypeError ( "window should be WindowSpec" ) jc = self . _jc . over ( window . _jspec ) return Column ( jc )
def _setup_ipc ( self ) : '''Subscribe to the right topic in the device IPC and publish to the publisher proxy .'''
self . ctx = zmq . Context ( ) # subscribe to device IPC log . debug ( 'Creating the dealer IPC for %s' , self . _name ) self . sub = self . ctx . socket ( zmq . DEALER ) if six . PY2 : self . sub . setsockopt ( zmq . IDENTITY , self . _name ) elif six . PY3 : self . sub . setsockopt ( zmq . IDENTITY , bytes ( ...
def do_reload ( self , msg ) : """Called when the dev server wants to reload the view ."""
# : TODO : This should use the autorelaoder app = self . app # : Show loading screen try : self . app . widget . showLoading ( "Reloading... Please wait." , now = True ) # self . app . widget . restartPython ( now = True ) # sys . exit ( 0) except : # : TODO : Implement for iOS . . . pass self . save_ch...
def _minimize_peak_memory_list ( graph ) : """Computes schedule according to the greedy list heuristic . Greedy list heuristic : schedule the operation which results in the most bytes of memory being ( immediately ) freed . TODO ( joshuawang ) : Experiment with tiebreaking by preferring more successors . Ar...
schedule = [ ] bytes_freed = { } # { operation _ name : bytes freed } users_of = collections . defaultdict ( set ) # { tensor _ name : set ( operation _ name ) } in_degree = collections . defaultdict ( int ) # { operation _ name : in degree } operation_id = { } # { operation _ name : id } # We want an updatable priorit...
def _process_degradation ( self , another_moc , order_op ) : """Degrade ( down - sampling ) self and ` ` another _ moc ` ` to ` ` order _ op ` ` order Parameters another _ moc : ` ~ mocpy . tmoc . TimeMoc ` order _ op : int the order in which self and ` ` another _ moc ` ` will be down - sampled to . Retu...
max_order = max ( self . max_order , another_moc . max_order ) if order_op > max_order : message = 'Requested time resolution for the operation cannot be applied.\n' 'The TimeMoc object resulting from the operation is of time resolution {0} sec.' . format ( TimeMOC . order_to_time_resolution ( max_order ) . sec ) ...
def fovtrg ( inst , target , tshape , tframe , abcorr , observer , et ) : """Determine if a specified ephemeris object is within the field - of - view ( FOV ) of a specified instrument at a given time . http : / / naif . jpl . nasa . gov / pub / naif / toolkit _ docs / C / cspice / fovtrg _ c . html : param i...
inst = stypes . stringToCharP ( inst ) target = stypes . stringToCharP ( target ) tshape = stypes . stringToCharP ( tshape ) tframe = stypes . stringToCharP ( tframe ) abcorr = stypes . stringToCharP ( abcorr ) observer = stypes . stringToCharP ( observer ) et = ctypes . c_double ( et ) visible = ctypes . c_int ( ) lib...
def _filter_options ( self , aliases = True , comments = True , historical = True ) : """Converts a set of boolean - valued options into the relevant HTTP values ."""
options = [ ] if not aliases : options . append ( 'noaliases' ) if not comments : options . append ( 'nocomments' ) if not historical : options . append ( 'nohistorical' ) return options
def _setup_sig_handler ( self ) : """Setup an interrupt handler so that SCons can shutdown cleanly in various conditions : a ) SIGINT : Keyboard interrupt b ) SIGTERM : kill or system shutdown c ) SIGHUP : Controlling shell exiting We handle all of these cases by stopping the taskmaster . It turns out t...
def handler ( signum , stack , self = self , parentpid = os . getpid ( ) ) : if os . getpid ( ) == parentpid : self . job . taskmaster . stop ( ) self . job . interrupted . set ( ) else : os . _exit ( 2 ) self . old_sigint = signal . signal ( signal . SIGINT , handler ) self . old_sigter...
def delete ( self ) : """Delete a registered DOI . If the PID is new then it ' s deleted only locally . Otherwise , also it ' s deleted also remotely . : returns : ` True ` if is deleted successfully ."""
try : if self . pid . is_new ( ) : self . pid . delete ( ) else : self . pid . delete ( ) self . api . metadata_delete ( self . pid . pid_value ) except ( DataCiteError , HttpError ) : logger . exception ( "Failed to delete in DataCite" , extra = dict ( pid = self . pid ) ) raise...
def get_spacy_model ( spacy_model_name : str , pos_tags : bool , parse : bool , ner : bool ) -> SpacyModelType : """In order to avoid loading spacy models a whole bunch of times , we ' ll save references to them , keyed by the options we used to create the spacy model , so any particular configuration only gets...
options = ( spacy_model_name , pos_tags , parse , ner ) if options not in LOADED_SPACY_MODELS : disable = [ 'vectors' , 'textcat' ] if not pos_tags : disable . append ( 'tagger' ) if not parse : disable . append ( 'parser' ) if not ner : disable . append ( 'ner' ) try : ...
def get_import_keychain_path ( cls , keychain_dir , namespace_id ) : """Get the path to the import keychain"""
cached_keychain = os . path . join ( keychain_dir , "{}.keychain" . format ( namespace_id ) ) return cached_keychain
def getMonitorById ( self , monitorId ) : """Returns monitor status and alltimeuptimeratio for a MonitorId ."""
url = self . baseUrl url += "getMonitors?apiKey=%s&monitors=%s" % ( self . apiKey , monitorId ) url += "&noJsonCallback=1&format=json" success , response = self . requestApi ( url ) if success : status = response . get ( 'monitors' ) . get ( 'monitor' ) [ 0 ] . get ( 'status' ) alltimeuptimeratio = response . g...
def backend_query ( self , ** kwargs ) : '''Build and return the : class : ` stdnet . utils . async . BackendQuery ` . This is a lazy method in the sense that it is evaluated once only and its result stored for future retrieval .'''
q = self . construct ( ) return q if isinstance ( q , EmptyQuery ) else q . backend_query ( ** kwargs )
def get_stp_mst_detail_output_last_instance_instance_id ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) get_stp_mst_detail = ET . Element ( "get_stp_mst_detail" ) config = get_stp_mst_detail output = ET . SubElement ( get_stp_mst_detail , "output" ) last_instance = ET . SubElement ( output , "last-instance" ) instance_id = ET . SubElement ( last_instance , "instance-id" ) instance_id . ...
def _create_data_files_directory ( symlink = False ) : """Install data _ files in the / etc directory ."""
current_directory = os . path . abspath ( os . path . dirname ( __file__ ) ) etc_kytos = os . path . join ( BASE_ENV , ETC_KYTOS ) if not os . path . exists ( etc_kytos ) : os . makedirs ( etc_kytos ) src = os . path . join ( current_directory , KYTOS_SKEL_PATH ) dst = os . path . join ( BASE_ENV , KYTOS_SKEL_PATH ...
def vera_request ( self , ** kwargs ) : """Perfom a vera _ request for this device ."""
request_payload = { 'output_format' : 'json' , 'DeviceNum' : self . device_id , } request_payload . update ( kwargs ) return self . vera_controller . data_request ( request_payload )
def save_q_df ( self , state_key , action_key , q_value ) : '''Insert or update Q - Value in ` self . q _ df ` . Args : state _ key : State . action _ key : Action . q _ value : Q - Value . Exceptions : TypeError : If the type of ` q _ value ` is not float .'''
if isinstance ( q_value , float ) is False : raise TypeError ( "The type of q_value must be float." ) new_q_df = pd . DataFrame ( [ ( state_key , action_key , q_value ) ] , columns = [ "state_key" , "action_key" , "q_value" ] ) if self . q_df is not None : self . q_df = pd . concat ( [ new_q_df , self . q_df ] ...
def from_db_value ( self , value , expression , connection , context ) : """" Called in all circumstances when the data is loaded from the database , including in aggregates and values ( ) calls . " """
if value is None : return value return json_decode ( value )
def get_success_url ( self ) : """Returns the URL to redirect the user to upon valid form processing ."""
return '{0}?post={1}#{1}' . format ( reverse ( 'forum_conversation:topic' , kwargs = { 'forum_slug' : self . forum_post . topic . forum . slug , 'forum_pk' : self . forum_post . topic . forum . pk , 'slug' : self . forum_post . topic . slug , 'pk' : self . forum_post . topic . pk , } , ) , self . forum_post . pk , )
def _setDriftList ( self , drift_length ) : """set drift length list of three elements : param drift _ length : input drift _ length in [ m ] , single float , or list / tuple of float numbers"""
if isinstance ( drift_length , tuple ) or isinstance ( drift_length , list ) : if len ( drift_length ) == 1 : self . dflist = drift_length * 3 elif len ( drift_length ) == 2 : self . dflist = [ ] self . dflist . extend ( drift_length ) self . dflist . append ( drift_length [ 0 ] ...
def _scratch_stream_name ( self ) : """A unique cache stream name for this QueryCache . Hashes the necessary facts about this QueryCache to generate a unique cache stream name . Different ` query _ function ` implementations at different ` bucket _ width ` values will be cached to different streams . TODO...
query_details = [ str ( QueryCache . QUERY_CACHE_VERSION ) , str ( self . _bucket_width ) , binascii . b2a_hex ( marshal . dumps ( self . _query_function . func_code ) ) , str ( self . _query_function_args ) , str ( self . _query_function_kwargs ) , ] return hashlib . sha512 ( '$' . join ( query_details ) ) . hexdigest...
def get_routes ( self , viewset ) : """Augment ` self . routes ` with any dynamically generated routes . Returns a list of the Route namedtuple ."""
known_actions = list ( flatten ( [ route . mapping . values ( ) for route in self . routes if isinstance ( route , Route ) ] ) ) # Determine any ` @ detail _ route ` or ` @ list _ route ` decorated methods on the viewset detail_routes = [ ] list_routes = [ ] for methodname in dir ( viewset ) : attr = getattr ( view...
def set_sensor_listener ( self , sensor_name , listener ) : """Set a sensor listener for a sensor even if it is not yet known The listener registration should persist across sensor disconnect / reconnect . sensor _ name : str Name of the sensor listener : callable Listening callable that will be registere...
sensor_name = resource . escape_name ( sensor_name ) sensor_obj = dict . get ( self . _sensor , sensor_name ) self . _sensor_listener_cache [ sensor_name ] . append ( listener ) sensor_dict = { } self . _logger . debug ( 'Cached listener {} for sensor {}' . format ( listener , sensor_name ) ) if sensor_obj : # The sens...
def save_binary ( self , fname , silent = True ) : """Save DMatrix to an XGBoost buffer . Saved binary can be later loaded by providing the path to : py : func : ` xgboost . DMatrix ` as input . Parameters fname : string Name of the output buffer file . silent : bool ( optional ; default : True ) If set...
_check_call ( _LIB . XGDMatrixSaveBinary ( self . handle , c_str ( fname ) , ctypes . c_int ( silent ) ) )
def _load_input_data_port_models ( self ) : """Reloads the input data port models directly from the the state"""
self . input_data_ports = [ ] for input_data_port in self . state . input_data_ports . values ( ) : self . _add_model ( self . input_data_ports , input_data_port , DataPortModel )
def open_writer ( self , reopen = False , endpoint = None , ** kwargs ) : """Open a volume partition to write to . You can use ` open ` method to open a file inside the volume and write to it , or use ` write ` method to write to specific files . : param bool reopen : whether we need to open an existing write s...
tunnel = self . _create_volume_tunnel ( endpoint = endpoint ) upload_id = self . _upload_id if not reopen else None upload_session = tunnel . create_upload_session ( volume = self . volume . name , partition_spec = self . name , upload_id = upload_id , ** kwargs ) file_dict = dict ( ) class FilesWriter ( object ) : ...
def get_request ( self ) : """Generate request from the batched up entries"""
if self . hostname_entry : self . entries . append ( self . hostname_entry ) request = { } for entry in self . entries : sans = sorted ( list ( set ( entry [ 'addresses' ] ) ) ) request [ entry [ 'cn' ] ] = { 'sans' : sans } if self . json_encode : return { 'cert_requests' : json . dumps ( request , sor...
def binary ( self ) : """return encoded representation"""
creation_size = len ( self . creation ) if creation_size == 1 : return ( b_chr ( _TAG_PORT_EXT ) + self . node . binary ( ) + self . id + self . creation ) elif creation_size == 4 : return ( b_chr ( _TAG_NEW_PORT_EXT ) + self . node . binary ( ) + self . id + self . creation ) else : raise OutputException (...
def handle_tsg_results ( permutation_result ) : """Handles result from TSG results . Takes in output from multiprocess _ permutation function and converts to a better formatted dataframe . Parameters permutation _ result : list output from multiprocess _ permutation Returns permutation _ df : pd . Dat...
permutation_df = pd . DataFrame ( sorted ( permutation_result , key = lambda x : x [ 2 ] if x [ 2 ] is not None else 1.1 ) , columns = [ 'gene' , 'inactivating count' , 'inactivating p-value' , 'Total SNV Mutations' , 'SNVs Unmapped to Ref Tx' ] ) permutation_df [ 'inactivating p-value' ] = permutation_df [ 'inactivati...
def summary ( self , name = None ) : """Return a summarized representation . . . deprecated : : 0.23.0"""
warnings . warn ( "'summary' is deprecated and will be removed in a " "future version." , FutureWarning , stacklevel = 2 ) return self . _summary ( name )
def _next_radiotap_extpm ( pkt , lst , cur , s ) : """Generates the next RadioTapExtendedPresenceMask"""
if cur is None or ( cur . present and cur . present . Ext ) : st = len ( lst ) + ( cur is not None ) return lambda * args : RadioTapExtendedPresenceMask ( * args , index = st ) return None
def pressure ( self ) : """The current pressure being applied on the tool in use , normalized to the range [ 0 , 1 ] and whether it has changed in this event . If this axis does not exist on the current tool , this property is (0 , : obj : ` False ` ) . Returns : ( float , bool ) : The current value of th...
pressure = self . _libinput . libinput_event_tablet_tool_get_pressure ( self . _handle ) changed = self . _libinput . libinput_event_tablet_tool_pressure_has_changed ( self . _handle ) return pressure , changed
def establish_connection ( self , width = None , height = None ) : """Establish SSH connection to the network device Timeout will generate a NetMikoTimeoutException Authentication failure will generate a NetMikoAuthenticationException width and height are needed for Fortinet paging setting . : param width :...
if self . protocol == "telnet" : self . remote_conn = telnetlib . Telnet ( self . host , port = self . port , timeout = self . timeout ) self . telnet_login ( ) elif self . protocol == "serial" : self . remote_conn = serial . Serial ( ** self . serial_settings ) self . serial_login ( ) elif self . proto...
def _remove_creds ( creds_file = None ) : """Remove ~ / . onecodex file , returning True if successul or False if the file didn ' t exist"""
if creds_file is None : creds_file = os . path . expanduser ( "~/.onecodex" ) try : os . remove ( creds_file ) except Exception as e : if e . errno == errno . ENOENT : return False elif e . errno == errno . EACCES : click . echo ( "Please check the permissions on {}" . format ( collapse_...
def target_group_exists ( name , region = None , key = None , keyid = None , profile = None ) : '''Check to see if an target group exists . CLI example : . . code - block : : bash salt myminion boto _ elbv2 . target _ group _ exists arn : aws : elasticloadbalancing : us - west - 2:644138682826 : targetgroup /...
conn = _get_conn ( region = region , key = key , keyid = keyid , profile = profile ) try : if name . startswith ( 'arn:aws:elasticloadbalancing' ) : alb = conn . describe_target_groups ( TargetGroupArns = [ name ] ) else : alb = conn . describe_target_groups ( Names = [ name ] ) if alb : ...
def dump ( state , host , remote_filename , database = None , # Details for speaking to PostgreSQL via ` psql ` CLI postgresql_user = None , postgresql_password = None , postgresql_host = None , postgresql_port = None , ) : '''Dump a PostgreSQL database into a ` ` . sql ` ` file . Requires ` ` mysqldump ` ` . + d...
yield '{0} > {1}' . format ( make_psql_command ( executable = 'pg_dump' , database = database , user = postgresql_user , password = postgresql_password , host = postgresql_host , port = postgresql_port , ) , remote_filename )
def append ( self , item ) : """Add the given item as children"""
if self . url : raise TypeError ( 'Menu items with URL cannot have childrens' ) # Look for already present common node if not item . is_leaf ( ) : for current_item in self . items : if item . name == current_item . name : for children in item . items : current_item . append (...
def _calc_checksum ( values ) : """Calculate the symbol check character ."""
checksum = values [ 0 ] for index , value in enumerate ( values ) : checksum += index * value return checksum % 103
def get_variables ( ) : """Send a dictionary of variables associated with the selected run . Usage description : This function is usually called to get and display the list of runs associated with a selected project available in the database for the user to view . : return : JSON , { < int _ keys > : < run ...
assert request . method == "POST" , "POST request expected received {}" . format ( request . method ) if request . method == "POST" : try : selected_run = request . form [ "selected_run" ] variables = utils . get_variables ( selected_run ) # Reset current _ index when you select a new run ...
def getCandScoresMapBruteForce ( self , profile ) : """Returns a dictonary that associates the integer representation of each candidate with the bayesian losses that we calculate using brute force . : ivar Profile profile : A Profile object that represents an election profile ."""
wmg = profile . getWmg ( True ) m = len ( wmg . keys ( ) ) cands = range ( m ) V = self . createBinaryRelation ( m ) gains = dict ( ) for cand in wmg . keys ( ) : gains [ cand ] = 0 graphs = itertools . product ( range ( 2 ) , repeat = m * ( m - 1 ) / 2 ) for comb in graphs : prob = 1 i = 0 for a , b in...
def df ( self , list_of_points , force_read = True ) : """When connected , calling DF should force a reading on the network ."""
his = [ ] for point in list_of_points : try : his . append ( self . _findPoint ( point , force_read = force_read ) . history ) except ValueError as ve : self . _log . error ( "{}" . format ( ve ) ) continue if not _PANDAS : return dict ( zip ( list_of_points , his ) ) return pd . Dat...
def get_stats_summary ( start = None , end = None , ** kwargs ) : """Stats Historical Summary Reference : https : / / iexcloud . io / docs / api / # stats - historical - summary Data Weighting : ` ` Free ` ` Parameters start : datetime . datetime , default None , optional Start of data retrieval period ...
return MonthlySummaryReader ( start = start , end = end , ** kwargs ) . fetch ( )
def decompose ( P ) : """Decompose a polynomial to component form . In array missing values are padded with 0 to make decomposition compatible with ` ` chaospy . sum ( Q , 0 ) ` ` . Args : P ( Poly ) : Input data . Returns : ( Poly ) : Decomposed polynomial with ` P . shape = = ( M , ) + Q . shape ` whe...
P = P . copy ( ) if not P : return P out = [ Poly ( { key : P . A [ key ] } ) for key in P . keys ] return Poly ( out , None , None , None )