signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def serverinfo ( url = 'http://localhost:8080/manager' , timeout = 180 ) : '''return details about the server url : http : / / localhost : 8080 / manager the URL of the server manager webapp timeout : 180 timeout for HTTP request CLI Examples : . . code - block : : bash salt ' * ' tomcat . serverinfo ...
data = _wget ( 'serverinfo' , { } , url , timeout = timeout ) if data [ 'res' ] is False : return { 'error' : data [ 'msg' ] } ret = { } data [ 'msg' ] . pop ( 0 ) for line in data [ 'msg' ] : tmp = line . split ( ':' ) ret [ tmp [ 0 ] . strip ( ) ] = tmp [ 1 ] . strip ( ) return ret
def create_scope ( self , name , status = ScopeStatus . ACTIVE , description = None , tags = None , start_date = None , due_date = None , team = None , ** kwargs ) : """Create a Scope . This will create a scope if the client has the right to do so . Sufficient permissions to create a scope are a superuser , a u...
if not isinstance ( name , ( str , text_type ) ) : raise IllegalArgumentError ( "'Name' should be provided as a string, was provided as '{}'" . format ( type ( name ) ) ) if status not in ScopeStatus . values ( ) : raise IllegalArgumentError ( "Please provide a valid scope status, please use one of `enums.Scope...
def event ( self , name , payload = None , coalesce = True ) : """Send an event to the cluster . Can take an optional payload as well , which will be sent in the form that it ' s provided ."""
return self . connection . call ( 'event' , { 'Name' : name , 'Payload' : payload , 'Coalesce' : coalesce } , expect_body = False )
def get_wd_data2 ( self ) : """Get 2.5 data from self . WD and put it into ErMagicBuilder object . Called by get _ dm _ and _ wd"""
wait = wx . BusyInfo ( 'Reading in data from current working directory, please wait...' ) # wx . Yield ( ) print ( '-I- Read in any available data from working directory (data model 2)' ) self . er_magic = builder . ErMagicBuilder ( self . WD , data_model = self . data_model ) del wait
async def _reload_message ( self ) : """Re - fetches this message to reload the sender and chat entities , along with their input versions ."""
try : chat = await self . get_input_chat ( ) if self . is_channel else None msg = await self . _client . get_messages ( chat , ids = self . id ) except ValueError : return # We may not have the input chat / get message failed if not msg : return # The message may be deleted and it will be None self ...
def get_modpath_from_modname ( modname , prefer_pkg = False , prefer_main = False ) : """Same as get _ modpath but doesnt import directly SeeAlso : get _ modpath"""
from os . path import dirname , basename , join , exists initname = '__init__.py' mainname = '__main__.py' if modname in sys . modules : modpath = sys . modules [ modname ] . __file__ . replace ( '.pyc' , '.py' ) else : import pkgutil loader = pkgutil . find_loader ( modname ) modpath = loader . filenam...
def CLASSDEF ( self , node ) : """Check names used in a class definition , including its decorators , base classes , and the body of its definition . Additionally , add its name to the current scope ."""
for deco in node . decorator_list : self . handleNode ( deco , node ) for baseNode in node . bases : self . handleNode ( baseNode , node ) if not PY2 : for keywordNode in node . keywords : self . handleNode ( keywordNode , node ) self . push_scope ( ClassScope ) if self . settings . get ( 'run_docte...
def et2lst ( et , body , lon , typein , timlen = _default_len_out , ampmlen = _default_len_out ) : """Given an ephemeris epoch , compute the local solar time for an object on the surface of a body at a specified longitude . http : / / naif . jpl . nasa . gov / pub / naif / toolkit _ docs / C / cspice / et2lst _...
et = ctypes . c_double ( et ) body = ctypes . c_int ( body ) lon = ctypes . c_double ( lon ) typein = stypes . stringToCharP ( typein ) timlen = ctypes . c_int ( timlen ) ampmlen = ctypes . c_int ( ampmlen ) hr = ctypes . c_int ( ) mn = ctypes . c_int ( ) sc = ctypes . c_int ( ) time = stypes . stringToCharP ( timlen )...
def set_help ( self ) : """Set help text markup ."""
if not ( self . field . help_text and self . attrs . get ( "_help" ) ) : return self . values [ "help" ] = HELP_TEMPLATE . format ( self . field . help_text )
def setup ( template_paths = { } , autoescape = False , cache_size = 100 , auto_reload = True , bytecode_cache = True ) : """Setup Jinja enviroment eg . sketch . jinja . setup ( { ' app ' : self . config . paths [ ' app _ template _ basedir ' ] , ' sketch ' : self . config . paths [ ' sketch _ template _ dir ...
global _jinja_env , _jinja_loaders if not _jinja_env : _jinja_env = JinjaEnviroment ( autoescape = autoescape , cache_size = cache_size , auto_reload = auto_reload , bytecode_cache = None ) # @ TODO alter so Marshall is not used # if bytecode _ cache and GAE _ CACHE : # _ jinja _ env . bytecode _ cache = GAEMemcach...
def batch_add_ips ( ips ) : """Adds the given list of IPs to the database if the IP is not already there . : param ips : list of IPs : return : number of created IPs : type ips : list : rtype : int"""
ips_created = 0 if len ( ips ) > 0 : # for each ip , check if already existent , if not add for ip in ips : ( s0 , s1 , s2 , s3 ) = ip . split ( '.' ) ( ip_db , is_ip_created ) = IP . objects . get_or_create ( seg_0 = s0 , seg_1 = s1 , seg_2 = s2 , seg_3 = s3 , ) if is_ip_created : ...
def get_color_list ( method_list ) : """获取method对应的color列表 ."""
color_list = [ ] for method in method_list : color = tuple ( [ random ( ) for _ in range ( 3 ) ] ) # 随机颜色画线 color_list . append ( color ) return color_list
def create_from_path ( self ) : """Create a file loader from the file extension to loading file . Supported file extensions are as follows : Extension Loader ` ` " csv " ` ` : py : class : ` ~ . CsvTableTextLoader ` ` ` " xls " ` ` / ` ` " xlsx " ` ` : py : class : ` ~ . ExcelTableFileLoader ` ` ` " htm "...
import requests url_path = urlparse ( self . __url ) . path try : url_extension = get_extension ( url_path . rstrip ( "/" ) ) except InvalidFilePathError : raise UrlError ( "url must include path" ) logger . debug ( "TableUrlLoaderFactory: extension={}" . format ( url_extension ) ) loader_class = self . _get_lo...
def generic_type_name ( v ) : """Return a descriptive type name that isn ' t Python specific . For example , an int type will return ' integer ' rather than ' int ' ."""
if isinstance ( v , AstExampleRef ) : return "reference" elif isinstance ( v , numbers . Integral ) : # Must come before real numbers check since integrals are reals too return 'integer' elif isinstance ( v , numbers . Real ) : return 'float' elif isinstance ( v , ( tuple , list ) ) : return 'list' elif...
def main ( argv = None ) : """Make a confidence report and save it to disk ."""
try : _name_of_script , filepath = argv except ValueError : raise ValueError ( argv ) make_confidence_report ( filepath = filepath , test_start = FLAGS . test_start , test_end = FLAGS . test_end , which_set = FLAGS . which_set , report_path = FLAGS . report_path , mc_batch_size = FLAGS . mc_batch_size , nb_iter...
def setChecked ( src , ids = [ ] , dpth = 0 , key = '' ) : """Recursively find checked item ."""
# tabs = lambda n : ' ' * n * 4 # or 2 or 8 or . . . # brace = lambda s , n : ' % s % s % s ' % ( ' [ ' * n , s , ' ] ' * n ) if isinstance ( src , dict ) : for key , value in src . iteritems ( ) : setChecked ( value , ids , dpth + 1 , key ) elif isinstance ( src , list ) : for litem in src : if...
def conv ( self , num_out_channels , k_height , k_width , d_height = 1 , d_width = 1 , mode = "SAME" , input_layer = None , num_channels_in = None , use_batch_norm = None , stddev = None , activation = "relu" , bias = 0.0 ) : """Construct a conv2d layer on top of cnn ."""
if input_layer is None : input_layer = self . top_layer if num_channels_in is None : num_channels_in = self . top_size kernel_initializer = None if stddev is not None : kernel_initializer = tf . truncated_normal_initializer ( stddev = stddev ) name = "conv" + str ( self . counts [ "conv" ] ) self . counts [...
def prepare_exception ( obj , messages = None , response = None , verbs = None ) : """Prepare excetion params or only an exception message parameters : messages : list of strings , that will be separated by new line response : response from a request to SFDC REST API verbs : list of options about verbosity"...
# pylint : disable = too - many - branches verbs = set ( verbs or [ ] ) known_options = [ 'method+url' ] if messages is None : messages = [ ] if isinstance ( messages , ( text_type , str ) ) : messages = [ messages ] assert isinstance ( messages , list ) assert not verbs . difference ( known_options ) data = No...
def trace_region_count ( self ) : """Retrieves a count of the number of available trace regions . Args : self ( JLink ) : the ` ` JLink ` ` instance . Returns : Count of the number of available trace regions ."""
cmd = enums . JLinkTraceCommand . GET_NUM_REGIONS data = ctypes . c_uint32 ( 0 ) res = self . _dll . JLINKARM_TRACE_Control ( cmd , ctypes . byref ( data ) ) if ( res == 1 ) : raise errors . JLinkException ( 'Failed to get trace region count.' ) return data . value
def getdminfo ( self , columnname = None ) : """Get data manager info . Each column in a table is stored using a data manager . A storage manager is a data manager storing the physically in a file . A virtual column engine is a data manager that does not store data but calculates it on the fly ( e . g . sca...
dminfo = self . _getdminfo ( ) if columnname is None : return dminfo # Find the info for the given column for fld in dminfo . values ( ) : if columnname in fld [ "COLUMNS" ] : fldc = fld . copy ( ) del fldc [ 'COLUMNS' ] # remove COLUMNS field return fldc raise KeyError ( "Column...
def unweave ( target , * advices ) : """Unweave advices from input target ."""
advices = ( advice if isinstance ( advice , Advice ) else Advice ( advice ) for advice in advices ) unweave ( target = target , * advices )
def spellcheck_region ( region_lines , valid_words_dictionary = None , technical_words_dictionary = None , user_dictionary_words = None ) : """Perform spellcheck on each word in : region _ lines : . Each word will be checked for existence in : valid _ words _ dictionary : . If it is not in : valid _ words _ dic...
user_dictionary_words = user_dictionary_words or set ( ) spellcheckable_words_regex = re . compile ( _SPELLCHECKABLE_WORDS ) line_offset = 0 for line in region_lines : for col_offset , word in _split_line_with_offsets ( line ) : word = word . strip ( ) if len ( word ) == 0 : continue ...
def _read_mode_utopt ( self , size , kind ) : """Read User Timeout option . Positional arguments : * size - int , length of option * kind - int , 28 ( User Timeout Option ) Returns : * dict - - extracted User Timeout ( TIMEOUT ) option Structure of TCP TIMEOUT [ RFC 5482 ] : 0 1 2 3 0 1 2 3 4 5 6 7 ...
temp = self . _read_fileng ( size ) data = dict ( kind = kind , length = size , granularity = 'minutes' if int ( temp [ 0 ] ) else 'seconds' , timeout = bytes ( chr ( int ( temp [ 0 : ] , base = 2 ) ) , encoding = 'utf-8' ) , ) return data
def check_range ( number , min_r , max_r , name = "" ) : """Check if a number is within a given range"""
try : number = float ( number ) if number < min_r or number > max_r : raise FFmpegNormalizeError ( "{} must be within [{},{}]" . format ( name , min_r , max_r ) ) return number pass except Exception as e : raise e
def is_connected ( self ) : """Return ` True ` if the Xmrs represents a connected graph . Subgraphs can be connected through things like arguments , QEQs , and label equalities ."""
nids = set ( self . _nodeids ) # the nids left to find if len ( nids ) == 0 : raise XmrsError ( 'Cannot compute connectedness of an empty Xmrs.' ) # build a basic dict graph of relations edges = [ ] # label connections for lbl in self . labels ( ) : lblset = self . labelset ( lbl ) edges . extend ( ( x , y ...
def GetParserAndPluginNames ( cls , parser_filter_expression = None ) : """Retrieves the parser and parser plugin names . Args : parser _ filter _ expression ( Optional [ str ] ) : parser filter expression , where None represents all parsers and plugins . Returns : list [ str ] : parser and parser plugin ...
parser_and_plugin_names = [ ] for parser_name , parser_class in cls . GetParsers ( parser_filter_expression = parser_filter_expression ) : parser_and_plugin_names . append ( parser_name ) if parser_class . SupportsPlugins ( ) : for plugin_name , _ in parser_class . GetPlugins ( ) : parser_an...
def create_environment ( self , name , default = False , zone = None ) : """Creates environment and returns Environment object ."""
from qubell . api . private . environment import Environment return Environment . new ( organization = self , name = name , zone_id = zone , default = default , router = self . _router )
def child_elements ( self , by = By . ID , value = None , el_class = None ) : """alias for ` ` find _ elements ` ` : param by : : param value : : param el _ class : : return :"""
el , selector = define_selector ( by , value , el_class ) return self . _init_element ( elements . PageElementsList ( selector , el ) )
def _get_next_empty_bitmap ( self ) : """Returns the next empty entry . Returns : int : The value of the empty entry"""
# TODO probably not the best way , redo for i , byte in enumerate ( self . _bitmap ) : if byte != 255 : for offset in range ( 8 ) : if not byte & ( 1 << offset ) : return ( i * 8 ) + offset
def _recv_callback ( self , msg ) : """Method is called when there is a message coming from a Mongrel2 server . This message should be a valid Request String ."""
m2req = MongrelRequest . parse ( msg [ 0 ] ) MongrelConnection ( m2req , self . _sending_stream , self . request_callback , no_keep_alive = self . no_keep_alive , xheaders = self . xheaders )
def move_nodes_constrained ( self , partition , constrained_partition , consider_comms = None ) : """Move nodes to alternative communities for * refining * the partition . Parameters partition The partition for which to move nodes . constrained _ partition The partition within which we may move nodes . ...
if ( consider_comms is None ) : consider_comms = self . refine_consider_comms diff = _c_leiden . _Optimiser_move_nodes_constrained ( self . _optimiser , partition . _partition , constrained_partition . _partition , consider_comms ) partition . _update_internal_membership ( ) return diff
def host_install ( self , user_name , host_names , ssh_port = None , password = None , private_key = None , passphrase = None , parallel_install_count = None , cm_repo_url = None , gpg_key_custom_url = None , java_install_strategy = None , unlimited_jce = None ) : """Install Cloudera Manager Agent on a set of hosts...
host_install_args = { } if user_name : host_install_args [ 'userName' ] = user_name if host_names : host_install_args [ 'hostNames' ] = host_names if ssh_port : host_install_args [ 'sshPort' ] = ssh_port if password : host_install_args [ 'password' ] = password if private_key : host_install_args [ '...
def resultsFor ( self , ps ) : """Retrieve a list of all results associated with the given parameters . : param ps : the parameters : returns : a list of results , 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 [ res for res in self . _results [ k ] if isinstance ( res , dict ) ] else : return [ ]
def connect_post_node_proxy_with_path ( self , name , path , ** kwargs ) : # noqa : E501 """connect _ post _ node _ proxy _ with _ path # noqa : E501 connect POST requests to proxy of Node # noqa : E501 This method makes a synchronous HTTP request by default . To make an asynchronous HTTP request , please pas...
kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'async_req' ) : return self . connect_post_node_proxy_with_path_with_http_info ( name , path , ** kwargs ) # noqa : E501 else : ( data ) = self . connect_post_node_proxy_with_path_with_http_info ( name , path , ** kwargs ) # noqa : E501 re...
def get_uncompleted_tasks ( self ) : """Return a list of all uncompleted tasks in this project . . . warning : : Requires Todoist premium . : return : A list of all uncompleted tasks in this project . : rtype : list of : class : ` pytodoist . todoist . Task ` > > > from pytodoist import todoist > > > user...
all_tasks = self . get_tasks ( ) completed_tasks = self . get_completed_tasks ( ) return [ t for t in all_tasks if t not in completed_tasks ]
def paint ( self , painter , option , widget ) : """Overloads the paint method from QGraphicsPathItem to handle custom drawing of the path using this items pens and polygons . : param painter < QPainter > : param option < QGraphicsItemStyleOption > : param widget < QWidget >"""
# following the arguments required by Qt # pylint : disable - msg = W0613 painter . setOpacity ( self . opacity ( ) ) # show the connection selected if not self . isEnabled ( ) : pen = QPen ( self . disabledPen ( ) ) elif self . isSelected ( ) : pen = QPen ( self . highlightPen ( ) ) else : pen = QPen ( sel...
def read_with_buffer ( self , command , fct = 0 , ext = 0 ) : """Test read info with buffered command ( ZK6 : 1503)"""
if self . tcp : MAX_CHUNK = 0xFFc0 else : MAX_CHUNK = 16 * 1024 command_string = pack ( '<bhii' , 1 , command , fct , ext ) if self . verbose : print ( "rwb cs" , command_string ) response_size = 1024 data = [ ] start = 0 cmd_response = self . __send_command ( 1503 , command_string , response_size ) if not ...
def guess_timefmt ( datestr ) : """Try to guess the format a date is written in . The following formats are supported : Format Example Python format ` ` YYYY - MM - DD ` ` 2002-04-21 % Y - % m - % d ` ` YYYY . MM . DD ` ` 2002.04.21 % Y . % m . % d ` ` YYYY MM DD ` ` 2002 04 21 % Y % m % d ` ` DD - MM -...
if isinstance ( datestr , float ) or isinstance ( datestr , int ) : return None seasonal_key = str ( config . get ( 'DEFAULT' , 'seasonal_key' , '9999' ) ) # replace ' T ' with space to handle ISO times . if datestr . find ( 'T' ) > 0 : dt_delim = 'T' else : dt_delim = ' ' delimiters = [ '-' , '.' , ' ' , '...
def add_endpoint ( self ) : '''Set endpoits'''
self . app . add_url_rule ( '/rest/mavlink/<path:arg>' , 'rest' , self . request ) self . app . add_url_rule ( '/rest/mavlink/' , 'rest' , self . request )
def get_object_or_404 ( queryset , * args , ** kwargs ) : """replacement of rest _ framework . generics and django . shrtcuts analogues"""
try : return queryset . get ( * args , ** kwargs ) except ( ValueError , TypeError , DoesNotExist , ValidationError ) : raise Http404 ( )
def compute_overlaps ( self , * args ) : """compute overlaps"""
olaps = [ ] Y = self . _Y psd = self . _catalog_object . psd for i in np . arange ( 0 , Y . shape [ 0 ] ) : olaps . append ( _overlap ( Y [ i , : ] , self . _Y_rec [ i , : ] , psd ) ) return olaps
def _generate_struct_class_m ( self , struct ) : """Defines an Obj C implementation file that represents a struct in Stone ."""
self . emit ( ) self . _generate_imports_m ( self . _get_imports_m ( struct , default_imports = [ 'DBStoneSerializers' , 'DBStoneValidators' ] ) ) struct_name = fmt_class_prefix ( struct ) self . emit ( '#pragma mark - API Object' ) self . emit ( ) with self . block_m ( struct_name ) : self . emit ( '#pragma mark -...
def run ( self , stat_name , criticity , commands , repeat , mustache_dict = None ) : """Run the commands ( in background ) . - stats _ name : plugin _ name ( + header ) - criticity : criticity of the trigger - commands : a list of command line with optional { { mustache } } - If True , then repeat the acti...
if ( self . get ( stat_name ) == criticity and not repeat ) or not self . start_timer . finished ( ) : # Action already executed = > Exit return False logger . debug ( "{} action {} for {} ({}) with stats {}" . format ( "Repeat" if repeat else "Run" , commands , stat_name , criticity , mustache_dict ) ) # Run all a...
def exists ( self , filename ) : """Report whether a file exists on all distribution points . Determines file type by extension . Args : filename : Filename you wish to check . ( No path ! e . g . : " AdobeFlashPlayer - 14.0.0.176 . pkg " ) Returns : Boolean"""
result = True for repo in self . _children : if not repo . exists ( filename ) : result = False return result
def put_object ( self , obj ) : # TODO consider putting into a ES class self . pr_dbg ( 'put_obj: %s' % self . json_dumps ( obj ) ) """Wrapper for es . index , determines metadata needed to index from obj . If you have a raw object json string you can hard code these : index is . kibana ( as of kibana4 ) ; ...
if obj [ '_index' ] is None or obj [ '_index' ] == "" : raise Exception ( "Invalid Object, no index" ) if obj [ '_id' ] is None or obj [ '_id' ] == "" : raise Exception ( "Invalid Object, no _id" ) if obj [ '_type' ] is None or obj [ '_type' ] == "" : raise Exception ( "Invalid Object, no _type" ) if obj [ ...
async def requests_get ( self , path : str , ** kwargs ) -> ClientResponse : """Requests GET wrapper in order to use API parameters . : param path : the request path : return :"""
logging . debug ( "Request : {0}" . format ( self . reverse_url ( self . connection_handler . http_scheme , path ) ) ) url = self . reverse_url ( self . connection_handler . http_scheme , path ) response = await self . connection_handler . session . get ( url , params = kwargs , headers = self . headers , proxy = self ...
def parse ( cls , compoundIdStr ) : """Parses the specified compoundId string and returns an instance of this CompoundId class . : raises : An ObjectWithIdNotFoundException if parsing fails . This is because this method is a client - facing method , and if a malformed identifier ( under our internal rules )...
if not isinstance ( compoundIdStr , basestring ) : raise exceptions . BadIdentifierException ( compoundIdStr ) try : deobfuscated = cls . deobfuscate ( compoundIdStr ) except TypeError : # When a string that cannot be converted to base64 is passed # as an argument , b64decode raises a TypeError . We must treat ...
def product ( target , prop1 , prop2 , ** kwargs ) : r"""Calculates the product of multiple property values Parameters target : OpenPNM Object The object which this model is associated with . This controls the length of the calculated array , and also provides access to other necessary properties . prop...
value = target [ prop1 ] * target [ prop2 ] for item in kwargs . values ( ) : value *= target [ item ] return value
def process_temporary_file ( self , tmp_file ) : """Truncates the filename if necessary , saves the model , and returns a response"""
# Truncate filename if necessary if len ( tmp_file . filename ) > 100 : base_filename = tmp_file . filename [ : tmp_file . filename . rfind ( "." ) ] tmp_file . filename = "%s.%s" % ( base_filename [ : 99 - len ( tmp_file . extension ) ] , tmp_file . extension ) tmp_file . save ( ) data = { 'uuid' : str ( tmp_f...
def calc_cost ( y , yhat , cost_matrix ) : """Calculate the cost with given cost matrix y : ground truth yhat : estimation cost _ matrix : array - like , shape = ( n _ classes , n _ classes ) The ith row , jth column represents the cost of the ground truth being ith class and prediction as jth class ."""
return np . mean ( cost_matrix [ list ( y ) , list ( yhat ) ] )
def handle_json_GET_neareststops ( self , params ) : """Return a list of the nearest ' limit ' stops to ' lat ' , ' lon '"""
schedule = self . server . schedule lat = float ( params . get ( 'lat' ) ) lon = float ( params . get ( 'lon' ) ) limit = int ( params . get ( 'limit' ) ) stops = schedule . GetNearestStops ( lat = lat , lon = lon , n = limit ) return [ StopToTuple ( s ) for s in stops ]
def _make_boundary ( self ) : """creates a boundary for multipart post ( form post )"""
if self . PY2 : return '===============%s==' % uuid . uuid4 ( ) . get_hex ( ) elif self . PY3 : return '===============%s==' % uuid . uuid4 ( ) . hex else : from random import choice digits = "0123456789" letters = "abcdefghijklmnopqrstuvwxyz" return '===============%s==' % '' . join ( choice ( ...
def common ( self , other ) : """Return two objects with the same dimensions if they lie in the same orthogonal plane . > > > l = Location ( pop = 1 , snap = 2) > > > m = Location ( crackle = 1 , snap = 3) > > > l . common ( m ) ( < Location snap : 2 > , < Location snap : 3 > )"""
selfDim = set ( self . keys ( ) ) otherDim = set ( other . keys ( ) ) dims = selfDim | otherDim newSelf = None newOther = None for dim in dims : sd = self . get ( dim , None ) od = other . get ( dim , None ) if sd is None or od is None : # axis is missing in one or the other continue if - _EPSIL...
def _send_container_healthcheck_sc ( self , containers_by_id ) : """Send health service checks for containers ."""
for container in containers_by_id . itervalues ( ) : healthcheck_tags = self . _get_tags ( container , HEALTHCHECK ) match = False for tag in healthcheck_tags : for rule in self . whitelist_patterns : if re . match ( rule , tag ) : match = True self . _sub...
def change_task_size ( self , size ) : """Blocking request to change number of running tasks"""
self . _pause . value = True self . log . debug ( "About to change task size to {0}" . format ( size ) ) try : size = int ( size ) except ValueError : self . log . error ( "Cannot change task size, non integer size provided" ) return False if size < 0 : self . log . error ( "Cannot change task size, les...
def get_as_bytes ( self , s3_path ) : """Get the contents of an object stored in S3 as bytes : param s3 _ path : URL for target S3 location : return : File contents as pure bytes"""
( bucket , key ) = self . _path_to_bucket_and_key ( s3_path ) obj = self . s3 . Object ( bucket , key ) contents = obj . get ( ) [ 'Body' ] . read ( ) return contents
def on_size ( self , event ) : '''handle window size changes'''
state = self . state self . need_redraw = True if state . report_size_changes : # tell owner the new size size = self . frame . GetSize ( ) if size != self . last_size : self . last_size = size state . out_queue . put ( MPImageNewSize ( size ) )
def formatbyindex ( string , fg = None , bg = None , indices = [ ] ) : """Wrap color syntax around characters using indices and return it . fg and bg specify foreground - and background colors , respectively ."""
if not string or not indices or ( fg is bg is None ) : return string result , p = '' , 0 # The lambda syntax is necessary to support both Python 2 and 3 for k , g in itertools . groupby ( enumerate ( sorted ( indices ) ) , lambda x : x [ 0 ] - x [ 1 ] ) : tmp = list ( map ( operator . itemgetter ( 1 ) , g ) ) ...
def print_textandtime ( text : str ) -> None : """Print the given string and the current date and time with high precision for logging purposes . > > > from hydpy . exe . commandtools import print _ textandtime > > > from hydpy . core . testtools import mock _ datetime _ now > > > from datetime import datet...
timestring = datetime . datetime . now ( ) . strftime ( '%Y-%m-%d %H:%M:%S.%f' ) print ( f'{text} ({timestring}).' )
def _deserialize ( self , response ) : """Attempt to deserialize resource from response . : param requests . Response response : latest REST call response ."""
# Hacking response with initial status _ code previous_status = response . status_code response . status_code = self . initial_status_code resource = self . get_outputs ( response ) response . status_code = previous_status # Hack for Storage or SQL , to workaround the bug in the Python generator if resource is None : ...
def to_dict ( self ) : """Pack the load averages into a nicely - keyed dictionary ."""
result = { } for meta in self . intervals . values ( ) : result [ meta . display ] = meta . value return result
def _shutdown_multicast_socket ( self ) : """Shutdown multicast socket : rtype : None"""
self . debug ( "()" ) self . _drop_membership_multicast_socket ( ) self . _listening . remove ( self . _multicast_socket ) self . _multicast_socket . close ( ) self . _multicast_socket = None
def action_remove ( cls , request , category_list ) : """Handles ` remove ` action from CategoryList editor . Removes an actual category if a target object is not set for the list . Removes a tie - to - category object if a target object is set for the list . : param Request request : Django request object ...
if not category_list . editor . allow_remove : raise SitecatsSecurityException ( '`action_remove()` is not supported by parent `%s`category.' % category_list . alias ) category_id = int ( request . POST . get ( 'category_id' , 0 ) ) if not category_id : raise SitecatsSecurityException ( 'Unsupported `category_i...
def get_small_file ( context , path ) : """Basic in - memory caching module fetcher . This generates one roundtrip for every previously unseen file , so it is only a temporary solution . : param context : Context we should direct FileService requests to . For now ( and probably forever ) this is just the to...
pool = mitogen . service . get_or_create_pool ( router = context . router ) service = pool . get_service ( u'mitogen.service.PushFileService' ) return service . get ( path )
def set_state ( self , updater = None , ** kwargs ) : """Update the datastore . : param func | dict updater : ( state ) = > state _ change or dict state _ change : rtype : Iterable [ tornado . concurrent . Future ]"""
if callable ( updater ) : state_change = updater ( self ) elif updater is not None : state_change = updater else : state_change = kwargs return [ callback_result for k , v in state_change . items ( ) for callback_result in self . set ( k , v ) ]
def sixlowpan_fragment ( packet , datagram_tag = 1 ) : """Split a packet into different links to transmit as 6lowpan packets . Usage example : > > > ipv6 = . . . . . ( very big packet ) > > > pkts = sixlowpan _ fragment ( ipv6 , datagram _ tag = 0x17) > > > send = [ Dot15d4 ( ) / Dot15d4Data ( ) / x for x i...
if not packet . haslayer ( IPv6 ) : raise Exception ( "SixLoWPAN only fragments IPv6 packets !" ) str_packet = raw ( packet [ IPv6 ] ) if len ( str_packet ) <= MAX_SIZE : return [ packet ] def chunks ( l , n ) : return [ l [ i : i + n ] for i in range ( 0 , len ( l ) , n ) ] new_packet = chunks ( str_packet...
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 ."""
C = self . COEFFS [ imt ] mag = rup . mag - 6 d = np . sqrt ( dists . rjb ** 2 + C [ 'c7' ] ** 2 ) mean = np . zeros_like ( d ) mean += C [ 'c1' ] + C [ 'c2' ] * mag + C [ 'c3' ] * mag ** 2 + C [ 'c6' ] idx = d <= 100. mean [ idx ] = mean [ idx ] + C [ 'c5' ] * np . log10 ( d [ idx ] ) idx = d > 100. mean [ idx ] = ( m...
def _central2 ( f , fx , x , h ) : """Eq . 8"""
n = len ( x ) ee = np . diag ( h ) dtype = np . result_type ( fx ) g = np . empty ( n , dtype = dtype ) gg = np . empty ( n , dtype = dtype ) for i in range ( n ) : g [ i ] = f ( x + ee [ i ] ) gg [ i ] = f ( x - ee [ i ] ) hess = np . empty ( ( n , n ) , dtype = dtype ) np . outer ( h , h , out = hess ) for i ...
def noise ( mesh , magnitude = None ) : """Add gaussian noise to every vertex of a mesh . Makes no effort to maintain topology or sanity . Parameters mesh : Trimesh object ( will not be mutated ) magnitude : float , what is the maximum distance per axis we can displace a vertex . Default value is mesh . s...
if magnitude is None : magnitude = mesh . scale / 100.0 random = ( np . random . random ( mesh . vertices . shape ) - .5 ) * magnitude vertices_noise = mesh . vertices . copy ( ) + random # make sure we ' ve re - ordered faces randomly triangles = np . random . permutation ( vertices_noise [ mesh . faces ] ) mesh_t...
def post ( self , path , data ) : """Call the Infoblox device to post the obj for the data passed in : param str obj : The object type : param dict data : The data for the post : rtype : requests . Response"""
LOGGER . debug ( 'Posting data: %r' , data ) return self . session . post ( self . _request_url ( path ) , data = json . dumps ( data or { } ) , headers = self . HEADERS , auth = self . auth , verify = False )
def listar_por_id ( self , id ) : """Obtém um equipamento a partir do seu identificador . : param id : ID do equipamento . : return : Dicionário com a seguinte estrutura : { ' equipamento ' : { ' id ' : < id _ equipamento > , ' nome ' : < nome _ equipamento > , ' id _ tipo _ equipamento ' : < id _ tipo ...
if id is None : raise InvalidParameterError ( u'O id do equipamento não foi informado.' ) url = 'equipamento/id/' + urllib . quote ( id ) + '/' code , xml = self . submit ( None , 'GET' , url ) return self . response ( code , xml )
def set_option ( self , optionname , value ) : """Set the named option to value . Ensure the original type of the option value is preserved ."""
for name , parms in zip ( self . opt_names , self . opt_parms ) : if name == optionname : # FIXME : ensure that the resulting type of the set option # matches that of the default value . This prevents a string # option from being coerced to int simply because it holds # a numeric value ( e . g . a passw...
def get_all_anchors_fpn ( strides = None , sizes = None ) : """Returns : [ anchors ] : each anchors is a SxSx NUM _ ANCHOR _ RATIOS x4 array ."""
if strides is None : strides = cfg . FPN . ANCHOR_STRIDES if sizes is None : sizes = cfg . RPN . ANCHOR_SIZES assert len ( strides ) == len ( sizes ) foas = [ ] for stride , size in zip ( strides , sizes ) : foa = get_all_anchors ( stride = stride , sizes = ( size , ) ) foas . append ( foa ) return foas
def list_node ( self , ** kwargs ) : """list or watch objects of kind Node This method makes a synchronous HTTP request by default . To make an asynchronous HTTP request , please pass async _ req = True > > > thread = api . list _ node ( async _ req = True ) > > > result = thread . get ( ) : param async _...
kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'async_req' ) : return self . list_node_with_http_info ( ** kwargs ) else : ( data ) = self . list_node_with_http_info ( ** kwargs ) return data
def __to_file ( self , message_no ) : """Write a single message to file"""
filename = self . __create_file_name ( message_no ) try : with codecs . open ( filename , mode = 'w' , encoding = self . messages [ message_no ] . encoding ) as file__ : file__ . write ( self . messages [ message_no ] . output ) except IOError as excep : print 'Unable for open the file \'{0}\' for writi...
def get_savename_from_varname ( varname , varname_prefix = None , savename_prefix = None ) : """Args : varname ( str ) : a variable name in the graph varname _ prefix ( str ) : an optional prefix that may need to be removed in varname savename _ prefix ( str ) : an optional prefix to append to all savename ...
name = varname if varname_prefix is not None and name . startswith ( varname_prefix ) : name = name [ len ( varname_prefix ) + 1 : ] if savename_prefix is not None : name = savename_prefix + '/' + name return name
def start ( self , min_nodes = None ) : """Starts up all the instances in the cloud . To speed things up , all instances are started in a seperate thread . To make sure ElastiCluster is not stopped during creation of an instance , it will overwrite the sigint handler . As soon as the last started instance ...
nodes = self . get_all_nodes ( ) log . info ( "Starting cluster nodes ..." ) if log . DO_NOT_FORK : nodes = self . _start_nodes_sequentially ( nodes ) else : nodes = self . _start_nodes_parallel ( nodes , self . thread_pool_max_size ) # checkpoint cluster state self . repository . save_or_update ( self ) not_st...
def ask_bool ( question : str , default : bool = True ) -> bool : """Asks a question yes no style"""
default_q = "Y/n" if default else "y/N" answer = input ( "{0} [{1}]: " . format ( question , default_q ) ) lower = answer . lower ( ) if not lower : return default return lower == "y"
async def plonks ( self , ctx ) : """Shows members banned from the bot ."""
plonks = self . config . get ( 'plonks' , { } ) guild = ctx . message . server db = plonks . get ( guild . id , [ ] ) members = '\n' . join ( map ( str , filter ( None , map ( guild . get_member , db ) ) ) ) if members : await self . bot . responses . basic ( title = "Plonked Users:" , message = members ) else : ...
def list_buckets ( self , offset = 0 , limit = 100 ) : """Limit breaks above 100"""
# TODO : If limit > 100 , do multiple fetches if limit > 100 : raise Exception ( "Zenobase can't handle limits over 100" ) return self . _get ( "/users/{}/buckets/?order=label&offset={}&limit={}" . format ( self . client_id , offset , limit ) )
def read_tf_records ( batch_size , tf_records , num_repeats = 1 , shuffle_records = True , shuffle_examples = True , shuffle_buffer_size = None , interleave = True , filter_amount = 1.0 ) : """Args : batch _ size : batch size to return tf _ records : a list of tf _ record filenames num _ repeats : how many ti...
if shuffle_examples and not shuffle_buffer_size : raise ValueError ( "Must set shuffle buffer size if shuffling examples" ) tf_records = list ( tf_records ) if shuffle_records : random . shuffle ( tf_records ) record_list = tf . data . Dataset . from_tensor_slices ( tf_records ) # compression _ type here must a...
def get_dashboard ( self , id , ** kwargs ) : """" Retrieve a ( v2 ) dashboard by id ."""
resp = self . _get_object_by_name ( self . _DASHBOARD_ENDPOINT_SUFFIX , id , ** kwargs ) return resp
def _prepare_consume_payload ( did , service_agreement_id , service_definition_id , signature , consumer_address ) : """Prepare a payload to send to ` Brizo ` . : param did : DID , str : param service _ agreement _ id : Service Agreement Id , str : param service _ definition _ id : identifier of the service i...
return json . dumps ( { 'did' : did , 'serviceAgreementId' : service_agreement_id , ServiceAgreement . SERVICE_DEFINITION_ID : service_definition_id , 'signature' : signature , 'consumerAddress' : consumer_address } )
def _set_profile ( self , v , load = False ) : """Setter method for profile , mapped from YANG variable / protocol / lldp / profile ( list ) If this variable is read - only ( config : false ) in the source YANG file , then _ set _ profile is considered as a private method . Backends looking to populate this v...
if hasattr ( v , "_utype" ) : v = v . _utype ( v ) try : t = YANGDynClass ( v , base = YANGListType ( "profile_name" , profile . profile , yang_name = "profile" , rest_name = "profile" , parent = self , is_container = 'list' , user_ordered = False , path_helper = self . _path_helper , yang_keys = 'profile-name'...
def create ( model , trust_region , entropy_coefficient , q_coefficient , max_grad_norm , discount_factor , rho_cap = 10.0 , retrace_rho_cap = 1.0 , average_model_alpha = 0.99 , trust_region_delta = 1.0 ) : """Vel factory function"""
return AcerPolicyGradient ( trust_region = trust_region , model_factory = model , entropy_coefficient = entropy_coefficient , q_coefficient = q_coefficient , rho_cap = rho_cap , retrace_rho_cap = retrace_rho_cap , max_grad_norm = max_grad_norm , discount_factor = discount_factor , average_model_alpha = average_model_al...
def get_coordinate_system ( self ) : """Check self . Data for available coordinate systems . Returns initial _ coordinate , coordinate _ list : str , list i . e . , ' geographic ' , [ ' specimen ' , ' geographic ' ]"""
coordinate_list = [ 'specimen' ] initial_coordinate = 'specimen' for specimen in self . specimens : if 'geographic' not in coordinate_list and self . Data [ specimen ] [ 'zijdblock_geo' ] : coordinate_list . append ( 'geographic' ) initial_coordinate = 'geographic' if 'tilt-corrected' not in coo...
def filter_for_probability ( key : str , population : Union [ pd . DataFrame , pd . Series , Index ] , probability : Array , index_map : IndexMap = None ) -> Union [ pd . DataFrame , pd . Series , Index ] : """Decide an event outcome for each individual in a population from probabilities . Given a population or i...
if population . empty : return population index = population if isinstance ( population , pd . Index ) else population . index draw = random ( key , index , index_map ) mask = np . array ( draw < probability ) return population [ mask ]
def _get_model_metadata ( model_class , metadata , version = None ) : """Returns user - defined metadata , making sure information all models should have is also available , as a dictionary"""
from turicreate import __version__ info = { 'turicreate_version' : __version__ , 'type' : model_class , } if version is not None : info [ 'version' ] = str ( version ) info . update ( metadata ) return info
def HasTable ( self , table_name ) : """Determines if a specific table exists . Args : table _ name ( str ) : table name . Returns : bool : True if the table exists . Raises : RuntimeError : if the database is not opened ."""
if not self . _connection : raise RuntimeError ( 'Cannot determine if table exists database not opened.' ) sql_query = self . _HAS_TABLE_QUERY . format ( table_name ) self . _cursor . execute ( sql_query ) if self . _cursor . fetchone ( ) : return True return False
def connect ( self , output_name , input_method ) : """Connect an output to any callable object . : py : meth : ` on _ connect ` is called after the connection is made to allow components to do something when an output is conected . : param str output _ name : the output to connect . Must be a member of : p...
self . logger . debug ( 'connect "%s"' , output_name ) if self . running ( ) : raise RuntimeError ( 'Cannot connect running component' ) self . _component_connections [ output_name ] . append ( input_method ) self . on_connect ( output_name )
def trace_generator ( trace , start = 0 , stop = None , step = 1 ) : """Return a generator returning values from the object ' s trace . Ex : T = trace _ generator ( theta . trace ) T . next ( ) for t in T : . . ."""
i = start stop = stop or np . inf size = min ( trace . length ( ) , stop ) while i < size : index = slice ( i , i + 1 ) yield trace . gettrace ( slicing = index ) [ 0 ] i += step
def __SendChunk ( self , start , additional_headers = None ) : """Send the specified chunk ."""
self . EnsureInitialized ( ) no_log_body = self . total_size is None request = http_wrapper . Request ( url = self . url , http_method = 'PUT' ) if self . __gzip_encoded : request . headers [ 'Content-Encoding' ] = 'gzip' body_stream , read_length , exhausted = compression . CompressStream ( self . stream , sel...
def sanitize_parse_mode ( mode ) : """Converts the given parse mode into an object with ` ` parse ` ` and ` ` unparse ` ` callable properties ."""
if not mode : return None if callable ( mode ) : class CustomMode : @ staticmethod def unparse ( text , entities ) : raise NotImplementedError CustomMode . parse = mode return CustomMode elif ( all ( hasattr ( mode , x ) for x in ( 'parse' , 'unparse' ) ) and all ( callable (...
def _compute_and_write_row_block ( i , left_matrix , right_matrix , train_indices_out_path , test_indices_out_path , remove_empty_rows ) : """Compute row block ( shard ) of expansion for row i of the left _ matrix . Compute a shard of the randomized Kronecker product and dump it on the fly . A standard Kronecke...
kron_blocks = [ ] num_rows = 0 num_removed_rows = 0 num_interactions = 0 num_train_interactions = 0 num_test_interactions = 0 # Construct blocks for j in xrange ( left_matrix . shape [ 1 ] ) : dropout_rate = 1.0 - left_matrix [ i , j ] kron_block = shuffle_sparse_coo_matrix ( right_matrix , dropout_rate ) i...
def lib_dir ( self ) : """Return standard library directory path used by RPM libs ."""
if not self . _lib_dir : lib_files = glob . glob ( "/usr/lib/*/librpm.so*" ) if not lib_files : raise InstallError ( "Can not find lib directory." ) self . _lib_dir = os . path . dirname ( lib_files [ 0 ] ) return self . _lib_dir
def init_atom_feed ( self , feed ) : """Initializing an atom feed ` feedgen . feed . FeedGenerator ` given a feed object : param feed : a feed object : return : an atom feed ` feedgen . feed . FeedGenerator `"""
atom_feed = FeedGenerator ( ) atom_feed . id ( id = self . request . route_url ( self . get_atom_feed_url , id = feed . id ) ) atom_feed . link ( href = self . request . route_url ( self . get_atom_feed_url , id = feed . id ) , rel = 'self' ) atom_feed . language ( 'nl-BE' ) self . link_to_sibling ( feed , 'previous' ,...
def titles ( self , key , value ) : """Populate the ` ` titles ` ` key ."""
if not key . startswith ( '245' ) : return { 'source' : value . get ( '9' ) , 'subtitle' : value . get ( 'b' ) , 'title' : value . get ( 'a' ) , } self . setdefault ( 'titles' , [ ] ) . insert ( 0 , { 'source' : value . get ( '9' ) , 'subtitle' : value . get ( 'b' ) , 'title' : value . get ( 'a' ) , } )
def _get_translation_field_names ( ) : """Returns Translation base model field names ( excepted " id " field ) ."""
from . models import Translation fields = [ f . name for f in Translation . _meta . get_fields ( ) ] fields . remove ( "id" ) return fields
def kvlclient ( self ) : '''Return a thread local ` ` kvlayer ` ` client .'''
if self . _kvlclient is None : self . _kvlclient = kvlayer . client ( ) return self . _kvlclient
def load_from_package ( ) : '''Try to load category ranges from module . : returns : category ranges dict or None : rtype : None or dict of RangeGroup'''
try : import pkg_resources f = pkg_resources . resource_stream ( meta . __app__ , 'cache/unicategories.cache' ) dversion , mversion , data = pickle . load ( f ) if dversion == data_version and mversion == module_version : return data warnings . warn ( 'Unicode unicategories database is outda...