signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def from_repeat_masker_string ( s ) : """Parse a RepeatMasker string . This format is white - space separated and has 15 columns . The first 11 are invariably as follows : | Description | Type | Example | Notes | | alignment score | int ( ? ) | 463 | | | percent divergence | float | 1.3 | | | percent dele...
parts = s . split ( ) if len ( parts ) != 15 and len ( parts ) != 14 : raise RetrotransposonError ( "incorrectly formated RepeatMasker entry: " + s ) # get rid of those pesky parentheses for i in [ 11 , 12 , 13 ] : parts [ i ] = parts [ i ] . strip ( ) if parts [ i ] [ 0 ] == "(" : parts [ i ] = par...
def setAndUpdateValues ( self , solution_next , IncomeDstn , LivPrb , DiscFac ) : '''Unpacks some of the inputs ( and calculates simple objects based on them ) , storing the results in self for use by other methods . These include : income shocks and probabilities , next period ' s marginal value function ( e...
# Run basic version of this method ConsIndShockSetup . setAndUpdateValues ( self , solution_next , IncomeDstn , LivPrb , DiscFac ) self . mLvlMinNext = solution_next . mLvlMin # Replace normalized human wealth ( scalar ) with human wealth level as function of persistent income self . hNrmNow = 0.0 pLvlCount = self . pL...
def indexes ( self ) -> 'Mapping[Any, pd.Index]' : """Mapping of pandas . Index objects used for label based indexing"""
if self . _indexes is None : self . _indexes = default_indexes ( self . _variables , self . _dims ) return Indexes ( self . _indexes )
def get_default_config_help ( self ) : """Return help text for collector"""
config_help = super ( PostgresqlCollector , self ) . get_default_config_help ( ) config_help . update ( { 'host' : 'Hostname' , 'dbname' : 'DB to connect to in order to get list of DBs in PgSQL' , 'user' : 'Username' , 'password' : 'Password' , 'port' : 'Port number' , 'password_provider' : "Whether to auth with suppli...
def WriteInit ( self , out ) : """Write a simple _ _ init _ _ . py for the generated client ."""
printer = self . _GetPrinter ( out ) if self . __init_wildcards_file : printer ( '"""Common imports for generated %s client library."""' , self . __client_info . package ) printer ( '# pylint:disable=wildcard-import' ) else : printer ( '"""Package marker file."""' ) printer ( ) printer ( 'import pkgutil' ) ...
def create_2D_grid_simple ( self , longitude , latitude , year , magnitude , completeness_table , t_f = 1. , mag_inc = 0.1 ) : '''Generates the grid from the limits using an approach closer to that of Frankel ( 1995) : param numpy . ndarray longitude : Vector of earthquake longitudes : param numpy . ndarray...
assert mag_inc > 0. xlim = np . ceil ( ( self . grid_limits [ 'xmax' ] - self . grid_limits [ 'xmin' ] ) / self . grid_limits [ 'xspc' ] ) ylim = np . ceil ( ( self . grid_limits [ 'ymax' ] - self . grid_limits [ 'ymin' ] ) / self . grid_limits [ 'yspc' ] ) ncolx = int ( xlim ) ncoly = int ( ylim ) grid_count = np . ze...
def parse_workflow_call_body_io_map ( self , i ) : """Required . : param i : : return :"""
io_map = OrderedDict ( ) if isinstance ( i , wdl_parser . Terminal ) : raise NotImplementedError elif isinstance ( i , wdl_parser . Ast ) : raise NotImplementedError elif isinstance ( i , wdl_parser . AstList ) : for ast in i : if ast . name == 'IOMapping' : key = self . parse_declaratio...
def save_font_awesome ( dirpath = '' , version = "4.7.0" ) : """Download and save the font - awesome package to a local directory . : type dirpath : str : type url : str"""
directory_name = "font-awesome-{0:s}" . format ( version ) directory_path = os . path . join ( dirpath , directory_name ) if os . path . exists ( directory_path ) : return directory_name url = "https://fontawesome.com/v{0:s}/assets/font-awesome-{0:s}.zip" . format ( version ) content , _encoding = download_to_bytes...
def instruction_COM_memory ( self , opcode , ea , m ) : """Replaces the contents of memory location M with its logical complement . source code forms : COM Q"""
r = self . COM ( value = m ) # log . debug ( " $ % x COM memory $ % x to $ % x " % ( # self . program _ counter , m , r , return ea , r & 0xff
def make_temp ( string , suffix = '' , decode = True , delete = True ) : """xmlsec needs files in some cases where only strings exist , hence the need for this function . It creates a temporary file with the string as only content . : param string : The information to be placed in the file : param suffix : ...
ntf = NamedTemporaryFile ( suffix = suffix , delete = delete ) # Python3 tempfile requires byte - like object if not isinstance ( string , six . binary_type ) : string = string . encode ( 'utf-8' ) if decode : ntf . write ( base64 . b64decode ( string ) ) else : ntf . write ( string ) ntf . seek ( 0 ) retur...
def interface_status ( self ) : """Obtain the interface status for this node . This will return an iterable that provides information about the existing interfaces . Retrieve a single interface status : : > > > node = engine . nodes [ 0] > > > node Node ( name = ngf - 1065) > > > node . interface _ stat...
result = self . make_request ( NodeCommandFailed , resource = 'appliance_status' ) return InterfaceStatus ( result . get ( 'interface_statuses' , [ ] ) )
def application ( self , value ) : """Update the application ."""
# Always allow None if value is None : self . _application = None return # Check that the state is valid if not isinstance ( value , application . Application ) : raise ValueError ( "application must be an instance of " "tendril.Application" ) self . _application = value
def override ( original , results ) : """If a receiver to a signal returns a value , we override the original value with the last returned value . : param original : The original value : param results : The results from the signal"""
overrides = [ v for fn , v in results if v is not None ] if len ( overrides ) == 0 : return original return overrides [ - 1 ]
def connect_hostport ( hostport , timeout = RPC_DEFAULT_TIMEOUT , my_hostport = None ) : """Connect to the given " host : port " string Returns a BlockstackRPCClient instance"""
host , port = url_to_host_port ( hostport ) assert host is not None and port is not None protocol = url_protocol ( hostport ) if protocol is None : log . warning ( "No scheme given in {}. Guessing by port number" . format ( hostport ) ) if port == RPC_SERVER_PORT or port == RPC_SERVER_TEST_PORT : protoc...
def _remove_bdb_context ( evalue ) : """Remove exception context from Pdb from the exception . E . g . " AttributeError : ' Pdb ' object has no attribute ' do _ foo ' " , when trying to look up commands ( bpo - 36494 ) ."""
removed_bdb_context = evalue while removed_bdb_context . __context__ : ctx = removed_bdb_context . __context__ if ( isinstance ( ctx , AttributeError ) and ctx . __traceback__ . tb_frame . f_code . co_name == "onecmd" ) : removed_bdb_context . __context__ = None break removed_bdb_context = r...
def CheckTemplates ( self , base_dir , version ) : """Verify we have at least one template that matches maj . minor version ."""
major_minor = "." . join ( version . split ( "." ) [ 0 : 2 ] ) templates = glob . glob ( os . path . join ( base_dir , "templates/*%s*.zip" % major_minor ) ) required_templates = set ( [ x . replace ( "maj.minor" , major_minor ) for x in self . REQUIRED_TEMPLATES ] ) # Client templates have an extra version digit , e ....
def complete ( response : Response , project : typing . Union [ Project , None ] , starting : ProjectStep = None , force : bool = False , limit : int = - 1 ) -> list : """Runs the entire project , writes the results files , and returns the URL to the report file : param response : : param project : : param ...
if project is None : project = cauldron . project . get_internal_project ( ) starting_index = 0 if starting : starting_index = project . steps . index ( starting ) count = 0 steps_run = [ ] for ps in project . steps : if 0 < limit <= count : break if ps . index < starting_index : continu...
def suspend_processes ( self , as_group , scaling_processes = None ) : """Suspends Auto Scaling processes for an Auto Scaling group . : type as _ group : string : param as _ group : The auto scaling group to suspend processes on . : type scaling _ processes : list : param scaling _ processes : Processes you...
params = { 'AutoScalingGroupName' : as_group } if scaling_processes : self . build_list_params ( params , scaling_processes , 'ScalingProcesses' ) return self . get_status ( 'SuspendProcesses' , params )
def polygon_filter_rm ( self , filt ) : """Remove a polygon filter from this instance Parameters filt : int or instance of ` PolygonFilter ` The polygon filter to remove"""
if not isinstance ( filt , ( PolygonFilter , int , float ) ) : msg = "`filt` must be a number or instance of PolygonFilter!" raise ValueError ( msg ) if isinstance ( filt , PolygonFilter ) : uid = filt . unique_id else : uid = int ( filt ) # remove item self . config [ "filtering" ] [ "polygon filters" ...
def perc_fltr ( dem , perc = ( 1.0 , 99.0 ) ) : """Percentile filter"""
rangelim = malib . calcperc ( dem , perc ) print ( 'Excluding values outside of percentile range: {0:0.2f} to {1:0.2f}' . format ( * perc ) ) out = range_fltr ( dem , rangelim ) return out
def resized ( self , dl , targ , new_path , resume = True , fn = None ) : """Return a copy of this dataset resized"""
return dl . dataset . resize_imgs ( targ , new_path , resume = resume , fn = fn ) if dl else None
def get_data_path ( filename ) : """Get the path of the given file within the batchup data directory Parameters filename : str The filename to locate within the batchup data directory Returns str The full path of the file"""
if os . path . isabs ( filename ) : return filename else : return os . path . join ( get_data_dir ( ) , filename )
def requests_view ( request , requestType ) : '''Generic request view . Parameters : request is the HTTP request requestType is URL name of a RequestType . e . g . " food " , " maintenance " , " network " , " site "'''
userProfile = UserProfile . objects . get ( user = request . user ) request_type = get_object_or_404 ( RequestType , url_name = requestType ) page_name = "{0} Requests" . format ( request_type . name . title ( ) ) if not request_type . enabled : message = "{0} requests have been disabled." . format ( request_type ....
def do_check_freshness ( self , hosts , services , timeperiods , macromodulations , checkmodulations , checks , when ) : # pylint : disable = too - many - nested - blocks , too - many - branches """Check freshness and schedule a check now if necessary . This function is called by the scheduler if Alignak is confi...
now = when # Before , check if class ( host or service ) have check _ freshness OK # Then check if item want freshness , then check freshness cls = self . __class__ if not self . in_checking and self . freshness_threshold and not self . freshness_expired : # logger . debug ( " Checking freshness for % s , last state up...
def load_json ( filename : str ) -> Union [ List , Dict ] : """Load JSON data from a file and return as dict or list . Defaults to returning empty dict if file is not found ."""
try : with open ( filename , encoding = 'utf-8' ) as fdesc : return json . loads ( fdesc . read ( ) ) except FileNotFoundError : # This is not a fatal error _LOGGER . debug ( 'JSON file not found: %s' , filename ) except ValueError as error : _LOGGER . exception ( 'Could not parse JSON content: %s' ...
def feeds ( self ) : """Property for accessing : class : ` FeedManager ` instance , which is used to manage feeds . : rtype : yagocd . resources . feed . FeedManager"""
if self . _feed_manager is None : self . _feed_manager = FeedManager ( session = self . _session ) return self . _feed_manager
def get_shard_by_key ( self , key ) : """get _ shard _ by _ key returns the Redis shard given a key . Keyword arguments : key - - the key ( e . g . ' friend _ request : { 12345 } ' ) If the key contains curly braces as in the example , then portion inside the curly braces will be used as the key id . Otherw...
key_id = self . _get_key_id_from_key ( key ) return self . get_shard_by_key_id ( key_id )
def export_handle ( self , directory ) : """Get a filehandle for exporting"""
filename = getattr ( self , 'filename' ) dest_file = "%s/%s" % ( directory , filename ) dest_dir = os . path . dirname ( dest_file ) if not os . path . isdir ( dest_dir ) : os . mkdir ( dest_dir , 0o700 ) return open ( dest_file , 'w' )
def get_hash ( path , form = 'sha256' , chunk_size = 65536 ) : '''Get the hash sum of a file This is better than ` ` get _ sum ` ` for the following reasons : - It does not read the entire file into memory . - It does not return a string on error . The returned value of ` ` get _ sum ` ` cannot really be tr...
hash_type = hasattr ( hashlib , form ) and getattr ( hashlib , form ) or None if hash_type is None : raise ValueError ( 'Invalid hash type: {0}' . format ( form ) ) with salt . utils . files . fopen ( path , 'rb' ) as ifile : hash_obj = hash_type ( ) # read the file in in chunks , not the entire file fo...
def show_user ( self , user ) : """Get a specific user : type user : str : param user : User Email : rtype : dict : return : a dictionary containing user information"""
res = self . post ( 'loadUsers' , { 'userId' : user } ) if isinstance ( res , list ) and len ( res ) > 0 : res = res [ 0 ] return _fix_user ( res )
def begin_stream_loop ( stream , poll_interval ) : """Start and maintain the streaming connection . . ."""
while should_continue ( ) : try : stream . start_polling ( poll_interval ) except Exception as e : # Infinite restart logger . error ( "Exception while polling. Restarting in 1 second." , exc_info = True ) time . sleep ( 1 )
def encode ( self , text : str ) -> str : """Encode @ username into < @ id > or < ! alias > ."""
def callback ( match : Match ) -> str : name = match . group ( "name" ) . lower ( ) if name in [ "here" , "everyone" , "channel" ] : return f"<!{name}>" else : for user in self . users . values ( ) : if user . name == name : return f"<@{user.id}>" return match...
def serialize_on_parent ( self , parent , # type : ET . Element value , # type : Any state # type : _ ProcessorState ) : # type : ( . . . ) - > None """Serialize the value and append it to the parent element ."""
if not value and self . required : state . raise_error ( MissingValue , 'Missing required array: "{}"' . format ( self . alias ) ) if not value and self . omit_empty : return # Do nothing if self . _nested is not None : array_parent = _element_get_or_add_from_parent ( parent , self . _nested ) else : # Embe...
def remove_objects ( self , bucket_name , objects_iter ) : """Removes multiple objects from a bucket . : param bucket _ name : Bucket from which to remove objects : param objects _ iter : A list , tuple or iterator that provides objects names to delete . : return : An iterator of MultiDeleteError instances ...
is_valid_bucket_name ( bucket_name ) if isinstance ( objects_iter , basestring ) : raise TypeError ( 'objects_iter cannot be `str` or `bytes` instance. It must be ' 'a list, tuple or iterator of object names' ) # turn list like objects into an iterator . objects_iter = itertools . chain ( objects_iter ) obj_batch =...
def setSearchedRecords ( self , records ) : """Sets a record set based off of an external search . Searched results provide an overridden entry to the tree widget , by passing the grouping mechanism . : param records | < orb . RecordSet > : return < bool > | records"""
self . _searchTerms = 'EXTERNAL_SEARCH' self . _currentRecordSet = records # update widget and notify any listeners if not self . signalsBlocked ( ) : self . refresh ( ) self . recordsChanged . emit ( ) return True
def url2domain ( url ) : """extract domain from url"""
parsed_uri = urlparse . urlparse ( url ) domain = '{uri.netloc}' . format ( uri = parsed_uri ) domain = re . sub ( "^.+@" , "" , domain ) domain = re . sub ( ":.+$" , "" , domain ) return domain
def pop_prefix ( string : str ) : """Erases the prefix and returns it . : throws IndexError : There is no prefix . : return A set with two elements : 1 - the prefix , 2 - the type without it ."""
result = string . split ( Naming . TYPE_PREFIX ) if len ( result ) == 1 : result = string . split ( Naming . RESOURCE_PREFIX ) if len ( result ) == 1 : raise IndexError ( ) return result
def _open_interface ( self , conn_id , iface , callback ) : """Open an interface on this device Args : conn _ id ( int ) : the unique identifier for the connection iface ( string ) : the interface name to open callback ( callback ) : Callback to be called when this command finishes callback ( conn _ id , ...
try : context = self . conns . get_context ( conn_id ) except ArgumentError : callback ( conn_id , self . id , False , "Could not find connection information" ) return self . conns . begin_operation ( conn_id , 'open_interface' , callback , self . get_config ( 'default_timeout' ) ) topics = context [ 'topic...
def add ( self , snapshot , component = 'main' ) : """Add snapshot of component to publish"""
try : self . components [ component ] . append ( snapshot ) except KeyError : self . components [ component ] = [ snapshot ]
def create_environment ( self , environment ) : """Method to create environment"""
uri = 'api/v3/environment/' data = dict ( ) data [ 'environments' ] = list ( ) data [ 'environments' ] . append ( environment ) return super ( ApiEnvironment , self ) . post ( uri , data )
def getTCPportConnStatus ( self , ipv4 = True , ipv6 = True , include_listen = False , ** kwargs ) : """Returns the number of TCP endpoints discriminated by status . @ param ipv4 : Include IPv4 ports in output if True . @ param ipv6 : Include IPv6 ports in output if True . @ param include _ listen : Include l...
status_dict = { } result = self . getStats ( tcp = True , udp = False , include_listen = include_listen , ipv4 = ipv4 , ipv6 = ipv6 , ** kwargs ) stats = result [ 'stats' ] for stat in stats : if stat is not None : status = stat [ 8 ] . lower ( ) status_dict [ status ] = status_dict . get ( status , 0 )...
def rpm ( self , vol_per_rev ) : """Return the pump speed required for the reactor ' s stock of material given the volume of fluid output per revolution by the stock ' s pump . : param vol _ per _ rev : Volume of fluid pumped per revolution ( dependent on pump and tubing ) : type vol _ per _ rev : float : r...
return Stock . rpm ( self , vol_per_rev , self . Q_stock ( ) ) . to ( u . rev / u . min )
def get_attribute_values ( self , att_name ) : """Returns the values of attribute " att _ name " of CPE Name . By default a only element in each part . : param string att _ name : Attribute name to get : returns : List of attribute values : rtype : list : exception : ValueError - invalid attribute name"""
lc = [ ] if not CPEComponent . is_valid_attribute ( att_name ) : errmsg = "Invalid attribute name: {0}" . format ( att_name ) raise ValueError ( errmsg ) for pk in CPE . CPE_PART_KEYS : elements = self . get ( pk ) for elem in elements : comp = elem . get ( att_name ) if isinstance ( com...
def mesh_stable_pose ( mesh , T_obj_table , T_table_world = RigidTransform ( from_frame = 'table' , to_frame = 'world' ) , style = 'wireframe' , smooth = False , color = ( 0.5 , 0.5 , 0.5 ) , dim = 0.15 , plot_table = True , plot_com = False , name = None ) : """Visualize a mesh in a stable pose . Parameters me...
T_obj_table = T_obj_table . as_frames ( 'obj' , 'table' ) T_obj_world = T_table_world * T_obj_table Visualizer3D . mesh ( mesh , T_obj_world , style = style , smooth = smooth , color = color , name = name ) if plot_table : Visualizer3D . table ( T_table_world , dim = dim ) if plot_com : Visualizer3D . points ( ...
def transform_tensor ( self , tensor ) : """Applies rotation portion to a tensor . Note that tensor has to be in full form , not the Voigt form . Args : tensor ( numpy array ) : a rank n tensor Returns : Transformed tensor ."""
dim = tensor . shape rank = len ( dim ) assert all ( [ i == 3 for i in dim ] ) # Build einstein sum string lc = string . ascii_lowercase indices = lc [ : rank ] , lc [ rank : 2 * rank ] einsum_string = ',' . join ( [ a + i for a , i in zip ( * indices ) ] ) einsum_string += ',{}->{}' . format ( * indices [ : : - 1 ] ) ...
def refresh ( self ) : """Refresh all class attributes ."""
strawpoll_response = requests . get ( '{api_url}/{poll_id}' . format ( api_url = api_url , poll_id = self . id ) ) raise_status ( strawpoll_response ) self . status_code = strawpoll_response . status_code self . response_json = strawpoll_response . json ( ) self . id = self . response_json [ 'id' ] self . title = self ...
def empirical_svd ( stream_list , linear = True ) : """Empirical subspace detector generation function . Takes a list of templates and computes the stack as the first order subspace detector , and the differential of this as the second order subspace detector following the empirical subspace method of ` Bar...
# Run a check to ensure all traces are the same length stachans = list ( set ( [ ( tr . stats . station , tr . stats . channel ) for st in stream_list for tr in st ] ) ) for stachan in stachans : lengths = [ ] for st in stream_list : lengths . append ( len ( st . select ( station = stachan [ 0 ] , chann...
def drain ( iterable ) : """Helper method that empties an iterable as it is iterated over . Works for : * ` ` dict ` ` * ` ` collections . deque ` ` * ` ` list ` ` * ` ` set ` `"""
if getattr ( iterable , "popleft" , False ) : def next_item ( coll ) : return coll . popleft ( ) elif getattr ( iterable , "popitem" , False ) : def next_item ( coll ) : return coll . popitem ( ) else : def next_item ( coll ) : return coll . pop ( ) while True : try : yie...
def K_plug_valve_Crane ( D1 , D2 , angle , fd = None , style = 0 ) : r'''Returns the loss coefficient for a plug valve or cock valve as shown in [1 ] _ . If β = 1: . . math : : K = K _ 1 = K _ 2 = Nf _ d Otherwise : . . math : : K _ 2 = \ frac { K + 0.5 \ sqrt { \ sin \ frac { \ theta } { 2 } } ( 1 - ...
if fd is None : fd = ft_Crane ( D2 ) beta = D1 / D2 try : K = plug_valve_Crane_coeffs [ style ] * fd except KeyError : raise KeyError ( 'Accepted valve styles are 0 (straight-through), 1 (3-way, flow straight-through), or 2 (3-way, flow 90°)' ) angle = radians ( angle ) if beta == 1 : return K else : ...
def _read_runtime_vars ( variable_file , sep = ',' ) : '''read the entire runtime variable file , and return a list of lists , each corresponding to a row . We also check the header , and exit if anything is missing or malformed . Parameters variable _ file : full path to the tabular file with token , exp _...
rows = [ x for x in read_file ( variable_file ) . split ( '\n' ) if x . strip ( ) ] valid_rows = [ ] if len ( rows ) > 0 : # Validate header and rows , exit if not valid header = rows . pop ( 0 ) . split ( sep ) validate_header ( header ) for row in rows : row = _validate_row ( row , sep = sep , req...
def readInfoElement ( self , infoElement , instanceObject ) : """Read the info element . < info / > < info " > < location / > < / info >"""
infoLocation = self . locationFromElement ( infoElement ) instanceObject . addInfo ( infoLocation , copySourceName = self . infoSource )
def draw_state ( self , name , pos , size , outcomes = None , input_ports_m = None , output_ports_m = None , selected = False , active = False , depth = 0 ) : """Draw a state with the given properties This method is called by the controller to draw the specified ( container ) state . : param name : Name of the ...
if not outcomes : outcomes = [ ] if not input_ports_m : input_ports_m = [ ] if not output_ports_m : output_ports_m = [ ] # " Generate " unique ID for each object opengl_id = self . name_counter self . name_counter += 1 glPushName ( opengl_id ) self . _set_closest_stroke_width ( 1.5 ) width = size [ 0 ] heig...
def delete_dagobah ( self , dagobah_id ) : """Deletes the Dagobah and all child Jobs from the database . Related run logs are deleted as well ."""
rec = self . dagobah_coll . find_one ( { '_id' : dagobah_id } ) for job in rec . get ( 'jobs' , [ ] ) : if 'job_id' in job : self . delete_job ( job [ 'job_id' ] ) self . log_coll . remove ( { 'parent_id' : dagobah_id } ) self . dagobah_coll . remove ( { '_id' : dagobah_id } )
def add_data ( self , t , msg , vars ) : '''add some data'''
mtype = msg . get_type ( ) for i in range ( 0 , len ( self . fields ) ) : if mtype not in self . field_types [ i ] : continue f = self . fields [ i ] simple = self . simple_field [ i ] if simple is not None : v = getattr ( vars [ simple [ 0 ] ] , simple [ 1 ] ) else : v = mav...
def csr_for_names ( names , key ) : """Generate a certificate signing request for the given names and private key . . . seealso : : ` acme . client . Client . request _ issuance ` . . seealso : : ` generate _ private _ key ` : param ` ` List [ str ] ` ` : One or more names ( subjectAltName ) for which to re...
if len ( names ) == 0 : raise ValueError ( 'Must have at least one name' ) if len ( names [ 0 ] ) > 64 : common_name = u'san.too.long.invalid' else : common_name = names [ 0 ] return ( x509 . CertificateSigningRequestBuilder ( ) . subject_name ( x509 . Name ( [ x509 . NameAttribute ( NameOID . COMMON_NAME ,...
def get_repositories_by_query ( self , repository_query ) : """Gets a list of ` ` Repositories ` ` matching the given repository query . arg : repository _ query ( osid . repository . RepositoryQuery ) : the repository query return : ( osid . repository . RepositoryList ) - the returned ` ` RepositoryList `...
# Implemented from template for # osid . resource . BinQuerySession . get _ bins _ by _ query _ template if self . _catalog_session is not None : return self . _catalog_session . get_catalogs_by_query ( repository_query ) query_terms = dict ( repository_query . _query_terms ) collection = JSONClientValidated ( 'rep...
def _validate ( url ) : """Validate a url . : param str url : Polling URL extracted from response header . : raises : ValueError if URL has no scheme or host ."""
if url is None : return parsed = urlparse ( url ) if not parsed . scheme or not parsed . netloc : raise ValueError ( "Invalid URL header" )
def Serialize ( self , writer ) : """Serialize full object . Args : writer ( neo . IO . BinaryWriter ) :"""
writer . WriteVarBytes ( self . Script ) writer . WriteVarBytes ( self . ParameterList ) writer . WriteByte ( self . ReturnType )
def p_object_literal ( self , p ) : """object _ literal : LBRACE RBRACE | LBRACE property _ list RBRACE | LBRACE property _ list COMMA RBRACE"""
if len ( p ) == 3 : p [ 0 ] = ast . Object ( ) else : p [ 0 ] = ast . Object ( properties = p [ 2 ] )
def export_data_dir ( target_path ) : """Exports the media files of the application and bundles a zip archive : return : the target path of the zip archive"""
from django_productline import utils from django . conf import settings utils . zipdir ( settings . PRODUCT_CONTEXT . DATA_DIR , target_path , wrapdir = '__data__' ) print ( '... wrote {target_path}' . format ( target_path = target_path ) ) return target_path
def update_locate_candidates ( candidate , next_candidates , x_val , y_val , degree ) : """Update list of candidate surfaces during geometric search for a point . . . note : : This is used * * only * * as a helper for : func : ` locate _ point ` . Checks if the point ` ` ( x _ val , y _ val ) ` ` is contained...
centroid_x , centroid_y , width , candidate_nodes = candidate point = np . asfortranarray ( [ x_val , y_val ] ) if not _helpers . contains_nd ( candidate_nodes , point ) : return nodes_a , nodes_b , nodes_c , nodes_d = _surface_helpers . subdivide_nodes ( candidate_nodes , degree ) half_width = 0.5 * width next_can...
def delete_user_entitlements ( self , user_id ) : """DeleteUserEntitlements . [ Preview API ] : param str user _ id :"""
route_values = { } if user_id is not None : route_values [ 'userId' ] = self . _serialize . url ( 'user_id' , user_id , 'str' ) self . _send ( http_method = 'DELETE' , location_id = '6490e566-b299-49a7-a4e4-28749752581f' , version = '5.1-preview.1' , route_values = route_values )
async def main ( ) -> None : # pylint : disable = too - many - statements """Create the aiohttp session and run the example ."""
logging . basicConfig ( level = logging . INFO ) async with ClientSession ( ) as websession : client = Client ( websession , api_key = '<API KEY>' ) # Get supported locations ( by location ) : try : _LOGGER . info ( await client . supported . countries ( ) ) _LOGGER . info ( await client . s...
def clone ( self ) : """Creates a clone of this aggregator ."""
return type ( self ) ( self . __cmp , self . __key , self . __reverse , name = self . name , dataFormat = self . _dataFormat )
def _lt_from_ge ( self , other ) : """Return a < b . Computed by @ total _ ordering from ( not a > = b ) ."""
op_result = self . __ge__ ( other ) if op_result is NotImplemented : return NotImplemented return not op_result
def _SConstruct_exists ( dirname = '' , repositories = [ ] , filelist = None ) : """This function checks that an SConstruct file exists in a directory . If so , it returns the path of the file . By default , it checks the current directory ."""
if not filelist : filelist = [ 'SConstruct' , 'Sconstruct' , 'sconstruct' ] for file in filelist : sfile = os . path . join ( dirname , file ) if os . path . isfile ( sfile ) : return sfile if not os . path . isabs ( sfile ) : for rep in repositories : if os . path . isfile (...
def pre_execute ( self , execution , context ) : """Make sure the named directory is created if possible"""
path = self . _fspath if path : path = path . format ( benchmark = context . benchmark , api = execution [ 'category' ] , ** execution . get ( 'metas' , { } ) ) if self . clean_path : shutil . rmtree ( path , ignore_errors = True ) if execution [ 'metas' ] [ 'file_mode' ] == 'onefile' : path...
def find_types_removed_from_unions ( old_schema : GraphQLSchema , new_schema : GraphQLSchema ) -> List [ BreakingChange ] : """Find types removed from unions . Given two schemas , returns a list containing descriptions of any breaking changes in the new _ schema related to removing types from a union type ."""
old_type_map = old_schema . type_map new_type_map = new_schema . type_map types_removed_from_union = [ ] for old_type_name , old_type in old_type_map . items ( ) : new_type = new_type_map . get ( old_type_name ) if not ( is_union_type ( old_type ) and is_union_type ( new_type ) ) : continue old_type...
def load_class_by_name ( name : str ) : """Given a dotted path , returns the class"""
mod_path , _ , cls_name = name . rpartition ( '.' ) mod = importlib . import_module ( mod_path ) cls = getattr ( mod , cls_name ) return cls
def printDatawraps ( ) : """print all available datawraps for bootstraping"""
l = listDatawraps ( ) printf ( "Available datawraps for boostraping\n" ) for k , v in l . iteritems ( ) : printf ( k ) printf ( "~" * len ( k ) + "|" ) for vv in v : printf ( " " * len ( k ) + "|" + "~~~:> " + vv ) printf ( '\n' )
def update_humidity_temp ( self ) : """This method utilizes the HIH7xxx sensor to read humidity and temperature in one call ."""
# Create mask for STATUS ( first two bits of 64 bit wide result ) STATUS = 0b11 << 6 TCA_select ( SensorCluster . bus , self . mux_addr , SensorCluster . humidity_chan ) SensorCluster . bus . write_quick ( SensorCluster . humidity_addr ) # Begin conversion sleep ( .25 ) # wait 100ms to make sure the conversion takes pl...
def get_frame ( ) : """Returns a QFrame formatted in a particular way"""
ret = QFrame ( ) ret . setLineWidth ( 1 ) ret . setMidLineWidth ( 0 ) ret . setFrameShadow ( QFrame . Sunken ) ret . setFrameShape ( QFrame . Box ) return ret
def setTableProperty ( self , login , tableName , property , value ) : """Parameters : - login - tableName - property - value"""
self . send_setTableProperty ( login , tableName , property , value ) self . recv_setTableProperty ( )
def get_isogeo_version ( self , component : str = "api" , prot : str = "https" ) : """Get Isogeo components versions . Authentication not required . : param str component : which platform component . Options : * api [ default ] * db * app"""
# which component if component == "api" : version_url = "{}://v1.{}.isogeo.com/about" . format ( prot , self . api_url ) elif component == "db" : version_url = "{}://v1.{}.isogeo.com/about/database" . format ( prot , self . api_url ) elif component == "app" and self . platform == "prod" : version_url = "htt...
def connection_service_name ( service , * args ) : '''the name of a service that manages the connection between services'''
# if the service is a string if isinstance ( service , str ) : return service return normalize_string ( type ( service ) . __name__ )
def check_power ( self ) : """Returns the power state of the smart power strip ."""
state = self . check_power_raw ( ) data = { } data [ 's1' ] = bool ( state & 0x01 ) data [ 's2' ] = bool ( state & 0x02 ) data [ 's3' ] = bool ( state & 0x04 ) data [ 's4' ] = bool ( state & 0x08 ) return data
def get_groups_for_user ( self , user_name , marker = None , max_items = None ) : """List the groups that a specified user belongs to . : type user _ name : string : param user _ name : The name of the user to list groups for . : type marker : string : param marker : Use this only when paginating results an...
params = { 'UserName' : user_name } if marker : params [ 'Marker' ] = marker if max_items : params [ 'MaxItems' ] = max_items return self . get_response ( 'ListGroupsForUser' , params , list_marker = 'Groups' )
def list_i2str ( ilist ) : """Convert an integer list into a string list ."""
slist = [ ] for el in ilist : slist . append ( str ( el ) ) return slist
def prune_old_authorization_codes ( ) : """Removes all unused and expired authorization codes from the database ."""
from . compat import now from . models import AuthorizationCode AuthorizationCode . objects . with_expiration_before ( now ( ) ) . delete ( )
def create_set_property_batch_request_content ( options ) : """Creates an XML for requesting of setting a property values for remote WebDAV resource in batch . : param options : the property attributes as list of dictionaries with following keys : ` namespace ` : ( optional ) the namespace for XML property whic...
root_node = etree . Element ( 'propertyupdate' , xmlns = 'DAV:' ) set_node = etree . SubElement ( root_node , 'set' ) prop_node = etree . SubElement ( set_node , 'prop' ) for option in options : opt_node = etree . SubElement ( prop_node , option [ 'name' ] , xmlns = option . get ( 'namespace' , '' ) ) opt_node ...
def bind_library ( self ) : """Binds the Library using functions registered in the * * self . _ _ functions * * attribute . Usage : : > > > import ctypes > > > path = " FreeImage . dll " > > > functions = ( LibraryHook ( name = " FreeImage _ GetVersion " , arguments _ types = None , return _ value = ctypes ...
if self . __functions : for function in self . __functions : self . bind_function ( function ) return True
def get_child_queues ( self , name ) : """Get information about all children of a parent queue . Parameters name : str The parent queue name . Returns queues : list of Queue Examples > > > client . get _ child _ queues ( ' myqueue ' ) [ Queue < name = ' child1 ' , percent _ used = 10.00 > , Queue ...
req = proto . QueueRequest ( name = name ) resp = self . _call ( 'getChildQueues' , req ) return [ Queue . from_protobuf ( q ) for q in resp . queues ]
def modify ( self , modification , parameters ) : """Apply a modification to the underlying point sources , with the same parameters for all sources"""
for src in self : src . modify ( modification , parameters )
def gp_sims_panel ( version ) : """panel plot of cocktail simulations at all energies , includ . total : param version : plot version / input subdir name : type version : str"""
inDir , outDir = getWorkDirs ( ) inDir = os . path . join ( inDir , version ) mesons = [ 'pion' , 'eta' , 'etap' , 'rho' , 'omega' , 'phi' , 'jpsi' ] fstems = [ 'cocktail_contribs/' + m for m in mesons ] + [ 'cocktail' , 'cocktail_contribs/ccbar' ] data = OrderedDict ( ( energy , [ np . loadtxt ( open ( os . path . joi...
def save ( self , file_or_wfs , filename = None , bbox = None , overwrite = None ) : '''Save a Werkzeug FileStorage object'''
self . _mark_as_changed ( ) override = filename is not None filename = filename or getattr ( file_or_wfs , 'filename' ) if self . basename and not override : basename = self . basename ( self . _instance ) elif filename : basename = splitext ( filename ) [ 0 ] else : raise ValueError ( 'Filename is required...
def report ( self , stream ) : """Output code coverage report ."""
if not self . xcoverageToStdout : # This will create a false stream where output will be ignored stream = StringIO ( ) super ( XCoverage , self ) . report ( stream ) if not hasattr ( self , 'coverInstance' ) : # nose coverage plugin 1.0 and earlier import coverage self . coverInstance = coverage . _the_cove...
def download_as_string ( self , client = None , start = None , end = None ) : """Download the contents of this blob as a string . If : attr : ` user _ project ` is set on the bucket , bills the API request to that project . : type client : : class : ` ~ google . cloud . storage . client . Client ` or ` ` No...
string_buffer = BytesIO ( ) self . download_to_file ( string_buffer , client = client , start = start , end = end ) return string_buffer . getvalue ( )
def rollback ( cls , resource , background = False ) : """Rollback a disk from a snapshot ."""
disk_id = cls . usable_id ( resource ) result = cls . call ( 'hosting.disk.rollback_from' , disk_id ) if background : return result cls . echo ( 'Disk rollback in progress.' ) cls . display_progress ( result ) return result
def _GetNormalizedTimestamp ( self ) : """Retrieves the normalized timestamp . Returns : float : normalized timestamp , which contains the number of seconds since January 1 , 1970 00:00:00 and a fraction of second used for increased precision , or None if the normalized timestamp cannot be determined ."""
if self . _normalized_timestamp is None : if ( self . _timestamp is not None and self . _timestamp >= self . _INT64_MIN and self . _timestamp <= self . _INT64_MAX ) : self . _normalized_timestamp = ( decimal . Decimal ( self . _timestamp ) / definitions . MICROSECONDS_PER_SECOND ) self . _normalized...
def _notify_create_process ( self , event ) : """Notify the creation of a new process . @ warning : This method is meant to be used internally by the debugger . @ type event : L { CreateProcessEvent } @ param event : Create process event . @ rtype : bool @ return : C { True } to call the user - defined ha...
dwProcessId = event . get_pid ( ) if dwProcessId not in self . __attachedDebugees : if dwProcessId not in self . __startedDebugees : self . __startedDebugees . add ( dwProcessId ) retval = self . system . _notify_create_process ( event ) # Set a breakpoint on the program ' s entry point if requested . # Try...
def proto_refactor ( proto_filename , namespace , namespace_path ) : """This method refactors a Protobuf file to import from a namespace that will map to the desired python package structure . It also ensures that the syntax is set to " proto2 " , since protoc complains without it . Args : proto _ filename ...
with open ( proto_filename ) as f : data = f . read ( ) if not re . search ( 'syntax = "proto2"' , data ) : insert_syntax = 'syntax = "proto2";\n' data = insert_syntax + data substitution = 'import "{}/\\1";' . format ( namespace_path ) data = re . sub ( 'import\s+"([^"]+\.proto)"\s*;' ,...
def highlight_problems ( self , has_problems ) : """Outline grid buttons in red if they have validation errors"""
if has_problems : self . validation_mode = set ( has_problems ) # highlighting doesn ' t work with Windows if sys . platform in [ 'win32' , 'win62' ] : self . message . SetLabel ( 'The following grid(s) have incorrect or incomplete data:\n{}' . format ( ', ' . join ( self . validation_mode ) ) ) ...
def validate_params ( cls , mtd_name , * args , ** kwargs ) : """Validates if the given args / kwargs match the method signature . Checks if : - at least all required args / kwargs are given - no redundant args / kwargs are given Parameters cls : Class mtd _ name : str Name of the method whose parameter...
mtd = getattr ( cls , mtd_name ) py3_mtd_condition = ( not ( inspect . isfunction ( mtd ) or inspect . ismethod ( mtd ) ) and hasattr ( cls , mtd_name ) ) py2_mtd_condition = ( not inspect . ismethod ( mtd ) and not isinstance ( cls . __dict__ [ mtd_name ] , staticmethod ) ) if ( PY3 and py3_mtd_condition ) or ( PY2 an...
def create_or_update_lun_id ( self , volume_id , lun_id ) : """Set the LUN ID on a volume . : param integer volume _ id : The id of the volume : param integer lun _ id : LUN ID to set on the volume : return : a SoftLayer _ Network _ Storage _ Property object"""
return self . client . call ( 'Network_Storage' , 'createOrUpdateLunId' , lun_id , id = volume_id )
def read ( self , key , array = False , embedded = True ) : """Read method of CRUD operation for working with KeyValue DB . This method will automatically check to see if a single variable is passed or if " mixed " data is passed and return the results from the DB . It will also automatically determine the va...
self . tcex . log . debug ( 'read variable {}' . format ( key ) ) # if a non - variable value is passed it should be the default data = key if key is not None : key = key . strip ( ) key_type = self . variable_type ( key ) if re . match ( self . _variable_match , key ) : if key_type in self . read_d...
def lookup ( self , vtype , vname , target_id = None ) : """Return value of vname from the variable store vtype . Valid vtypes are ` strings ` ' counters ' , and ` pending ` . If the value is not found in the current steps store , earlier steps will be checked . If not found , ' ' , 0 , or ( None , None ) is ...
nullvals = { 'strings' : '' , 'counters' : 0 , 'pending' : ( None , None ) } nullval = nullvals [ vtype ] vstyle = None if vtype == 'counters' : if len ( vname ) > 1 : vname , vstyle = vname else : vname = vname [ 0 ] if target_id is not None : try : state = self . state [ vtype ] [ ...
def main ( ) : '''Organization function - setups logging - gets inputdata - calls plotting function'''
args = get_args ( ) try : utils . make_output_dir ( args . outdir ) utils . init_logs ( args ) args . format = nanoplotter . check_valid_format ( args . format ) settings = vars ( args ) settings [ "path" ] = path . join ( args . outdir , args . prefix ) sources = { "fastq" : args . fastq , "bam...
def get_children ( self , root = None , target = None ) : """return list of all the children of root of given tree : param root : treectrl item , treeitemid : param target : treectrl object"""
if root is None : print ( "Warning: TreeCtrl root/child must be given." ) return None if target is None : print ( "Warning: TreeCtrl target must be given." ) return None child , cookie = target . GetFirstChild ( root ) child_list = [ ] while child . IsOk ( ) : if target . ItemHasChildren ( child ) :...
def PROFILE_RAUTIAN ( sg0 , GamD , Gam0 , Shift0 , anuVC , eta , sg ) : """# Rautian profile based on HTP . # Input parameters : # sg0 : Unperturbed line position in cm - 1 ( Input ) . # GamD : Doppler HWHM in cm - 1 ( Input ) # Gam0 : Speed - averaged line - width in cm - 1 ( Input ) . # anuVC : Velocity...
return pcqsdhc ( sg0 , GamD , Gam0 , cZero , Shift0 , cZero , anuVC , cZero , sg )
def on_delivery ( self , channel , method , properties , body ) : """Invoked by pika when RabbitMQ delivers a message from a queue . : param channel : The channel the message was delivered on : type channel : pika . channel . Channel : param method : The AMQP method frame : type method : pika . frame . Fram...
self . callbacks . on_delivery ( self . name , channel , method , properties , body )