signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def __run ( self ) : """The main loop"""
already_cleaned = False try : while not self . _done_event . is_set ( ) : try : # Wait for an action ( blocking ) task = self . _queue . get ( True , self . _timeout ) if task is self . _done_event : # Stop event in the queue : get out self . _queue . task_done ( ) ...
def flush ( self ) : """Flushes all log files ."""
self . acquire ( ) try : self . stream . flush ( ) except ( EnvironmentError , ValueError ) : # A ValueError is thrown if we try to flush a closed file . pass finally : self . release ( )
def encoding ( self ) : """the character encoding of the request , usually only set in POST type requests"""
encoding = None ct = self . get_header ( 'content-type' ) if ct : ah = AcceptHeader ( ct ) if ah . media_types : encoding = ah . media_types [ 0 ] [ 2 ] . get ( "charset" , None ) return encoding
def YieldFromList ( service , request , global_params = None , limit = None , batch_size = 100 , method = 'List' , field = 'items' , predicate = None , current_token_attribute = 'pageToken' , next_token_attribute = 'nextPageToken' , batch_size_attribute = 'maxResults' ) : """Make a series of List requests , keeping...
request = encoding . CopyProtoMessage ( request ) setattr ( request , current_token_attribute , None ) while limit is None or limit : if batch_size_attribute : # On Py3 , None is not comparable so min ( ) below will fail . # On Py2 , None is always less than any number so if batch _ size # is None , the req...
def basis_function_one ( degree , knot_vector , span , knot ) : """Computes the value of a basis function for a single parameter . Implementation of Algorithm 2.4 from The NURBS Book by Piegl & Tiller . : param degree : degree , : math : ` p ` : type degree : int : param knot _ vector : knot vector : type...
# Special case at boundaries if ( span == 0 and knot == knot_vector [ 0 ] ) or ( span == len ( knot_vector ) - degree - 2 ) and knot == knot_vector [ len ( knot_vector ) - 1 ] : return 1.0 # Knot is outside of span range if knot < knot_vector [ span ] or knot >= knot_vector [ span + degree + 1 ] : return 0.0 N ...
def clicked ( self ) : """Selected item was double - clicked or enter / return was pressed"""
fnames = self . get_selected_filenames ( ) for fname in fnames : if osp . isdir ( fname ) : self . directory_clicked ( fname ) else : self . open ( [ fname ] )
def is_valid_request ( self , request , parameters = { } , fake_method = None , handle_error = True ) : '''Validates an OAuth request using the python - oauth2 library : https : / / github . com / simplegeo / python - oauth2'''
try : # Set the parameters to be what we were passed earlier # if we didn ' t get any passed to us now if not parameters and hasattr ( self , 'params' ) : parameters = self . params method , url , headers , parameters = self . parse_request ( request , parameters , fake_method ) oauth_request = oaut...
def decrypt ( self ) : """Decrypt decrypts the secret and returns the plaintext . Calling decrypt ( ) may incur side effects such as a call to a remote service for decryption ."""
if not self . _crypter : return b'' try : plaintext = self . _crypter . decrypt ( self . _ciphertext , ** self . _decrypt_params ) return plaintext except Exception as e : exc_info = sys . exc_info ( ) six . reraise ( ValueError ( 'Invalid ciphertext "%s", error: %s' % ( self . _ciphertext , e ) ) ,...
def define_attribute ( self , name , atype , data = None ) : """Define a new attribute . atype has to be one of ' integer ' , ' real ' , ' numeric ' , ' string ' , ' date ' or ' nominal ' . For nominal attributes , pass the possible values as data . For date attributes , pass the format as data ."""
self . attributes . append ( name ) assert atype in TYPES , "Unknown type '%s'. Must be one of: %s" % ( atype , ', ' . join ( TYPES ) , ) self . attribute_types [ name ] = atype self . attribute_data [ name ] = data
def _launch_editor ( starting_text = '' ) : "Launch editor , let user write text , then return that text ."
# TODO : What is a reasonable default for windows ? Does this approach even # make sense on windows ? editor = os . environ . get ( 'EDITOR' , 'vim' ) with tempfile . TemporaryDirectory ( ) as dirname : filename = pathlib . Path ( dirname ) / 'metadata.yml' with filename . open ( mode = 'wt' ) as handle : ...
def get_profile_data ( self , auth_response ) : """Retrieve profile data from provider"""
res = auth_response token = res . get ( 'access_token' ) me = res . get ( 'user' ) if not me . get ( 'id' ) : raise x . UserException ( 'Instagram must return a user id' ) data = dict ( provider = self . provider , email = None , id = me . get ( 'id' ) , token = token , ) return data
def delete_user ( self , id , ** kwargs ) : # noqa : E501 """Deletes a user identified by id # noqa : E501 # noqa : E501 This method makes a synchronous HTTP request by default . To make an asynchronous HTTP request , please pass async _ req = True > > > thread = api . delete _ user ( id , async _ req = Tru...
kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'async_req' ) : return self . delete_user_with_http_info ( id , ** kwargs ) # noqa : E501 else : ( data ) = self . delete_user_with_http_info ( id , ** kwargs ) # noqa : E501 return data
def subset ( self , subtxns ) : """Construct a new Positions object from the new Txns object ( which is assumed to be a subset ) of current Txns object"""
result = Positions ( subtxns ) if hasattr ( self , '_frame' ) : result . _frame = self . _frame . ix [ subtxns . pids ] # passing in array results in index name being removed for some reason ? ? ? if result . _frame . index . name != self . _frame . index . name : result . _frame . index . name = se...
def from_start_and_end ( cls , start , end , aa = None , major_pitch = 225.8 , major_radius = 5.07 , major_handedness = 'l' , minor_helix_type = 'alpha' , orientation = 1 , phi_c_alpha = 0.0 , minor_repeat = None ) : """Creates a ` HelicalHelix ` between a ` start ` and ` end ` point ."""
start = numpy . array ( start ) end = numpy . array ( end ) if aa is None : minor_rise_per_residue = _helix_parameters [ minor_helix_type ] [ 1 ] aa = int ( ( numpy . linalg . norm ( end - start ) / minor_rise_per_residue ) + 1 ) instance = cls ( aa = aa , major_pitch = major_pitch , major_radius = major_radius...
def list_known_codes ( s , unique = True , rgb_mode = False ) : """Find and print all known escape codes in a string , using get _ known _ codes ."""
total = 0 for codedesc in get_known_codes ( s , unique = unique , rgb_mode = rgb_mode ) : total += 1 print ( codedesc ) plural = 'code' if total == 1 else 'codes' codetype = ' unique' if unique else '' print ( '\nFound {}{} escape {}.' . format ( total , codetype , plural ) ) return 0 if total > 0 else 1
def _process_incoming ( self , xmlstream , queue_entry ) : """Dispatch to the different methods responsible for the different stanza types or handle a non - stanza stream - level element from ` stanza _ obj ` , which has arrived over the given ` xmlstream ` ."""
stanza_obj , exc = queue_entry # first , handle SM stream objects if isinstance ( stanza_obj , nonza . SMAcknowledgement ) : self . _logger . debug ( "received SM ack: %r" , stanza_obj ) if not self . _sm_enabled : self . _logger . warning ( "received SM ack, but SM not enabled" ) return sel...
def create_countries_geo_zone ( cls , countries_geo_zone , ** kwargs ) : """Create CountriesGeoZone Create a new CountriesGeoZone This method makes a synchronous HTTP request by default . To make an asynchronous HTTP request , please pass async = True > > > thread = api . create _ countries _ geo _ zone ( c...
kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'async' ) : return cls . _create_countries_geo_zone_with_http_info ( countries_geo_zone , ** kwargs ) else : ( data ) = cls . _create_countries_geo_zone_with_http_info ( countries_geo_zone , ** kwargs ) return data
def end_workunit ( self , workunit ) : """Implementation of Reporter callback ."""
if not self . is_under_main_root ( workunit ) : return if workunit . outcome ( ) != WorkUnit . SUCCESS and not self . _show_output ( workunit ) : # Emit the suppressed workunit output , if any , to aid in debugging the problem . if self . _get_label_format ( workunit ) != LabelFormat . FULL : self . _em...
def _match_stmt ( ctx , stmt , specs , canonical ) : """Match stmt against the spec . Return None | spec ' spec ' is an updated spec with the matching spec consumed"""
( spec , canspec ) = specs i = 0 while i < len ( spec ) : ( keywd , occurance ) = spec [ i ] if keywd == '$any' : return ( spec , canspec ) if keywd == '$1.1' : ( keywd , occurance ) = occurance if ( stmt . i_module . i_version == '1' and keywd == stmt . keyword ) : retur...
def _buildTraitCovar ( self , trait_covar_type = 'freeform' , rank = 1 , fixed_trait_covar = None , jitter = 1e-4 ) : """Internal functions that builds the trait covariance matrix using the LIMIX framework Args : trait _ covar _ type : type of covaraince to use . Default ' freeform ' . possible values are ran...
assert trait_covar_type in [ 'freeform' , 'diag' , 'lowrank' , 'lowrank_id' , 'lowrank_diag' , 'block' , 'block_id' , 'block_diag' , 'fixed' ] , 'VarianceDecomposition:: trait_covar_type not valid' if trait_covar_type == 'freeform' : cov = FreeFormCov ( self . P , jitter = jitter ) elif trait_covar_type == 'fixed' ...
def export_obo ( self , path_to_export_file , name_of_ontology = "uniprot" , taxids = None ) : """export complete database to OBO ( http : / / www . obofoundry . org / ) file : param path _ to _ export _ file : path to export file : param taxids : NCBI taxonomy identifiers to export ( optional )"""
fd = open ( path_to_export_file , 'w' ) header = "format-version: 0.1\ndata: {}\n" . format ( time . strftime ( "%d:%m:%Y %H:%M" ) ) header += "ontology: {}\n" . format ( name_of_ontology ) header += 'synonymtypedef: GENE_NAME "GENE NAME"\nsynonymtypedef: ALTERNATIVE_NAME "ALTERNATIVE NAME"\n' fd . write ( header ) que...
def map_verbose ( func , seq , msg = "{}" , every = 25 , start = True , end = True , offset = 0 , callback = None ) : """Same as the built - in map function but prints a * msg * after chunks of size * every * iterations . When * start * ( * stop * ) is * True * , the * msg * is also printed after the first ( last...
# default callable if not callable ( callback ) : def callback ( i ) : print ( msg . format ( i + offset ) ) results = [ ] for i , obj in enumerate ( seq ) : results . append ( func ( obj ) ) do_call = ( start and i == 0 ) or ( i + 1 ) % every == 0 if do_call : callback ( i ) else : ...
def _build ( self , build_method ) : """build image from provided build _ args : return : BuildResults"""
logger . info ( "building image '%s'" , self . image ) self . ensure_not_built ( ) self . temp_dir = tempfile . mkdtemp ( ) temp_path = os . path . join ( self . temp_dir , BUILD_JSON ) try : with open ( temp_path , 'w' ) as build_json : json . dump ( self . build_args , build_json ) self . build_contai...
def copy ( self ) : """Return a copy of the current ColorVisuals object . Returns copied : ColorVisuals Contains the same information as self"""
copied = ColorVisuals ( ) copied . _data . data = copy . deepcopy ( self . _data . data ) return copied
def setup_dirs ( ) : """Make required directories to hold logfile . : returns : str"""
try : top_dir = os . path . abspath ( os . path . expanduser ( os . environ [ "XDG_CACHE_HOME" ] ) ) except KeyError : top_dir = os . path . abspath ( os . path . expanduser ( "~/.cache" ) ) our_cache_dir = os . path . join ( top_dir , PROJECT_NAME ) os . makedirs ( our_cache_dir , mode = 0o775 , exist_ok = Tru...
def turn_off_syncing ( for_post_save = True , for_post_delete = True , for_m2m_changed = True , for_post_bulk_operation = True ) : """Disables all of the signals for syncing entities . By default , everything is turned off . If the user wants to turn off everything but one signal , for example the post _ save sig...
if for_post_save : post_save . disconnect ( save_entity_signal_handler , dispatch_uid = 'save_entity_signal_handler' ) if for_post_delete : post_delete . disconnect ( delete_entity_signal_handler , dispatch_uid = 'delete_entity_signal_handler' ) if for_m2m_changed : m2m_changed . disconnect ( m2m_changed_en...
def angular_templates ( context ) : """Generate a dictionary of template contents for all static HTML templates . If the template has been overridden by a theme , load the override contents instead of the original HTML file . One use for this is to pre - populate the angular template cache . Args : contex...
template_paths = context [ 'HORIZON_CONFIG' ] [ 'external_templates' ] all_theme_static_files = context [ 'HORIZON_CONFIG' ] [ 'theme_static_files' ] this_theme_static_files = all_theme_static_files [ context [ 'THEME' ] ] template_overrides = this_theme_static_files [ 'template_overrides' ] angular_templates = { } for...
def __map_button ( self , button ) : """Get the linux xpad code from the Windows xinput code ."""
_ , start_code , start_value = button value = start_value ev_type = "Key" code = self . manager . codes [ 'xpad' ] [ start_code ] if 1 <= start_code <= 4 : ev_type = "Absolute" if start_code == 1 and start_value == 1 : value = - 1 elif start_code == 3 and start_value == 1 : value = - 1 return code , value ,...
def sumlogs ( x , axis = None , out = None ) : """Sum of vector where numbers are represented by their logarithms . Calculates ` ` np . log ( np . sum ( np . exp ( x ) , axis = axis ) ) ` ` in such a fashion that it works even when elements have large magnitude ."""
maxx = x . max ( axis = axis , keepdims = True ) xnorm = x - maxx np . exp ( xnorm , out = xnorm ) out = np . sum ( xnorm , axis = axis , out = out ) if isinstance ( out , np . ndarray ) : np . log ( out , out = out ) else : out = np . log ( out ) out += np . squeeze ( maxx ) return out
def binary_dumps ( obj , alt_format = False ) : """Serialize ` ` obj ` ` to a binary VDF formatted ` ` bytes ` ` ."""
return b'' . join ( _binary_dump_gen ( obj , alt_format = alt_format ) )
def move_mission ( self , key , selection_index ) : '''move a mission point'''
idx = self . selection_index_to_idx ( key , selection_index ) self . moving_wp = idx print ( "Moving wp %u" % idx )
def set_data_value ( datastore , path , data ) : '''Get a data entry in a datastore : param datastore : The datastore , e . g . running , operational . One of the NETCONF store IETF types : type datastore : : class : ` DatastoreType ` ( ` ` str ` ` enum ) . : param path : The device path to set the value at...
client = _get_client ( ) return client . set_data_value ( datastore , path , data )
def partition_by_cores ( a : Collection , n_cpus : int ) -> List [ Collection ] : "Split data in ` a ` equally among ` n _ cpus ` cores"
return partition ( a , len ( a ) // n_cpus + 1 )
def detector_voltage ( self , channels = None ) : """Get the detector voltage used for the specified channel ( s ) . The detector voltage for channel " n " is extracted from the $ PnV parameter , if available . Parameters channels : int , str , list of int , list of str Channel ( s ) for which to get the ...
# Check default if channels is None : channels = self . _channels # Get numerical indices of channels channels = self . _name_to_index ( channels ) # Get detector type of the specified channels if hasattr ( channels , '__iter__' ) and not isinstance ( channels , six . string_types ) : return [ self . _detector_...
def conv2d_fixed_padding ( inputs , filters , kernel_size , strides , data_format = "channels_first" , use_td = False , targeting_rate = None , keep_prob = None , is_training = None ) : """Strided 2 - D convolution with explicit padding . The padding is consistent and is based only on ` kernel _ size ` , not on t...
if strides > 1 : inputs = fixed_padding ( inputs , kernel_size , data_format = data_format ) if use_td : inputs_shape = common_layers . shape_list ( inputs ) if use_td == "weight" : if data_format == "channels_last" : size = kernel_size * kernel_size * inputs_shape [ - 1 ] else :...
def convert ( self ) : """Returns RPM SPECFILE . Returns : rendered RPM SPECFILE ."""
# move file into position try : local_file = self . getter . get ( ) except ( exceptions . NoSuchPackageException , OSError ) as e : logger . error ( "Failed and exiting:" , exc_info = True ) logger . info ( "Pyp2rpm failed. See log for more info." ) sys . exit ( e ) # save name and version from the fil...
def gets ( self , key ) : "Like ` get ` , but return all matches , not just the first ."
result_list = [ ] if key in self . keys ( ) : result_list . append ( self [ key ] ) for v in self . values ( ) : if isinstance ( v , self . __class__ ) : sub_res_list = v . gets ( key ) for res in sub_res_list : result_list . append ( res ) elif isinstance ( v , dict ) : ...
def present ( name , host = 'localhost' , password = None , password_hash = None , allow_passwordless = False , unix_socket = False , password_column = None , ** connection_args ) : '''Ensure that the named user is present with the specified properties . A passwordless user can be configured by omitting ` ` passw...
ret = { 'name' : name , 'changes' : { } , 'result' : True , 'comment' : 'User {0}@{1} is already present' . format ( name , host ) } passwordless = not any ( ( password , password_hash ) ) # check if user exists with the same password ( or passwordless login ) if passwordless : if not salt . utils . data . is_true ...
def translate ( otp , to = MODHEX ) : """Return set ( ) of possible modhex interpretations of a Yubikey otp . If otp uses all 16 characters in its alphabet , there will be only one possible interpretation of that Yubikey otp ( except for two Armenian keyboard layouts ) . otp : Yubikey output . to : 16 - c...
if PY3 : if isinstance ( otp , bytes ) : raise ValueError ( "otp must be unicode" ) if isinstance ( to , bytes ) : raise ValueError ( "to must be unicode" ) else : if not isinstance ( otp , unicode ) : raise ValueError ( "otp must be unicode" ) if not isinstance ( to , unicode ) ...
def find_db_attributes ( self , table , * conditions ) : """Lists records satisfying ' conditions ' in ' table ' . This method is corresponding to the following ovs - vsctl command : : $ ovs - vsctl find TBL CONDITION . . . . . Note : : Currently , only ' = ' condition is supported . To support other cond...
args = [ table ] args . extend ( conditions ) command = ovs_vsctl . VSCtlCommand ( 'find' , args ) self . run_command ( [ command ] ) if command . result : return command . result return [ ]
def similarity ( self , other ) : """Calculate similarity based on best matching permutation of items ."""
# Select the longer list as the basis for comparison if len ( self . items ) > len ( other . items ) : first , second = self , other else : first , second = other , self items = list ( first . items ) # backup items list length = len ( items ) sim = self . Similarity ( 0.0 if length else 1.0 ) # Calculate the s...
def create_transaction ( self , * args : Any , ** kwargs : Any ) -> BaseTransaction : """Proxy for instantiating a signed transaction for this VM ."""
return self . get_transaction_class ( ) ( * args , ** kwargs )
def _stat_name ( feat_name , stat_mode ) : '''Set stat name based on feature name and stat mode'''
if feat_name [ - 1 ] == 's' : feat_name = feat_name [ : - 1 ] if feat_name == 'soma_radii' : feat_name = 'soma_radius' if stat_mode == 'raw' : return feat_name return '%s_%s' % ( stat_mode , feat_name )
def get_admin_email_link ( application ) : """Retrieve a link that can be emailed to the administrator ."""
url = '%s/applications/%d/' % ( settings . ADMIN_BASE_URL , application . pk ) is_secret = False return url , is_secret
def is_excel_file ( inputfile ) : """Return whether the provided file is a CSV file or not . This checks if the first row of the file can be splitted by ' , ' and if the resulting line contains more than 4 columns ( Markers , linkage group , chromosome , trait ) ."""
try : xlrd . open_workbook ( inputfile ) except Exception as err : print ( err ) return False return True
def parse ( self , input_text , syncmap ) : """Read from SMIL file . Limitations : 1 . parses only ` ` < par > ` ` elements , in order 2 . timings must have ` ` hh : mm : ss . mmm ` ` or ` ` ss . mmm ` ` format ( autodetected ) 3 . both ` ` clipBegin ` ` and ` ` clipEnd ` ` attributes of ` ` < audio > ` ` m...
from lxml import etree smil_ns = "{http://www.w3.org/ns/SMIL}" root = etree . fromstring ( gf . safe_bytes ( input_text ) ) for par in root . iter ( smil_ns + "par" ) : for child in par : if child . tag == ( smil_ns + "text" ) : identifier = gf . safe_unicode ( gf . split_url ( child . get ( "sr...
def scan_temperature ( self , measure , temperature , rate , delay = 1 ) : """Performs a temperature scan . Measures until the target temperature is reached . : param measure : A callable called repeatedly until stability at target temperature is reached . : param temperature : The target temperature in kel...
if not hasattr ( measure , '__call__' ) : raise TypeError ( 'measure parameter not callable.' ) self . set_temperature ( temperature , rate , 'no overshoot' , wait_for_stability = False ) start = datetime . datetime . now ( ) while True : # The PPMS needs some time to update the status code , we therefore ignore it...
def split ( self , meta = False ) : """split disconnected structure to connected substructures : param meta : copy metadata to each substructure : return : list of substructures"""
return [ self . substructure ( c , meta , False ) for c in connected_components ( self ) ]
def concat ( self , to_concat , new_axis ) : """Concatenate a list of SingleBlockManagers into a single SingleBlockManager . Used for pd . concat of Series objects with axis = 0. Parameters to _ concat : list of SingleBlockManagers new _ axis : Index of the result Returns SingleBlockManager"""
non_empties = [ x for x in to_concat if len ( x ) > 0 ] # check if all series are of the same block type : if len ( non_empties ) > 0 : blocks = [ obj . blocks [ 0 ] for obj in non_empties ] if len ( { b . dtype for b in blocks } ) == 1 : new_block = blocks [ 0 ] . concat_same_type ( blocks ) else :...
def user_parser ( user ) : """Parses a user object"""
if __is_deleted ( user ) : return deleted_parser ( user ) if user [ 'id' ] in item_types : raise Exception ( 'Not a user name' ) if type ( user [ 'id' ] ) == int : raise Exception ( 'Not a user name' ) return User ( user [ 'id' ] , user [ 'delay' ] , user [ 'created' ] , user [ 'karma' ] , user [ 'about' ] ...
def modular_sqrt ( a , p ) : """Find a quadratic residue ( mod p ) of ' a ' . p must be an odd prime . Solve the congruence of the form : x ^ 2 = a ( mod p ) And returns x . Note that p - x is also a root . 0 is returned is no square root exists for these a and p . The Tonelli - Shanks algorithm is us...
# Simple cases if legendre_symbol ( a , p ) != 1 : return 0 elif a == 0 : return 0 elif p == 2 : return p elif p % 4 == 3 : return pow ( a , ( p + 1 ) / 4 , p ) # Partition p - 1 to s * 2 ^ e for an odd s ( i . e . # reduce all the powers of 2 from p - 1) s = p - 1 e = 0 while s % 2 == 0 : s /= 2 ...
def pos ( self ) : """Lazy - loads the part of speech tag for this word : getter : Returns the plain string value of the POS tag for the word : type : str"""
if self . _pos is None : poses = self . _element . xpath ( 'POS/text()' ) if len ( poses ) > 0 : self . _pos = poses [ 0 ] return self . _pos
def extract_path_info ( environ_or_baseurl , path_or_url , charset = "utf-8" , errors = "werkzeug.url_quote" , collapse_http_schemes = True , ) : """Extracts the path info from the given URL ( or WSGI environment ) and path . The path info returned is a unicode string , not a bytestring suitable for a WSGI envi...
def _normalize_netloc ( scheme , netloc ) : parts = netloc . split ( u"@" , 1 ) [ - 1 ] . split ( u":" , 1 ) if len ( parts ) == 2 : netloc , port = parts if ( scheme == u"http" and port == u"80" ) or ( scheme == u"https" and port == u"443" ) : port = None else : netloc =...
def data ( self ) : """A 2D cutout image of the segment using the minimal bounding box , where pixels outside of the labeled region are set to zero ( i . e . neighboring segments within the rectangular cutout image are not shown ) ."""
cutout = np . copy ( self . _segment_img [ self . slices ] ) cutout [ cutout != self . label ] = 0 return cutout
def _update_summary ( self , summary = None ) : """Update all parts of the summary or clear when no summary ."""
board_image_label = self . _parts [ 'board image label' ] # get content for update or use blanks when no summary if summary : # make a board image with the swap drawn on it # board , action , text = summary . board , summary . action , summary . text board_image_cv = self . _create_board_image_cv ( summary . board ...
def inDignities ( self , idA , idB ) : """Returns the dignities of A which belong to B ."""
objA = self . chart . get ( idA ) info = essential . getInfo ( objA . sign , objA . signlon ) # Should we ignore exile and fall ? return [ dign for ( dign , ID ) in info . items ( ) if ID == idB ]
def audio_detection_sensitivity ( self ) : """Sensitivity level of Camera audio detection ."""
if not self . triggers : return None for trigger in self . triggers : if trigger . get ( "type" ) != "audioAmplitude" : continue sensitivity = trigger . get ( "sensitivity" ) if sensitivity : return sensitivity . get ( "default" ) return None
def extract_fcp_data ( raw_data , status ) : """extract data from smcli System _ WWPN _ Query output . Input : raw data returned from smcli Output : data extracted would be like : ' status : Free \n fcp _ dev _ no : 1D2F \n physical _ wwpn : C05076E9928051D1 \n channel _ path _ id : 8B \n npiv _ w...
raw_data = raw_data . split ( '\n' ) # clear blank lines data = [ ] for i in raw_data : i = i . strip ( ' \n' ) if i == '' : continue else : data . append ( i ) # process data into one list of dicts results = [ ] for i in range ( 0 , len ( data ) , 5 ) : temp = data [ i + 1 ] . split ( '...
def open ( self ) : '''Open notification or quick settings . Usage : d . open . notification ( ) d . open . quick _ settings ( )'''
@ param_to_property ( action = [ "notification" , "quick_settings" ] ) def _open ( action ) : if action == "notification" : return self . server . jsonrpc . openNotification ( ) else : return self . server . jsonrpc . openQuickSettings ( ) return _open
def vdatainfo ( self , listAttr = 0 ) : """Return info about all the file vdatas . Args : : listAttr Set to 0 to ignore vdatas used to store attribute values , 1 to list them ( see the VD . _ isattr readonly attribute ) Returns : : List of vdata descriptions . Each vdata is described as a 9 - element ...
lst = [ ] ref = - 1 # start at beginning while True : try : nxtRef = self . next ( ref ) except HDF4Error : # no vdata left break # Attach the vdata and check for an " attribute " vdata . ref = nxtRef vdObj = self . attach ( ref ) if listAttr or not vdObj . _isattr : # Append a l...
def GetParentFileEntry ( self ) : """Retrieves the parent file entry . Returns : ZipFileEntry : parent file entry or None if not available ."""
location = getattr ( self . path_spec , 'location' , None ) if location is None : return None parent_location = self . _file_system . DirnamePath ( location ) if parent_location is None : return None parent_path_spec = getattr ( self . path_spec , 'parent' , None ) if parent_location == '' : parent_location...
def add_annotation ( self , about , content , motivated_by = "oa:describing" ) : # type : ( str , List [ str ] , str ) - > str """Cheap URI relativize for current directory and / ."""
self . self_check ( ) curr = self . base_uri + METADATA + "/" content = [ c . replace ( curr , "" ) . replace ( self . base_uri , "../" ) for c in content ] uri = uuid . uuid4 ( ) . urn ann = { "uri" : uri , "about" : about , "content" : content , "oa:motivatedBy" : { "@id" : motivated_by } } self . annotations . appen...
def add_prefix ( self , ncname : str ) -> None : """Look up ncname and add it to the prefix map if necessary @ param ncname : name to add"""
if ncname not in self . prefixmap : uri = cu . expand_uri ( ncname + ':' , self . curi_maps ) if uri and '://' in uri : self . prefixmap [ ncname ] = uri else : print ( f"Unrecognized prefix: {ncname}" , file = sys . stderr ) self . prefixmap [ ncname ] = f"http://example.org/unknown...
def attachRequest ( PTmsiSignature_presence = 0 , GprsTimer_presence = 0 , TmsiStatus_presence = 0 ) : """ATTACH REQUEST Section 9.4.1"""
a = TpPd ( pd = 0x3 ) b = MessageType ( mesType = 0x1 ) # 000001 c = MsNetworkCapability ( ) d = AttachTypeAndCiphKeySeqNr ( ) f = DrxParameter ( ) g = MobileId ( ) h = RoutingAreaIdentification ( ) i = MsRadioAccessCapability ( ) packet = a / b / c / d / f / g / h / i if PTmsiSignature_presence is 1 : j = PTmsiSig...
def optimize ( self , method = "simplex" , verbosity = False , tolerance = 1e-9 , ** kwargs ) : """Run the linprog function on the problem . Returns None ."""
c = np . array ( [ self . objective . get ( name , 0 ) for name in self . _variables ] ) if self . direction == "max" : c *= - 1 bounds = list ( six . itervalues ( self . bounds ) ) solution = linprog ( c , self . A , self . upper_bounds , bounds = bounds , method = method , options = { "maxiter" : 10000 , "disp" :...
def add_inline_l2fw_interface ( self , interface_id , second_interface_id , logical_interface_ref = None , vlan_id = None , zone_ref = None , second_zone_ref = None , comment = None ) : """. . versionadded : : 0.5.6 Requires NGFW engine > = 6.3 and layer 3 FW or cluster An inline L2 FW interface is a new interf...
_interface = { 'interface_id' : interface_id , 'second_interface_id' : second_interface_id , 'logical_interface_ref' : logical_interface_ref , 'failure_mode' : 'normal' , 'zone_ref' : zone_ref , 'second_zone_ref' : second_zone_ref , 'comment' : comment , 'interface' : 'inline_l2fw_interface' , 'vlan_id' : vlan_id } ret...
def plot_sens_center ( self , frequency = 2 ) : """plot sensitivity center distribution for all configurations in config . dat . The centers of mass are colored by the data given in volt _ file ."""
try : colors = np . loadtxt ( self . volt_file , skiprows = 1 ) except IOError : print ( 'IOError opening {0}' . format ( volt_file ) ) exit ( ) # check for 1 - dimensionality if ( len ( colors . shape ) > 1 ) : print ( 'Artificial or Multi frequency data' ) colors = colors [ : , frequency ] . flatt...
def get_json ( identifier , namespace = 'cid' , domain = 'compound' , operation = None , searchtype = None , ** kwargs ) : """Request wrapper that automatically parses JSON response and supresses NotFoundError ."""
try : return json . loads ( get ( identifier , namespace , domain , operation , 'JSON' , searchtype , ** kwargs ) . decode ( ) ) except NotFoundError as e : log . info ( e ) return None
def offset ( self , points , offsets , along , offset_axis , units = "same" , offset_units = "same" , mode = "valid" , method = "linear" , verbose = True , ) : """Offset one axis based on another axis ' values . Useful for correcting instrumental artifacts such as zerotune . Parameters points : 1D array - lik...
raise NotImplementedError # axis - - - - - if isinstance ( along , int ) : axis_index = along elif isinstance ( along , str ) : axis_index = self . axis_names . index ( along ) else : raise TypeError ( "along: expected {int, str}, got %s" % type ( along ) ) axis = self . _axes [ axis_index ] # values & poin...
def contrast ( x , severity = 1 ) : """Change contrast of images . Args : x : numpy array , uncorrupted image , assumed to have uint8 pixel in [ 0,255 ] . severity : integer , severity of corruption . Returns : numpy array , image with uint8 pixels in [ 0,255 ] . Changed contrast ."""
c = [ 0.4 , .3 , .2 , .1 , .05 ] [ severity - 1 ] x = np . array ( x ) / 255. means = np . mean ( x , axis = ( 0 , 1 ) , keepdims = True ) x_clip = np . clip ( ( x - means ) * c + means , 0 , 1 ) * 255 return around_and_astype ( x_clip )
def verify_data_signature ( self , signature_url , data_url , data ) : """Verify data against it ' s remote signature : type signature _ url : str : param signature _ url : remote path to signature for data _ url : type data _ url : str : param data _ url : url from which data was fetched : type data : st...
req = requests . get ( signature_url ) if req . status_code is 200 : tm = int ( time . time ( ) ) datestamp = datetime . utcfromtimestamp ( tm ) . isoformat ( ) sigfile = "repo-{0}-tmp.sig" . format ( datestamp ) logger . debug ( "writing {0} to {1}" . format ( signature_url , sigfile ) ) with open ...
def remove_redundant_verts ( self , eps = 1e-10 ) : """Given verts and faces , this remove colocated vertices"""
import numpy as np from scipy . spatial import cKDTree # FIXME pylint : disable = no - name - in - module fshape = self . f . shape tree = cKDTree ( self . v ) close_pairs = list ( tree . query_pairs ( eps ) ) if close_pairs : close_pairs = np . sort ( close_pairs , axis = 1 ) # update faces to not refer to red...
def remake_images_variants ( profiles , clear = True ) : """Перестворює варіанти для картинок згідно налаштувань . profiles - список профілів , для картинок яких треба перестворити варіанти . clear - якщо True , тоді перед створенням варіантів будуть видалені ВСІ попередні варіанти ."""
assert isinstance ( profiles , ( list , tuple ) ) or profiles is None if profiles is None : profiles = dju_settings . DJU_IMG_UPLOAD_PROFILES . keys ( ) profiles = set ( ( 'default' , ) + tuple ( profiles ) ) removed = remade = 0 for profile in profiles : conf = get_profile_configs ( profile = profile ) roo...
def get_confidence ( self ) : """return confidence based on existing data"""
# if we didn ' t receive any character in our consideration range , # return negative answer if self . _mTotalChars <= 0 or self . _mFreqChars <= MINIMUM_DATA_THRESHOLD : return SURE_NO if self . _mTotalChars != self . _mFreqChars : r = ( self . _mFreqChars / ( ( self . _mTotalChars - self . _mFreqChars ) * sel...
def imagetransformer_sep_channels_8l_8h_local_and_global_att ( ) : """separate rgb embeddings ."""
hparams = imagetransformer_sep_channels_8l_8h ( ) hparams . num_heads = 8 hparams . batch_size = 1 hparams . attention_key_channels = hparams . attention_value_channels = 0 hparams . hidden_size = 256 hparams . filter_size = 256 hparams . num_hidden_layers = 4 hparams . sampling_method = "random" hparams . local_and_gl...
def autoformat_pep8 ( sourcecode , ** kwargs ) : r"""Args : code ( str ) : CommandLine : python - m utool . util _ str - - exec - autoformat _ pep8 Kwargs : ' aggressive ' : 0, ' diff ' : False , ' exclude ' : [ ] , ' experimental ' : False , ' files ' : [ u ' ' ] , ' global _ config ' : ~ / . c...
import autopep8 default_ignore = { 'E126' , # continuation line hanging - indent 'E127' , # continuation line over - indented for visual indent 'E201' , # whitespace after ' ( ' 'E202' , # whitespace before ' ] ' 'E203' , # whitespace before ' , ' 'E221' , # multiple spaces before operator 'E222' , # multiple spaces af...
def edit ( self , customer_id , data = { } , ** kwargs ) : """Edit Customer information from given dict Returns : Customer Dict which was edited"""
url = '{}/{}' . format ( self . base_url , customer_id ) return self . put_url ( url , data , ** kwargs )
def get_auth_from_url ( url ) : """Given a url with authentication components , extract them into a tuple of username , password . : rtype : ( str , str )"""
parsed = urlparse ( url ) try : auth = ( unquote ( parsed . username ) , unquote ( parsed . password ) ) except ( AttributeError , TypeError ) : auth = ( '' , '' ) return auth
def upload_news_picture ( self , file ) : """上传图文消息内的图片 。 : param file : 要上传的文件 , 一个 File - object : return : 返回的 JSON 数据包"""
return self . post ( url = "https://api.weixin.qq.com/cgi-bin/media/uploadimg" , params = { "access_token" : self . token } , files = { "media" : file } )
def recv ( self , timeout = - 1 ) : """Receive and item from our Sender . This will block unless our Sender is ready , either forever or unless * timeout * milliseconds ."""
if self . ready : return self . other . handover ( self ) return self . pause ( timeout = timeout )
def _extract ( self , resource ) : """Extract a single archive , returns Promise - > path to extraction result ."""
if isinstance ( resource , six . string_types ) : resource = resource_lib . Resource ( path = resource ) path = resource . path extract_method = resource . extract_method if extract_method == resource_lib . ExtractMethod . NO_EXTRACT : logging . info ( 'Skipping extraction for %s (method=NO_EXTRACT).' , path ) ...
def modify_ack_deadline ( self , items ) : """Modify the ack deadline for the given messages . Args : items ( Sequence [ ModAckRequest ] ) : The items to modify ."""
ack_ids = [ item . ack_id for item in items ] seconds = [ item . seconds for item in items ] request = types . StreamingPullRequest ( modify_deadline_ack_ids = ack_ids , modify_deadline_seconds = seconds ) self . _manager . send ( request )
def _find_group_coordinator_id ( self , group_id ) : """Find the broker node _ id of the coordinator of the given group . Sends a FindCoordinatorRequest message to the cluster . Will block until the FindCoordinatorResponse is received . Any errors are immediately raised . : param group _ id : The consumer g...
# Note : Java may change how this is implemented in KAFKA - 6791. # TODO add support for dynamically picking version of # GroupCoordinatorRequest which was renamed to FindCoordinatorRequest . # When I experimented with this , GroupCoordinatorResponse _ v1 didn ' t # match GroupCoordinatorResponse _ v0 and I couldn ' t ...
def load_streets ( self , filename ) : """Load up all streets in lowercase for easier matching . The file should have one street per line , with no extra characters . This isn ' t strictly required , but will vastly increase the accuracy ."""
with open ( filename , 'r' ) as f : for line in f : self . streets . append ( line . strip ( ) . lower ( ) )
def t_bin_ZERO ( t ) : r'[ ^ 01]'
t . lexer . begin ( 'INITIAL' ) t . type = 'NUMBER' t . value = 0 t . lexer . lexpos -= 1 return t
def calculate_curvature_tangent ( self , step_range = False , step = None , store_tangent = False ) : """To calculate curvatures and tangent vectors along the helical axis . The curvature and tangent vectors are calculated using Frenet - Serret formula . The calculated values are stored in ` ` DNA . data ` ` di...
if not self . smooth_axis : raise ValueError ( "The helical axis is not smooth. At first, smooth the axis using generate_smooth_axis() method as described in http://rjdkmr.github.io/do_x3dna/apidoc.html#dnaMD.DNA.generate_smooth_axis." ) if ( step_range ) and ( step == None ) : raise ValueError ( "See, document...
def start_server ( self ) : """Starts the TCP stream server , binding to the configured host and port . Host and port are configured via the command line arguments . . . note : : The server does not process requests unless : meth : ` handle ` is called in regular intervals ."""
if self . _server is None : if self . _options . telnet_mode : self . interface . in_terminator = '\r\n' self . interface . out_terminator = '\r\n' self . _server = StreamServer ( self . _options . bind_address , self . _options . port , self . interface , self . device_lock )
async def main ( loop ) : """Log packets from Bus ."""
# Setting debug PYVLXLOG . setLevel ( logging . DEBUG ) stream_handler = logging . StreamHandler ( ) stream_handler . setLevel ( logging . DEBUG ) PYVLXLOG . addHandler ( stream_handler ) # Connecting to KLF 200 pyvlx = PyVLX ( 'pyvlx.yaml' , loop = loop ) await pyvlx . load_scenes ( ) await pyvlx . load_nodes ( ) # an...
def _create_options ( self , items ) : """Helper method to create options from list , or instance . Applies preprocess method if available to create a uniform output"""
return OrderedDict ( map ( lambda x : ( x . name , x ) , coerce_to_list ( items , self . preprocess ) ) )
def start ( self ) : """Starts the camera recording process ."""
self . _started = True self . _camera = _Camera ( self . _actual_camera , self . _cmd_q , self . _res , self . _codec , self . _fps , self . _rate ) self . _camera . start ( )
def rename ( self , ** kwargs ) : '''Rename series in the group .'''
for old , new in kwargs . iteritems ( ) : if old in self . groups : self . groups [ new ] = self . groups [ old ] del self . groups [ old ]
def from_string ( cls , string , format_ = None , fps = None , ** kwargs ) : """Load subtitle file from string . See : meth : ` SSAFile . load ( ) ` for full description . Arguments : string ( str ) : Subtitle file in a string . Note that the string must be Unicode ( in Python 2 ) . Returns : SSAFile ...
fp = io . StringIO ( string ) return cls . from_file ( fp , format_ , fps = fps , ** kwargs )
def get ( self , name ) : """Returns a Vxlan interface as a set of key / value pairs The Vxlan interface resource returns the following : * name ( str ) : The name of the interface * type ( str ) : Always returns ' vxlan ' * source _ interface ( str ) : The vxlan source - interface value * multicast _ gro...
config = self . get_block ( '^interface %s' % name ) if not config : return None response = super ( VxlanInterface , self ) . get ( name ) response . update ( dict ( name = name , type = 'vxlan' ) ) response . update ( self . _parse_source_interface ( config ) ) response . update ( self . _parse_multicast_group ( c...
def unflatten ( flat_weights ) : """Pivot weights from long DataFrame into weighting matrix . Parameters flat _ weights : pandas . DataFrame A long DataFrame of weights , where columns are " date " , " contract " , " generic " , " weight " and optionally " key " . If " key " column is present a dictionary...
# NOQA if flat_weights . columns . contains ( "key" ) : weights = { } for key in flat_weights . loc [ : , "key" ] . unique ( ) : flt_wts = flat_weights . loc [ flat_weights . loc [ : , "key" ] == key , : ] flt_wts = flt_wts . drop ( labels = "key" , axis = 1 ) wts = flt_wts . pivot_table...
def paramsReport ( self ) : """See docs for ` Model ` abstract base class ."""
report = { } for param in self . _REPORTPARAMS : pvalue = getattr ( self , param ) if isinstance ( pvalue , float ) : report [ param ] = pvalue elif isinstance ( pvalue , scipy . ndarray ) and pvalue . shape == ( 3 , N_NT ) : for p in range ( 3 ) : for w in range ( N_NT - 1 ) : ...
def http_form_post_message ( message , location , relay_state = "" , typ = "SAMLRequest" , ** kwargs ) : """The HTTP POST binding defines a mechanism by which SAML protocol messages may be transmitted within the base64 - encoded content of a HTML form control . : param message : The message : param location...
if not isinstance ( message , six . string_types ) : message = str ( message ) if not isinstance ( message , six . binary_type ) : message = message . encode ( 'utf-8' ) if typ == "SAMLRequest" or typ == "SAMLResponse" : _msg = base64 . b64encode ( message ) else : _msg = message _msg = _msg . decode ( ...
def alias ( self , aliases , stats ) : """Apply the login / email alias if configured ."""
login = email = None if stats is None : return # Attempt to use alias directly from the config section try : config = dict ( Config ( ) . section ( stats ) ) try : email = config [ "email" ] except KeyError : pass try : login = config [ "login" ] except KeyError : ...
def set_interact_items ( glob ) : """This function prepares the interaction items for inclusion in main script ' s global scope . : param glob : main script ' s global scope dictionary reference"""
a , l = glob [ 'args' ] , glob [ 'logger' ] enabled = getattr ( a , a . _collisions . get ( "interact" ) or "interact" , False ) if enabled : readline . parse_and_bind ( 'tab: complete' ) # InteractiveConsole as defined in the code module , but handling a banner # using the logging of tinyscript class InteractiveCo...
def load_initial_files ( self , locations , in_tab_pages = False , hsplit = False , vsplit = False ) : """Load a list of files ."""
assert in_tab_pages + hsplit + vsplit <= 1 # Max one of these options . # When no files were given , open at least one empty buffer . locations2 = locations or [ None ] # First file self . window_arrangement . open_buffer ( locations2 [ 0 ] ) for f in locations2 [ 1 : ] : if in_tab_pages : self . window_arr...
def ecef2aer ( x : float , y : float , z : float , lat0 : float , lon0 : float , h0 : float , ell = None , deg : bool = True ) -> Tuple [ float , float , float ] : """gives azimuth , elevation and slant range from an Observer to a Point with ECEF coordinates . ECEF input location is with units of meters Paramet...
xEast , yNorth , zUp = ecef2enu ( x , y , z , lat0 , lon0 , h0 , ell , deg = deg ) return enu2aer ( xEast , yNorth , zUp , deg = deg )