signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def set_bucket_props ( self , bucket , props ) : """Serialize set bucket property request and deserialize response"""
if not self . pb_all_bucket_props ( ) : for key in props : if key not in ( 'n_val' , 'allow_mult' ) : raise NotImplementedError ( 'Server only supports n_val and ' 'allow_mult properties over PBC' ) msg_code = riak . pb . messages . MSG_CODE_SET_BUCKET_REQ codec = self . _get_codec ( msg_code ) ...
def change_range_cb ( self , setting , value , fitsimage ) : """This method is called when the cut level values ( lo / hi ) have changed in a channel . We adjust them in the ColorBar to match ."""
if not self . gui_up : return if fitsimage != self . fv . getfocus_viewer ( ) : # values have changed in a channel that doesn ' t have the focus return False loval , hival = value self . colorbar . set_range ( loval , hival )
def set_bios_configuration ( irmc_info , settings ) : """Set BIOS configurations on the server . : param irmc _ info : node info : param settings : Dictionary containing the BIOS configuration . : raise : BiosConfigNotFound , if there is wrong settings for bios configuration ."""
bios_config_data = { 'Server' : { 'SystemConfig' : { 'BiosConfig' : { } } } } versions = elcm_profile_get_versions ( irmc_info ) server_version = versions [ 'Server' ] . get ( '@Version' ) bios_version = versions [ 'Server' ] [ 'SystemConfig' ] [ 'BiosConfig' ] . get ( '@Version' ) if server_version : bios_config_d...
def chunk_pandas ( frame_or_series , chunksize = None ) : """Chunk a frame into smaller , equal parts ."""
if not isinstance ( chunksize , int ) : raise ValueError ( 'argument chunksize needs to be integer type' ) bins = np . arange ( 0 , len ( frame_or_series ) , step = chunksize ) for b in bins : yield frame_or_series [ b : b + chunksize ]
def get_undo_redo_list_from_active_trail_history_item_to_version_id ( self , version_id ) : """Perform fast search from currently active branch to specific version _ id and collect all recovery steps ."""
all_trail_action = [ a . version_id for a in self . single_trail_history ( ) if a is not None ] all_active_action = self . get_all_active_actions ( ) undo_redo_list = [ ] _undo_redo_list = [ ] intermediate_version_id = version_id if self . with_verbose : logger . verbose ( "Version_id : {0} in" . format ( interm...
def till ( self ) : """Queries the current shop till and returns the amount Returns str - - Amount of NPs in shop till Raises parseException"""
pg = self . usr . getPage ( "http://www.neopets.com/market.phtml?type=till" ) try : return pg . find_all ( text = "Shop Till" ) [ 1 ] . parent . next_sibling . b . text . replace ( " NP" , "" ) . replace ( "," , "" ) except Exception : logging . getLogger ( "neolib.shop" ) . exception ( "Could not grab shop til...
def graceful_stop ( self , signal_number = None , stack_frame = None ) : """This function will be called when a graceful - stop is initiated ."""
stop_msg = "Hard" if self . shutdown else "Graceful" if signal_number is None : self . log . info ( "%s stop called manually. " "Shutting down." , stop_msg ) else : self . log . info ( "%s stop called by signal #%s. Shutting down." "Stack Frame: %s" , stop_msg , signal_number , stack_frame ) self . shutdown = T...
def _parse_peer_link ( self , config ) : """Scans the config block and parses the peer - link value Args : config ( str ) : The config block to scan Returns : dict : A dict object that is intended to be merged into the resource dict"""
match = re . search ( r'peer-link (\S+)' , config ) value = match . group ( 1 ) if match else None return dict ( peer_link = value )
def upper2_for_ramp_wall ( self ) -> Set [ Point2 ] : """Returns the 2 upper ramp points of the main base ramp required for the supply depot and barracks placement properties used in this file ."""
if len ( self . upper ) > 5 : # NOTE : this was way too slow on large ramps return set ( ) # HACK : makes this work for now # FIXME : please do upper2 = sorted ( list ( self . upper ) , key = lambda x : x . distance_to ( self . bottom_center ) , reverse = True ) while len ( upper2 ) > 2 : upper2 . pop ( ) retur...
def _to_variable_type ( x ) : """Convert CWL variables to WDL variables , handling nested arrays ."""
var_mapping = { "string" : "String" , "File" : "File" , "null" : "String" , "long" : "Float" , "int" : "Int" } if isinstance ( x , dict ) : if x [ "type" ] == "record" : return "Object" else : assert x [ "type" ] == "array" , x return "Array[%s]" % _to_variable_type ( x [ "items" ] ) eli...
def box_iter ( self ) : """Get an iterator over all boxes in the Sudoku"""
for i in utils . range_ ( self . order ) : for j in utils . range_ ( self . order ) : yield self . box ( i * 3 , j * 3 )
def rotate_point ( self , p ) : """Rotate a Point instance using this quaternion ."""
# Prepare p = Quaternion ( 0 , p [ 0 ] , p [ 1 ] , p [ 2 ] , False ) # Do not normalize ! q1 = self . normalize ( ) q2 = self . inverse ( ) # Apply rotation r = ( q1 * p ) * q2 # Make point and return return r . x , r . y , r . z
def run ( self , address , port , unix_path ) : """Starts the Daemon , handling commands until interrupted . @ return False if error . Runs indefinitely otherwise ."""
assert address or unix_path if unix_path : sock = bind_unix_socket ( unix_path ) else : sock = bind_socket ( address , port ) if sock is None : return False sock . setblocking ( False ) inputs = [ sock ] outputs = [ ] try : while True : readable , _ , _ = select . select ( inputs , outputs , inp...
def replace_chars ( astring ) : """Replace certain unicode characters to avoid errors when trying to read various strings . Returns str"""
for k , v in CHAR_REPLACE . items ( ) : astring = astring . replace ( k , v ) return astring
def dataset ( node_parser , include = lambda x : True , input_transform = None , target_transform = None ) : """Convert immediate children of a GroupNode into a torch . data . Dataset Keyword arguments * node _ parser = callable that converts a DataNode to a Dataset item * include = lambda x : True lambda (...
def _dataset ( node , paths ) : # pylint : disable = unused - argument return DatasetFromGroupNode ( node , node_parser = node_parser , include = include , input_transform = input_transform , target_transform = target_transform ) return _dataset
def catch_timeout ( f ) : """A decorator to handle read timeouts from Twitter ."""
def new_f ( self , * args , ** kwargs ) : try : return f ( self , * args , ** kwargs ) except ( requests . exceptions . ReadTimeout , requests . packages . urllib3 . exceptions . ReadTimeoutError ) as e : log . warning ( "caught read timeout: %s" , e ) self . connect ( ) return f...
def set_remote ( self , key = None , value = None , data = None , scope = None , ** kwdata ) : """Set data for the remote end ( s ) of the : class : ` Conversation ` with the given scope . In Python , this is equivalent to : : relation . conversation ( scope ) . set _ remote ( key , value , data , scope , * * k...
self . conversation ( scope ) . set_remote ( key , value , data , ** kwdata )
def percent_change ( value , decimal_places = 1 , multiply = True , failure_string = 'N/A' ) : """Converts a floating point value into a percentage change value . Number of decimal places set by the ` precision ` kwarg . Default is one . Non - floats are assumed to be zero division errors and are presented as ...
try : f = float ( value ) if multiply : f = f * 100 except ValueError : return failure_string s = _saferound ( f , decimal_places ) if f > 0 : return '+' + s + '%' else : return s + '%'
def time_recommendation ( move_num , seconds_per_move = 5 , time_limit = 15 * 60 , decay_factor = 0.98 ) : """Given the current move number and the ' desired ' seconds per move , return how much time should actually be used . This is intended specifically for CGOS time controls , which has an absolute 15 - minu...
# Divide by two since you only play half the moves in a game . player_move_num = move_num / 2 # Sum of geometric series maxes out at endgame _ time seconds . endgame_time = seconds_per_move / ( 1 - decay_factor ) if endgame_time > time_limit : # There is so little main time that we ' re already in ' endgame ' mode . ...
def _Constructor ( cls , ptr = _internal_guard ) : """( INTERNAL ) New wrapper from ctypes ."""
if ptr == _internal_guard : raise VLCException ( "(INTERNAL) ctypes class. You should get references for this class through methods of the LibVLC API." ) if ptr is None or ptr == 0 : return None return _Cobject ( cls , ctypes . c_void_p ( ptr ) )
def annotated ( self ) : """Return an AnnotatedGraph with the same structure as this graph ."""
annotated_vertices = { vertex : AnnotatedVertex ( id = vertex_id , annotation = six . text_type ( vertex ) , ) for vertex_id , vertex in zip ( itertools . count ( ) , self . vertices ) } annotated_edges = [ AnnotatedEdge ( id = edge_id , annotation = six . text_type ( edge ) , head = annotated_vertices [ self . head ( ...
def get_lookup ( self , main_field , for_remote , alias ) : """create a fake field for the lookup capability : param CompositeForeignKey main _ field : the local fk : param Field for _ remote : the remote field to match : return :"""
lookup_class = for_remote . get_lookup ( "exact" ) return lookup_class ( for_remote . get_col ( alias ) , self . value )
def _should_recover ( self , exception ) : """Determine if an error on the RPC stream should be recovered . If the exception is one of the retryable exceptions , this will signal to the consumer thread that it should " recover " from the failure . This will cause the stream to exit when it returns : data : ` ...
exception = _maybe_wrap_exception ( exception ) # If this is in the list of idempotent exceptions , then we want to # recover . if isinstance ( exception , _RETRYABLE_STREAM_ERRORS ) : _LOGGER . info ( "Observed recoverable stream error %s" , exception ) return True _LOGGER . info ( "Observed non-recoverable st...
def get_posterior ( self , twig = None , feedback = None , ** kwargs ) : """[ NOT IMPLEMENTED ] : raises NotImplementedError : because it isn ' t"""
raise NotImplementedError kwargs [ 'context' ] = 'posterior' return self . filter ( twig = twig , ** kwargs )
def removed ( self ) : """Return the total number of deleted lines in the file . : return : int lines _ deleted"""
removed = 0 for line in self . diff . replace ( '\r' , '' ) . split ( "\n" ) : if line . startswith ( '-' ) and not line . startswith ( '---' ) : removed += 1 return removed
def desymbolize ( self ) : """We believe this was a pointer and symbolized it before . Now we want to desymbolize it . The following actions are performed : - Reload content from memory - Mark the sort as ' unknown ' : return : None"""
self . sort = 'unknown' content = self . binary . fast_memory_load ( self . addr , self . size , bytes ) self . content = [ content ]
def new_sent ( self , text , ID = None , ** kwargs ) : '''Create a new sentence and add it to this Document'''
if ID is None : ID = next ( self . __idgen ) return self . add_sent ( Sentence ( text , ID = ID , ** kwargs ) )
def write_paula ( docgraph , output_root_dir , human_readable = False ) : """converts a DiscourseDocumentGraph into a set of PAULA XML files representing the same document . Parameters docgraph : DiscourseDocumentGraph the document graph to be converted"""
paula_document = PaulaDocument ( docgraph , human_readable = human_readable ) error_msg = ( "Please specify an output directory.\nPaula documents consist" " of multiple files, so we can't just pipe them to STDOUT." ) assert isinstance ( output_root_dir , str ) , error_msg document_dir = os . path . join ( output_root_d...
def eval_js ( self , expr ) : """Evaluate a Javascript expression ."""
if not self . is_built ( ) : self . _pending_js_eval . append ( expr ) return logger . log ( 5 , "Evaluate Javascript: `%s`." , expr ) out = self . page ( ) . mainFrame ( ) . evaluateJavaScript ( expr ) return _to_py ( out )
def _from_dict ( cls , _dict ) : """Initialize a RecognitionJobs object from a json dictionary ."""
args = { } if 'recognitions' in _dict : args [ 'recognitions' ] = [ RecognitionJob . _from_dict ( x ) for x in ( _dict . get ( 'recognitions' ) ) ] else : raise ValueError ( 'Required property \'recognitions\' not present in RecognitionJobs JSON' ) return cls ( ** args )
def to_kaf ( self ) : """Converts the element to NAF"""
if self . type == 'NAF' : # # convert all the properties for node in self . node . findall ( 'properties/property' ) : node . set ( 'pid' , node . get ( 'id' ) ) del node . attrib [ 'id' ]
def get_route ( ip ) : '''Return routing information for given destination ip . . versionadded : : 2015.5.3 . . versionchanged : : 2015.8.0 Added support for SunOS ( Solaris 10 , Illumos , SmartOS ) Added support for OpenBSD . . versionchanged : : 2016.11.4 Added support for AIX CLI Example : : salt...
if __grains__ [ 'kernel' ] == 'Linux' : cmd = 'ip route get {0}' . format ( ip ) out = __salt__ [ 'cmd.run' ] ( cmd , python_shell = True ) regexp = re . compile ( r'(via\s+(?P<gateway>[\w\.:]+))?\s+dev\s+(?P<interface>[\w\.\:\-]+)\s+.*src\s+(?P<source>[\w\.:]+)' ) m = regexp . search ( out . splitlines...
def jwt_is_expired ( self , access_token = None , leeway = 0 ) : """Validate JWT access token expiration . Args : access _ token ( str ) : Access token to validate . Defaults to ` ` None ` ` . leeway ( float ) : Time in seconds to adjust for local clock skew . Defaults to 0. Returns : bool : ` ` True ` ` ...
if access_token is not None : exp = self . _decode_exp ( access_token ) else : exp = self . jwt_exp now = time ( ) if exp < ( now - leeway ) : return True return False
def fast_exit ( code ) : """Exit without garbage collection , this speeds up exit by about 10ms for things like bash completion ."""
sys . stdout . flush ( ) sys . stderr . flush ( ) os . _exit ( code )
async def execute_command ( self , container , * args ) : '''Execute command on Redis server : - For ( P ) SUBSCRIBE / ( P ) UNSUBSCRIBE , the command is sent to the subscribe connection . It is recommended to use ( p ) subscribe / ( p ) unsubscribe method instead of directly call the command - For BLPOP , BR...
if args : cmd = _str ( args [ 0 ] ) . upper ( ) if cmd in ( 'SUBSCRIBE' , 'UNSUBSCRIBE' , 'PSUBSCRIBE' , 'PUNSUBSCRIBE' ) : await self . _get_subscribe_connection ( container ) return await self . _protocol . execute_command ( self . _subscribeconn , container , * args ) elif cmd in ( 'BLPOP...
def process_csr ( cls , common_name , csr = None , private_key = None , country = None , state = None , city = None , organisation = None , branch = None ) : """Create a PK and a CSR if needed ."""
if csr : if branch or organisation or city or state or country : cls . echo ( 'Following options are only used to generate' ' the CSR.' ) else : params = ( ( 'CN' , common_name ) , ( 'OU' , branch ) , ( 'O' , organisation ) , ( 'L' , city ) , ( 'ST' , state ) , ( 'C' , country ) ) params = [ ( key ,...
def send_file ( self , url , name , ** fileinfo ) : """Send a pre - uploaded file to the room . See http : / / matrix . org / docs / spec / r0.2.0 / client _ server . html # m - file for fileinfo . Args : url ( str ) : The mxc url of the file . name ( str ) : The filename of the image . fileinfo ( ) : E...
return self . client . api . send_content ( self . room_id , url , name , "m.file" , extra_information = fileinfo )
def asarray ( self , key = None , series = None , out = None , validate = True , maxworkers = None ) : """Return image data from selected TIFF page ( s ) as numpy array . By default , the data from the first series is returned . Parameters key : int , slice , or sequence of indices Defines which pages to re...
if not self . pages : return numpy . array ( [ ] ) if key is None and series is None : series = 0 if series is None : pages = self . pages else : try : series = self . series [ series ] except ( KeyError , TypeError ) : pass pages = series . pages if key is None : pass elif s...
def frequency2phase ( freqdata , rate ) : """integrate fractional frequency data and output phase data Parameters freqdata : np . array Data array of fractional frequency measurements ( nondimensional ) rate : float The sampling rate for phase or frequency , in Hz Returns phasedata : np . array Time...
dt = 1.0 / float ( rate ) # Protect against NaN values in input array ( issue # 60) # Reintroduces data trimming as in commit 503cb82 freqdata = trim_data ( freqdata ) phasedata = np . cumsum ( freqdata ) * dt phasedata = np . insert ( phasedata , 0 , 0 ) # FIXME : why do we do this ? # so that phase starts at zero and...
def remove ( self , list ) : """Removes a list from the site ."""
xml = SP . DeleteList ( SP . listName ( list . id ) ) self . opener . post_soap ( LIST_WEBSERVICE , xml , soapaction = 'http://schemas.microsoft.com/sharepoint/soap/DeleteList' ) self . all_lists . remove ( list )
def get_item_content ( self , repository_id , path , project = None , scope_path = None , recursion_level = None , include_content_metadata = None , latest_processed_change = None , download = None , version_descriptor = None , include_content = None , resolve_lfs = None , ** kwargs ) : """GetItemContent . Get It...
route_values = { } if project is not None : route_values [ 'project' ] = self . _serialize . url ( 'project' , project , 'str' ) if repository_id is not None : route_values [ 'repositoryId' ] = self . _serialize . url ( 'repository_id' , repository_id , 'str' ) query_parameters = { } if path is not None : q...
def _on_access_token ( self , future , response ) : """Invoked as a callback when StackExchange has returned a response to the access token request . : param method future : The callback method to pass along : param tornado . httpclient . HTTPResponse response : The HTTP response"""
LOGGER . info ( response . body ) content = escape . json_decode ( response . body ) if 'error' in content : LOGGER . error ( 'Error fetching access token: %s' , content [ 'error' ] ) future . set_exception ( auth . AuthError ( 'StackExchange auth error: %s' % str ( content [ 'error' ] ) ) ) return callback...
def download ( self , file : Optional [ IO ] = None , rewind : bool = True , duration_timeout : Optional [ float ] = None ) -> Response : '''Read the response content into file . Args : file : A file object or asyncio stream . rewind : Seek the given file back to its original offset after reading is finishe...
if self . _session_state != SessionState . file_request_sent : raise RuntimeError ( 'File request not sent' ) if rewind and file and hasattr ( file , 'seek' ) : original_offset = file . tell ( ) else : original_offset = None if not hasattr ( file , 'drain' ) : self . _response . body = file if not i...
def ik_robot_eef_joint_cartesian_pose ( self ) : """Returns the current cartesian pose of the last joint of the ik robot with respect to the base frame as a ( pos , orn ) tuple where orn is a x - y - z - w quaternion"""
eef_pos_in_world = np . array ( p . getLinkState ( self . ik_robot , 6 ) [ 0 ] ) eef_orn_in_world = np . array ( p . getLinkState ( self . ik_robot , 6 ) [ 1 ] ) eef_pose_in_world = T . pose2mat ( ( eef_pos_in_world , eef_orn_in_world ) ) base_pos_in_world = np . array ( p . getBasePositionAndOrientation ( self . ik_ro...
def pipe ( self , command , timeout = None , cwd = None ) : """Runs the current command and passes its output to the next given process ."""
if not timeout : timeout = self . timeout if not self . was_run : self . run ( block = False , cwd = cwd ) data = self . out if timeout : c = Command ( command , timeout ) else : c = Command ( command ) c . run ( block = False , cwd = cwd ) if data : c . send ( data ) c . block ( ) return c
def list_unit_states ( self , machine_id = None , unit_name = None ) : """Return the current UnitState for the fleet cluster Args : machine _ id ( str ) : filter all UnitState objects to those originating from a specific machine unit _ name ( str ) : filter all UnitState objects to those related to a spec...
for page in self . _request ( 'UnitState.List' , machineID = machine_id , unitName = unit_name ) : for state in page . get ( 'states' , [ ] ) : yield UnitState ( data = state )
def assets ( lon = None , lat = None , begin = None , end = None ) : '''HTTP REQUEST GET https : / / api . nasa . gov / planetary / earth / assets QUERY PARAMETERS ParameterTypeDefaultDescription latfloatn / aLatitude lonfloatn / aLongitude beginYYYY - MM - DDn / abeginning of date range end YYYY - MM...
base_url = "https://api.nasa.gov/planetary/earth/assets?" if not lon or not lat : raise ValueError ( "assets endpoint expects lat and lon, type has to be float. Call the method with keyword args. Ex : lon=100.75, lat=1.5" ) else : try : validate_float ( lon , lat ) # Floats are entered / display...
def _write_lat_lon ( data_out_nc , rivid_lat_lon_z_file ) : """Add latitude and longitude each netCDF feature Lookup table is a CSV file with rivid , Lat , Lon , columns . Columns must be in that order and these must be the first three columns ."""
# only add if user adds if rivid_lat_lon_z_file and os . path . exists ( rivid_lat_lon_z_file ) : # get list of COMIDS lookup_table = np . loadtxt ( rivid_lat_lon_z_file , delimiter = "," , usecols = ( 0 , 1 , 2 ) , skiprows = 1 , dtype = { 'names' : ( 'rivid' , 'lat' , 'lon' ) , 'formats' : ( 'i8' , 'f8' , 'f8' ) ...
def _head ( self , client_kwargs ) : """Returns object HTTP header . Args : client _ kwargs ( dict ) : Client arguments . Returns : dict : HTTP header ."""
with _handle_client_exception ( ) : # Object if 'obj' in client_kwargs : return self . client . head_object ( ** client_kwargs ) # Container return self . client . head_container ( ** client_kwargs )
def convert_unicode_to_str ( data ) : """Py2 , always translate to utf8 from unicode Py3 , always translate to unicode : param data : : return :"""
if six . PY2 and isinstance ( data , six . text_type ) : return data . encode ( 'utf8' ) elif six . PY3 and isinstance ( data , six . binary_type ) : return data . decode ( 'utf8' ) elif isinstance ( data , collections . Mapping ) : return dict ( ( Util . convert_unicode_to_str ( k ) , Util . convert_unicod...
def update ( self , ** kwargs ) : u"""Updating or creation of new simple nodes . Each dict key is used as a tagname and value as text ."""
for key , value in kwargs . items ( ) : helper = helpers . CAST_DICT . get ( type ( value ) , str ) tag = self . _get_aliases ( ) . get ( key , key ) elements = list ( self . _xml . iterchildren ( tag = tag ) ) if elements : for element in elements : element . text = helper ( value )...
def new_ipy ( s = '' ) : """Create a new IPython kernel ( optionally with extra arguments ) XXX : Allow passing of profile information here Examples new _ ipy ( )"""
# Modified by Bo Peng . # This package has been deprecated . Need to import from ipykernel from jupyter_client . manager import KernelManager km = KernelManager ( ) km . start_kernel ( ) return km_from_string ( km . connection_file )
def insertData ( self , offset : int , string : str ) -> None : """Insert ` ` string ` ` at offset on this node ."""
self . _insert_data ( offset , string )
def del_permission ( self , name ) : """Deletes a permission from the backend , model permission : param name : name of the permission : ' can _ add ' , ' can _ edit ' etc . . ."""
perm = self . find_permission ( name ) if perm : try : self . get_session . delete ( perm ) self . get_session . commit ( ) except Exception as e : log . error ( c . LOGMSG_ERR_SEC_DEL_PERMISSION . format ( str ( e ) ) ) self . get_session . rollback ( )
def import_prices ( self , prices : List [ PriceModel ] ) : """Import prices ( from csv )"""
result = { } for price in prices : result [ price . symbol ] = self . import_price ( price ) return result
def get_all_subdomains ( self , offset = None , count = None , min_sequence = None , cur = None ) : """Get and all subdomain names , optionally over a range"""
get_cmd = 'SELECT DISTINCT fully_qualified_subdomain FROM {}' . format ( self . subdomain_table ) args = ( ) if min_sequence is not None : get_cmd += ' WHERE sequence >= ?' args += ( min_sequence , ) if count is not None : get_cmd += ' LIMIT ?' args += ( count , ) if offset is not None : get_cmd += ...
def insert ( self , i , x ) : """Insert an item ( x ) at a given position ( i ) ."""
if i == len ( self ) : # end of list or empty list : append self . append ( x ) elif len ( self . matches ) > i : # create a new xml node at the requested position insert_index = self . matches [ i ] . getparent ( ) . index ( self . matches [ i ] ) _create_xml_node ( self . xast , self . node , self . conte...
def from_file ( xmu_dat_file = "xmu.dat" , feff_inp_file = "feff.inp" ) : """Get Xmu from file . Args : xmu _ dat _ file ( str ) : filename and path for xmu . dat feff _ inp _ file ( str ) : filename and path of feff . inp input file Returns : Xmu object"""
data = np . loadtxt ( xmu_dat_file ) header = Header . from_file ( feff_inp_file ) parameters = Tags . from_file ( feff_inp_file ) pots = Potential . pot_string_from_file ( feff_inp_file ) # site index ( Note : in feff it starts from 1) if "RECIPROCAL" in parameters : absorbing_atom = parameters [ "TARGET" ] # spec...
def plot_bhist ( samples , file_type , ** plot_args ) : """Create line graph plot of histogram data for BBMap ' bhist ' output . The ' samples ' parameter could be from the bbmap mod _ data dictionary : samples = bbmap . MultiqcModule . mod _ data [ file _ type ]"""
all_x = set ( ) for item in sorted ( chain ( * [ samples [ sample ] [ 'data' ] . items ( ) for sample in samples ] ) ) : all_x . add ( item [ 0 ] ) columns_to_plot = { 'GC' : { 1 : 'C' , 2 : 'G' , } , 'AT' : { 0 : 'A' , 3 : 'T' , } , 'N' : { 4 : 'N' } , } nucleotide_data = [ ] for column_type in columns_to_plot : ...
def createEditor ( self , parent , option , index ) : """Returns the widget used to edit the item specified by index for editing . The parent widget and style option are used to control how the editor widget appears . Args : parent ( QWidget ) : parent widget . option ( QStyleOptionViewItem ) : controls how e...
editor = QtGui . QLineEdit ( parent ) return editor
def integer_ceil ( a , b ) : '''Return the ceil integer of a div b .'''
quanta , mod = divmod ( a , b ) if mod : quanta += 1 return quanta
def _recv_get_response ( self , method_frame ) : '''Handle either get _ ok or get _ empty . This is a hack because the synchronous callback stack is expecting one method to satisfy the expectation . To keep that loop as tight as possible , work within those constraints . Use of get is not recommended anyway ....
if method_frame . method_id == 71 : return self . _recv_get_ok ( method_frame ) elif method_frame . method_id == 72 : return self . _recv_get_empty ( method_frame )
def hash64 ( key , seed ) : """Wrapper around mmh3 . hash64 to get us single 64 - bit value . This also does the extra work of ensuring that we always treat the returned values as big - endian unsigned long , like smhasher used to do ."""
hash_val = mmh3 . hash64 ( key , seed ) [ 0 ] return struct . unpack ( '>Q' , struct . pack ( 'q' , hash_val ) ) [ 0 ]
def log_prob ( self , hidden ) : r"""Computes log probabilities for all : math : ` n \ _ classes ` From : https : / / github . com / pytorch / pytorch / blob / master / torch / nn / modules / adaptive . py Args : hidden ( Tensor ) : a minibatch of examples Returns : log - probabilities of for each class :...
if self . n_clusters == 0 : logit = self . _compute_logit ( hidden , self . out_layers [ 0 ] . weight , self . out_layers [ 0 ] . bias , self . out_projs [ 0 ] ) return F . log_softmax ( logit , dim = - 1 ) else : # construct weights and biases weights , biases = [ ] , [ ] for i in range ( len ( self . ...
def assertFileEncodingNotEqual ( self , filename , encoding , msg = None ) : '''Fail if ` ` filename ` ` is encoded with the given ` ` encoding ` ` as determined by the ' ! = ' operator . Parameters filename : str , bytes , file - like encoding : str , bytes msg : str If not provided , the : mod : ` mar...
fencoding = self . _get_file_encoding ( filename ) fname = self . _get_file_name ( filename ) standardMsg = '%s is %s encoded' % ( fname , encoding ) self . assertNotEqual ( fencoding . lower ( ) , encoding . lower ( ) , self . _formatMessage ( msg , standardMsg ) )
def RQ_sigma ( self , sigma ) : """Given a policy ` sigma ` , return the reward vector ` R _ sigma ` and the transition probability matrix ` Q _ sigma ` . Parameters sigma : array _ like ( int , ndim = 1) Policy vector , of length n . Returns R _ sigma : ndarray ( float , ndim = 1) Reward vector for `...
if self . _sa_pair : sigma = np . asarray ( sigma ) sigma_indices = np . empty ( self . num_states , dtype = int ) _find_indices ( self . a_indices , self . a_indptr , sigma , out = sigma_indices ) R_sigma , Q_sigma = self . R [ sigma_indices ] , self . Q [ sigma_indices ] else : R_sigma = self . R ...
def set_theme ( self , theme ) : """Pick a palette from the list of supported THEMES . : param theme : The name of the theme to set ."""
if theme in THEMES : self . palette = THEMES [ theme ] if self . _scroll_bar : # TODO : fix protected access . self . _scroll_bar . _palette = self . palette
def _update_statechanges ( storage : SQLiteStorage ) : """Update each ContractReceiveChannelNew ' s channel _ state member by setting the ` mediation _ fee ` that was added to the NettingChannelState"""
batch_size = 50 batch_query = storage . batch_query_state_changes ( batch_size = batch_size , filters = [ ( '_type' , 'raiden.transfer.state_change.ContractReceiveChannelNew' ) , ] , ) for state_changes_batch in batch_query : updated_state_changes = list ( ) for state_change in state_changes_batch : dat...
def _phrase_doc_stream ( paths , n , tokenizer = word_tokenize ) : """Generator to feed sentences to the phrase model ."""
i = 0 p = Progress ( ) for path in paths : with open ( path , 'r' ) as f : for line in f : i += 1 p . print_progress ( i / n ) for sent in sent_tokenize ( line . lower ( ) ) : tokens = tokenizer ( sent ) yield tokens
def enter_diff_mode ( self , context_model = None ) : """Enter diff mode . Args : context _ model ( ` ContextModel ` ) : Context to diff against . If None , a copy of the current context is used ."""
assert not self . diff_mode self . diff_mode = True if context_model is None : self . diff_from_source = True self . diff_context_model = self . context_model . copy ( ) else : self . diff_from_source = False self . diff_context_model = context_model self . clear ( ) self . setColumnCount ( 5 ) self . r...
def write ( write_entry : FILE_WRITE_ENTRY ) : """Writes the contents of the specified file entry to its destination path ."""
output_path = environ . paths . clean ( write_entry . path ) make_output_directory ( output_path ) writer . write_file ( output_path , write_entry . contents )
def create ( cls , title , conn = None , google_user = None , google_password = None ) : """Create a new spreadsheet with the given ` ` title ` ` ."""
conn = Connection . connect ( conn = conn , google_user = google_user , google_password = google_password ) res = Resource ( type = 'spreadsheet' , title = title ) res = conn . docs_client . CreateResource ( res ) id = res . id . text . rsplit ( '%3A' , 1 ) [ - 1 ] return cls ( id , conn , resource = res )
def use_comparative_sequence_rule_enabler_rule_view ( self ) : """Pass through to provider SequenceRuleEnablerRuleLookupSession . use _ comparative _ sequence _ rule _ enabler _ rule _ view"""
self . _object_views [ 'sequence_rule_enabler_rule' ] = COMPARATIVE # self . _ get _ provider _ session ( ' sequence _ rule _ enabler _ rule _ lookup _ session ' ) # To make sure the session is tracked for session in self . _get_provider_sessions ( ) : try : session . use_comparative_sequence_rule_enabler_r...
def count_distinct_characters ( string : str ) -> int : """Given a string , find out how many distinct characters ( regardless of case ) it consists of . : param string : String to be analyzed : type string : str : return : Count of distinct characters : rtype : int > > > count _ distinct _ characters ( '...
return len ( set ( string . lower ( ) ) ) # convert string to lower case , create a set ( which eliminates duplicates ) , and then count the elements in the set
def nrmse_range ( simulated_array , observed_array , replace_nan = None , replace_inf = None , remove_neg = False , remove_zero = False ) : """Compute the range normalized root mean square error between the simulated and observed data . . . image : : / pictures / NRMSE _ Range . png * * Range : * * 0 ≤ NRMSE < ...
# Checking and cleaning the data simulated_array , observed_array = treat_values ( simulated_array , observed_array , replace_nan = replace_nan , replace_inf = replace_inf , remove_neg = remove_neg , remove_zero = remove_zero ) rmse_value = np . sqrt ( np . mean ( ( simulated_array - observed_array ) ** 2 ) ) obs_max =...
def setup_logging ( verbose = 0 , colors = False , name = None ) : """Configure console logging . Info and below go to stdout , others go to stderr . : param int verbose : Verbosity level . > 0 print debug statements . > 1 passed to sphinx - build . : param bool colors : Print color text in non - verbose mode ....
root_logger = logging . getLogger ( name ) root_logger . setLevel ( logging . DEBUG if verbose > 0 else logging . INFO ) formatter = ColorFormatter ( verbose > 0 , colors ) if colors : colorclass . Windows . enable ( ) handler_stdout = logging . StreamHandler ( sys . stdout ) handler_stdout . setFormatter ( formatt...
def live ( self , kill_port = False , check_url = None ) : """Starts a live server in a separate process and checks whether it is running . : param bool kill _ port : If ` ` True ` ` , processes running on the same port as ` ` self . port ` ` will be killed . : param str check _ url : URL where to check...
pid = port_in_use ( self . port , kill_port ) if pid : raise LiveAndLetDieError ( 'Port {0} is already being used by process {1}!' . format ( self . port , pid ) ) host = str ( self . host ) if re . match ( _VALID_HOST_PATTERN , host ) : with open ( os . devnull , "w" ) as devnull : if self . suppress_o...
def check_solution ( self ) -> bool : """Checks if the the found solution correctly reproduces the input . : return : True if solution correctly reproduces input bitstring map : rtype : Bool"""
if self . solution is None : raise AssertionError ( "You need to `run` this algorithm first" ) assert_map = create_bv_bitmap ( * self . solution ) return all ( [ assert_map [ k ] == v for k , v in self . input_bitmap . items ( ) ] )
def _remove_overlaps ( in_file , out_dir , data ) : """Remove regions that overlap with next region , these result in issues with PureCN ."""
out_file = os . path . join ( out_dir , "%s-nooverlaps%s" % utils . splitext_plus ( os . path . basename ( in_file ) ) ) if not utils . file_uptodate ( out_file , in_file ) : with file_transaction ( data , out_file ) as tx_out_file : with open ( in_file ) as in_handle : with open ( tx_out_file ,...
def verify_signature ( self , signature_filename , data_filename , keystore = None ) : """Verify a signature for a file . : param signature _ filename : The pathname to the file containing the signature . : param data _ filename : The pathname to the file containing the signed data . : param keystore : Th...
if not self . gpg : raise DistlibException ( 'verification unavailable because gpg ' 'unavailable' ) cmd = self . get_verify_command ( signature_filename , data_filename , keystore ) rc , stdout , stderr = self . run_command ( cmd ) if rc not in ( 0 , 1 ) : raise DistlibException ( 'verify command failed with e...
def call ( self , name , options = None , o = None ) : """Call another command . : param name : The command name : type name : str : param options : The options : type options : list or None : param o : The output : type o : cleo . outputs . output . Output"""
if options is None : options = [ ] command = self . get_application ( ) . find ( name ) options = [ ( 'command' , command . get_name ( ) ) ] + options return command . run ( ListInput ( options ) , o )
def getControllerStateWithPose ( self , eOrigin , unControllerDeviceIndex , unControllerStateSize = sizeof ( VRControllerState_t ) ) : """fills the supplied struct with the current state of the controller and the provided pose with the pose of the controller when the controller state was updated most recently . U...
fn = self . function_table . getControllerStateWithPose pControllerState = VRControllerState_t ( ) pTrackedDevicePose = TrackedDevicePose_t ( ) result = fn ( eOrigin , unControllerDeviceIndex , byref ( pControllerState ) , unControllerStateSize , byref ( pTrackedDevicePose ) ) return result , pControllerState , pTracke...
def _division ( divisor , dividend , remainder , base ) : """Get the quotient and remainder : param int divisor : the divisor : param dividend : the divident : type dividend : sequence of int : param int remainder : initial remainder : param int base : the base : returns : quotient and remainder : rty...
quotient = [ ] for value in dividend : remainder = remainder * base + value ( quot , rem ) = divmod ( remainder , divisor ) quotient . append ( quot ) if quot > 0 : remainder = rem return ( quotient , remainder )
def get_bibtex ( identifier ) : """Try to fetch BibTeX from a found identifier . . . note : : Calls the functions in the respective identifiers module . : param identifier : a tuple ( type , identifier ) with a valid type . : returns : A BibTeX string or ` ` None ` ` if an error occurred . # TODO : Should...
identifier_type , identifier_id = identifier if identifier_type not in __valid_identifiers__ : return None # Dynamically call the ` ` get _ bibtex ` ` method from the associated module . module = sys . modules . get ( "libbmc.%s" % ( identifier_type , ) , None ) if module is None : return None return getattr ( ...
def messages ( self ) : '''A generator yielding the : class : ` MacIndexMessage ` structures in this index file .'''
# The file contains the fixed - size file header followed by # fixed - size message structures , followed by minimal message # information ( subject , from , to ) . Start after the file # header and then simply return the message structures in # sequence until we have returned the number of messages in # this folder , ...
def full_installation ( self , location = None ) : """Return the full details of the installation ."""
url = ( "https://tccna.honeywell.com/WebAPI/emea/api/v1/location" "/%s/installationInfo?includeTemperatureControlSystems=True" % self . _get_location ( location ) ) response = requests . get ( url , headers = self . _headers ( ) ) response . raise_for_status ( ) return response . json ( )
def _lw_decode ( self , msg ) : """LW : temperatures from all keypads and zones 1-16."""
keypad_temps = [ ] zone_temps = [ ] for i in range ( 16 ) : keypad_temps . append ( int ( msg [ 4 + 3 * i : 7 + 3 * i ] ) - 40 ) zone_temps . append ( int ( msg [ 52 + 3 * i : 55 + 3 * i ] ) - 60 ) return { 'keypad_temps' : keypad_temps , 'zone_temps' : zone_temps }
def _to_dict ( self ) : """Return a json dictionary representing this model ."""
_dict = { } if hasattr ( self , 'credential_type' ) and self . credential_type is not None : _dict [ 'credential_type' ] = self . credential_type if hasattr ( self , 'client_id' ) and self . client_id is not None : _dict [ 'client_id' ] = self . client_id if hasattr ( self , 'enterprise_id' ) and self . enterpr...
def compute_ecc_params ( max_block_size , rate , hasher ) : '''Compute the ecc parameters ( size of the message , size of the hash , size of the ecc ) . This is an helper function to easily compute the parameters from a resilience rate to instanciate an ECCMan object .'''
# message _ size = max _ block _ size - int ( round ( max _ block _ size * rate * 2 , 0 ) ) # old way to compute , wasn ' t really correct because we applied the rate on the total message + ecc size , when we should apply the rate to the message size only ( that is not known beforehand , but we want the ecc size ( k ) ...
def validate_results ( self , results , checks = None ) : '''Valdiate results from the Anisble Run .'''
results [ 'status' ] = 'PASS' failed_hosts = [ ] # First validation is to make sure connectivity to # all the hosts was ok . if results [ 'dark' ] : print "Host connectivity issues on %s" , results [ 'dark' ] . keys ( ) failed_hosts . append ( results [ 'dark' ] . keys ( ) ) results [ 'status' ] = 'FAIL...
def read_file ( self , path , ** kwargs ) : """Read file input into memory , returning deserialized objects : param path : Path of file to read"""
try : parsed_data = Parser ( ) . parse_file ( path ) return parsed_data except ( IOError , TypeError , ImportError ) : LOGGER . warning ( "Error reading file: {0}" . format ( path ) ) return None
def get_config ( self , hostname ) : """Returns a configuration for hostname ."""
version , config = self . _get ( self . associations . get ( hostname ) ) return config
def assert_variable_type ( variable , expected_type , raise_exception = True ) : """Return True if a variable is of a certain type or types . Otherwise raise a ValueError exception . Positional arguments : variable - - the variable to be checked expected _ type - - the expected type or types of the variable...
# if expected type is not a list make it one if not isinstance ( expected_type , list ) : expected_type = [ expected_type ] # make sure all entries in the expected _ type list are types for t in expected_type : if not isinstance ( t , type ) : raise ValueError ( 'expected_type argument "%s" is not a typ...
def Realization ( M , C , * args , ** kwargs ) : """f = Realization ( M , C [ , init _ mesh , init _ vals , check _ repeats = True , regularize = True ] ) Returns a realization from a Gaussian process . : Arguments : - ` M ` : A Gaussian process mean function . - ` C ` : A Covariance instance . - ` init _...
if isinstance ( C , BasisCovariance ) : return BasisRealization ( M , C , * args , ** kwargs ) else : return StandardRealization ( M , C , * args , ** kwargs )
def dogeo_V ( indat ) : """Rotates declination and inclination into geographic coordinates using the azimuth and plunge of the X direction ( lab arrow ) of a specimen . Parameters indat : nested list of [ dec , inc , az , pl ] data Returns rotated _ directions : arrays of Declinations and Inclinations"""
indat = indat . transpose ( ) # unpack input array into separate arrays dec , inc , az , pl = indat [ 0 ] , indat [ 1 ] , indat [ 2 ] , indat [ 3 ] Dir = np . array ( [ dec , inc ] ) . transpose ( ) X = dir2cart ( Dir ) . transpose ( ) # get cartesian coordinates N = np . size ( dec ) A1 = dir2cart ( np . array ( [ az ...
def send_generic_message ( self , recipient_id , elements , notification_type = NotificationType . regular ) : """Send generic messages to the specified recipient . https : / / developers . facebook . com / docs / messenger - platform / send - api - reference / generic - template Input : recipient _ id : reci...
return self . send_message ( recipient_id , { "attachment" : { "type" : "template" , "payload" : { "template_type" : "generic" , "elements" : elements } } } , notification_type )
def make_function ( function , name , arity ) : """Make a function node , a representation of a mathematical relationship . This factory function creates a function node , one of the core nodes in any program . The resulting object is able to be called with NumPy vectorized arguments and return a resulting ve...
if not isinstance ( arity , int ) : raise ValueError ( 'arity must be an int, got %s' % type ( arity ) ) if not isinstance ( function , np . ufunc ) : if function . __code__ . co_argcount != arity : raise ValueError ( 'arity %d does not match required number of ' 'function arguments of %d.' % ( arity , ...
def select ( self , channels , dataframe = False , record_offset = 0 , raw = False , copy_master = True ) : """retrieve the channels listed in * channels * argument as * Signal * objects Parameters channels : list list of items to be filtered ; each item can be : * a channel name string * ( channel name...
# group channels by group index gps = { } indexes = [ ] for item in channels : if isinstance ( item , ( list , tuple ) ) : if len ( item ) not in ( 2 , 3 ) : raise MdfException ( "The items used for filtering must be strings, " "or they must match the first 3 argumens of the get " "method" ) ...
def flush_mod ( self ) : """Flush all pending LDAP modifications ."""
for dn in self . __pending_mod_dn__ : try : if self . __ro__ : for mod in self . __mod_queue__ [ dn ] : if mod [ 0 ] == ldap . MOD_DELETE : mod_str = "DELETE" elif mod [ 0 ] == ldap . MOD_ADD : mod_str = "ADD" ...
def count ( cls , path = None , objtype = None , query = None , ** kwargs ) : """Like _ _ init _ _ , but simply returns the number of objects that match the query rather than returning the objects NOTE : The path and objtype parameters to this function are to allow use of the DatabaseCollection class directly...
if not objtype : objtype = cls . OBJTYPE if not path : path = cls . PATH if not query : query = kwargs return objtype . db ( path ) . find ( query ) . count ( )