signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def MGMT_COMM_SET ( self , Addr = 'ff02::1' , xCommissionerSessionID = None , xSteeringData = None , xBorderRouterLocator = None , xChannelTlv = None , ExceedMaxPayload = False ) : """send MGMT _ COMM _ SET command Returns : True : successful to send MGMT _ COMM _ SET False : fail to send MGMT _ COMM _ SET"""
print '%s call MGMT_COMM_SET' % self . port try : cmd = 'commissioner mgmtset' if xCommissionerSessionID != None : # use assigned session id cmd += ' sessionid ' cmd += str ( xCommissionerSessionID ) elif xCommissionerSessionID is None : # use original session id if self . isActiveCo...
def _shell_to_ini ( shell_file_contents : List [ str ] ) -> List [ str ] : """Converts a shell file , which just contains comments and " export * " statements into an ini file . : param shell _ file _ contents : the contents of the shell file : return : lines of an equivalent ini file"""
line_number = 0 while line_number < len ( shell_file_contents ) : line = shell_file_contents [ line_number ] . strip ( ) if "=" not in line : del shell_file_contents [ line_number ] else : if line . strip ( ) . startswith ( _EXPORT_COMMAND ) : shell_file_contents [ line_number ] ...
def _get_edges ( self ) : """Get the edges for the current surface . If they haven ' t been computed yet , first compute and store them . This is provided as a means for internal calls to get the edges without copying ( since : attr : ` . edges ` copies before giving to a user to keep the stored data immuta...
if self . _edges is None : self . _edges = self . _compute_edges ( ) return self . _edges
def offset ( img , offset , fill_value = 0 ) : """Moves the contents of image without changing the image size . The missing values are given a specified fill value . Parameters img : array Image . offset : ( vertical _ offset , horizontal _ offset ) Tuple of length 2 , specifying the offset along the tw...
sh = img . shape if sh == ( 0 , 0 ) : return img else : x = np . empty ( sh ) x [ : ] = fill_value x [ max ( offset [ 0 ] , 0 ) : min ( sh [ 0 ] + offset [ 0 ] , sh [ 0 ] ) , max ( offset [ 1 ] , 0 ) : min ( sh [ 1 ] + offset [ 1 ] , sh [ 1 ] ) ] = img [ max ( - offset [ 0 ] , 0 ) : min ( sh [ 0 ] - off...
def clear ( self ) : """clears all child changes and drops the reference to them"""
super ( SuperChange , self ) . clear ( ) for c in self . changes : c . clear ( ) self . changes = tuple ( )
def get_newest_possible_languagetool_version ( ) : """Return newest compatible version . > > > version = get _ newest _ possible _ languagetool _ version ( ) > > > version in [ JAVA _ 6 _ COMPATIBLE _ VERSION , LATEST _ VERSION ] True"""
java_path = find_executable ( 'java' ) if not java_path : # Just ignore this and assume an old version of Java . It might not be # found because of a PATHEXT - related issue # ( https : / / bugs . python . org / issue2200 ) . return JAVA_6_COMPATIBLE_VERSION output = subprocess . check_output ( [ java_path , '-vers...
def setPalette ( self , palette ) : """Sets the palette for this button to the inputed palette . This will update the drop shadow to the palette ' s Shadow color property if the shadowed mode is on . : param palette | < QtGui . QPalette >"""
super ( XToolButton , self ) . setPalette ( palette ) self . updateUi ( )
def get_area_extent ( self , size , offsets , factors , platform_height ) : """Get the area extent of the file . Until December 2017 , the data is shifted by 1.5km SSP North and West against the nominal GEOS projection . Since December 2017 this offset has been corrected . A flag in the data indicates if the co...
nlines , ncols = size h = platform_height loff , coff = offsets loff -= nlines offsets = loff , coff # count starts at 1 cols = 1 - 0.5 lines = 0.5 - 1 ll_x , ll_y = self . get_xy_from_linecol ( - lines , cols , offsets , factors ) cols += ncols lines += nlines ur_x , ur_y = self . get_xy_from_linecol ( - lines , cols ...
def xmoe_tr_1d ( ) : """Mixture of experts ( 16 experts ) . 623M Params , einsum = 1.09e13 Returns : a hparams"""
hparams = xmoe_tr_dense_2k ( ) hparams . encoder_layers = [ "self_att" , "moe_1d" ] * 4 hparams . decoder_layers = [ "self_att" , "enc_att" , "moe_1d" ] * 4 hparams . layout = "batch:batch;experts:batch" hparams . moe_hidden_size = 2048 hparams . moe_num_experts = 16 return hparams
def put_file_range ( ase , offsets , data , timeout = None ) : # type : ( blobxfer . models . azure . StorageEntity , # blobxfer . models . upload . Offsets , bytes , int ) - > None """Puts a range of bytes into the remote file : param blobxfer . models . azure . StorageEntity ase : Azure StorageEntity : param ...
dir , fpath , _ = parse_file_path ( ase . name ) ase . client . update_range ( share_name = ase . container , directory_name = dir , file_name = fpath , data = data , start_range = offsets . range_start , end_range = offsets . range_end , validate_content = False , # integrity is enforced with HTTPS timeout = timeout )
def CheckSchema ( self , database ) : """Checks the schema of a database with that defined in the plugin . Args : database ( SQLiteDatabase ) : database . Returns : bool : True if the schema of the database matches that defined by the plugin , or False if the schemas do not match or no schema is defined...
schema_match = False if self . SCHEMAS : for schema in self . SCHEMAS : if database and database . schema == schema : schema_match = True return schema_match
def do_add ( argdict ) : '''Add a new page to the site .'''
site = make_site_obj ( argdict ) if not site . tree_ready : print "Cannot add page. You are not within a simplystatic \ tree and you didn't specify a directory." sys . exit ( ) title = argdict [ 'title' ] try : new_page = site . add_page ( title ) new_page . write ( ) print "Added page '" + title + ...
def install_traversals ( cls , node_set ) : """For a StructuredNode class install Traversal objects for each relationship definition on a NodeSet instance"""
rels = cls . defined_properties ( rels = True , aliases = False , properties = False ) for key , value in rels . items ( ) : if hasattr ( node_set , key ) : raise ValueError ( "Can't install traversal '{0}' exists on NodeSet" . format ( key ) ) rel = getattr ( cls , key ) rel . _lookup_node_class ( ...
def connect ( uri , factory = pymongo . MongoClient ) : """Use the factory to establish a connection to uri ."""
warnings . warn ( "do not use. Just call MongoClient directly." , DeprecationWarning ) return factory ( uri )
def getcols ( sheetMatch = None , colMatch = "Decay" ) : """find every column in every sheet and put it in a new sheet or book ."""
book = BOOK ( ) if sheetMatch is None : matchingSheets = book . sheetNames print ( 'all %d sheets selected ' % ( len ( matchingSheets ) ) ) else : matchingSheets = [ x for x in book . sheetNames if sheetMatch in x ] print ( '%d of %d sheets selected matching "%s"' % ( len ( matchingSheets ) , len ( book...
def remove_data_point ( self , x , y ) : """Removes the given data point from the series . : param x : The numerical x value of the data point to be removed . : param y : The numerical y value of the data point to be removed . : raises ValueError : if you try to remove the last data point from a series ."""
if len ( self . _data ) == 1 : raise ValueError ( "You cannot remove a Series' last data point" ) self . _data . remove ( ( x , y ) )
def _handle_docstrings ( self ) : """Searches through the lines affected by this operation to find blocks of adjacent docstrings to parse for the current element ."""
# Docstrings have to be continuous sets of lines that start with ! ! # When they change in any way ( i . e . any of the three modes ) , we # have to reparse the entire block because it has XML dependencies # Because of that , the cached version of the docstrings is actually # pointless and we only need to focus on the ...
def _consolidate_classpath ( self , targets , classpath_products ) : """Convert loose directories in classpath _ products into jars ."""
# TODO : find a way to not process classpath entries for valid VTs . # NB : It is very expensive to call to get entries for each target one at a time . # For performance reasons we look them all up at once . entries_map = defaultdict ( list ) for ( cp , target ) in classpath_products . get_product_target_mappings_for_t...
def attach_volume ( self , volume , device = "/dev/sdp" ) : """Attach an EBS volume to this server : param volume : EBS Volume to attach : type volume : boto . ec2 . volume . Volume : param device : Device to attach to ( default to / dev / sdp ) : type device : string"""
if hasattr ( volume , "id" ) : volume_id = volume . id else : volume_id = volume return self . ec2 . attach_volume ( volume_id = volume_id , instance_id = self . instance_id , device = device )
def destroy ( name , call = None , kwargs = None ) : # pylint : disable = unused - argument '''Destroy a VM . CLI Examples : . . code - block : : bash salt - cloud - d myminion salt - cloud - a destroy myminion service _ name = myservice'''
if kwargs is None : kwargs = { } if call == 'function' : raise SaltCloudSystemExit ( 'The destroy action must be called with -d, --destroy, ' '-a or --action.' ) compconn = get_conn ( client_type = 'compute' ) node_data = show_instance ( name , call = 'action' ) if node_data [ 'storage_profile' ] [ 'os_disk' ] ...
def map ( self , callable ) : """Apply ' callable ' function over all values ."""
for k , v in self . iteritems ( ) : self [ k ] = callable ( v )
def build ( cls , local_scheduler = True , ** task_params ) : """Instantiate the task and build it with luigi Args : local _ scheduler ( bool ) : use a local scheduler ( True , default ) or a remote scheduler task _ params : parameters to pass to task for instantiation"""
luigi . build ( [ cls ( ** task_params ) ] , local_scheduler = local_scheduler )
def readTempC ( self ) : """Read sensor and return its value in degrees celsius ."""
# Read temperature register value . t = self . _device . readU16BE ( MCP9808_REG_AMBIENT_TEMP ) self . _logger . debug ( 'Raw ambient temp register value: 0x{0:04X}' . format ( t & 0xFFFF ) ) # Scale and convert to signed value . temp = ( t & 0x0FFF ) / 16.0 if t & 0x1000 : temp -= 256.0 return temp
def GetCheckButtonSelect ( selectList , title = "Select" , msg = "" ) : """Get selected check button options title : Window name mag : Label of the check button return selected dictionary { ' sample b ' : False , ' sample c ' : False , ' sample a ' : False }"""
root = tkinter . Tk ( ) root . title ( title ) label = tkinter . Label ( root , text = msg ) label . pack ( ) optList = [ ] for item in selectList : opt = tkinter . BooleanVar ( ) opt . set ( False ) tkinter . Checkbutton ( root , text = item , variable = opt ) . pack ( ) optList . append ( opt ) tkinte...
def _gen_records ( self , record , zone_id , creating = False ) : '''Turns an octodns . Record into one or more ` _ Route53 * ` s'''
return _Route53Record . new ( self , record , zone_id , creating )
def get ( self , name , default = None ) : '''Retrieves the object with " name " , like with SessionManager . get ( ) , but removes the object from the database after retrieval , so that it can be retrieved only once'''
session_object = super ( NotificationManager , self ) . get ( name , default ) if session_object is not None : self . delete ( name ) return session_object
def close_tab ( self , * args ) : """Closes the current tab ."""
prompt_cfg = self . settings . general . get_int ( 'prompt-on-close-tab' ) self . get_notebook ( ) . delete_page_current ( prompt = prompt_cfg )
def setMaximum ( self , value ) : """Sets the maximum value for this slider - this will also adjust the minimum size value to match the width of the icons by the number for the maximu . : param value | < int >"""
super ( XRatingSlider , self ) . setMaximum ( value ) self . adjustMinimumWidth ( )
def _next_merge ( merge_node ) : """Gets a node that has only leaf nodes below it . This table and the ones below are ready to be merged to make a new leaf node ."""
if all ( _is_leaf_node ( d ) for d in _dict_value_to_pairs ( merge_node ) ) : return merge_node else : for d in tz . remove ( _is_leaf_node , _dict_value_to_pairs ( merge_node ) ) : return _next_merge ( d ) else : raise OrcaError ( 'No node found for next merge.' )
def uninstall_hook ( ctx ) : """Uninstall gitlint commit - msg hook ."""
try : lint_config = ctx . obj [ 0 ] hooks . GitHookInstaller . uninstall_commit_msg_hook ( lint_config ) # declare victory : - ) hook_path = hooks . GitHookInstaller . commit_msg_hook_path ( lint_config ) click . echo ( u"Successfully uninstalled gitlint commit-msg hook from {0}" . format ( hook_pat...
def report_all_label ( self ) : """Return the best label of the asked entry . Parameters Returns labels : list of object , shape = ( m ) The best label of all samples ."""
labels = np . empty ( len ( self . dataset ) , dtype = int ) for pruning in self . prunings : best_label = self . _best_label ( pruning ) leaves = self . _find_leaves ( pruning ) labels [ leaves ] = best_label return labels
def _find_closing_token ( self , tag , tokens , pos ) : """Given the current tag options , a list of tokens , and the current position in the token list , this function will find the position of the closing token associated with the specified tag . This may be a closing tag , a newline , or simply the end of ...
embed_count = 0 block_count = 0 lt = len ( tokens ) while pos < lt : token_type , tag_name , tag_opts , token_text = tokens [ pos ] if token_type == self . TOKEN_DATA : # Short - circuit for performance . pos += 1 continue if tag . newline_closes and token_type in ( self . TOKEN_TAG_START , ...
def _objectdata_cache_key ( func , obj ) : """Cache Key for object data"""
uid = api . get_uid ( obj ) modified = api . get_modification_date ( obj ) . millis ( ) review_state = api . get_review_status ( obj ) return "{}-{}-{}" . format ( uid , review_state , modified )
def emit_node ( self , node ) : """Emit a single node ."""
emit = getattr ( self , "%s_emit" % node . kind , self . default_emit ) return emit ( node )
def get_full_command_record ( self , command_history_id , merge_session_environ = True ) : """Get fully retrieved : class : ` CommandRecord ` instance by ID . By " fully " , it means that complex slots such as ` environ ` and ` pipestatus ` are available . : type command _ history _ id : int : type merge _ ...
with self . connection ( ) as db : crec = self . _select_command_record ( db , command_history_id ) crec . pipestatus = self . _get_pipestatus ( db , command_history_id ) # Set environment variables cenv = self . _select_environ ( db , 'command' , command_history_id ) crec . environ . update ( cenv ...
def GetMessages ( self , formatter_mediator , event ) : """Determines the formatted message strings for an event object . Args : formatter _ mediator ( FormatterMediator ) : mediates the interactions between formatters and other components , such as storage and Windows EventLog resources . event ( EventOb...
if self . DATA_TYPE != event . data_type : raise errors . WrongFormatter ( 'Unsupported data type: {0:s}.' . format ( event . data_type ) ) event_values = event . CopyToDict ( ) file_entry_type = event_values . get ( 'file_entry_type' , None ) if file_entry_type is not None : event_values [ 'file_entry_type' ] ...
def _generate_password ( ) : """Create a random password The password is made by taking a uuid and passing it though sha1sum . We may change this in future to gain more entropy . This is based on the tripleo command os - make - password"""
uuid_str = six . text_type ( uuid . uuid4 ( ) ) . encode ( "UTF-8" ) return hashlib . sha1 ( uuid_str ) . hexdigest ( )
def save ( self , * args , ** kwargs ) : """Override save ( ) method to make sure that standard _ name and systematic _ name won ' t be null or empty , or consist of only space characters ( such as space , tab , new line , etc ) ."""
empty_std_name = False if not self . standard_name or self . standard_name . isspace ( ) : empty_std_name = True empty_sys_name = False if not self . systematic_name or self . systematic_name . isspace ( ) : empty_sys_name = True if empty_std_name and empty_sys_name : raise ValueError ( "Both standard_name ...
def tail ( self , n = 10 ) : """Get an SArray that contains the last n elements in the SArray . Parameters n : int The number of elements to fetch Returns out : SArray A new SArray which contains the last n rows of the current SArray ."""
with cython_context ( ) : return SArray ( _proxy = self . __proxy__ . tail ( n ) )
def add_child ( self , child ) : """Adds self as parent to child , and then adds child ."""
child . parent = self self . children . append ( child ) return child
def to_utc ( self , dt ) : """Convert any timestamp to UTC ( with tzinfo ) ."""
if dt . tzinfo is None : return dt . replace ( tzinfo = self . utc ) return dt . astimezone ( self . utc )
def _update_tcs_helper_catalogue_tables_info_with_new_tables ( self ) : """update tcs helper catalogue tables info with new tables . . todo : : - update key arguments values and definitions with defaults - update return values and definitions - update usage examples and text - update docstring text - ch...
self . log . debug ( 'starting the ``_update_tcs_helper_catalogue_tables_info_with_new_tables`` method' ) sqlQuery = u""" SELECT max(id) as thisId FROM tcs_helper_catalogue_tables_info; """ % locals ( ) thisId = readquery ( log = self . log , sqlQuery = sqlQuery , dbConn = self . cataloguesDbConn , ...
def on_natural_language ( keywords : Union [ Optional [ Iterable ] , Callable ] = None , * , permission : int = perm . EVERYBODY , only_to_me : bool = True , only_short_message : bool = True , allow_empty_message : bool = False ) -> Callable : """Decorator to register a function as a natural language processor . ...
def deco ( func : Callable ) -> Callable : nl_processor = NLProcessor ( func = func , keywords = keywords , permission = permission , only_to_me = only_to_me , only_short_message = only_short_message , allow_empty_message = allow_empty_message ) _nl_processors . add ( nl_processor ) return func if isinstanc...
def getfieldidd_item ( bch , fieldname , iddkey ) : """return an item from the fieldidd , given the iddkey will return and empty list if it does not have the iddkey or if the fieldname does not exist"""
fieldidd = getfieldidd ( bch , fieldname ) try : return fieldidd [ iddkey ] except KeyError as e : return [ ]
def refresh_address_presence ( self , address ) : """Update synthesized address presence state from cached user presence states . Triggers callback ( if any ) in case the state has changed . This method is only provided to cover an edge case in our use of the Matrix protocol and should * * not * * generally b...
composite_presence = { self . _fetch_user_presence ( uid ) for uid in self . _address_to_userids [ address ] } # Iterate over UserPresence in definition order ( most to least online ) and pick # first matching state new_presence = UserPresence . UNKNOWN for presence in UserPresence . __members__ . values ( ) : if p...
def metrics ( self , queue_type = None , queue_id = None ) : """Provides a way to get statistics about various parameters like , * global enqueue / dequeue rates per min . * per queue enqueue / dequeue rates per min . * queue length of each queue . * list of queue ids for each queue type ."""
if queue_id is not None and not is_valid_identifier ( queue_id ) : raise BadArgumentException ( '`queue_id` has an invalid value.' ) if queue_type is not None and not is_valid_identifier ( queue_type ) : raise BadArgumentException ( '`queue_type` has an invalid value.' ) response = { 'status' : 'failure' } if n...
def enrollment_search_by_regid ( regid , verbose = 'true' , transcriptable_course = 'all' , changed_since_date = '' , include_unfinished_pce_course_reg = True ) : """: return : a dictionary of { Term : Enrollment }"""
return _json_to_term_enrollment_dict ( _enrollment_search ( regid , verbose , transcriptable_course , changed_since_date ) , include_unfinished_pce_course_reg )
def _sentence_to_features ( self , sentence : list ) : # type : ( List [ Tuple [ Text , Text , Text , Text ] ] ) - > List [ Dict [ Text , Any ] ] """Convert a word into discrete features in self . crf _ features , including word before and word after ."""
sentence_features = [ ] prefixes = ( '-1' , '0' , '+1' ) for word_idx in range ( len ( sentence ) ) : # word before ( - 1 ) , current word ( 0 ) , next word ( + 1) word_features = { } for i in range ( 3 ) : if word_idx == len ( sentence ) - 1 and i == 2 : word_features [ 'EOS' ] = True ...
def update_rows ( server_context , schema_name , query_name , rows , container_path = None , timeout = _default_timeout ) : """Update a set of rows : param server _ context : A LabKey server context . See utils . create _ server _ context . : param schema _ name : schema of table : param query _ name : table ...
url = server_context . build_url ( 'query' , 'updateRows.api' , container_path = container_path ) payload = { 'schemaName' : schema_name , 'queryName' : query_name , 'rows' : rows } return server_context . make_request ( url , json_dumps ( payload , sort_keys = True ) , headers = _query_headers , timeout = timeout )
def apply_network_profile ( name , network_profile , nic_opts = None , path = None ) : '''. . versionadded : : 2015.5.0 Apply a network profile to a container network _ profile profile name or default values ( dict ) nic _ opts values to override in defaults ( dict ) indexed by nic card names path p...
cpath = get_root_path ( path ) cfgpath = os . path . join ( cpath , name , 'config' ) before = [ ] with salt . utils . files . fopen ( cfgpath , 'r' ) as fp_ : for line in fp_ : before . append ( line ) lxcconfig = _LXCConfig ( name = name , path = path ) old_net = lxcconfig . _filter_data ( 'lxc.network' )...
def originalTextFor ( expr , asString = True ) : """Helper to return the original , untokenized text for a given expression . Useful to restore the parsed fields of an HTML start tag into the raw tag text itself , or to revert separate tokens with intervening whitespace back to the original matching input tex...
locMarker = Empty ( ) . setParseAction ( lambda s , loc , t : loc ) endlocMarker = locMarker . copy ( ) endlocMarker . callPreparse = False matchExpr = locMarker ( "_original_start" ) + expr + endlocMarker ( "_original_end" ) if asString : extractText = lambda s , l , t : s [ t . _original_start : t . _original_end...
def decode ( self , value , force = False ) : "Return a unicode string from the byte representation"
if ( self . decode_responses or force ) and isinstance ( value , bytes ) : value = value . decode ( self . encoding , self . encoding_errors ) return value
def dict_of_sets_add ( dictionary , key , value ) : # type : ( DictUpperBound , Any , Any ) - > None """Add value to a set in a dictionary by key Args : dictionary ( DictUpperBound ) : Dictionary to which to add values key ( Any ) : Key within dictionary value ( Any ) : Value to add to set in dictionary R...
set_objs = dictionary . get ( key , set ( ) ) set_objs . add ( value ) dictionary [ key ] = set_objs
def setup_prefix_suffix ( self ) : """Set up the compile prefix , sourcepath and the targetpath suffix attributes , which are the prefix to the function name and the suffixes to retrieve the values from for creating the generator function ."""
self . compile_prefix = 'compile_' self . sourcepath_suffix = '_sourcepath' self . modpath_suffix = '_modpaths' self . targetpath_suffix = '_targetpaths'
def hugepage_support ( user , group = 'hugetlb' , nr_hugepages = 256 , max_map_count = 65536 , mnt_point = '/run/hugepages/kvm' , pagesize = '2MB' , mount = True , set_shmmax = False ) : """Enable hugepages on system . Args : user ( str ) - - Username to allow access to hugepages to group ( str ) - - Group na...
group_info = add_group ( group ) gid = group_info . gr_gid add_user_to_group ( user , group ) if max_map_count < 2 * nr_hugepages : max_map_count = 2 * nr_hugepages sysctl_settings = { 'vm.nr_hugepages' : nr_hugepages , 'vm.max_map_count' : max_map_count , 'vm.hugetlb_shm_group' : gid , } if set_shmmax : shmmax...
def ls ( self ) : """Return a list of * all * files & dirs in the repo . Think of this as a recursive ` ls ` command from the root of the repo ."""
tree = self . ls_tree ( ) return [ t . get ( 'file' ) for t in tree if t . get ( 'file' ) ]
def _Plot_CrossProj_Ves ( V , ax = None , Elt = 'PIBsBvV' , Pdict = _def . TorPd , Idict = _def . TorId , Bsdict = _def . TorBsd , Bvdict = _def . TorBvd , Vdict = _def . TorVind , LegDict = _def . TorLegd , indices = False , draw = True , fs = None , wintit = _wintit , Test = True ) : """Plot the poloidal projecti...
if Test : ax , C0 , C1 , C2 = _check_Lax ( ax , n = 1 ) assert type ( Pdict ) is dict , 'Arg Pdict should be a dictionary !' assert type ( Idict ) is dict , "Arg Idict should be a dictionary !" assert type ( Bsdict ) is dict , "Arg Bsdict should be a dictionary !" assert type ( Bvdict ) is dict , "A...
def runcode ( self , code ) : """Execute a code object . When an exception occurs , self . showtraceback ( ) is called to display a traceback . All exceptions are caught except SystemExit , which is reraised . A note about KeyboardInterrupt : this exception may occur elsewhere in this code , and may not a...
try : exec code in self . locals except SystemExit : raise except : self . showtraceback ( ) else : if softspace ( sys . stdout , 0 ) : sys . stdout . write ( '\n' )
def _listen_for_dweets_from_response ( response ) : """Yields dweets as received from dweet . io ' s streaming API"""
streambuffer = '' for byte in response . iter_content ( ) : if byte : streambuffer += byte . decode ( 'ascii' ) try : dweet = json . loads ( streambuffer . splitlines ( ) [ 1 ] ) except ( IndexError , ValueError ) : continue if isstr ( dweet ) : yi...
def _leaf_list_stmt ( self , stmt : Statement , sctx : SchemaContext ) -> None : """Handle leaf - list statement ."""
node = LeafListNode ( ) node . type = DataType . _resolve_type ( stmt . find1 ( "type" , required = True ) , sctx ) self . _handle_child ( node , stmt , sctx )
def calc_max_min ( ss ) : """" Calculates ( x , y ) ( max , min ) for a list of Spectrum objects . Returns ( xmin , xmax , ymin , ymax , xspan , yspan )"""
xmin , xmax , ymin , ymax = 1e38 , - 1e38 , 1e38 , - 1e38 for s in ss : assert isinstance ( s , ft . Spectrum ) if len ( s . x ) > 0 : xmin , xmax = min ( min ( s . x ) , xmin ) , max ( max ( s . x ) , xmax ) ymin , ymax = min ( min ( s . y ) , ymin ) , max ( max ( s . y ) , ymax ) xspan = xmax ...
def _run_cmd ( self , command ) : """Run a DQL command"""
if self . throttle : tables = self . engine . describe_all ( False ) limiter = self . throttle . get_limiter ( tables ) else : limiter = None self . engine . rate_limit = limiter results = self . engine . execute ( command ) if results is None : pass elif isinstance ( results , basestring ) : print ...
def asa_scp_handler ( ssh_conn , cmd = "ssh scopy enable" , mode = "enable" ) : """Enable / disable SCP on Cisco ASA ."""
if mode == "disable" : cmd = "no " + cmd return ssh_conn . send_config_set ( [ cmd ] )
def fetch_object ( self , obj_name , include_meta = False , chunk_size = None ) : """Alias for self . fetch ( ) ; included for backwards compatibility"""
return self . fetch ( obj = obj_name , include_meta = include_meta , chunk_size = chunk_size )
def close ( self ) : """Close the canvas Notes This will usually destroy the GL context . For Qt , the context ( and widget ) will be destroyed only if the widget is top - level . To avoid having the widget destroyed ( more like standard Qt behavior ) , consider making the widget a sub - widget ."""
if self . _backend is not None and not self . _closed : self . _closed = True self . events . close ( ) self . _backend . _vispy_close ( ) forget_canvas ( self )
def env ( self ) : """Env vars for kernels"""
# Add our PYTHONPATH to the kernel pathlist = CONF . get ( 'main' , 'spyder_pythonpath' , default = [ ] ) default_interpreter = CONF . get ( 'main_interpreter' , 'default' ) pypath = add_pathlist_to_PYTHONPATH ( [ ] , pathlist , ipyconsole = True , drop_env = False ) # Environment variables that we need to pass to our ...
def load ( cls , path , reader = None ) : """Loads the corpus from the given path , using the given reader . If no reader is given the : py : class : ` audiomate . corpus . io . DefaultReader ` is used . Args : path ( str ) : Path to load the corpus from . reader ( str , CorpusReader ) : The reader or the n...
if reader is None : from . import io reader = io . DefaultReader ( ) elif type ( reader ) == str : from . import io reader = io . create_reader_of_type ( reader ) return reader . load ( path )
def _FixedSizer ( value_size ) : """Like _ SimpleSizer except for a fixed - size field . The input is the size of one value ."""
def SpecificSizer ( field_number , is_repeated , is_packed ) : tag_size = _TagSize ( field_number ) if is_packed : local_VarintSize = _VarintSize def PackedFieldSize ( value ) : result = len ( value ) * value_size return result + local_VarintSize ( result ) + tag_size ...
def get_terminal_size ( fallback = ( 80 , 24 ) ) : """Get the size of the terminal window . For each of the two dimensions , the environment variable , COLUMNS and LINES respectively , is checked . If the variable is defined and the value is a positive integer , it is used . When COLUMNS or LINES is not def...
# Try the environment first try : columns = int ( os . environ [ "COLUMNS" ] ) except ( KeyError , ValueError ) : columns = 0 try : lines = int ( os . environ [ "LINES" ] ) except ( KeyError , ValueError ) : lines = 0 # Only query if necessary if columns <= 0 or lines <= 0 : try : size = _ge...
def get ( self , uid : int ) -> FrozenSet [ Flag ] : """Return the session flags for the mailbox session . Args : uid : The message UID value ."""
recent = _recent_set if uid in self . _recent else frozenset ( ) flags = self . _flags . get ( uid ) return recent if flags is None else ( flags | recent )
def authorize ( self , email , permission_type = 'read' , cloud = None , api_key = None , version = None , ** kwargs ) : """This API endpoint allows you to authorize another user to access your model in a read or write capacity . Before calling authorize , you must first make sure your model has been registered ....
kwargs [ 'permission_type' ] = permission_type kwargs [ 'email' ] = email url_params = { "batch" : False , "api_key" : api_key , "version" : version , "method" : "authorize" } return self . _api_handler ( None , cloud = cloud , api = "custom" , url_params = url_params , ** kwargs )
def _leave_event_hide ( self ) : """Hides the tooltip after some time has passed ( assuming the cursor is not over the tooltip ) ."""
if ( self . hide_timer_on and not self . _hide_timer . isActive ( ) and # If Enter events always came after Leave events , we wouldn ' t need # this check . But on Mac OS , it sometimes happens the other way # around when the tooltip is created . self . app . topLevelAt ( QCursor . pos ( ) ) != self ) : self . _hid...
def convert ( self , value , fromunits , tounits ) : '''convert a value from one set of units to another'''
if fromunits == tounits : return value if ( fromunits , tounits ) in self . unitmap : return value * self . unitmap [ ( fromunits , tounits ) ] if ( tounits , fromunits ) in self . unitmap : return value / self . unitmap [ ( tounits , fromunits ) ] raise fgFDMError ( "unknown unit mapping (%s,%s)" % ( fromu...
def get_expected_bindings ( self ) : """Query the neutron DB for SG - > switch interface bindings Bindings are returned as a dict of bindings for each switch : { < switch1 > : set ( [ ( intf1 , acl _ name , direction ) , ( intf2 , acl _ name , direction ) ] ) , < switch2 > : set ( [ ( intf1 , acl _ name , d...
sg_bindings = db_lib . get_baremetal_sg_bindings ( ) all_expected_bindings = collections . defaultdict ( set ) for sg_binding , port_binding in sg_bindings : sg_id = sg_binding [ 'security_group_id' ] try : binding_profile = json . loads ( port_binding . profile ) except ValueError : binding...
def get_index_range ( working_dir ) : """Get the bitcoin block index range . Mask connection failures with timeouts . Always try to reconnect . The last block will be the last block to search for names . This will be NUM _ CONFIRMATIONS behind the actual last - block the cryptocurrency node knows about ."...
bitcoind_session = get_bitcoind ( new = True ) assert bitcoind_session is not None first_block = None last_block = None wait = 1.0 while last_block is None and is_running ( ) : first_block , last_block = virtualchain . get_index_range ( 'bitcoin' , bitcoind_session , virtualchain_hooks , working_dir ) if first_...
from collections import Counter def highest_total ( data ) : """Function that calculates the individual with the highest cumulative score in the data . The data is expected in the form of a list of tuples , where each tuple includes a name and a score . Example : > > > highest _ total ( [ ( ' Juan Whelan ' , ...
score_counter = Counter ( ) for ( individual , score ) in data : score_counter [ individual ] += score return max ( score_counter . items ( ) , key = lambda x : x [ 1 ] )
def _GetFormatter ( self , format_str ) : """The user ' s formatters are consulted first , then the default formatters ."""
formatter , args , func_type = self . formatters . LookupWithType ( format_str ) if formatter : return formatter , args , func_type else : raise BadFormatter ( '%r is not a valid formatter' % format_str )
def int_to_bitlist ( x : int , pad : int = None ) -> Sequence [ int ] : """Converts an integer to a binary sequence of bits . Pad prepends with sufficient zeros to ensures that the returned list contains at least this number of bits . > > > from quantumflow . utils import int _ to _ bitlist > > > int _ to _...
if pad is None : form = '{:0b}' else : form = '{:0' + str ( pad ) + 'b}' return [ int ( b ) for b in form . format ( x ) ]
def _load_list ( self , response ) : """Converts * response * to a list of entities . * response * is assumed to be a : class : ` Record ` containing an HTTP response , of the form : : { ' status ' : 200, ' headers ' : [ ( ' content - length ' , ' 232642 ' ) , ( ' expires ' , ' Fri , 30 Oct 1998 00:00:00 ...
# Some subclasses of Collection have to override this because # splunkd returns something that doesn ' t match # < feed > < entry > < / entry > < feed > . entries = _load_atom_entries ( response ) if entries is None : return [ ] entities = [ ] for entry in entries : state = _parse_atom_entry ( entry ) entit...
def _checkResponseRegisterAddress ( payload , registeraddress ) : """Check that the start adress as given in the response is correct . The first two bytes in the payload holds the address value . Args : * payload ( string ) : The payload * registeraddress ( int ) : The register address ( use decimal numbers...
_checkString ( payload , minlength = 2 , description = 'payload' ) _checkRegisteraddress ( registeraddress ) BYTERANGE_FOR_STARTADDRESS = slice ( 0 , 2 ) bytesForStartAddress = payload [ BYTERANGE_FOR_STARTADDRESS ] receivedStartAddress = _twoByteStringToNum ( bytesForStartAddress ) if receivedStartAddress != registera...
def save_kb_dyn_config ( kb_id , field , expression , collection = None ) : """Save a dynamic knowledge base configuration . : param kb _ id : the id : param field : the field where values are extracted : param expression : . . using this expression : param collection : . . in a certain collection ( default...
# check that collection exists if collection : collection = Collection . query . filter_by ( name = collection ) . one ( ) kb = get_kb_by_id ( kb_id ) kb . set_dyn_config ( field , expression , collection )
def nla_put_u8 ( msg , attrtype , value ) : """Add 8 bit integer attribute to Netlink message . https : / / github . com / thom311 / libnl / blob / libnl3_2_25 / lib / attr . c # L563 Positional arguments : msg - - Netlink message ( nl _ msg class instance ) . attrtype - - attribute type ( integer ) . val...
data = bytearray ( value if isinstance ( value , c_uint8 ) else c_uint8 ( value ) ) return nla_put ( msg , attrtype , SIZEOF_U8 , data )
def setAnimated ( self , state ) : """Sets whether or not the popup widget should animate its opacity when it is shown . : param state | < bool >"""
self . _animated = state self . setAttribute ( Qt . WA_TranslucentBackground , state )
def on_disconnect ( self , client , userdata , result_code ) : """Callback when the MQTT client is disconnected . In this case , the server waits five seconds before trying to reconnected . : param client : the client being disconnected . : param userdata : unused . : param result _ code : result code ."""
self . log_info ( "Disconnected with result code " + str ( result_code ) ) self . state_handler . set_state ( State . goodbye ) time . sleep ( 5 ) self . thread_handler . run ( target = self . start_blocking )
def getMirrorTextureGL ( self , eEye ) : """Access to mirror textures from OpenGL ."""
fn = self . function_table . getMirrorTextureGL pglTextureId = glUInt_t ( ) pglSharedTextureHandle = glSharedTextureHandle_t ( ) result = fn ( eEye , byref ( pglTextureId ) , byref ( pglSharedTextureHandle ) ) return result , pglTextureId , pglSharedTextureHandle
def translate_sbml_compound ( entry , new_id , compartment_map ) : """Translate SBML compound entry ."""
new_entry = DictCompoundEntry ( entry , id = new_id ) if 'compartment' in new_entry . properties : old_compartment = new_entry . properties [ 'compartment' ] new_entry . properties [ 'compartment' ] = compartment_map . get ( old_compartment , old_compartment ) # Get XHTML notes properties for key , value in ite...
def arrays_split ( mask : NPArrayMask , * arrs : NPArrayableList ) -> SplitArrayList : "Given ` arrs ` is [ a , b , . . . ] and ` mask ` index - return [ ( a [ mask ] , a [ ~ mask ] ) , ( b [ mask ] , b [ ~ mask ] ) , . . . ] ."
assert all ( [ len ( arr ) == len ( arrs [ 0 ] ) for arr in arrs ] ) , 'All arrays should have same length' mask = array ( mask ) return list ( zip ( * [ ( a [ mask ] , a [ ~ mask ] ) for a in map ( np . array , arrs ) ] ) )
def remove_by_hash ( hashval : str ) : """Remove the key whose md5 sum matches hashval . : raises : KeyError if the hashval wasn ' t found"""
key_details = get_keys ( ) with authorized_keys ( 'w' ) as ak : for keyhash , key in key_details : if keyhash != hashval : ak . write ( f'{key}\n' ) break else : raise KeyError ( hashval )
def slfo ( wnd , res = 50 , neighbors = 2 , max_miss = .7 , start_delta = 1e-4 ) : """Side Lobe Fall Off ( dB / oct ) . Finds the side lobe peak fall off numerically in dB / octave by using the ` ` scipy . optimize . fmin ` ` function . Hint Originally , Harris rounded the results he found to a multiple of ...
# Finds all side lobe peaks , to find the " best " line for it afterwards spectrum = dB20 ( rfft ( wnd , res * len ( wnd ) ) ) peak_indices = list ( get_peaks ( spectrum , neighbors = neighbors ) ) log2_peak_indices = np . log2 ( peak_indices ) # Base 2 ensures result in dB / oct peaks = spectrum [ peak_indices ] npeak...
def retrieve_collection ( collection , query_arguments = None ) : """Return the resources in * collection * , possibly filtered by a series of values to use in a ' where ' clause search . : param string collection : a : class : ` sandman . model . Model ` endpoint : param dict query _ arguments : a list of fi...
session = _get_session ( ) cls = endpoint_class ( collection ) if query_arguments : filters = [ ] order = [ ] limit = None for key , value in query_arguments . items ( ) : if key == 'page' : continue if value . startswith ( '%' ) : filters . append ( getattr ( cls...
def pprint ( self , indent = '' , f = None ) : """debug function"""
if self . arg is not None : print ( indent + util . keyword_to_str ( self . keyword ) + " " + self . arg ) else : print ( indent + util . keyword_to_str ( self . keyword ) ) if f is not None : f ( self , indent ) for x in self . substmts : x . pprint ( indent + ' ' , f ) if hasattr ( self , 'i_children'...
def scale_up_dynos ( id ) : """Scale up the Heroku dynos ."""
# Load psiTurk configuration . config = PsiturkConfig ( ) config . load_config ( ) dyno_type = config . get ( 'Server Parameters' , 'dyno_type' ) num_dynos_web = config . get ( 'Server Parameters' , 'num_dynos_web' ) num_dynos_worker = config . get ( 'Server Parameters' , 'num_dynos_worker' ) log ( "Scaling up the dyno...
def _decrypt_data_key ( self , encrypted_data_key , algorithm , encryption_context ) : """Decrypts an encrypted data key and returns the plaintext . : param data _ key : Encrypted data key : type data _ key : aws _ encryption _ sdk . structures . EncryptedDataKey : param algorithm : Algorithm object which dir...
# Wrapped EncryptedDataKey to deserialized EncryptedData encrypted_wrapped_key = aws_encryption_sdk . internal . formatting . deserialize . deserialize_wrapped_key ( wrapping_algorithm = self . config . wrapping_key . wrapping_algorithm , wrapping_key_id = self . key_id , wrapped_encrypted_key = encrypted_data_key , ) ...
def _compute_diff ( self ) : """Computes the diff of the functions and saves the result ."""
# get the attributes for all blocks l . debug ( "Computing diff of functions: %s, %s" , ( "%#x" % self . _function_a . startpoint . addr ) if self . _function_a . startpoint is not None else "None" , ( "%#x" % self . _function_b . startpoint . addr ) if self . _function_b . startpoint is not None else "None" ) self . a...
def validate_all_types ( kwargs ) : """validates that all values of the arguments are types"""
for key in kwargs : assert isinstance ( kwargs [ key ] , type ) , """\n Typedtuple needs its arguments to be types. Argument "{k:}" was {type_name:}({val_repr}). You might want to try: {k:} = {type_name:}\n\n""" . format ( k = key , type_name = type ( kwargs [ key ] ) . __name__ , val_repr = kwargs ...
def call ( self , uri , params = None , access_token = None , api_version = None , timeout = None ) : """Calls wepay . com / v2 / ` ` uri ` ` with ` ` params ` ` and returns the JSON response as a python ` dict ` . The optional ` ` access _ token ` ` parameter takes precedence over instance ' s ` ` access _ tok...
url = self . api_endpoint + uri params = params or { } headers = { 'Content-Type' : 'application/json' , 'User-Agent' : 'Python WePay SDK (third party)' } access_token = access_token or self . access_token headers [ 'Authorization' ] = 'Bearer %s' % access_token api_version = api_version or self . api_version if not ap...
def extract_uhs ( dstore , what ) : """Extracts uniform hazard spectra . Use it as / extract / uhs ? kind = mean or / extract / uhs ? kind = rlz - 0 , etc"""
info = get_info ( dstore ) if what == '' : # npz exports for QGIS sitecol = dstore [ 'sitecol' ] mesh = get_mesh ( sitecol , complete = False ) dic = { } for stat , s in info [ 'stats' ] . items ( ) : hmap = dstore [ 'hmaps-stats' ] [ : , s ] dic [ stat ] = calc . make_uhs ( hmap , info ...
def process_har ( self ) : """Detect plugins present in the page ."""
hints = [ ] version_plugins = self . _plugins . with_version_matchers ( ) generic_plugins = self . _plugins . with_generic_matchers ( ) for entry in self . har : for plugin in version_plugins : pm = self . apply_plugin_matchers ( plugin , entry ) if not pm : continue # Set name i...
def _initialize ( self ) : """Open from caffe weights"""
self . _graph = tf . Graph ( ) with self . _graph . as_default ( ) : self . _input_node = tf . placeholder ( tf . float32 , ( self . _batch_size , self . _im_height , self . _im_width , self . _num_channels ) ) weights = self . build_alexnet_weights ( ) self . _output_tensor = self . build_alexnet ( weights...
def compose_ants_transforms ( transform_list ) : """Compose multiple ANTsTransform ' s together ANTsR function : ` composeAntsrTransforms ` Arguments transform _ list : list / tuple of ANTsTransform object list of transforms to compose together Returns ANTsTransform one transform that contains all giv...
precision = transform_list [ 0 ] . precision dimension = transform_list [ 0 ] . dimension for tx in transform_list : if precision != tx . precision : raise ValueError ( 'All transforms must have the same precision' ) if dimension != tx . dimension : raise ValueError ( 'All transforms must have t...