signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def tablespace_exists ( name , user = None , host = None , port = None , maintenance_db = None , password = None , runas = None ) : '''Checks if a tablespace exists on the Postgres server . CLI Example : . . code - block : : bash salt ' * ' postgres . tablespace _ exists ' dbname ' . . versionadded : : 2015...
tablespaces = tablespace_list ( user = user , host = host , port = port , maintenance_db = maintenance_db , password = password , runas = runas ) return name in tablespaces
def ExpandRelativePath ( method_config , params , relative_path = None ) : """Determine the relative path for request ."""
path = relative_path or method_config . relative_path or '' for param in method_config . path_params : param_template = '{%s}' % param # For more details about " reserved word expansion " , see : # http : / / tools . ietf . org / html / rfc6570 # section - 3.2.2 reserved_chars = '' reserved_template...
def seek ( self , offset , whence = SEEK_SET ) : """Seek pointer in lob data buffer to requested position . Might trigger further loading of data from the database if the pointer is beyond currently read data ."""
# A nice trick is to ( ab ) use BytesIO . seek ( ) to go to the desired position for easier calculation . # This will not add any data to the buffer however - very convenient ! self . data . seek ( offset , whence ) new_pos = self . data . tell ( ) missing_bytes_to_read = new_pos - self . _current_lob_length if missing...
def fire ( obj , name , * args , ** kwargs ) : """Arrange for ` func ( * args , * * kwargs ) ` to be invoked for every function registered for the named signal on ` obj ` ."""
signals = vars ( obj ) . get ( '_signals' , { } ) for func in signals . get ( name , ( ) ) : func ( * args , ** kwargs )
def concat_align ( fastas ) : """concatenate alignments"""
# read in sequences fa2len = { } seqs = { } IDs = [ ] for fasta in fastas : seqs [ fasta ] = { } for seq in parse_fasta ( fasta ) : ID = seq [ 0 ] . split ( '>' ) [ 1 ] . split ( ) [ 0 ] IDs . append ( ID ) seqs [ fasta ] [ ID ] = seq [ 1 ] fa2len [ fasta ] = len ( seq [ 1 ] ) # conc...
def greenlet_timeouts ( self ) : """This greenlet kills jobs in other greenlets if they timeout ."""
while True : now = datetime . datetime . utcnow ( ) for greenlet in list ( self . gevent_pool ) : job = get_current_job ( id ( greenlet ) ) if job and job . timeout and job . datestarted : expires = job . datestarted + datetime . timedelta ( seconds = job . timeout ) if n...
def _Members ( self , group ) : """Unify members of a group and accounts with the group as primary gid ."""
group . members = set ( group . members ) . union ( self . gids . get ( group . gid , [ ] ) ) return group
def _export_project_file ( project , path , z , include_images , keep_compute_id , allow_all_nodes , temporary_dir ) : """Take a project file ( . gns3 ) and patch it for the export We rename the . gns3 project . gns3 to avoid the task to the client to guess the file name : param path : Path of the . gns3"""
# Image file that we need to include in the exported archive images = [ ] with open ( path ) as f : topology = json . load ( f ) if "topology" in topology : if "nodes" in topology [ "topology" ] : for node in topology [ "topology" ] [ "nodes" ] : compute_id = node . get ( 'compute_id' , 'loc...
def handle_details ( self , username ) : """Print user details"""
try : user = User . objects . get ( username = username ) except User . DoesNotExist : raise CommandError ( "Unable to find user '%s'" % username ) self . stdout . write ( "username : %s" % username ) self . stdout . write ( "is_active : %s" % user . is_active ) self . stdout . write ( "is_staff : %s" %...
def connect ( components , connections , force_SLH = False , expand_simplify = True ) : """Connect a list of components according to a list of connections . Args : components ( list ) : List of Circuit instances connections ( list ) : List of pairs ` ` ( ( c1 , port1 ) , ( c2 , port2 ) ) ` ` where ` ` c1 ` ...
combined = Concatenation . create ( * components ) cdims = [ c . cdim for c in components ] offsets = _cumsum ( [ 0 ] + cdims [ : - 1 ] ) imap = [ ] omap = [ ] counts = defaultdict ( int ) for component in components : counts [ component ] += 1 for ( ic , ( ( c1 , op ) , ( c2 , ip ) ) ) in enumerate ( connections )...
def get_node_type ( dgtree ) : """Returns the type of the root node of a DGParentedTree ."""
if is_leaf ( dgtree ) : return TreeNodeTypes . leaf_node root_label = dgtree . label ( ) if root_label == '' : assert dgtree == DGParentedTree ( '' , [ ] ) , "The tree has no root label, but isn't empty: {}" . format ( dgtree ) return TreeNodeTypes . empty_tree elif root_label in NUCLEARITY_LABELS : ret...
def add ( self , * tasks ) : """Interfaces the GraphNode ` add ` method"""
nodes = [ x . node for x in tasks ] self . node . add ( * nodes ) return self
def load_and_process_igor_model ( self , marginals_file_name ) : """Set attributes by reading a generative model from IGoR marginal file . Sets attributes PVJ , PdelV _ given _ V , PdelJ _ given _ J , PinsVJ , and Rvj . Parameters marginals _ file _ name : str File name for a IGoR model marginals file ."""
raw_model = read_igor_marginals_txt ( marginals_file_name ) self . PinsVJ = raw_model [ 0 ] [ 'vj_ins' ] self . PdelV_given_V = raw_model [ 0 ] [ 'v_3_del' ] . T self . PdelJ_given_J = raw_model [ 0 ] [ 'j_5_del' ] . T self . PVJ = np . multiply ( raw_model [ 0 ] [ 'j_choice' ] . T , raw_model [ 0 ] [ 'v_choice' ] ) . ...
def get_retry_after ( self , response ) : """Get the value of Retry - After in seconds ."""
retry_after = response . getheader ( "Retry-After" ) if retry_after is None : return None return self . parse_retry_after ( retry_after )
def compile_dictionary ( self , lang , wordlists , encoding , output ) : """Compile user dictionary ."""
wordlist = '' try : output_location = os . path . dirname ( output ) if not os . path . exists ( output_location ) : os . makedirs ( output_location ) if os . path . exists ( output ) : os . remove ( output ) self . log ( "Compiling Dictionary..." , 1 ) # Read word lists and create a...
def register_on_machine_state_changed ( self , callback ) : """Set the callback function to consume on machine state changed events . Callback receives a IMachineStateChangedEvent object . Returns the callback _ id"""
event_type = library . VBoxEventType . on_machine_state_changed return self . event_source . register_callback ( callback , event_type )
def get_custom_fields ( self ) : """Return a list of custom fields for this model"""
return CustomField . objects . filter ( content_type = ContentType . objects . get_for_model ( self ) )
def tarbell_update ( command , args ) : """Update the current tarbell project ."""
with ensure_settings ( command , args ) as settings , ensure_project ( command , args ) as site : puts ( "Updating to latest blueprint\n" ) git = sh . git . bake ( _cwd = site . base . base_dir ) # stash then pull puts ( colored . yellow ( "Stashing local changes" ) ) puts ( git . stash ( ) ) pu...
def new_pos ( self , html_div ) : """factory method pattern"""
pos = self . Position ( self , html_div ) pos . bind_mov ( ) self . positions . append ( pos ) return pos
def duplicate_node ( self , source_node_id , destination_node_id ) : """Duplicate a node : param node _ id : Node identifier : returns : New node instance"""
source_node = self . get_node ( source_node_id ) destination_node = self . get_node ( destination_node_id ) # Not a Dynamips router if not hasattr ( source_node , "startup_config_path" ) : return ( yield from super ( ) . duplicate_node ( source_node_id , destination_node_id ) ) try : with open ( source_node . s...
def command ( cmd ) : """Execute command and raise an exception upon an error . > > > ' README ' in command ( ' ls ' ) True > > > command ( ' nonexistingcommand ' ) # doctest : + ELLIPSIS Traceback ( most recent call last ) : SdistCreationError"""
status , out = commands . getstatusoutput ( cmd ) if status is not 0 : logger . error ( "Something went wrong:" ) logger . error ( out ) raise SdistCreationError ( ) return out
def is_all_field_none ( self ) : """: rtype : bool"""
if self . _id_ is not None : return False if self . _created is not None : return False if self . _updated is not None : return False if self . _status is not None : return False if self . _sub_status is not None : return False if self . _type_ is not None : return False if self . _counterparty_...
def forge_fdf ( pdf_form_url = None , fdf_data_strings = [ ] , fdf_data_names = [ ] , fields_hidden = [ ] , fields_readonly = [ ] , checkbox_checked_name = b"Yes" ) : """Generates fdf string from fields specified * pdf _ form _ url ( default : None ) : just the url for the form . * fdf _ data _ strings ( defaul...
fdf = [ b'%FDF-1.2\x0a%\xe2\xe3\xcf\xd3\x0d\x0a' ] fdf . append ( b'1 0 obj\x0a<</FDF' ) fdf . append ( b'<</Fields[' ) fdf . append ( b'' . join ( handle_data_strings ( fdf_data_strings , fields_hidden , fields_readonly , checkbox_checked_name ) ) ) fdf . append ( b'' . join ( handle_data_names ( fdf_data_names , fiel...
def insert ( self , stim , position ) : """Inserts a new stimulus into the list at the given position : param stim : stimulus to insert into protocol : type stim : : class : ` StimulusModel < sparkle . stim . stimulus _ model . StimulusModel > ` : param position : index ( row ) of location to insert to : ty...
if position == - 1 : position = self . rowCount ( ) stim . setReferenceVoltage ( self . caldb , self . calv ) stim . setCalibration ( self . calibrationVector , self . calibrationFrequencies , self . calibrationFrange ) self . _tests . insert ( position , stim )
def uid ( self ) : """Return the user id that the process will run as : rtype : int"""
if not self . _uid : if self . config . daemon . user : self . _uid = pwd . getpwnam ( self . config . daemon . user ) . pw_uid else : self . _uid = os . getuid ( ) return self . _uid
def zero_pad ( matrix , to_length ) : """Zero pads along the 0th dimension to make sure the utterance array x is of length to _ length ."""
assert matrix . shape [ 0 ] <= to_length if not matrix . shape [ 0 ] <= to_length : logger . error ( "zero_pad cannot be performed on matrix with shape {}" " to length {}" . format ( matrix . shape [ 0 ] , to_length ) ) raise ValueError result = np . zeros ( ( to_length , ) + matrix . shape [ 1 : ] ) result [ :...
def mad ( data ) : r"""Median absolute deviation This method calculates the median absolute deviation of the input data . Parameters data : np . ndarray Input data array Returns float MAD value Examples > > > from modopt . math . stats import mad > > > a = np . arange ( 9 ) . reshape ( 3 , 3) > ...
return np . median ( np . abs ( data - np . median ( data ) ) )
def _set_as_cached ( self , item , cacher ) : """Set the _ cacher attribute on the calling object with a weakref to cacher ."""
self . _cacher = ( item , weakref . ref ( cacher ) )
def prepare_cew_for_windows ( ) : """Copy files needed to compile the ` ` cew ` ` Python C extension on Windows . A glorious day , when Microsoft will offer a decent support for Python and shared libraries , all this mess will be unnecessary and it should be removed . May that day come soon . Return ` ` T...
try : # copy espeak _ sapi . dll to C : \ Windows \ System32 \ espeak . dll espeak_dll_win_path = "C:\\Windows\\System32\\espeak.dll" espeak_dll_dst_path = "aeneas\\cew\\espeak.dll" espeak_dll_src_paths = [ "C:\\aeneas\\eSpeak\\espeak_sapi.dll" , "C:\\sync\\eSpeak\\espeak_sapi.dll" , "C:\\Program Files\\eSp...
def reset ( self ) : """Deactivate all cells ."""
self . activeCells = np . empty ( 0 , dtype = "uint32" ) self . activeDeltaSegments = np . empty ( 0 , dtype = "uint32" ) self . activeFeatureLocationSegments = np . empty ( 0 , dtype = "uint32" )
def convert_destination_to_id ( destination_node , destination_port , nodes ) : """Convert a destination to device and port ID : param str destination _ node : Destination node name : param str destination _ port : Destination port name : param list nodes : list of nodes from : py : meth : ` generate _ nodes ...
device_id = None device_name = None port_id = None if destination_node != 'NIO' : for node in nodes : if destination_node == node [ 'properties' ] [ 'name' ] : device_id = node [ 'id' ] device_name = destination_node for port in node [ 'ports' ] : if desti...
def _phi2deriv ( self , R , phi = 0. , t = 0. ) : """NAME : _ phi2deriv PURPOSE : evaluate the second azimuthal derivative INPUT : phi OUTPUT : d2phi / dphi2 HISTORY : 2016-06-02 - Written - Bovy ( UofT )"""
return self . _Pot . phi2deriv ( R , 0. , phi = phi , t = t , use_physical = False )
def get_distribution_list ( self , dl_description ) : """: param : dl _ description : a DistributionList specifying either : - id : the account _ id - name : the name of the list : returns : the DistributionList"""
selector = dl_description . to_selector ( ) resp = self . request_single ( 'GetDistributionList' , { 'dl' : selector } ) dl = zobjects . DistributionList . from_dict ( resp ) return dl
def image ( self ) : """Returns an image array of current render window"""
if not hasattr ( self , 'ren_win' ) and hasattr ( self , 'last_image' ) : return self . last_image ifilter = vtk . vtkWindowToImageFilter ( ) ifilter . SetInput ( self . ren_win ) ifilter . ReadFrontBufferOff ( ) if self . image_transparent_background : ifilter . SetInputBufferTypeToRGBA ( ) else : ifilter ...
def get_optimized_symbol ( executor ) : """Take an executor ' s underlying symbol graph and return its generated optimized version . Parameters executor : An executor for which you want to see an optimized symbol . Getting an optimized symbol is useful to compare and verify the work TensorRT has done agains...
handle = SymbolHandle ( ) try : check_call ( _LIB . MXExecutorGetOptimizedSymbol ( executor . handle , ctypes . byref ( handle ) ) ) result = sym . Symbol ( handle = handle ) return result except MXNetError : logging . error ( 'Error while trying to fetch TRT optimized symbol for graph. Please ensure ' ...
def check_value ( self , value_hash , value , salt = '' ) : '''Checks the specified hash value against the hash of the provided salt and value . An example usage of : class : ` check _ value ` would be : : val _ hash = hashing . hash _ value ( ' mysecretdata ' , salt = ' abcd ' ) if hashing . check _ value ...
h = self . hash_value ( value , salt = salt ) return h == value_hash
def read_backend ( self , client = None ) : '''The read : class : ` stdnet . BackendDatServer ` for this instance . It can be ` ` None ` ` .'''
session = self . session if session : return session . model ( self ) . read_backend
def deviator_stress ( self ) : """returns the deviatoric component of the stress"""
if not self . is_symmetric : raise warnings . warn ( "The stress tensor is not symmetric, " "so deviator stress will not be either" ) return self - self . mean_stress * np . eye ( 3 )
async def build_pool_restart_request ( submitter_did : str , action : str , datetime : str ) -> str : """Builds a POOL _ RESTART request : param submitter _ did : Id of Identity that sender transaction : param action : Action that pool has to do after received transaction . Can be " start " or " cancel " : ...
logger = logging . getLogger ( __name__ ) logger . debug ( "build_pool_restart_request: >>> submitter_did: %r, action: %r, datetime: %r" ) if not hasattr ( build_pool_restart_request , "cb" ) : logger . debug ( "build_pool_restart_request: Creating callback" ) build_pool_restart_request . cb = create_cb ( CFUNC...
def shared_edges ( faces_a , faces_b ) : """Given two sets of faces , find the edges which are in both sets . Parameters faces _ a : ( n , 3 ) int , set of faces faces _ b : ( m , 3 ) int , set of faces Returns shared : ( p , 2 ) int , set of edges"""
e_a = np . sort ( faces_to_edges ( faces_a ) , axis = 1 ) e_b = np . sort ( faces_to_edges ( faces_b ) , axis = 1 ) shared = grouping . boolean_rows ( e_a , e_b , operation = np . intersect1d ) return shared
def inv ( self ) : """inversion operation of self Returns Matrix : Matrix inverse of self"""
if self . isdiagonal : inv = 1.0 / self . __x if ( np . any ( ~ np . isfinite ( inv ) ) ) : idx = np . isfinite ( inv ) np . savetxt ( "testboo.dat" , idx ) invalid = [ self . row_names [ i ] for i in range ( idx . shape [ 0 ] ) if idx [ i ] == 0.0 ] raise Exception ( "Matrix.inv...
def setAll ( self , pairs ) : """Set multiple parameters , passed as a list of key - value pairs . : param pairs : list of key - value pairs to set"""
for ( k , v ) in pairs : self . set ( k , v ) return self
def listing ( source : list , ordered : bool = False , expand_full : bool = False ) : """An unordered or ordered list of the specified * source * iterable where each element is converted to a string representation for display . : param source : The iterable to display as a list . : param ordered : Whether...
r = _get_report ( ) r . append_body ( render . listing ( source = source , ordered = ordered , expand_full = expand_full ) ) r . stdout_interceptor . write_source ( '[ADDED] Listing\n' )
def pack_small_tensors ( tower_grads , max_bytes = 0 ) : """Concatenate gradients together more intelligently . Does binpacking Args : tower _ grads : List of lists of ( gradient , variable ) tuples . max _ bytes : Int giving max number of bytes in a tensor that may be considered small ."""
assert max_bytes >= 0 orig_grads = [ g for g , _ in tower_grads [ 0 ] ] # Check to make sure sizes are accurate ; not entirely important assert all ( g . dtype == tf . float32 for g in orig_grads ) sizes = [ 4 * g . shape . num_elements ( ) for g in orig_grads ] print_stats ( sizes ) small_ranges = [ ] large_indices = ...
def hardware_flexport_flexport_type_instance ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) hardware = ET . SubElement ( config , "hardware" , xmlns = "urn:brocade.com:mgmt:brocade-hardware" ) flexport = ET . SubElement ( hardware , "flexport" ) id_key = ET . SubElement ( flexport , "id" ) id_key . text = kwargs . pop ( 'id' ) flexport_type = ET . SubElement ( flexport , "fl...
def buildSources ( self , sourceTime = None ) : """Return a dictionary of date / time tuples based on the keys found in self . re _ sources . The current time is used as the default and any specified item found in self . re _ sources is inserted into the value and the generated dictionary is returned ."""
if sourceTime is None : ( yr , mth , dy , hr , mn , sec , wd , yd , isdst ) = time . localtime ( ) else : ( yr , mth , dy , hr , mn , sec , wd , yd , isdst ) = sourceTime sources = { } defaults = { 'yr' : yr , 'mth' : mth , 'dy' : dy , 'hr' : hr , 'mn' : mn , 'sec' : sec , } for item in self . re_sources : ...
def paintEvent ( self , event ) : """Overloads the paint event to paint additional hint information if no text is set on the editor . : param event | < QPaintEvent >"""
super ( XLineEdit , self ) . paintEvent ( event ) # paint the hint text if not text is set if self . text ( ) and not ( self . icon ( ) and not self . icon ( ) . isNull ( ) ) : return # paint the hint text with XPainter ( self ) as painter : painter . setPen ( self . hintColor ( ) ) icon = self . icon ( ) ...
def table_cells_2_spans ( table , spans ) : """Converts the table to a list of spans , for consistency . This method combines the table data with the span data into a single , more consistent type . Any normal cell will become a span of just 1 column and 1 row . Parameters table : list of lists of str s...
new_spans = [ ] for row in range ( len ( table ) ) : for column in range ( len ( table [ row ] ) ) : span = get_span ( spans , row , column ) if not span : new_spans . append ( [ [ row , column ] ] ) new_spans . extend ( spans ) new_spans = list ( sorted ( new_spans ) ) return new_spans
def add_organization ( db , organization ) : """Add an organization to the registry . This function adds an organization to the registry . It checks first whether the organization is already on the registry . When it is not found , the new organization is added . Otherwise , it raises a ' AlreadyExistsError...
with db . connect ( ) as session : try : add_organization_db ( session , organization ) except ValueError as e : raise InvalidValueError ( e )
def data_as_matrix ( self , keys = None , return_basis = False , basis = None , alias = None , start = None , stop = None , step = None , window_length = None , window_step = 1 , ) : """Provide a feature matrix , given a list of data items . I think this will probably fail if there are striplogs in the data dic...
if keys is None : keys = [ k for k , v in self . data . items ( ) if isinstance ( v , Curve ) ] else : # Only look at the alias list if keys were passed . if alias is not None : _keys = [ ] for k in keys : if k in alias : added = False for a in alias [...
async def wait_done ( self ) -> int : """Coroutine to wait for subprocess run completion . Returns : The exit code of the subprocess ."""
await self . _done_running_evt . wait ( ) if self . _exit_code is None : raise SublemonLifetimeError ( 'Subprocess exited abnormally with `None` exit code' ) return self . _exit_code
def reset_weights ( self ) : """Initialize properly model weights"""
self . input_block . reset_weights ( ) self . backbone . reset_weights ( ) self . action_head . reset_weights ( ) self . value_head . reset_weights ( )
def parse_config_file ( job , config_file , max_cores = None ) : """Parse the config file and spawn a ProTECT job for every input sample . : param str config _ file : Path to the input config file : param int max _ cores : The maximum cores to use for any single high - compute job ."""
sample_set , univ_options , processed_tool_inputs = _parse_config_file ( job , config_file , max_cores ) # Start a job for each sample in the sample set for patient_id in sample_set . keys ( ) : job . addFollowOnJobFn ( launch_protect , sample_set [ patient_id ] , univ_options , processed_tool_inputs ) return None
def insert ( self , instance ) : """inserts a unit of work into MongoDB . : raises DuplicateKeyError : if such record already exist"""
assert isinstance ( instance , UnitOfWork ) collection = self . ds . connection ( COLLECTION_UNIT_OF_WORK ) try : return collection . insert_one ( instance . document ) . inserted_id except MongoDuplicateKeyError as e : exc = DuplicateKeyError ( instance . process_name , instance . start_timeperiod , instance ....
def search ( self , args ) : """Executes a search flickr : ( credsfile ) , search , ( arg1 ) = ( val1 ) , ( arg2 ) = ( val2 ) . . ."""
kwargs = { } for a in args : k , v = a . split ( '=' ) kwargs [ k ] = v return self . _paged_api_call ( self . flickr . photos_search , kwargs )
def power_off ( self , context , ports ) : """Powers off the remote vm : param models . QualiDriverModels . ResourceRemoteCommandContext context : the context the command runs on : param list [ string ] ports : the ports of the connection between the remote resource and the local resource , NOT IN USE ! ! !"""
return self . _power_command ( context , ports , self . vm_power_management_command . power_off )
def _cache_get_for_dn ( self , dn : str ) -> Dict [ str , bytes ] : """Object state is cached . When an update is required the update will be simulated on this cache , so that rollback information can be correct . This function retrieves the cached data ."""
# no cached item , retrieve from ldap self . _do_with_retry ( lambda obj : obj . search ( dn , '(objectclass=*)' , ldap3 . BASE , attributes = [ '*' , '+' ] ) ) results = self . _obj . response if len ( results ) < 1 : raise NoSuchObject ( "No results finding current value" ) if len ( results ) > 1 : raise Runt...
def _sanity_check_block_pairwise_constraints ( ir_blocks ) : """Assert that adjacent blocks obey all invariants ."""
for first_block , second_block in pairwise ( ir_blocks ) : # Always Filter before MarkLocation , never after . if isinstance ( first_block , MarkLocation ) and isinstance ( second_block , Filter ) : raise AssertionError ( u'Found Filter after MarkLocation block: {}' . format ( ir_blocks ) ) # There ' s ...
def maximum_position_of_labels ( image , labels , indices ) : '''Return the i , j coordinates of the maximum value within each object image - measure the maximum within this image labels - use the objects within this labels matrix indices - label # s to measure The result returned is an 2 x n numpy array wh...
if len ( indices ) == 0 : return np . zeros ( ( 2 , 0 ) , int ) result = scind . maximum_position ( image , labels , indices ) result = np . array ( result , int ) if result . ndim == 1 : result . shape = ( 2 , 1 ) return result return result . transpose ( )
def index ( request ) : """Listing page for event ` Occurrence ` s . : param request : Django request object . : param is _ preview : Should the listing page be generated as a preview ? This will allow preview specific actions to be done in the template such as turning off tracking options or adding links...
warnings . warn ( "icekit_events.views.index is deprecated and will disappear in a " "future version. If you need this code, copy it into your project." , DeprecationWarning ) occurrences = models . Occurrence . objects . visible ( ) context = { 'occurrences' : occurrences , } return TemplateResponse ( request , 'iceki...
def File ( self , name , directory = None , create = 1 ) : """Create ` SCons . Node . FS . File `"""
return self . _create_node ( name , self . env . fs . File , directory , create )
def get_metadata ( audio_filepaths ) : """Return a tuple of album , artist , has _ embedded _ album _ art from a list of audio files ."""
artist , album , has_embedded_album_art = None , None , None for audio_filepath in audio_filepaths : try : mf = mutagen . File ( audio_filepath ) except Exception : continue if mf is None : continue # artist for key in ( "albumartist" , "artist" , # ogg "TPE1" , "TPE2" , ...
def addVariable ( self , variable , domain ) : """Add a variable to the problem Example : > > > problem = Problem ( ) > > > problem . addVariable ( " a " , [ 1 , 2 ] ) > > > problem . getSolution ( ) in ( { ' a ' : 1 } , { ' a ' : 2 } ) True @ param variable : Object representing a problem variable @ ...
if variable in self . _variables : msg = "Tried to insert duplicated variable %s" % repr ( variable ) raise ValueError ( msg ) if isinstance ( domain , Domain ) : domain = copy . deepcopy ( domain ) elif hasattr ( domain , "__getitem__" ) : domain = Domain ( domain ) else : msg = "Domains must be in...
def from_content ( cls , content ) : """Parses the content of the World Overview section from Tibia . com into an object of this class . Parameters content : : class : ` str ` The HTML content of the World Overview page in Tibia . com Returns : class : ` WorldOverview ` An instance of this class contain...
parsed_content = parse_tibiacom_content ( content , html_class = "TableContentAndRightShadow" ) world_overview = WorldOverview ( ) try : record_row , titles_row , * rows = parsed_content . find_all ( "tr" ) m = record_regexp . search ( record_row . text ) if not m : raise InvalidContent ( "content d...
def add ( self , attribute ) : """Add an attribute to this attribute exchange request . @ param attribute : The attribute that is being requested @ type attribute : C { L { AttrInfo } } @ returns : None @ raise KeyError : when the requested attribute is already present in this fetch request ."""
if attribute . type_uri in self . requested_attributes : raise KeyError ( 'The attribute %r has already been requested' % ( attribute . type_uri , ) ) self . requested_attributes [ attribute . type_uri ] = attribute
def render ( self , ctx = None ) : '''Render the current value into a : class : ` bitstring . Bits ` object : rtype : : class : ` bitstring . Bits ` : return : the rendered field'''
self . _initialize ( ) if ctx is None : ctx = RenderContext ( ) # if we are called from within render , return a dummy object . . . if self in ctx : self . _current_rendered = self . _in_render_value ( ) else : ctx . push ( self ) if self . dependency_type == Calculated . VALUE_BASED : self . _r...
def process_form ( self , instance , field , form , empty_marker = None , emptyReturnsMarker = False ) : """Return a UID so that ReferenceField understands ."""
fieldName = field . getName ( ) if fieldName + "_uid" in form : uid = form . get ( fieldName + "_uid" , '' ) if field . multiValued and ( isinstance ( uid , str ) or isinstance ( uid , unicode ) ) : uid = uid . split ( "," ) elif fieldName in form : uid = form . get ( fieldName , '' ) if field ....
def css ( self , path ) : """Link / embed CSS file ."""
if self . settings . embed_content : content = codecs . open ( path , 'r' , encoding = 'utf8' ) . read ( ) tag = Style ( content , type = "text/css" ) else : tag = Link ( href = path , rel = "stylesheet" , type_ = "text/css" ) self . head . append ( tag )
def get_skos ( self , id = None , uri = None , match = None ) : """get the saved skos concept with given ID or via other methods . . . Note : it tries to guess what is being passed as above"""
if not id and not uri and not match : return None if type ( id ) == type ( "string" ) : uri = id id = None if not is_http ( uri ) : match = uri uri = None if match : if type ( match ) != type ( "string" ) : return [ ] res = [ ] if ":" in match : # qname for x ...
def get_app_env ( ) : """if the app and the envi are passed in the command line as ' app = $ app : $ env ' : return : tuple app , env"""
app , env = None , get_env ( ) if "app" in os . environ : app = os . environ [ "app" ] . lower ( ) if ":" in app : app , env = os . environ [ "app" ] . split ( ":" , 2 ) set_env ( env ) return app , env
def merge_datetime ( date , time = '' , date_format = '%d/%m/%Y' , time_format = '%H:%M' ) : """Create ` ` datetime ` ` object from date and time strings ."""
day = datetime . strptime ( date , date_format ) if time : time = datetime . strptime ( time , time_format ) time = datetime . time ( time ) day = datetime . date ( day ) day = datetime . combine ( day , time ) return day
def convert_feature_layers_to_dict ( feature_layers ) : """takes a list of ' feature _ layer ' objects and converts to a dict keyed by the layer name"""
features_by_layer = { } for feature_layer in feature_layers : layer_name = feature_layer [ 'name' ] features = feature_layer [ 'features' ] features_by_layer [ layer_name ] = features return features_by_layer
def get_mean_and_stddevs ( self , sites , rup , dists , imt , stddev_types ) : """See : meth : ` superclass method < . base . GroundShakingIntensityModel . get _ mean _ and _ stddevs > ` for spec of input and result values ."""
R = ( dists . rrup ) M = rup . mag # get constants Ssr = self . get_Ssr_term ( sites . vs30 ) Shr = self . get_Shr_term ( sites . vs30 ) rake = rup . rake F = self . get_fault_term ( rake ) # compute mean mean = - 3.512 + ( 0.904 * M ) - ( 1.328 * np . log ( np . sqrt ( R ** 2 + ( 0.149 * np . exp ( 0.647 * M ) ) ** 2 ...
def create_base_logger ( config = None , parallel = None ) : """Setup base logging configuration , also handling remote logging . Correctly sets up for local , multiprocessing and distributed runs . Creates subscribers for non - local runs that will be references from local logging . Retrieves IP address us...
if parallel is None : parallel = { } parallel_type = parallel . get ( "type" , "local" ) cores = parallel . get ( "cores" , 1 ) if parallel_type == "ipython" : from bcbio . log import logbook_zmqpush fqdn_ip = socket . gethostbyname ( socket . getfqdn ( ) ) ips = [ fqdn_ip ] if ( fqdn_ip and not fqdn_ip...
def git_check ( ) : """Check that all changes , besides versioning files , are committed : return :"""
# check that changes staged for commit are pushed to origin output = local ( 'git diff --name-only | egrep -v "^(pynb/version.py)|(version.py)$" | tr "\\n" " "' , capture = True ) . strip ( ) if output : fatal ( 'Stage for commit and commit all changes first: {}' . format ( output ) ) output = local ( 'git diff --c...
def get_options ( argv = None ) : """Convert options into commands return commands , message"""
parser = argparse . ArgumentParser ( usage = "spyder [options] files" ) parser . add_argument ( '--new-instance' , action = 'store_true' , default = False , help = "Run a new instance of Spyder, even if the single " "instance mode has been turned on (default)" ) parser . add_argument ( '--defaults' , dest = "reset_to_d...
def assert_compile_finished ( app_folder ) : """Once builder . sh has invoked the compile script , it should return and we should set a flag to the script returned . If that flag is missing , then it is an indication that the container crashed , and we generate an error . This function will clean up the flag ...
fpath = os . path . join ( app_folder , '.postbuild.flag' ) if not os . path . isfile ( fpath ) : msg = ( 'No postbuild flag set, LXC container may have crashed while ' 'building. Check compile logs for build.' ) raise AssertionError ( msg ) try : os . remove ( fpath ) except OSError : # It doesn ' t matter...
def is_valid ( self , name = None , debug = False ) : """Check to see if the current xml path is to be processed ."""
valid_tags = self . action_tree invalid = False for item in self . current_tree : try : if item in valid_tags or self . ALL_TAGS in valid_tags : valid_tags = valid_tags [ item if item in valid_tags else self . ALL_TAGS ] else : valid_tags = None invalid = True ...
def domestic_mobile_phone_number ( value ) : """Confirms that the phone number is a valid UK phone number . @ param { str } value @ returns { None } @ raises AssertionError"""
try : parsed = phonenumbers . parse ( value , 'GB' ) except NumberParseException : pass else : is_mobile = carrier . _is_mobile ( number_type ( parsed ) ) if is_mobile and phonenumbers . is_valid_number ( parsed ) : return None raise ValidationError ( MESSAGE_INVALID_PHONE_NUMBER )
def launchRequest ( request ) : '''Method to launch a given request . : param request : The request object . : return : A dictionary containinf the results of the person and a list of dicts containing the references for the record .'''
person = { } records = [ ] try : response = request . send ( ) # Trying to recover a person object . This is a dict : try : person = ( response . person ) . to_dict ( ) except : pass # Trying to recover a list of record objects . This is a list dicts try : aux = response ...
def create_parser ( ) : """Create the language parser"""
select = create_select ( ) scan = create_scan ( ) delete = create_delete ( ) update = create_update ( ) insert = create_insert ( ) create = create_create ( ) drop = create_drop ( ) alter = create_alter ( ) dump = create_dump ( ) load = create_load ( ) base = ( select | scan | delete | update | insert | create | drop | ...
def train ( self , traindata : np . ndarray ) -> None : """Trains on dataset"""
self . clf . fit ( traindata [ : , 1 : 5 ] , traindata [ : , 5 ] )
async def _query_chunked_post ( self , path , method = "POST" , * , params = None , data = None , headers = None , timeout = None ) : """A shorthand for uploading data by chunks"""
if headers is None : headers = { } if headers and "content-type" not in headers : headers [ "content-type" ] = "application/octet-stream" response = await self . _query ( path , method , params = params , data = data , headers = headers , timeout = timeout , chunked = True , ) return response
def __make_security_role_api_request ( server_context , api , role , email = None , user_id = None , container_path = None ) : """Execute a request against the LabKey Security Controller Group Membership apis : param server _ context : A LabKey server context . See utils . create _ server _ context . : param ap...
if email is None and user_id is None : raise ValueError ( "Must supply either/both [email] or [user_id]" ) url = server_context . build_url ( security_controller , api , container_path ) return server_context . make_request ( url , { 'roleClassName' : role [ 'uniqueName' ] , 'principalId' : user_id , 'email' : emai...
def extract_irc_colours ( msg ) : """Extract the IRC colours from the start of the string . Extracts the colours from the start , and returns the colour code in our format , and then the rest of the message ."""
# first colour fore , msg = _extract_irc_colour_code ( msg ) if not fore : return '[]' , msg if not len ( msg ) or msg [ 0 ] != ',' : return '[{}]' . format ( _ctos ( fore ) ) , msg msg = msg [ 1 : ] # strip comma # second colour back , msg = _extract_irc_colour_code ( msg ) if back : return '[{},{}]' . for...
def export_collada ( mesh , ** kwargs ) : """Export a mesh or a list of meshes as a COLLADA . dae file . Parameters mesh : Trimesh object or list of Trimesh objects The mesh ( es ) to export . Returns export : str , string of COLLADA format output"""
meshes = mesh if not isinstance ( mesh , ( list , tuple , set , np . ndarray ) ) : meshes = [ mesh ] c = collada . Collada ( ) nodes = [ ] for i , m in enumerate ( meshes ) : # Load uv , colors , materials uv = None colors = None mat = _unparse_material ( None ) if m . visual . defined : if ...
def _check_length_equal ( param_1 , param_2 , name_param_1 , name_param_2 ) : """Raises an error when the length of given two arguments is not equal"""
if len ( param_1 ) != len ( param_2 ) : raise ValueError ( "Length of {} must be same as Length of {}" . format ( name_param_1 , name_param_2 ) )
def get_site_orbital_dos ( self , site , orbital ) : """Get the Dos for a particular orbital of a particular site . Args : site : Site in Structure associated with CompleteDos . orbital : Orbital in the site . Returns : Dos containing densities for orbital of site ."""
return Dos ( self . efermi , self . energies , self . pdos [ site ] [ orbital ] )
def update_or_create ( cls , name , external_endpoint = None , vpn_site = None , trust_all_cas = True , with_status = False ) : """Update or create an ExternalGateway . The ` ` external _ endpoint ` ` and ` ` vpn _ site ` ` parameters are expected to be a list of dicts with key / value pairs to satisfy the resp...
if external_endpoint : for endpoint in external_endpoint : if 'name' not in endpoint : raise ValueError ( 'External endpoints are configured ' 'but missing the name parameter.' ) if vpn_site : for site in vpn_site : if 'name' not in site : raise ValueError ( 'VPN sites ar...
def getNodePosition ( cls , start , height = None ) -> int : """Calculates node position based on start and height : param start : The sequence number of the first leaf under this tree . : param height : Height of this node in the merkle tree : return : the node ' s position"""
pwr = highest_bit_set ( start ) - 1 height = height or pwr if count_bits_set ( start ) == 1 : adj = height - pwr return start - 1 + adj else : c = pow ( 2 , pwr ) return cls . getNodePosition ( c , pwr ) + cls . getNodePosition ( start - c , height )
def get_sanitized_bot_name ( dict : Dict [ str , int ] , name : str ) -> str : """Cut off at 31 characters and handle duplicates . : param dict : Holds the list of names for duplicates : param name : The name that is being sanitized : return : A sanitized version of the name"""
if name not in dict : new_name = name [ : 31 ] # Make sure name does not exceed 31 characters dict [ name ] = 1 else : count = dict [ name ] new_name = name [ : 27 ] + "(" + str ( count + 1 ) + ")" # Truncate at 27 because we can have up to ' ( 10 ) ' appended assert new_name not in dict ...
def search ( self , criterion , table , columns = '' , fetch = False , radius = 1 / 60. , use_converters = False , sql_search = False ) : """General search method for tables . For ( ra , dec ) input in decimal degrees , i . e . ( 12.3456 , - 65.4321 ) , returns all sources within 1 arcminute , or the specified ra...
# Get list of columns to search and format properly t = self . query ( "PRAGMA table_info({})" . format ( table ) , unpack = True , fmt = 'table' ) all_columns = t [ 'name' ] . tolist ( ) types = t [ 'type' ] . tolist ( ) columns = columns or all_columns columns = np . asarray ( [ columns ] if isinstance ( columns , st...
def start_recording ( self , output_file ) : """Starts recording to a given output video file . Parameters output _ file : : obj : ` str ` filename to write video to"""
if not self . _started : raise Exception ( "Must start the video recorder first by calling .start()!" ) if self . _recording : raise Exception ( "Cannot record a video while one is already recording!" ) self . _recording = True self . _cmd_q . put ( ( 'start' , output_file ) )
def on_modified ( self , event ) : """Handle a file modified event ."""
path = event . src_path if path not in self . saw : self . saw . add ( path ) self . recompile ( path )
def _create_pax_generic_header ( cls , pax_headers , type , encoding ) : """Return a POSIX . 1-2008 extended or global header sequence that contains a list of keyword , value pairs . The values must be strings ."""
# Check if one of the fields contains surrogate characters and thereby # forces hdrcharset = BINARY , see _ proc _ pax ( ) for more information . binary = False for keyword , value in pax_headers . items ( ) : try : value . encode ( "utf8" , "strict" ) except UnicodeEncodeError : binary = True ...
def same_types ( self , index1 , index2 ) : """Returns True if both symbol table elements are of the same type"""
try : same = self . table [ index1 ] . type == self . table [ index2 ] . type != SharedData . TYPES . NO_TYPE except Exception : self . error ( ) return same
def get_and_update_package_metadata ( ) : """Update the package metadata for this package if we are building the package . : return : metadata - Dictionary of metadata information"""
global setup_arguments global METADATA_FILENAME if not os . path . exists ( '.git' ) and os . path . exists ( METADATA_FILENAME ) : with open ( METADATA_FILENAME ) as fh : metadata = json . load ( fh ) else : git = Git ( version = setup_arguments [ 'version' ] ) metadata = { 'version' : git . versio...
def get_value ( self , context , obj , field_name ) : """gets the translated value of field name . If ` FALLBACK ` evaluates to ` True ` and the field has no translation for the current language , it tries to find a fallback value , using the languages defined in ` settings . LANGUAGES ` ."""
try : language = get_language ( ) value = self . get_translated_value ( obj , field_name , language ) if value : return value if self . FALLBACK : for lang , lang_name in settings . LANGUAGES : if lang == language : # already tried this one . . . continue ...
def prepare_injection_directions ( self ) : """provide genotypic directions for TPA and selective mirroring , with no specific length normalization , to be used in the coming iteration . Details : This method is called in the end of ` tell ` . The result is assigned to ` ` self . pop _ injection _ directi...
# self . pop _ injection _ directions is supposed to be empty here if hasattr ( self , 'pop_injection_directions' ) and self . pop_injection_directions : ValueError ( "Looks like a bug in calling order/logics" ) ary = [ ] if ( isinstance ( self . adapt_sigma , CMAAdaptSigmaTPA ) or self . opts [ 'mean_shift_line_sa...
def acquire ( self , resources , prop_name ) : """Starting with self , walk until you find prop or None"""
# Instance custom_prop = getattr ( self . props , prop_name , None ) if custom_prop : return custom_prop # Parents . . . can ' t use acquire as have to keep going on acquireds for parent in self . parents ( resources ) : acquireds = parent . props . acquireds if acquireds : # First try in the per - type acq...