signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def cli ( ctx ) : """This is a command line app to get useful stats from a trello board and report on them in useful ways . Requires the following environment varilables : TRELLOSTATS _ APP _ KEY = < your key here > TRELLOSTATS _ APP _ TOKEN = < your token here >"""
ctx . obj = dict ( ) ctx . obj [ 'app_key' ] = os . environ . get ( 'TRELLOSTATS_APP_KEY' ) ctx . obj [ 'app_token' ] = os . environ . get ( 'TRELLOSTATS_APP_TOKEN' ) init_db ( db_proxy )
def add_tags ( self , * tags ) : '''Set tags for a given archive'''
normed_tags = self . api . manager . _normalize_tags ( tags ) self . api . manager . add_tags ( self . archive_name , normed_tags )
def get ( self , index ) : """Gets data values for specified : index : . : index : Index for which to get data . : returns : A list in form [ parent , name , priority , comment , done , children ] ."""
data = self . data index2 = self . _split ( index ) for c in index2 [ : - 1 ] : i = int ( c ) - 1 data = data [ i ] [ 4 ] return [ index [ : - 2 ] or "" ] + data [ int ( index [ - 1 ] ) - 1 ]
def compile_args ( args , kwargs , sep , prefix ) : """takes args and kwargs , as they were passed into the command instance being executed with _ _ call _ _ , and compose them into a flat list that will eventually be fed into exec . example : with this call : sh . ls ( " - l " , " / tmp " , color = " never...
processed_args = [ ] encode = encode_to_py3bytes_or_py2str # aggregate positional args for arg in args : if isinstance ( arg , ( list , tuple ) ) : if isinstance ( arg , GlobResults ) and not arg : arg = [ arg . path ] for sub_arg in arg : processed_args . append ( encode ( s...
def _length_hint ( obj ) : """Returns the length hint of an object ."""
try : return len ( obj ) except TypeError : try : get_hint = type ( obj ) . __length_hint__ except AttributeError : return None try : hint = get_hint ( obj ) except TypeError : return None if hint is NotImplemented or not isinstance ( hint , ( int , long ) ) or hi...
def report ( cls ) : """Return the state of the all of the registered pools . : rtype : dict"""
return { 'timestamp' : datetime . datetime . utcnow ( ) . isoformat ( ) , 'process' : os . getpid ( ) , 'pools' : dict ( [ ( i , p . report ( ) ) for i , p in cls . _pools . items ( ) ] ) }
def download_bundle_view ( self , request , pk ) : """A view that allows the user to download a certificate bundle in PEM format ."""
return self . _download_response ( request , pk , bundle = True )
def get_name ( self , origin = None ) : """Read the next token and interpret it as a DNS name . @ raises dns . exception . SyntaxError : @ rtype : dns . name . Name object"""
token = self . get ( ) if not token . is_identifier ( ) : raise dns . exception . SyntaxError ( 'expecting an identifier' ) return dns . name . from_text ( token . value , origin )
def _get_galaxy_data_table ( name , dt_config_file ) : """Parse data table config file for details on tool * . loc location and columns ."""
out = { } if os . path . exists ( dt_config_file ) : tdtc = ElementTree . parse ( dt_config_file ) for t in tdtc . getiterator ( "table" ) : if t . attrib . get ( "name" , "" ) in [ name , "%s_indexes" % name ] : out [ "column" ] = [ x . strip ( ) for x in t . find ( "columns" ) . text . spl...
def get_to ( self , ins ) : """Resolve the output attribute value for ' chromosome _ id ' . Valid values are immutable , ie . the attribute key is not an actual entity . Mutable values will be changed to match the immutable value if unique . Otherwise an error is thrown . : param ins : iterable of input workf...
input_entities = set ( ) attribute_values = set ( ) for in_ in ins : if self . ATTRIBUTE not in self . entity_graph . has_a . get_descendants ( in_ . head . name ) : attribute_values . update ( in_ . head . attributes [ self . ATTRIBUTE ] ) input_entities . add ( in_ . head . name ) if len ( attribu...
def _rt_update_docindices ( self , element , docstart , docend ) : """Updates the docstart , docend , start and end attributes for the specified element using the new limits for the docstring ."""
# see how many characters have to be added / removed from the end # of the current doc limits . delta = element . docend - docend element . docstart = docstart element . docend = docend element . start += delta element . end += delta return delta
def _clean_data ( api_response ) : '''Returns the DATA response from a Linode API query as a single pre - formatted dictionary api _ response The query to be cleaned .'''
data = { } data . update ( api_response [ 'DATA' ] ) if not data : response_data = api_response [ 'DATA' ] data . update ( response_data ) return data
def get_defs ( self , cache = True ) : """Gets the defitions args : cache : True will read from the file cache , False queries the triplestore"""
log . debug ( " *** Started" ) cache = self . __use_cache__ ( cache ) if cache : log . info ( " loading json cache" ) try : with open ( self . cache_filepath ) as file_obj : self . results = json . loads ( file_obj . read ( ) ) except FileNotFoundError : self . results = [ ] if n...
def _cleanly_slice_encoded_string ( encoded_string , length_limit ) : """Takes a byte string ( a UTF - 8 encoded string ) and splits it into two pieces such that the first slice is no longer than argument ` length _ limit ` , then returns a tuple containing the first slice and remainder of the byte string , res...
sliced , remaining = encoded_string [ : length_limit ] , encoded_string [ length_limit : ] try : sliced . decode ( 'utf-8' ) except UnicodeDecodeError as e : sliced , remaining = sliced [ : e . start ] , sliced [ e . start : ] + remaining return sliced , remaining
def fit_ahrs ( A , H , Aoff , Arot , Hoff , Hrot ) : """Calculate yaw , pitch and roll for given A / H and calibration set . Author : Vladimir Kulikovsky Parameters A : list , tuple or numpy . array of shape ( 3 , ) H : list , tuple or numpy . array of shape ( 3 , ) Aoff : numpy . array of shape ( 3 , ) ...
Acal = np . dot ( A - Aoff , Arot ) Hcal = np . dot ( H - Hoff , Hrot ) # invert axis for DOM upside down for i in ( 1 , 2 ) : Acal [ i ] = - Acal [ i ] Hcal [ i ] = - Hcal [ i ] roll = arctan2 ( - Acal [ 1 ] , - Acal [ 2 ] ) pitch = arctan2 ( Acal [ 0 ] , np . sqrt ( Acal [ 1 ] * Acal [ 1 ] + Acal [ 2 ] * Acal...
def victims ( self , filters = None , params = None ) : """Gets all victims from a tag ."""
victim = self . _tcex . ti . victim ( None ) for v in self . tc_requests . victims_from_tag ( victim , self . name , filters = filters , params = params ) : yield v
def _draw_feature ( self , feature , extent , colour , bg , xo , yo ) : """Draw a single feature from a layer in a vector tile ."""
geometry = feature [ "geometry" ] if geometry [ "type" ] == "Polygon" : self . _draw_polygons ( feature , bg , colour , extent , geometry [ "coordinates" ] , xo , yo ) elif feature [ "geometry" ] [ "type" ] == "MultiPolygon" : for multi_polygon in geometry [ "coordinates" ] : self . _draw_polygons ( fea...
def _scalar_field_to_json ( field , row_value ) : """Maps a field and value to a JSON - safe value . Args : field ( : class : ` ~ google . cloud . bigquery . schema . SchemaField ` , ) : The SchemaField to use for type conversion and field name . row _ value ( any ) : Value to be converted , based on the ...
converter = _SCALAR_VALUE_TO_JSON_ROW . get ( field . field_type ) if converter is None : # STRING doesn ' t need converting return row_value return converter ( row_value )
def legal_graph ( graph ) : '''judge if a graph is legal or not .'''
descriptor = graph . extract_descriptor ( ) skips = descriptor . skip_connections if len ( skips ) != len ( set ( skips ) ) : return False return True
def citation_count ( doi , url = "http://www.crossref.org/openurl/" , key = "cboettig@ropensci.org" , ** kwargs ) : '''Get a citation count with a DOI : param doi : [ String ] DOI , digital object identifier : param url : [ String ] the API url for the function ( should be left to default ) : param keyc : [ S...
args = { "id" : "doi:" + doi , "pid" : key , "noredirect" : True } args = dict ( ( k , v ) for k , v in args . items ( ) if v ) res = requests . get ( url , params = args , headers = make_ua ( ) , ** kwargs ) xmldoc = minidom . parseString ( res . content ) val = xmldoc . getElementsByTagName ( 'query' ) [ 0 ] . attrib...
def _send_timer_failed ( self , fail ) : """Our _ send _ batch ( ) function called by the LoopingCall failed . Some error probably came back from Kafka and _ check _ error ( ) raised the exception For now , just log the failure and restart the loop"""
log . warning ( '_send_timer_failed:%r: %s' , fail , fail . getBriefTraceback ( ) ) self . _sendLooperD = self . _sendLooper . start ( self . batch_every_t , now = False )
def _convert_xml_to_service_properties ( response ) : '''< ? xml version = " 1.0 " encoding = " utf - 8 " ? > < StorageServiceProperties > < Logging > < Version > version - number < / Version > < Delete > true | false < / Delete > < Read > true | false < / Read > < Write > true | false < / Write > < R...
if response is None or response . body is None : return None service_properties_element = ETree . fromstring ( response . body ) service_properties = ServiceProperties ( ) # Logging logging = service_properties_element . find ( 'Logging' ) if logging is not None : service_properties . logging = Logging ( ) ...
def login ( self ) : """This method performs the login on TheTVDB given the api key , user name and account identifier . : return : None"""
auth_data = dict ( ) auth_data [ 'apikey' ] = self . api_key auth_data [ 'username' ] = self . username auth_data [ 'userkey' ] = self . account_identifier auth_resp = requests_util . run_request ( 'post' , self . API_BASE_URL + '/login' , data = json . dumps ( auth_data ) , headers = self . __get_header ( ) ) if auth_...
def p_arguments ( p ) : """arguments : arguments COMMA expr"""
if p [ 1 ] is None or p [ 3 ] is None : p [ 0 ] = None else : p [ 0 ] = make_arg_list ( p [ 1 ] , make_argument ( p [ 3 ] , p . lineno ( 2 ) ) )
def remove_user ( config , group , username ) : """Remove specified user from specified group ."""
client = Client ( ) client . prepare_connection ( ) group_api = API ( client ) try : group_api . remove_user ( group , username ) except ldap_tools . exceptions . NoGroupsFound : # pragma : no cover print ( "Group ({}) not found" . format ( group ) ) except ldap_tools . exceptions . TooManyResults : # pragma : ...
def transformer ( self ) : """Return the class for this field that transforms non - Entity objects ( e . g . , dicts or binding objects ) into Entity instances . Any non - None value returned from this method should implement a from _ obj ( ) and from _ dict ( ) method . Returns : None if no type _ or fac...
if self . factory : return self . factory elif self . type_ : return self . type_ else : return None
def add_openmp ( self ) : """Indicates that this wrapper should use OpenMP by setting the $ OMP _ NUM _ THREADS environment variable equal to the number of threads specified in the BioLite configuration file ."""
threads = min ( int ( config . get_resource ( 'threads' ) ) , self . max_concurrency ) self . env [ 'OMP_NUM_THREADS' ] = str ( threads )
def linearWalk ( rootPath , currentDirFilter = None ) : """Returns a list of LinearWalkItem ' s , one for each file in the tree whose root is " rootPath " . The parameter " currentDirFilter " is a method applied to every tuple ( dirPath , dirNames , fileNames ) automatically processed by os . walk ( ) : - - i...
for dirTuple in os . walk ( rootPath ) : ( dirPath , dirNames , fileNames ) = dirTuple if currentDirFilter is not None and not currentDirFilter ( dirPath , dirNames , fileNames ) : continue for fileName in fileNames : yield LinearWalkItem ( dirPath , fileName )
def _fullsize_link_tag ( self , kwargs , title ) : """Render a < a href > that points to the fullsize rendition specified"""
return utils . make_tag ( 'a' , { 'href' : self . get_fullsize ( kwargs ) , 'data-lightbox' : kwargs [ 'gallery_id' ] , 'title' : title } )
def wilcoxont ( x , y ) : """Calculates the Wilcoxon T - test for related samples and returns the result . A non - parametric T - test . Usage : lwilcoxont ( x , y ) Returns : a t - statistic , two - tail probability estimate"""
if len ( x ) != len ( y ) : raise ValueError ( 'Unequal N in wilcoxont. Aborting.' ) d = [ ] for i in range ( len ( x ) ) : diff = x [ i ] - y [ i ] if diff != 0 : d . append ( diff ) count = len ( d ) absd = map ( abs , d ) absranked = rankdata ( absd ) r_plus = 0.0 r_minus = 0.0 for i in range ( ...
def as_array ( self , transpose = False , items = None ) : """Convert the blockmanager data into an numpy array . Parameters transpose : boolean , default False If True , transpose the return array items : list of strings or None Names of block items that will be included in the returned array . ` ` Non...
if len ( self . blocks ) == 0 : arr = np . empty ( self . shape , dtype = float ) return arr . transpose ( ) if transpose else arr if items is not None : mgr = self . reindex_axis ( items , axis = 0 ) else : mgr = self if self . _is_single_block and mgr . blocks [ 0 ] . is_datetimetz : # TODO ( Block . ...
def _sequence_search ( self , start : GridQubit , current : List [ GridQubit ] ) -> List [ GridQubit ] : """Search for the continuous linear sequence from the given qubit . This method is called twice for the same starting qubit , so that sequences that begin and end on this qubit are searched for . Args : ...
used = set ( current ) seq = [ ] n = start # type : Optional [ GridQubit ] while n is not None : # Append qubit n to the sequence and mark it is as visited . seq . append ( n ) used . add ( n ) # Advance search to the next qubit . n = self . _choose_next_qubit ( n , used ) return seq
def get_workspace_disk_usage ( workspace , summarize = False ) : """Retrieve disk usage information of a workspace ."""
command = [ 'du' , '-h' ] if summarize : command . append ( '-s' ) else : command . append ( '-a' ) command . append ( workspace ) disk_usage_info = subprocess . check_output ( command ) . decode ( ) . split ( ) # create pairs of ( size , filename ) filesize_pairs = list ( zip ( disk_usage_info [ : : 2 ] , disk...
def on_medium_change ( self , medium_attachment , force ) : """Triggered when attached media of the associated virtual machine have changed . in medium _ attachment of type : class : ` IMediumAttachment ` The medium attachment which changed . in force of type bool If the medium change was forced . raise...
if not isinstance ( medium_attachment , IMediumAttachment ) : raise TypeError ( "medium_attachment can only be an instance of type IMediumAttachment" ) if not isinstance ( force , bool ) : raise TypeError ( "force can only be an instance of type bool" ) self . _call ( "onMediumChange" , in_p = [ medium_attachme...
def get_file_extension_type ( filename ) : """Return the group associated to the file : param filename : : return : str"""
ext = get_file_extension ( filename ) if ext : for name , group in EXTENSIONS . items ( ) : if ext in group : return name return "OTHER"
def get_filename_extensions ( url = 'https://www.webopedia.com/quick_ref/fileextensionsfull.asp' ) : """Load a DataFrame of filename extensions from the indicated url > > > df = get _ filename _ extensions ( ' https : / / www . openoffice . org / dev _ docs / source / file _ extensions . html ' ) > > > df . hea...
df = get_longest_table ( url ) columns = list ( df . columns ) columns [ 0 ] = 'ext' columns [ 1 ] = 'description' if len ( columns ) > 2 : columns [ 2 ] = 'details' df . columns = columns return df
def read_namespaced_controller_revision ( self , name , namespace , ** kwargs ) : # noqa : E501 """read _ namespaced _ controller _ revision # noqa : E501 read the specified ControllerRevision # noqa : E501 This method makes a synchronous HTTP request by default . To make an asynchronous HTTP request , please...
kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'async_req' ) : return self . read_namespaced_controller_revision_with_http_info ( name , namespace , ** kwargs ) # noqa : E501 else : ( data ) = self . read_namespaced_controller_revision_with_http_info ( name , namespace , ** kwargs ) # noqa...
async def get_update_info ( self , from_network = True ) -> SoftwareUpdateInfo : """Get information about updates ."""
if from_network : from_network = "true" else : from_network = "false" # from _ network = " " info = await self . services [ "system" ] [ "getSWUpdateInfo" ] ( network = from_network ) return SoftwareUpdateInfo . make ( ** info )
def open ( self , filename , mode = 'r' , ** kwargs ) : '''Open the file and return a file - like object . : param str filename : The storage root - relative filename : param str mode : The open mode ( ` ` ( r | w ) b ? ` ` ) : raises FileNotFound : If trying to read a file that does not exists'''
if 'r' in mode and not self . backend . exists ( filename ) : raise FileNotFound ( filename ) return self . backend . open ( filename , mode , ** kwargs )
def sparsify ( dirname , output_every ) : """Remove files from an output directory at regular interval , so as to make it as if there had been more iterations between outputs . Can be used to reduce the storage size of a directory . If the new number of iterations between outputs is not an integer multiple ...
fnames = get_filenames ( dirname ) output_every_old = get_output_every ( dirname ) if output_every % output_every_old != 0 : raise ValueError ( 'Directory with output_every={} cannot be coerced to' 'desired new value.' . format ( output_every_old ) ) keep_every = output_every // output_every_old fnames_to_keep = fn...
def surfplot ( self , z , titletext ) : """Plot if you want to - for troubleshooting - 1 figure"""
if self . latlon : plt . imshow ( z , extent = ( 0 , self . dx * z . shape [ 0 ] , self . dy * z . shape [ 1 ] , 0 ) ) # , interpolation = ' nearest ' plt . xlabel ( 'longitude [deg E]' , fontsize = 12 , fontweight = 'bold' ) plt . ylabel ( 'latitude [deg N]' , fontsize = 12 , fontweight = 'bold' ) else...
def decimal ( self , column , total = 8 , places = 2 ) : """Create a new decimal column on the table . : param column : The column : type column : str : type total : int : type places : 2 : rtype : Fluent"""
return self . _add_column ( "decimal" , column , total = total , places = places )
def suggest ( self , name , text , field , type = 'term' , size = None , params = None , ** kwargs ) : """Execute suggester of given type . : param name : name for the suggester : param text : text to search for : param field : field to search : param type : One of : completion , phrase , term : param siz...
from . query import Suggest suggest = Suggest ( ) suggest . add ( text , name , field , type = type , size = size , params = params ) return self . suggest_from_object ( suggest , ** kwargs )
def guass ( self , mu : float , sigma : float ) -> float : """Return a random number using Gaussian distribution . Args : mu ( float ) : The median returned value . sigma ( float ) : The standard deviation . Returns : float : A random float ."""
return float ( lib . TCOD_random_get_gaussian_double ( self . random_c , mu , sigma ) )
def update ( self , new_lease_time , client = None ) : """Update the duration of a task lease : type new _ lease _ time : int : param new _ lease _ time : the new lease time in seconds . : type client : : class : ` gcloud . taskqueue . client . Client ` or ` ` NoneType ` ` : param client : Optional . The cl...
return self . taskqueue . update_task ( self . id , new_lease_time = new_lease_time , client = client )
def get_commands_aliases_and_macros_for_completion ( self ) -> List [ str ] : """Return a list of visible commands , aliases , and macros for tab completion"""
visible_commands = set ( self . get_visible_commands ( ) ) alias_names = set ( self . get_alias_names ( ) ) macro_names = set ( self . get_macro_names ( ) ) return list ( visible_commands | alias_names | macro_names )
def pendingResultsFor ( self , ps ) : """Retrieve a list of all pending results associated with the given parameters . : param ps : the parameters : returns : a list of pending result job ids , which may be empty"""
k = self . _parametersAsIndex ( ps ) if k in self . _results . keys ( ) : # filter out pending job ids , which can be anything except dicts return [ j for j in self . _results [ k ] if not isinstance ( j , dict ) ] else : return [ ]
def raw_audit_trail ( request , pid , type = None , repo = None ) : '''View to display the raw xml audit trail for a Fedora Object . Returns an : class : ` ~ django . http . HttpResponse ` with the response content populated with the content of the audit trial . If the object is not found or does not have an ...
if repo is None : repo = Repository ( ) # no special options are * needed * to access audit trail , since it # is available on any DigitalObject ; but a particular view may be # restricted to a certain type of object get_obj_opts = { } if type is not None : get_obj_opts [ 'type' ] = type obj = repo . get_object...
def get_go2obj ( self , goids ) : """Return a go2obj dict for just the user goids ."""
go2obj = self . go2obj return { go : go2obj [ go ] for go in goids }
def serialize ( self ) : """Serialize the query to a structure using the query DSL ."""
data = { 'doc' : self . doc } if isinstance ( self . query , Query ) : data [ 'query' ] = self . query . serialize ( ) return data
def _eq ( self , other ) : """Compare two nodes for equality ."""
return ( self . type , self . children ) == ( other . type , other . children )
def mutator ( * cache_names ) : """Decorator for ` ` Document ` ` methods that change the document . This decorator ensures that the object ' s caches are kept in sync when changes are made ."""
def deco ( fn ) : @ wraps ( fn ) def _fn ( self , * args , ** kwargs ) : try : return fn ( self , * args , ** kwargs ) finally : for cache_name in cache_names : setattr ( self , cache_name , None ) return _fn return deco
def add_edurange ( self , edurange ) : """Parameters edurange : etree . Element etree representation of a < edurange > element ( annotation that groups a number of EDUs ) < edu - range > seems to glue together a number of ` < edu > elements , which may be scattered over a number of sentences < edu - ran...
edurange_id = self . get_element_id ( edurange ) edurange_attribs = self . element_attribs_to_dict ( edurange ) # contains ' span ' or nothing self . add_node ( edurange_id , layers = { self . ns , self . ns + ':edu:range' } , attr_dict = edurange_attribs ) for edu in edurange . iterdescendants ( 'edu' ) : edu_id =...
def get_server_setting ( self , protocol , host = '127.0.0.1' , port = 8000 , debug = False , ssl = None , sock = None , workers = 1 , loop = None , backlog = 100 , has_log = True ) : '''Helper function used by ` run ` .'''
if isinstance ( ssl , dict ) : # try common aliaseses cert = ssl . get ( 'cert' ) or ssl . get ( 'certificate' ) key = ssl . get ( 'key' ) or ssl . get ( 'keyfile' ) if cert is None or key is None : raise ValueError ( 'SSLContext or certificate and key required.' ) context = create_default_conte...
def make_segment ( data , mode , encoding = None ) : """Creates a : py : class : ` Segment ` . : param data : The segment data : param mode : The mode . : param encoding : The encoding . : rtype : _ Segment"""
segment_data , segment_length , segment_encoding = data_to_bytes ( data , encoding ) segment_mode = mode # If the user prefers BYTE , use BYTE and do not try to find a better mode # Necessary since BYTE < KANJI and find _ mode may return KANJI as ( more ) # appropriate mode and the encoder throws an exception # if " us...
def Addition ( left : vertex_constructor_param_types , right : vertex_constructor_param_types , label : Optional [ str ] = None ) -> Vertex : """Adds one vertex to another : param left : a vertex to add : param right : a vertex to add"""
return Double ( context . jvm_view ( ) . AdditionVertex , label , cast_to_double_vertex ( left ) , cast_to_double_vertex ( right ) )
def do_transition_for ( brain_or_object , transition ) : """Performs a workflow transition for the passed in object . : param brain _ or _ object : A single catalog brain or content object : type brain _ or _ object : ATContentType / DexterityContentType / CatalogBrain : returns : The object where the transti...
if not isinstance ( transition , basestring ) : fail ( "Transition type needs to be string, got '%s'" % type ( transition ) ) obj = get_object ( brain_or_object ) try : ploneapi . content . transition ( obj , transition ) except ploneapi . exc . InvalidParameterError as e : fail ( "Failed to perform transit...
def objectsFromPEM ( pemdata ) : """Load some objects from a PEM ."""
certificates = [ ] keys = [ ] blobs = [ b"" ] for line in pemdata . split ( b"\n" ) : if line . startswith ( b'-----BEGIN' ) : if b'CERTIFICATE' in line : blobs = certificates else : blobs = keys blobs . append ( b'' ) blobs [ - 1 ] += line blobs [ - 1 ] += b'...
async def select ( ** data ) : """RPC method for selecting data from the database : return selected data"""
try : select_data = clickhouse_queries . select_from_table ( table = data [ 'table' ] , query = data [ 'query' ] , fields = data [ 'fields' ] ) return str ( select_data ) except ServerException as e : exception_code = int ( str ( e ) [ 5 : 8 ] . strip ( ) ) if exception_code == 60 : return 'Tabl...
def _processLostJobs ( self ) : """Process jobs that have gone awry"""
# In the case that there is nothing happening ( no updated jobs to # gather for rescueJobsFrequency seconds ) check if there are any jobs # that have run too long ( see self . reissueOverLongJobs ) or which have # gone missing from the batch system ( see self . reissueMissingJobs ) if ( ( time . time ( ) - self . timeS...
def process_host_check_result ( self , host , status_code , plugin_output ) : """Process host check result Format of the line that triggers function call : : PROCESS _ HOST _ CHECK _ RESULT ; < host _ name > ; < status _ code > ; < plugin _ output > : param host : host to process check to : type host : alig...
now = time . time ( ) cls = host . __class__ # If globally disabled OR host disabled , do not launch . . if not cls . accept_passive_checks or not host . passive_checks_enabled : return try : plugin_output = plugin_output . decode ( 'utf8' , 'ignore' ) logger . debug ( '%s > Passive host check plugin output...
def from_ini ( cls , ic , folder = '.' , ini_file = 'star.ini' ) : """Initialize a StarModel from a . ini file File should contain all arguments with which to initialize StarModel ."""
if not os . path . isabs ( ini_file ) : ini_file = os . path . join ( folder , ini_file ) config = ConfigObj ( ini_file ) kwargs = { } for kw in config . keys ( ) : try : kwargs [ kw ] = float ( config [ kw ] ) except : kwargs [ kw ] = ( float ( config [ kw ] [ 0 ] ) , float ( config [ kw ] ...
def delete ( table , where = ( ) , ** kwargs ) : """Convenience wrapper for database DELETE ."""
where = dict ( where , ** kwargs ) . items ( ) sql , args = makeSQL ( "DELETE" , table , where = where ) return execute ( sql , args ) . rowcount
def get_example ( ) : """Retrieve an example of the metadata"""
example = dict ( ) for section_key , section in Metadata . MAIN_SECTIONS . items ( ) : example [ section_key ] = section . EXAMPLE . copy ( ) return example
def menu_daily ( self , building_id ) : """Get a menu object corresponding to the daily menu for the venue with building _ id . : param building _ id : A string representing the id of a building , e . g . " abc " . > > > commons _ today = din . menu _ daily ( " 593 " )"""
today = str ( datetime . date . today ( ) ) v2_response = DiningV2 ( self . bearer , self . token ) . menu ( building_id , today ) response = { 'result_data' : { 'Document' : { } } } response [ "result_data" ] [ "Document" ] [ "menudate" ] = datetime . datetime . strptime ( today , '%Y-%m-%d' ) . strftime ( '%-m/%d/%Y'...
def _ensure_classification ( self ) : """Ensures a single TextLogError ' s related bugs have Classifications . If the linked Job has a single meaningful TextLogError : - find the bugs currently related to it via a Classification - find the bugs mapped to the job related to this note - find the bugs that are...
# if this note was automatically filed , don ' t update the auto - classification information if not self . user : return # if the failure type isn ' t intermittent , ignore if self . failure_classification . name not in [ "intermittent" , "intermittent needs filing" ] : return # if the linked Job has more than...
def update ( cyg_arch = 'x86_64' , mirrors = None ) : '''Update all packages . cyg _ arch : x86_64 Specify the cygwin architecture update Current options are x86 and x86_64 CLI Example : . . code - block : : bash salt ' * ' cyg . update salt ' * ' cyg . update dos2unix mirrors = " [ { ' http : / / mir...
args = [ ] args . append ( '--upgrade-also' ) # Can ' t update something that isn ' t installed if not _check_cygwin_installed ( cyg_arch ) : LOG . debug ( 'Cygwin (%s) not installed, could not update' , cyg_arch ) return False return _run_silent_cygwin ( cyg_arch = cyg_arch , args = args , mirrors = mirrors )
def mgmt_sec_grp_id ( cls ) : """Returns id of security group used by the management network ."""
if not extensions . is_extension_supported ( bc . get_plugin ( ) , "security-group" ) : return if cls . _mgmt_sec_grp_id is None : # Get the id for the _ mgmt _ security _ group _ id tenant_id = cls . l3_tenant_id ( ) res = bc . get_plugin ( ) . get_security_groups ( bc . context . get_admin_context ( ) , {...
def get_duration ( self , matrix_name ) : """Get duration for a concrete matrix . Args : matrix _ name ( str ) : name of the Matrix . Returns : float : duration of concrete matrix in seconds ."""
duration = 0.0 if matrix_name in self . data : duration = sum ( [ stage . duration ( ) for stage in self . data [ matrix_name ] ] ) return duration
def depth_soil_density ( self , value = None ) : """Corresponds to IDD Field ` depth _ soil _ density ` Args : value ( float ) : value for IDD Field ` depth _ soil _ density ` Unit : kg / m3 if ` value ` is None it will not be checked against the specification and is assumed to be a missing value Raises...
if value is not None : try : value = float ( value ) except ValueError : raise ValueError ( 'value {} need to be of type float ' 'for field `depth_soil_density`' . format ( value ) ) self . _depth_soil_density = value
def filter_nodes ( n : Node , query : str ) -> CompatNodeIterator : """Utility function . Same as filter ( ) but will only filter for nodes ( i . e . it will exclude scalars and positions ) ."""
return CompatNodeIterator ( filter ( n , query ) . _nodeit , only_nodes = True )
def _exec_appcommand_post ( self , command , param ) : """Prepare xml command for AVR"""
xml = """<?xml version="1.0" encoding="UTF-8"?> <harman> <avr> <common> <control> <name>""" + command + """</name> <zone>""" + self . _zone + """</zone> <para>""" + param + """</para> ...
def get_enabled_plugins ( ) : '''Returns enabled preview plugins . Plugins are sorted , defaults come last'''
plugins = entrypoints . get_enabled ( 'udata.preview' , current_app ) . values ( ) valid = [ p for p in plugins if issubclass ( p , PreviewPlugin ) ] for plugin in plugins : if plugin not in valid : clsname = plugin . __name__ msg = '{0} is not a valid preview plugin' . format ( clsname ) wa...
def accepts_manager_roles ( func ) : """Decorator that accepts only manager roles : param func : : return :"""
if inspect . isclass ( func ) : apply_function_to_members ( func , accepts_manager_roles ) return func else : @ functools . wraps ( func ) def decorator ( * args , ** kwargs ) : return accepts_roles ( * ROLES_MANAGER ) ( func ) ( * args , ** kwargs ) return decorator
def add_handlers ( self , room_handler = None , transaction_handler = None , user_handler = None ) : """Adds routes to Application that use specified handlers ."""
# Add all the normal matrix API routes if room_handler : room = resources . Room ( room_handler , self . Api ) self . add_route ( "/rooms/{room_alias}" , room ) if transaction_handler : transaction = resources . Transaction ( transaction_handler , self . Api ) self . add_route ( "/transactions/{txn_id}"...
def exists ( self , path ) : """Use ` ` hadoop fs - stat ` ` to check file existence ."""
cmd = load_hadoop_cmd ( ) + [ 'fs' , '-stat' , path ] logger . debug ( 'Running file existence check: %s' , subprocess . list2cmdline ( cmd ) ) p = subprocess . Popen ( cmd , stdout = subprocess . PIPE , stderr = subprocess . PIPE , close_fds = True , universal_newlines = True ) stdout , stderr = p . communicate ( ) if...
def _get_value ( self , entity ) : """Internal helper to get the value for this Property from an entity . For a repeated Property this initializes the value to an empty list if it is not set ."""
if entity . _projection : if self . _name not in entity . _projection : raise UnprojectedPropertyError ( 'Property %s is not in the projection' % ( self . _name , ) ) return self . _get_user_value ( entity )
def union ( self , * sets ) : """Combines all unique items . Each items order is defined by its first appearance . Example : > > > oset = OrderedSet . union ( OrderedSet ( [ 3 , 1 , 4 , 1 , 5 ] ) , [ 1 , 3 ] , [ 2 , 0 ] ) > > > print ( oset ) OrderedSet ( [ 3 , 1 , 4 , 5 , 2 , 0 ] ) > > > oset . union (...
cls = self . __class__ if isinstance ( self , OrderedSet ) else OrderedSet containers = map ( list , it . chain ( [ self ] , sets ) ) items = it . chain . from_iterable ( containers ) return cls ( items )
def display_list_by_prefix ( names_list , starting_spaces = 0 ) : """Creates a help string for names _ list grouped by prefix ."""
cur_prefix , result_lines = None , [ ] space = " " * starting_spaces for name in sorted ( names_list ) : split = name . split ( "_" , 1 ) prefix = split [ 0 ] if cur_prefix != prefix : result_lines . append ( space + prefix + ":" ) cur_prefix = prefix result_lines . append ( space + " *...
def Turner_Wallis ( x , rhol , rhog , mul , mug ) : r'''Calculates void fraction in two - phase flow according to the model of [1 ] _ , as given in [ 2 ] _ and [ 3 ] _ . . . math : : \ alpha = \ left [ 1 + \ left ( \ frac { 1 - x } { x } \ right ) ^ { 0.72 } \ left ( \ frac { \ rho _ g } { \ rho _ l } \ rig...
return ( 1 + ( ( 1 - x ) / x ) ** 0.72 * ( rhog / rhol ) ** 0.4 * ( mul / mug ) ** 0.08 ) ** - 1
def terminate ( self , nowait = False ) : """Finalize and stop service Args : nowait : set to True to terminate immediately and skip processing messages still in the queue"""
logger . debug ( "Acquiring lock for service termination" ) with self . lock : logger . debug ( "Terminating service" ) if not self . listener : logger . warning ( "Service already stopped." ) return self . listener . stop ( nowait ) try : if not nowait : self . _post...
def duration_expired ( start_time , duration_seconds ) : """Return True if ` ` duration _ seconds ` ` have expired since ` ` start _ time ` `"""
if duration_seconds is not None : delta_seconds = datetime_delta_to_seconds ( dt . datetime . now ( ) - start_time ) if delta_seconds >= duration_seconds : return True return False
def zthread_fork ( ctx , func , * args , ** kwargs ) : """Create an attached thread . An attached thread gets a ctx and a PAIR pipe back to its parent . It must monitor its pipe , and exit if the pipe becomes unreadable . Returns pipe , or NULL if there was an error ."""
a = ctx . socket ( zmq . PAIR ) a . setsockopt ( zmq . LINGER , 0 ) a . setsockopt ( zmq . RCVHWM , 100 ) a . setsockopt ( zmq . SNDHWM , 100 ) a . setsockopt ( zmq . SNDTIMEO , 5000 ) a . setsockopt ( zmq . RCVTIMEO , 5000 ) b = ctx . socket ( zmq . PAIR ) b . setsockopt ( zmq . LINGER , 0 ) b . setsockopt ( zmq . RCV...
def steady_connection ( self ) : """Get a steady , unpooled PostgreSQL connection ."""
return SteadyPgConnection ( self . _maxusage , self . _setsession , True , * self . _args , ** self . _kwargs )
def edge_length_check ( length , edge ) : """Raises error if length is not in interval [ 0 , edge . length ]"""
try : assert 0 <= length <= edge . length except AssertionError : if length < 0 : raise TreeError ( 'Negative edge-lengths are disallowed' ) raise TreeError ( 'This edge isn\'t long enough to prune at length {0}\n' '(Edge length = {1})' . format ( length , edge . length ) )
def get_unused_paths ( self ) : """Returns which include _ paths or exclude _ paths that were not used via include _ path method . : return : [ str ] list of filtering paths that were not used ."""
return [ path for path in self . filter . paths if path not in self . seen_paths ]
def infer_getattr ( node , context = None ) : """Understand getattr calls If one of the arguments is an Uninferable object , then the result will be an Uninferable object . Otherwise , the normal attribute lookup will be done ."""
obj , attr = _infer_getattr_args ( node , context ) if ( obj is util . Uninferable or attr is util . Uninferable or not hasattr ( obj , "igetattr" ) ) : return util . Uninferable try : return next ( obj . igetattr ( attr , context = context ) ) except ( StopIteration , InferenceError , AttributeInferenceError )...
def get_B_factors ( self , force = False ) : '''This reads in all ATOM lines and compute the mean and standard deviation of each residue ' s B - factors . It returns a table of the mean and standard deviation per residue as well as the mean and standard deviation over all residues with each residue having equ...
# Read in the list of bfactors for each ATOM line . if ( not self . bfactors ) or ( force == True ) : bfactors = { } old_chain_residue_id = None for line in self . lines : if line [ 0 : 4 ] == "ATOM" : chain_residue_id = line [ 21 : 27 ] if chain_residue_id != old_chain_resid...
def breeding_plugevent ( request , breeding_id ) : """This view defines a form for adding new plug events from a breeding cage . This form requires a breeding _ id from a breeding set and restricts the PlugFemale and PlugMale to animals that are defined in that breeding cage ."""
breeding = get_object_or_404 ( Breeding , pk = breeding_id ) if request . method == "POST" : form = BreedingPlugForm ( request . POST , request . FILES ) if form . is_valid ( ) : plug = form . save ( commit = False ) plug . Breeding_id = breeding . id plug . save ( ) form . save ...
def send_periodic ( bus , message , period , * args , ** kwargs ) : """Send a : class : ` ~ can . Message ` every ` period ` seconds on the given bus . : param can . BusABC bus : A CAN bus which supports sending . : param can . Message message : Message to send periodically . : param float period : The minimu...
warnings . warn ( "The function `can.send_periodic` is deprecated and will " + "be removed in an upcoming version. Please use `can.Bus.send_periodic` instead." , DeprecationWarning ) return bus . send_periodic ( message , period , * args , ** kwargs )
def uninstall ( pkg , dir = None , runas = None , env = None ) : '''Uninstall an NPM package . If no directory is specified , the package will be uninstalled globally . pkg A package name in any format accepted by NPM dir The target directory from which to uninstall the package , or None for global inst...
# Protect against injection if pkg : pkg = _cmd_quote ( pkg ) env = env or { } if runas : uid = salt . utils . user . get_uid ( runas ) if uid : env . update ( { 'SUDO_UID' : uid , 'SUDO_USER' : '' } ) cmd = [ 'npm' , 'uninstall' , '"{0}"' . format ( pkg ) ] if not dir : cmd . append ( '--global...
def fix_re_escapes ( self , txt : str ) -> str : """The ShEx RE engine allows escaping any character . We have to remove that escape for everything except those that CAN be legitimately escaped : param txt : text to be escaped"""
def _subf ( matchobj ) : # o = self . fix _ text _ escapes ( matchobj . group ( 0 ) ) o = matchobj . group ( 0 ) . translate ( self . re_trans_table ) if o [ 1 ] in '\b\f\n\t\r' : return o [ 0 ] + 'bfntr' [ '\b\f\n\t\r' . index ( o [ 1 ] ) ] else : return o if o [ 1 ] in '\\.?*+^$()[]{|}' el...
def query ( self , action = None ) : """returns cached query string ( without & format = json ) for given action , or list of cached actions"""
if action in self . cache : return self . cache [ action ] [ 'query' ] . replace ( '&format=json' , '' ) return self . cache . keys ( ) or None
def info ( self , product , store_view = None , attributes = None , identifierType = None ) : """Retrieve product data : param product : ID or SKU of product : param store _ view : ID or Code of store view : param attributes : List of fields required : param identifierType : Defines whether the product or S...
return self . call ( 'catalog_product.info' , [ product , store_view , attributes , identifierType ] )
def encode ( cls , command ) : """Encode a command as an unambiguous string . Args : command ( Command ) : The command to encode . Returns : str : The encoded command"""
args = [ ] for arg in command . args : if not isinstance ( arg , str ) : arg = str ( arg ) if "," in arg or arg . startswith ( " " ) or arg . endswith ( " " ) or arg . startswith ( "hex:" ) : arg = "hex:{}" . format ( hexlify ( arg . encode ( 'utf-8' ) ) . decode ( 'utf-8' ) ) args . append ...
def get_mean_table ( self , imt , rctx ) : """Returns amplification factors for the mean , given the rupture and intensity measure type . : returns : amplification table as an array of [ Number Distances , Number Levels ]"""
# Levels by Distances if imt . name in 'PGA PGV' : interpolator = interp1d ( self . magnitudes , numpy . log10 ( self . mean [ imt . name ] ) , axis = 2 ) output_table = 10.0 ** ( interpolator ( rctx . mag ) . reshape ( self . shape [ 0 ] , self . shape [ 3 ] ) ) else : # For spectral accelerations - need two s...
def _get_description ( arg ) : """Generates a proper description for the given argument ."""
desc = [ ] otherwise = False if arg . can_be_inferred : desc . append ( 'If left unspecified, it will be inferred automatically.' ) otherwise = True elif arg . is_flag : desc . append ( 'This argument defaults to ' '<code>None</code> and can be omitted.' ) otherwise = True if arg . type in { 'InputPeer'...
def get_spectrogram ( self ) : """Calculate the spectrogram to be plotted This exists as a separate method to allow subclasses to override this and not the entire ` get _ plot ` method , e . g . ` Coherencegram ` . This method should not apply the normalisation from ` args . norm ` ."""
args = self . args fftlength = float ( args . secpfft ) overlap = fftlength * args . overlap self . log ( 2 , "Calculating spectrogram secpfft: %s, overlap: %s" % ( fftlength , overlap ) ) stride = self . get_stride ( ) if stride : specgram = self . timeseries [ 0 ] . spectrogram ( stride , fftlength = fftlength , ...
def to_array ( self , * args , ** kwargs ) : """Convert this tree into a NumPy structured array"""
from root_numpy import tree2array return tree2array ( self , * args , ** kwargs )
def ansi ( string , * args ) : """Convenience function to chain multiple ColorWrappers to a string"""
ansi = '' for arg in args : arg = str ( arg ) if not re . match ( ANSI_PATTERN , arg ) : raise ValueError ( 'Additional arguments must be ansi strings' ) ansi += arg return ansi + string + colorama . Style . RESET_ALL