signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def group ( self , * args , ** kwargs ) : """A group allows a command to have subcommands attached . This is the most common way to implement nesting in Click . : param name : the name of the group ( optional ) : param commands : a dictionary of commands ."""
return super ( ) . group ( * args , cls = kwargs . pop ( 'cls' , AppGroup ) or AppGroup , ** kwargs )
def get_datastream_info ( self , dsinfo ) : '''Use regular expressions to pull datastream [ version ] details ( id , mimetype , size , and checksum ) for binary content , in order to sanity check the decoded data . : param dsinfo : text content just before a binaryContent tag : returns : dict with keys for ...
# we only need to look at the end of this section of content dsinfo = dsinfo [ - 750 : ] # if not enough content is present , include the end of # the last read chunk , if available if len ( dsinfo ) < 750 and self . end_of_last_chunk is not None : dsinfo = self . end_of_last_chunk + dsinfo # force text needed for ...
def detachChildren ( self ) : """Detach and return this element ' s children . @ return : The element ' s children ( detached ) . @ rtype : [ L { Element } , . . . ]"""
detached = self . children self . children = [ ] for child in detached : child . parent = None return detached
def _handle_mouse ( self , ev ) : """Handle mouse events . Return a list of KeyPress instances ."""
FROM_LEFT_1ST_BUTTON_PRESSED = 0x1 result = [ ] # Check event type . if ev . ButtonState == FROM_LEFT_1ST_BUTTON_PRESSED : # On a key press , generate both the mouse down and up event . for event_type in [ MouseEventType . MOUSE_DOWN , MouseEventType . MOUSE_UP ] : data = ';' . join ( [ event_type , str ( e...
def indentby ( parser , token ) : """Add indentation to text between the tags by the given indentation level . { % indentby < indent _ level > [ if < statement > ] % } { % endindentby % } Arguments : indent _ level - Number of spaces to indent text with . statement - Only apply indent _ level if the boole...
args = token . split_contents ( ) largs = len ( args ) if largs not in ( 2 , 4 ) : raise template . TemplateSyntaxError ( "indentby tag requires 1 or 3 arguments" ) indent_level = args [ 1 ] if_statement = None if largs == 4 : if_statement = args [ 3 ] nodelist = parser . parse ( ( 'endindentby' , ) ) parser . ...
def _only_if_file_not_exist ( func_ , * args , ** kwargs ) : """horribly non - atomic : param func _ : : param args : : param kwargs : : return :"""
obj_dict = args [ 1 ] conn = args [ - 1 ] try : RBF . get ( obj_dict [ PRIMARY_FIELD ] ) . pluck ( PRIMARY_FIELD ) . run ( conn ) err_str = "Duplicate primary key `Name`: {}" . format ( obj_dict [ PRIMARY_FIELD ] ) err_dict = { 'errors' : 1 , 'first_error' : err_str } return err_dict except r . errors ....
def fromBrdict ( cls , master , brdict ) : """Construct a new L { BuildRequest } from a dictionary as returned by L { BuildRequestsConnectorComponent . getBuildRequest } . This method uses a cache , which may result in return of stale objects ; for the most up - to - date information , use the database connec...
cache = master . caches . get_cache ( "BuildRequests" , cls . _make_br ) return cache . get ( brdict [ 'buildrequestid' ] , brdict = brdict , master = master )
def _glob_escape ( pathname ) : """Escape all special characters ."""
drive , pathname = os . path . splitdrive ( pathname ) pathname = _magic_check . sub ( r'[\1]' , pathname ) return drive + pathname
def _setup_bar ( self ) : """Setup the process bar ."""
bar = u"" items_cnt = len ( PROGRESS_BAR_ITEMS ) bar_val = float ( self . _time_left ) / self . _section_time * self . num_progress_bars while bar_val > 0 : selector = int ( bar_val * items_cnt ) selector = min ( selector , items_cnt - 1 ) bar += PROGRESS_BAR_ITEMS [ selector ] bar_val -= 1 bar = bar . ...
def plot_dos ( self , sigma = 0.05 ) : """plot dos Args : sigma : a smearing Returns : a matplotlib object"""
plotter = DosPlotter ( sigma = sigma ) plotter . add_dos ( "t" , self . _bz . dos ) return plotter . get_plot ( )
def import_tasks ( self , path ) : """Attempts to load tasks from a given path . : param path : Path to tasks . : return : None ."""
for zz in os . walk ( path ) : for module in zz [ 2 ] : if module . endswith ( '.py' ) : import importlib # from tasks . message _ popup import * importlib . import_module ( 'tasks.' + module [ : - 3 ] ) print 'imported' , module
def surface_tessellate ( v1 , v2 , v3 , v4 , vidx , tidx , trim_curves , tessellate_args ) : """Triangular tessellation algorithm for surfaces with no trims . This function can be directly used as an input to : func : ` . make _ triangle _ mesh ` using ` ` tessellate _ func ` ` keyword argument . : param v1 :...
# Triangulate vertices tris = polygon_triangulate ( tidx , v1 , v2 , v3 , v4 ) # Return vertex and triangle lists return [ ] , tris
def commit_token_operation ( self , token_op , current_block_number ) : """Commit a token operation that debits one account and credits another Returns the new canonicalized record ( with all compatibility quirks preserved ) DO NOT CALL THIS DIRECTLY"""
# have to have read - write disposition if self . disposition != DISPOSITION_RW : log . error ( "FATAL: borrowing violation: not a read-write connection" ) traceback . print_stack ( ) os . abort ( ) cur = self . db . cursor ( ) opcode = token_op . get ( 'opcode' , None ) clean_token_op = self . sanitize_op ...
def to_dict ( self ) : """Transforms the object to a Python dictionary . Note : If an Input hasn ' t been signed yet , this method returns a dictionary representation . Returns : dict : The Input as an alternative serialization format ."""
try : fulfillment = self . fulfillment . serialize_uri ( ) except ( TypeError , AttributeError , ASN1EncodeError , ASN1DecodeError ) : fulfillment = _fulfillment_to_details ( self . fulfillment ) try : # NOTE : ` self . fulfills ` can be ` None ` and that ' s fine fulfills = self . fulfills . to_dict ( ) ex...
def get_summary_string ( self ) : """Get a string summarising the state of Rez as a whole . Returns : String ."""
from rez . plugin_managers import plugin_manager txt = "Rez %s" % __version__ txt += "\n\n%s" % plugin_manager . get_summary_string ( ) return txt
def table ( self , name : str ) : """Display info about a table : number of rows and columns : param name : name of the table : type name : str : example : ` ` tables = ds . table ( " mytable " ) ` `"""
if self . _check_db ( ) == False : return try : res = self . getall ( name ) except Exception as e : self . err ( e , self . table , "Can not get records from database" ) return if res is None : self . warning ( "Table" , name , "does not contain any record" ) return num = len ( res ) self . inf...
def log_event ( event , logger = root_logger , ** log_dict ) : """Utility function for logging an event ( e . g . for metric analysis ) . If no logger is given , fallback to the root logger ."""
msg = "event={}" . format ( event ) msg = add_items_to_message ( msg , log_dict ) log_dict . update ( { 'event' : event } ) logger . info ( msg , extra = log_dict )
def imp_print ( self , text , end ) : """Use win _ unicode _ console"""
PRINT ( text , end = end , file = win_unicode_console . streams . stdout_text_transcoded )
def _marker_line ( self ) : # type : ( ) - > str """Generate a correctly sized marker line . e . g . : return : str"""
output = '' for col in sorted ( self . col_widths ) : line = self . COLUMN_MARK + ( self . DASH * ( self . col_widths [ col ] + self . PADDING * 2 ) ) output += line output += self . COLUMN_MARK + '\n' return output
def heading2table ( soup , table , row ) : """add heading row to table"""
tr = Tag ( soup , name = "tr" ) table . append ( tr ) for attr in row : th = Tag ( soup , name = "th" ) tr . append ( th ) th . append ( attr )
def get_coreml_model ( self , mode = 'classifier' ) : """Parameters mode : str ( ' classifier ' , ' regressor ' or None ) Mode of the converted coreml model . When mode = ' classifier ' , a NeuralNetworkClassifier spec will be constructed . When mode = ' regressor ' , a NeuralNetworkRegressor spec will be c...
import mxnet as _mx from . _mxnet import _mxnet_utils from . _mxnet . _mxnet_to_coreml import _mxnet_converter ( sym , arg_params , aux_params ) = self . ptModel . mxmodel fe_mxmodel = self . ptModel . mxmodel if self . ptModel . is_feature_layer_final : feature_layer_size = self . ptModel . feature_layer_size ...
def worker_thread ( context ) : """The worker thread routines ."""
queue = context . task_queue parameters = context . worker_parameters if parameters . initializer is not None : if not run_initializer ( parameters . initializer , parameters . initargs ) : context . state = ERROR return for task in get_next_task ( context , parameters . max_tasks ) : execute_ne...
def get_object_or_None ( klass , * args , ** kwargs ) : """Uses get ( ) to return an object or None if the object does not exist . klass may be a Model , Manager , or QuerySet object . All other passed arguments and keyword arguments are used in the get ( ) query . Note : Like with get ( ) , a MultipleObjects...
queryset = _get_queryset ( klass ) try : return queryset . get ( * args , ** kwargs ) except queryset . model . DoesNotExist : return None
def CalculateForecastStats ( matched , available , possible = None ) : """Calculate forecast percentage stats . Args : matched : The number of matched impressions . available : The number of available impressions . possible : The optional number of possible impressions . Returns : The percentage of impr...
if matched > 0 : available_percent = ( float ( available ) / matched ) * 100. else : available_percent = 0 if possible is not None : if matched > 0 : possible_percent = ( possible / float ( matched ) ) * 100. else : possible_percent = 0 else : possible_percent = None return available...
def stack ( cls , areas ) : """Stacks an ( Nd ) Overlay of Area or Curve Elements by offsetting their baselines . To stack a HoloMap or DynamicMap use the map method ."""
if not len ( areas ) : return areas baseline = np . zeros ( len ( areas . values ( ) [ 0 ] ) ) stacked = areas . clone ( shared_data = False ) vdims = [ areas . values ( ) [ 0 ] . vdims [ 0 ] , 'Baseline' ] for k , area in areas . items ( ) : x , y = ( area . dimension_values ( i ) for i in range ( 2 ) ) st...
def add_stylesheets ( self , * css_files ) : """add stylesheet files in HTML head"""
for css_file in css_files : self . main_soup . style . append ( self . _text_file ( css_file ) )
def vis_splitting ( Verts , splitting , output = 'vtk' , fname = 'output.vtu' ) : """Coarse grid visualization for C / F splittings . Parameters Verts : { array } coordinate array ( N x D ) splitting : { array } coarse ( 1 ) / fine ( 0 ) flags fname : { string , file object } file to be written , e . ...
check_input ( Verts , splitting ) N = Verts . shape [ 0 ] Ndof = int ( len ( splitting ) / N ) E2V = np . arange ( 0 , N , dtype = int ) # adjust name in case of multiple variables a = fname . split ( '.' ) if len ( a ) < 2 : fname1 = a [ 0 ] fname2 = '.vtu' elif len ( a ) >= 2 : fname1 = "" . join ( a [ : ...
def ScanForStorageMediaImage ( self , source_path_spec ) : """Scans the path specification for a supported storage media image format . Args : source _ path _ spec ( PathSpec ) : source path specification . Returns : PathSpec : storage media image path specification or None if no supported storage media i...
try : type_indicators = analyzer . Analyzer . GetStorageMediaImageTypeIndicators ( source_path_spec , resolver_context = self . _resolver_context ) except RuntimeError as exception : raise errors . BackEndError ( ( 'Unable to process source path specification with error: ' '{0!s}' ) . format ( exception ) ) if ...
def to_frame ( self , slot = 1 ) : """Return the current configuration as a YubiKeyFrame object ."""
data = self . to_string ( ) payload = data . ljust ( 64 , yubico_util . chr_byte ( 0x0 ) ) if slot is 1 : if self . _update_config : command = SLOT . UPDATE1 else : command = SLOT . CONFIG elif slot is 2 : if self . _update_config : command = SLOT . UPDATE2 else : command...
def check_stoplimit_prices ( price , label ) : """Check to make sure the stop / limit prices are reasonable and raise a BadOrderParameters exception if not ."""
try : if not isfinite ( price ) : raise BadOrderParameters ( msg = "Attempted to place an order with a {} price " "of {}." . format ( label , price ) ) # This catches arbitrary objects except TypeError : raise BadOrderParameters ( msg = "Attempted to place an order with a {} price " "of {}." . format ( ...
def write_boundaries ( self , filename ) : """Write boundary lines X1 Y1 X2 Y2 TYPE to file"""
fid = open ( filename , 'w' ) for i in self . Boundaries : print ( i ) # fid . write ( ' { 0 } { 1 } { 2 } \ n ' . format ( i [ 0 ] , i [ 1 ] , i [ 2 ] ) ) fid . write ( '{0} {1} {2} {3} {4}\n' . format ( i [ 0 ] [ 0 ] , i [ 0 ] [ 1 ] , i [ 1 ] [ 0 ] , i [ 1 ] [ 1 ] , i [ 2 ] ) ) fid . close ( )
def set_my_info ( self , message , contact_info = "" ) : """set my contact info to _ _ _ _ : Set your emergency contact info ."""
contacts = self . load ( "contact_info" , { } ) contacts [ message . sender . handle ] = { "info" : contact_info , "name" : message . sender . name , } self . save ( "contact_info" , contacts ) self . say ( "Got it." , message = message )
def start ( self ) : '''Start listening for messages .'''
log . debug ( 'Creating the TCP server' ) if ':' in self . address : self . skt = socket . socket ( socket . AF_INET6 , socket . SOCK_STREAM ) else : self . skt = socket . socket ( socket . AF_INET , socket . SOCK_STREAM ) if self . reuse_port : self . skt . setsockopt ( socket . SOL_SOCKET , socket . SO_RE...
def gen_req_sfc ( lat_x , lon_x , start , end , grid = [ 0.125 , 0.125 ] , scale = 0 ) : '''generate a dict of reqs kwargs for ( lat _ x , lon _ x ) spanning [ start , end ] Parameters lat _ x : [ type ] [ description ] lon _ x : [ type ] [ description ] start : [ type ] [ description ] end : [ type...
# scale is a factor to rescale grid size size = grid [ 0 ] * scale # generate pd . Series for timestamps ser_datetime = pd . date_range ( start , end , freq = '1h' ) . to_series ( ) # surface requests lat_c , lon_c = ( roundPartial ( x , grid [ 0 ] ) for x in [ lat_x , lon_x ] ) area = [ lat_c + size , lon_c - size , l...
def checkMarkovInputs ( self ) : '''Many parameters used by MarkovConsumerType are arrays . Make sure those arrays are the right shape . Parameters None Returns None'''
StateCount = self . MrkvArray [ 0 ] . shape [ 0 ] # Check that arrays are the right shape assert self . Rfree . shape == ( StateCount , ) , 'Rfree not the right shape!' # Check that arrays in lists are the right shape for MrkvArray_t in self . MrkvArray : assert MrkvArray_t . shape == ( StateCount , StateCount ) , ...
def load_data ( self , data_np ) : """Load raw numpy data into the viewer ."""
image = AstroImage . AstroImage ( logger = self . logger ) image . set_data ( data_np ) self . set_image ( image )
async def get_partition_ids_async ( self ) : """Returns a list of all the event hub partition IDs . : rtype : list [ str ]"""
if not self . partition_ids : try : eh_client = EventHubClientAsync ( self . host . eh_config . client_address , debug = self . host . eph_options . debug_trace , http_proxy = self . host . eph_options . http_proxy ) try : eh_info = await eh_client . get_eventhub_info_async ( ) ...
def init_weights ( self , m ) : """Initialize the weights ."""
classname = m . __class__ . __name__ if classname . find ( 'Linear' ) != - 1 : if hasattr ( m , 'weight' ) and m . weight is not None : self . init_weight ( m . weight ) if hasattr ( m , 'bias' ) and m . bias is not None : self . init_bias ( m . bias ) elif classname . find ( 'AdaptiveEmbedding'...
def on_menu_save_interpretation ( self , event ) : '''save interpretations to a redo file'''
thellier_gui_redo_file = open ( os . path . join ( self . WD , "thellier_GUI.redo" ) , 'w' ) # write interpretations to thellier _ GUI . redo spec_list = list ( self . Data . keys ( ) ) spec_list . sort ( ) redo_specimens_list = [ ] for sp in spec_list : if 'saved' not in self . Data [ sp ] [ 'pars' ] : con...
def get_column_definition_all ( self , table ) : """Retrieve the column definition statement for all columns in a table ."""
# Get complete table definition col_defs = self . get_table_definition ( table ) . split ( '\n' ) # Return only column definitions return [ i [ 0 : - 1 ] . strip ( ) . replace ( ',' , ', ' ) for i in col_defs if i . strip ( ) . startswith ( '`' ) ]
def foreground_mask ( self , tolerance , ignore_black = True , use_hsv = False , scale = 8 , bgmodel = None ) : """Creates a binary image mask for the foreground of an image against a uniformly colored background . The background is assumed to be the mode value of the histogram for each of the color channels . ...
# get a background model if bgmodel is None : bgmodel = self . background_model ( ignore_black = ignore_black , use_hsv = use_hsv , scale = scale ) # get the bounds lower_bound = np . array ( [ bgmodel [ i ] - tolerance for i in range ( self . channels ) ] ) upper_bound = np . array ( [ bgmodel [ i ] + tolerance fo...
def makedirs ( self , path , mode = 0x777 ) : "Super - mkdir : create a leaf directory and all intermediate ones ."
self . directory_create ( path , mode , [ library . DirectoryCreateFlag . parents ] )
def decayWeights ( self , decayConst = 60 ) : """Decay the network ' s weights . : param decayConst : The time constant ( in seconds ) to use for decay . Note : If applied , decay must be used extremely carefully , as it has a tendency to cause asymmetries in the network weights ."""
self . weightsII -= self . weightsII * self . dt / decayConst self . weightsELI -= self . weightsELI * self . dt / decayConst self . weightsERI -= self . weightsERI * self . dt / decayConst self . weightsIEL -= self . weightsIEL * self . dt / decayConst self . weightsIER -= self . weightsIER * self . dt / decayConst
def route ( cls , route , config = None ) : """This method provides a decorator for adding endpoints to the http server . Args : route ( str ) : The url to be handled by the RequestHandled config ( dict ) : Configuration for the request handler Example : . . code - block : : python import nautilus f...
def decorator ( wrapped_class , ** kwds ) : # add the endpoint at the given route cls . _routes . append ( dict ( url = route , request_handler = wrapped_class ) ) # return the class undecorated return wrapped_class # return the decorator return decorator
def labeller ( rows = None , cols = None , multi_line = True , default = label_value , ** kwargs ) : """Return a labeller function Parameters rows : str | function | None How to label the rows cols : str | function | None How to label the columns multi _ line : bool Whether to place each variable on a...
# Sort out the labellers along each dimension rows_labeller = as_labeller ( rows , default , multi_line ) cols_labeller = as_labeller ( cols , default , multi_line ) def _labeller ( label_info ) : # When there is no variable specific labeller , # use that of the dimension if label_info . _meta [ 'dimension' ] == 'r...
def send ( cfg , ** kwargs ) : """Send a text message , file , or directory"""
for name , value in kwargs . items ( ) : setattr ( cfg , name , value ) with cfg . timing . add ( "import" , which = "cmd_send" ) : from . import cmd_send return go ( cmd_send . send , cfg )
def retrieve_dcnm_subnet_info ( self , tenant_id , direc ) : """Retrieves the DCNM subnet info for a tenant ."""
serv_obj = self . get_service_obj ( tenant_id ) subnet_dict = serv_obj . get_dcnm_subnet_dict ( direc ) return subnet_dict
def verify_ed25519_signature ( public_key , contents , signature , message ) : """Verify that ` ` signature ` ` comes from ` ` public _ key ` ` and ` ` contents ` ` . Args : public _ key ( Ed25519PublicKey ) : the key to verify the signature contents ( bytes ) : the contents that was signed signature ( byte...
try : public_key . verify ( signature , contents ) except InvalidSignature as exc : raise ScriptWorkerEd25519Error ( message % { 'exc' : str ( exc ) } )
def fill_polygon ( self , polygons , colour = 7 , bg = 0 ) : """Draw a filled polygon . This function uses the scan line algorithm to create the polygon . See https : / / www . cs . uic . edu / ~ jbell / CourseNotes / ComputerGraphics / PolygonFilling . html for details . : param polygons : A list of polygons...
def _add_edge ( a , b ) : # Ignore horizontal lines - they are redundant if a [ 1 ] == b [ 1 ] : return # Ignore any edges that do not intersect the visible raster lines at all . if ( a [ 1 ] < 0 and b [ 1 ] < 0 ) or ( a [ 1 ] >= self . height and b [ 1 ] >= self . height ) : return # Sa...
def run ( self ) : """actual consuming of incoming works starts here"""
self . input_channel . basic_consume ( self . handle_message , queue = self . INPUT_QUEUE_NAME , no_ack = True ) try : self . input_channel . start_consuming ( ) except ( KeyboardInterrupt , SystemExit ) : log . info ( " Exiting" ) self . exit ( )
def defer_sync ( self , func ) : """Arrange for ` func ( ) ` to execute on : class : ` Broker ` thread , blocking the current thread until a result or exception is available . : returns : Return value of ` func ( ) ` ."""
latch = Latch ( ) def wrapper ( ) : try : latch . put ( func ( ) ) except Exception : latch . put ( sys . exc_info ( ) [ 1 ] ) self . defer ( wrapper ) res = latch . get ( ) if isinstance ( res , Exception ) : raise res return res
def handler ( event , context ) : # pylint : disable = W0613 """Historical security group event differ . Listens to the Historical current table and determines if there are differences that need to be persisted in the historical record ."""
# De - serialize the records : records = deserialize_records ( event [ 'Records' ] ) for record in records : process_dynamodb_differ_record ( record , CurrentSecurityGroupModel , DurableSecurityGroupModel )
def _get_struct_linestylearray ( self , shape_number ) : """Get the values for the LINESTYLEARRAY record ."""
obj = _make_object ( "LineStyleArray" ) obj . LineStyleCount = count = unpack_ui8 ( self . _src ) if count == 0xFF : obj . LineStyleCountExtended = count = unpack_ui16 ( self . _src ) obj . LineStyles = line_styles = [ ] for _ in range ( count ) : if shape_number <= 3 : record = _make_object ( "LineStyl...
def _create_tooltips ( hist : Histogram1D , vega : dict , kwargs : dict ) : """In one - dimensional plots , show values above the value on hover ."""
if kwargs . pop ( "tooltips" , False ) : vega [ "signals" ] = vega . get ( "signals" , [ ] ) vega [ "signals" ] . append ( { "name" : "tooltip" , "value" : { } , "on" : [ { "events" : "rect:mouseover" , "update" : "datum" } , { "events" : "rect:mouseout" , "update" : "{}" } ] } ) font_size = kwargs . get ( ...
def get_fw_dev_map ( self , fw_id ) : """Return the object dict and mgmt ip for a firewall ."""
for cnt in self . res : if fw_id in self . res . get ( cnt ) . get ( 'fw_id_lst' ) : return self . res [ cnt ] . get ( 'obj_dict' ) , ( self . res [ cnt ] . get ( 'mgmt_ip' ) ) return None , None
def update ( self , claim , ttl = None , grace = None ) : """Updates the specified claim with either a new TTL or grace period , or both ."""
body = { } if ttl is not None : body [ "ttl" ] = ttl if grace is not None : body [ "grace" ] = grace if not body : raise exc . MissingClaimParameters ( "You must supply a value for " "'ttl' or 'grace' when calling 'update()'" ) uri = "/%s/%s" % ( self . uri_base , utils . get_id ( claim ) ) resp , resp_body...
def action ( fun = None , cloudmap = None , names = None , provider = None , instance = None , ** kwargs ) : '''Execute a single action on the given provider / instance CLI Example : . . code - block : : bash salt minionname cloud . action start instance = myinstance salt minionname cloud . action stop inst...
client = _get_client ( ) try : info = client . action ( fun , cloudmap , names , provider , instance , kwargs ) except SaltCloudConfigError as err : log . error ( err ) return None return info
def start_task ( self , task_type_str , current_task_index = None ) : """Call when processing is about to start on a single task of the given task type , typically at the top inside of the loop that processes the tasks . Args : task _ type _ str ( str ) : The name of the task , used as a dict key and printe...
assert ( task_type_str in self . _task_dict ) , "Task type has not been started yet: {}" . format ( task_type_str ) if current_task_index is not None : self . _task_dict [ task_type_str ] [ "task_idx" ] = current_task_index else : self . _task_dict [ task_type_str ] [ "task_idx" ] += 1 self . _log_progress_if_i...
def get_buildout_config ( buildout_filename ) : """Parse buildout config with zc . buildout ConfigParser"""
print ( "[localhost] get_buildout_config: {0:s}" . format ( buildout_filename ) ) buildout = Buildout ( buildout_filename , [ ( 'buildout' , 'verbosity' , '-100' ) ] ) while True : try : len ( buildout . items ( ) ) break except OSError : pass return buildout
def value_type ( type_ ) : """returns reference to ` boost : : shared _ ptr ` or ` std : : shared _ ptr ` value type"""
if not smart_pointer_traits . is_smart_pointer ( type_ ) : raise TypeError ( 'Type "%s" is not an instantiation of \ boost::shared_ptr or std::shared_ptr' % type_ . decl_string ) try : return internal_type_traits . get_by_name ( type_ , "element_type" ) except runtime_errors . declaration_not_fo...
def order_by_raw ( self , sql , bindings = None ) : """Add a raw " order by " clause to the query : param sql : The raw clause : type sql : str : param bindings : The bdings : param bindings : list : return : The current QueryBuilder instance : rtype : QueryBuilder"""
if bindings is None : bindings = [ ] type = "raw" self . orders . append ( { "type" : type , "sql" : sql } ) self . add_binding ( bindings , "order" ) return self
def _get_annotations ( self , text , language = '' ) : """Returns the list of annotations retrieved from the given text . Args : text ( str ) : Input text . language ( : obj : ` str ` , optional ) : Language code . Returns : Results in a dictionary . : code : ` tokens ` contains the list of annotations ...
body = { 'document' : { 'type' : 'PLAIN_TEXT' , 'content' : text , } , 'features' : { 'extract_syntax' : True , } , 'encodingType' : 'UTF32' , } if language : body [ 'document' ] [ 'language' ] = language request = self . service . documents ( ) . annotateText ( body = body ) response = request . execute ( ) tokens...
def search_bugs ( self , terms ) : '''http : / / bugzilla . readthedocs . org / en / latest / api / core / v1 / bug . html # search - bugs terms = [ { ' product ' : ' Infrastructure & Operations ' } , { ' status ' : ' NEW ' } ]'''
params = '' for i in terms : k = i . popitem ( ) params = '{p}&{new}={value}' . format ( p = params , new = quote_url ( k [ 0 ] ) , value = quote_url ( k [ 1 ] ) ) return DotDict ( self . _get ( 'bug' , params = params ) )
def dict_encode ( in_dict ) : """returns a new dictionary with encoded values useful for encoding http queries ( python < 3)"""
if _IS_PY2 : out_dict = { } for k , v in list ( in_dict . items ( ) ) : if isinstance ( v , unicode ) : v = v . encode ( 'utf8' ) elif isinstance ( v , str ) : # Must be encoded in UTF - 8 v . decode ( 'utf8' ) out_dict [ k ] = v return out_dict else : rai...
def p_static_scalar ( p ) : '''static _ scalar : common _ scalar | QUOTE QUOTE | QUOTE ENCAPSED _ AND _ WHITESPACE QUOTE'''
if len ( p ) == 2 : p [ 0 ] = p [ 1 ] elif len ( p ) == 3 : p [ 0 ] = '' else : p [ 0 ] = p [ 2 ] . decode ( 'string_escape' )
def sign ( message : bytes , sign_key : SignKey ) -> Signature : """Signs the message and returns signature . : param : message - Message to sign : param : sign _ key - Sign key : return : Signature"""
logger = logging . getLogger ( __name__ ) logger . debug ( "Bls::sign: >>> message: %r, sign_key: %r" , message , sign_key ) c_instance = c_void_p ( ) do_call ( 'indy_crypto_bls_sign' , message , len ( message ) , sign_key . c_instance , byref ( c_instance ) ) res = Signature ( c_instance ) logger . debug ( "Bls::sign:...
def get_pickled_ontology ( filename ) : """try to retrieve a cached ontology"""
pickledfile = os . path . join ( ONTOSPY_LOCAL_CACHE , filename + ".pickle" ) # pickledfile = ONTOSPY _ LOCAL _ CACHE + " / " + filename + " . pickle " if GLOBAL_DISABLE_CACHE : printDebug ( "WARNING: DEMO MODE cache has been disabled in __init__.py ==============" , "red" ) if os . path . isfile ( pickledfile ) an...
def plot_all_spectra ( self , outdir ) : """This is a convenience function to plot ALL spectra currently stored in the container . It is useful to asses whether data filters do perform correctly . Note that the function just iterates over all ids and plots the corresponding spectra , thus it is slow . Spe...
os . makedirs ( outdir , exist_ok = True ) g = self . data . groupby ( 'id' ) for nr , ( name , item ) in enumerate ( g ) : print ( 'Plotting spectrum with id {} ({} / {})' . format ( name , nr , len ( g . groups . keys ( ) ) ) ) plot_filename = '' . join ( ( outdir + os . sep , '{:04}_spectrum_id_{}.png' . for...
def add_host ( zone , name , ttl , ip , nameserver = '127.0.0.1' , replace = True , timeout = 5 , port = 53 , ** kwargs ) : '''Add , replace , or update the A and PTR ( reverse ) records for a host . CLI Example : . . code - block : : bash salt ns1 ddns . add _ host example . com host1 60 10.1.1.1'''
res = update ( zone , name , ttl , 'A' , ip , nameserver , timeout , replace , port , ** kwargs ) if res is False : return False fqdn = '{0}.{1}.' . format ( name , zone ) parts = ip . split ( '.' ) [ : : - 1 ] popped = [ ] # Iterate over possible reverse zones while len ( parts ) > 1 : p = parts . pop ( 0 ) ...
def predictions ( self ) : """Returns the predictions . : return : the predictions . None if not available : rtype : list"""
preds = javabridge . get_collection_wrapper ( javabridge . call ( self . jobject , "predictions" , "()Ljava/util/ArrayList;" ) ) if self . discard_predictions : result = None else : result = [ ] for pred in preds : if is_instance_of ( pred , "weka.classifiers.evaluation.NominalPrediction" ) : ...
def remove ( self , locator ) : """Removes a previously added reference that matches specified locator . If many references match the locator , it removes only the first one . When all references shall be removed , use [ [ removeAll ] ] method instead . : param locator : a locator to remove reference : retu...
if locator == None : return None self . _lock . acquire ( ) try : for reference in reversed ( self . _references ) : if reference . match ( locator ) : self . _references . remove ( reference ) return reference . get_component ( ) finally : self . _lock . release ( ) return N...
def clean_up ( self ) : """: return :"""
if self . auth_type == 'registry_rubber' and self . user : self . _registry_rubber_uonce ( 'delete' ) # clean up old docker configs . user_home = os . environ . get ( 'HOME' ) for file_name in os . listdir ( user_home ) : if 'dockercfg' in file_name : if file_name . count ( '.' ) is 2 : try ...
def output_aliases ( aliases ) : """Display git aliases"""
for alias in aliases : cmd = '!legit ' + alias click . echo ( columns ( [ colored . yellow ( 'git ' + alias ) , 20 ] , [ cmd , None ] ) )
def create_header_data ( coord , radius = 10. , ** kwargs ) : """Make an empty sky region at location of skydir skydir : skymaps . SkyDir object size : size of region ( deg . ) kwargs : arguments passed to create _ header"""
header = create_header ( coord , radius = radius , ** kwargs ) data = np . zeros ( ( header [ 'NAXIS1' ] , header [ 'NAXIS2' ] ) ) return header , data
def label ( self ) -> str : """A latex formatted label representing axis expression ."""
label = self . expression . replace ( "_" , "\\;" ) if self . units_kind : symbol = wt_units . get_symbol ( self . units ) for v in self . variables : vl = "%s_{%s}" % ( symbol , v . label ) vl = vl . replace ( "_{}" , "" ) # label can be empty , no empty subscripts label = label...
def SESSION_TIME ( stats , info ) : """Total time of this session . Reports the time elapsed from the construction of the ` Stats ` object to this ` submit ( ) ` call . This is a flag you can pass to ` Stats . submit ( ) ` ."""
duration = time . time ( ) - stats . started_time secs = int ( duration ) msecs = int ( ( duration - secs ) * 1000 ) info . append ( ( 'session_time' , '%d.%d' % ( secs , msecs ) ) )
def set_attr ( obj , path , value ) : """SAME AS object . _ _ setattr _ _ ( ) , BUT USES DOT - DELIMITED path RETURN OLD VALUE"""
try : return _set_attr ( obj , split_field ( path ) , value ) except Exception as e : Log = get_logger ( ) if PATH_NOT_FOUND in e : Log . warning ( PATH_NOT_FOUND + ": {{path}}" , path = path , cause = e ) else : Log . error ( "Problem setting value" , cause = e )
def forget_area ( self , area_uuid ) : """Remove an Upload Area from out cache of known areas . : param str area _ uuid : The RFC4122 - compliant UUID of the Upload Area ."""
if self . _config . upload . current_area == area_uuid : self . _config . upload . current_area = None if area_uuid in self . _config . upload . areas : del self . _config . upload . areas [ area_uuid ] self . save ( )
def transpose ( self ) : """Builds a new graph with the edges reversed . Returns : : class : ` stacker . dag . DAG ` : The transposed graph ."""
graph = self . graph transposed = DAG ( ) for node , edges in graph . items ( ) : transposed . add_node ( node ) for node , edges in graph . items ( ) : # for each edge A - > B , transpose it so that B - > A for edge in edges : transposed . add_edge ( edge , node ) return transposed
def to_date ( value , default = None ) : """Tries to convert the passed in value to Zope ' s DateTime : param value : The value to be converted to a valid DateTime : type value : str , DateTime or datetime : return : The DateTime representation of the value passed in or default"""
if isinstance ( value , DateTime ) : return value if not value : if default is None : return None return to_date ( default ) try : if isinstance ( value , str ) and '.' in value : # https : / / docs . plone . org / develop / plone / misc / datetime . html # datetime - problems - and - pitfalls ...
def pipe_fetchsitefeed ( context = None , _INPUT = None , conf = None , ** kwargs ) : """A source that fetches and parses the first feed found on one or more sites . Loopable . Parameters context : pipe2py . Context object _ INPUT : pipeforever pipe or an iterable of items or fields conf : URL - - url Y...
conf = DotDict ( conf ) urls = utils . listize ( conf [ 'URL' ] ) for item in _INPUT : for item_url in urls : url = utils . get_value ( DotDict ( item_url ) , DotDict ( item ) , ** kwargs ) url = utils . get_abspath ( url ) if context and context . verbose : print "pipe_fetchsite...
def add_one_en_passant_move ( self , direction , position ) : """Yields en _ passant moves in given direction if it is legal . : type : direction : function : type : position : Board : rtype : gen"""
try : if self . _is_en_passant_valid ( direction ( self . location ) , position ) : yield self . create_move ( end_loc = self . square_in_front ( direction ( self . location ) ) , status = notation_const . EN_PASSANT ) except IndexError : pass
def label_correcting_get_cycle ( self , j , pred ) : '''API : label _ correcting _ get _ cycle ( self , labelled , pred ) Description : In label correcting check cycle it is decided pred has a cycle and nodes in the cycle are labelled . We will create a list of nodes in the cycle using labelled and pred i...
cycle = [ ] cycle . append ( j ) current = pred [ j ] while current != j : cycle . append ( current ) current = pred [ current ] cycle . reverse ( ) return cycle
def find_ML ( sampler , modelidx ) : """Find Maximum Likelihood parameters as those in the chain with a highest log probability ."""
index = np . unravel_index ( np . argmax ( sampler . lnprobability ) , sampler . lnprobability . shape ) MLp = sampler . chain [ index ] if modelidx is not None and hasattr ( sampler , "blobs" ) : blob = sampler . blobs [ index [ 1 ] ] [ index [ 0 ] ] [ modelidx ] if isinstance ( blob , u . Quantity ) : ...
def _GetCurrentControlSet ( self , key_path_suffix ) : """Virtual key callback to determine the current control set . Args : key _ path _ suffix ( str ) : current control set Windows Registry key path suffix with leading path separator . Returns : WinRegistryKey : the current control set Windows Registry ...
select_key_path = 'HKEY_LOCAL_MACHINE\\System\\Select' select_key = self . GetKeyByPath ( select_key_path ) if not select_key : return None # To determine the current control set check : # 1 . The " Current " value . # 2 . The " Default " value . # 3 . The " LastKnownGood " value . control_set = None for value_name...
def set_layout ( self , layout ) : """Sets the LayoutParams of this widget . Since the available properties that may be set for the layout params depends on the parent , actual creation of the params is delegated to the parent Parameters layout : Dict A dict of layout parameters the parent should used t...
# Update the layout with the widget defaults update = self . layout_params is not None params = self . default_layout . copy ( ) params . update ( layout ) # Create the layout params parent = self . parent ( ) if not isinstance ( parent , AndroidView ) : # Root node parent = self update = True parent . apply_la...
def kilometers ( meters = 0 , miles = 0 , feet = 0 , nautical = 0 ) : """TODO docs ."""
ret = 0. if meters : ret += meters / 1000. if feet : ret += feet / ft ( 1. ) if nautical : ret += nautical / nm ( 1. ) ret += miles * 1.609344 return ret
def split_dataframe ( df , train_percentage = 0.6 , cv_percentage = 0.2 , test_percentage = 0.2 ) : """@ return training , cv , test ( as pandas dataframes ) @ param df : pandas dataframe @ param train _ percentage : float | percentage of data for training set ( default = 0.6) @ param cv _ percentage : floa...
assert train_percentage + cv_percentage + test_percentage == 1.0 N = len ( df ) l = range ( N ) shuffle ( l ) # get splitting indices train_len = int ( N * train_percentage ) cv_len = int ( N * cv_percentage ) test_len = int ( N * test_percentage ) # get training , cv , and test sets training = df . ix [ l [ : train_le...
def cli ( env , identifier ) : """Cancel virtual servers ."""
vsi = SoftLayer . VSManager ( env . client ) vs_id = helpers . resolve_id ( vsi . resolve_ids , identifier , 'VS' ) if not ( env . skip_confirmations or formatting . no_going_back ( vs_id ) ) : raise exceptions . CLIAbort ( 'Aborted' ) vsi . cancel_instance ( vs_id )
def _dates ( self , key , value ) : """Don ' t populate any key through the return value . On the other hand , populates the ` ` date _ proposed ` ` , ` ` date _ approved ` ` , ` ` date _ started ` ` , ` ` date _ cancelled ` ` , and the ` ` date _ completed ` ` keys through side effects ."""
if value . get ( 'q' ) : self [ 'date_proposed' ] = normalize_date ( value [ 'q' ] ) if value . get ( 'r' ) : self [ 'date_approved' ] = normalize_date ( value [ 'r' ] ) if value . get ( 's' ) : self [ 'date_started' ] = normalize_date ( value [ 's' ] ) if value . get ( 'c' ) : self [ 'date_cancelled' ]...
def get_program_files_dir ( ) : """returns the location of the " program files " directory on a windows platform"""
ProgramFiles = bjam . variable ( "ProgramFiles" ) if ProgramFiles : ProgramFiles = ' ' . join ( ProgramFiles ) else : ProgramFiles = "c:\\Program Files" return ProgramFiles
def Validate ( self ) : """Check the source is well constructed ."""
self . _ValidateReturnedTypes ( ) self . _ValidatePaths ( ) self . _ValidateType ( ) self . _ValidateRequiredAttributes ( ) self . _ValidateCommandArgs ( )
def _args_for_remote ( self ) : """Generate arguments for ' terraform remote config ' . Return None if not present in configuration . : return : list of args for ' terraform remote config ' or None : rtype : : std : term : ` list `"""
conf = self . config . get ( 'terraform_remote_state' ) if conf is None : return None args = [ '-backend=%s' % conf [ 'backend' ] ] for k , v in sorted ( conf [ 'config' ] . items ( ) ) : args . append ( '-backend-config="%s=%s"' % ( k , v ) ) return args
def _setup_direct_converter ( self , converter ) : '''Given a converter , set up the direct _ output routes for conversions , which is used for transcoding between similar datatypes .'''
inputs = ( converter . direct_inputs if hasattr ( converter , 'direct_inputs' ) else converter . inputs ) for in_ in inputs : for out in converter . direct_outputs : self . direct_converters [ ( in_ , out ) ] = converter
def value ( self ) : '''The final value , if it has arrived : raises : AttributeError , if not yet complete : raises : an exception if the Future was : meth : ` abort ` \ ed'''
if not self . _done . is_set ( ) : raise AttributeError ( "value" ) if self . _failure : raise self . _failure [ 0 ] , self . _failure [ 1 ] , self . _failure [ 2 ] return self . _value
def fatal ( msg , * args , ** kwargs ) : """Print a red ` msg ` to STDERR and exit . To be used in a context of an exception , also prints out the exception . The message is formatted with ` args ` & ` kwargs ` ."""
exc_str = format_exc ( ) if exc_str . strip ( ) != 'NoneType: None' : logger . info ( '{}' , format_exc ( ) ) fatal_noexc ( msg , * args , ** kwargs )
def _dpi ( self , resolution_tag ) : """Return the dpi value calculated for * resolution _ tag * , which can be either TIFF _ TAG . X _ RESOLUTION or TIFF _ TAG . Y _ RESOLUTION . The calculation is based on the values of both that tag and the TIFF _ TAG . RESOLUTION _ UNIT tag in this parser ' s | _ IfdEntri...
ifd_entries = self . _ifd_entries if resolution_tag not in ifd_entries : return 72 # resolution unit defaults to inches ( 2) resolution_unit = ( ifd_entries [ TIFF_TAG . RESOLUTION_UNIT ] if TIFF_TAG . RESOLUTION_UNIT in ifd_entries else 2 ) if resolution_unit == 1 : # aspect ratio only return 72 # resolution _...
def initialize ( self , name , reuse = False ) : """Create an empty Sorting Hat registry . This method creates a new database including the schema of Sorting Hat . Any attempt to create a new registry over an existing instance will produce an error , except if reuse = True . In that case , the database will...
user = self . _kwargs [ 'user' ] password = self . _kwargs [ 'password' ] host = self . _kwargs [ 'host' ] port = self . _kwargs [ 'port' ] if '-' in name : self . error ( "dabase name '%s' cannot contain '-' characters" % name ) return CODE_VALUE_ERROR try : Database . create ( user , password , name , hos...
def right_axis_label ( self , label , position = None , rotation = - 60 , offset = 0.08 , ** kwargs ) : """Sets the label on the right axis . Parameters label : String The axis label position : 3 - Tuple of floats , None The position of the text label rotation : float , - 60 The angle of rotation of t...
if not position : position = ( 2. / 5 + offset , 3. / 5 , 0 ) self . _labels [ "right" ] = ( label , position , rotation , kwargs )
def _buildTemplates ( self ) : """do all the things necessary to build the viz should be adapted to work for single - file viz , or multi - files etc . : param output _ path : : return :"""
# in this case we only have one contents = self . _renderTemplate ( self . template_name , extraContext = None ) # the main url used for opening viz f = self . main_file_name main_url = self . _save2File ( contents , f , self . output_path ) return main_url