signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def can_unconsign ( self ) : """bool : : const : ` True ` if : attr : ` address ` can unconsign the edition : attr : ` edition _ number ` of : attr : ` piece _ address ` else : const : ` False ` . If the last transaction is a consignment of the edition to the user ."""
chain = BlockchainSpider . chain ( self . _tree , self . edition_number ) if len ( chain ) == 0 : self . reason = 'Master edition not yet registered' return False chain = BlockchainSpider . strip_loan ( chain ) action = chain [ - 1 ] [ 'action' ] piece_address = chain [ - 1 ] [ 'piece_address' ] edition_number ...
def create_presentation ( self ) : """Create the presentation . The audio track is mixed with the slides . The resulting file is saved as self . output DownloadError is raised if some resources cannot be fetched . ConversionError is raised if the final video cannot be created ."""
# Avoid wasting time and bandwidth if we known that conversion will fail . if not self . overwrite and os . path . exists ( self . output ) : raise ConversionError ( "File %s already exist and --overwrite not specified" % self . output ) video = self . download_video ( ) raw_slides = self . download_slides ( ) # ff...
def setDigitalMinimum ( self , edfsignal , digital_minimum ) : """Sets the minimum digital value of signal edfsignal . Usually , the value - 32768 is used for EDF + and - 8388608 for BDF + . Usually this will be ( - ( digital _ maximum + 1 ) ) . Parameters edfsignal : int signal number digital _ minimum :...
if ( edfsignal < 0 or edfsignal > self . n_channels ) : raise ChannelDoesNotExist ( edfsignal ) self . channels [ edfsignal ] [ 'digital_min' ] = digital_minimum self . update_header ( )
def spin1z_from_mass1_mass2_chi_eff_chi_a ( mass1 , mass2 , chi_eff , chi_a ) : """Returns spin1z ."""
return ( mass1 + mass2 ) / ( 2.0 * mass1 ) * ( chi_eff - chi_a )
def load_file ( self , filepath ) : """This function opens any type of a readable file and decompose the file object into a list , for each line , of lists containing splitted line strings using space as a spacer . Parameters filepath : : class : ` str ` The full path or a relative path to any type of fil...
self . file_path = filepath _ , self . file_type = os . path . splitext ( filepath ) _ , self . file_name = os . path . split ( filepath ) with open ( filepath ) as ffile : self . file_content = ffile . readlines ( ) return ( self . _load_funcs [ self . file_type ] ( ) )
def is_in_intervall ( value , min_value , max_value , name = 'variable' ) : """Raise an exception if value is not in an interval . Parameters value : orderable min _ value : orderable max _ value : orderable name : str Name of the variable to print in exception ."""
if not ( min_value <= value <= max_value ) : raise ValueError ( '{}={} is not in [{}, {}]' . format ( name , value , min_value , max_value ) )
def dashed_line ( self , x1 , y1 , x2 , y2 , dash_length = 1 , space_length = 1 ) : """Draw a dashed line . Same interface as line ( ) except : - dash _ length : Length of the dash - space _ length : Length of the space between dashes"""
self . _set_dash ( dash_length , space_length ) self . line ( x1 , y1 , x2 , y2 ) self . _set_dash ( )
def index_name ( self ) : """Get Elasticsearch index name associated to the campaign"""
fmt = self . campaign . export . elasticsearch . index_name fields = dict ( date = self . report [ 'date' ] ) return fmt . format ( ** fields ) . lower ( )
def _get_csv_from_section ( sections , crumbs , csvs ) : """Get table name , variable name , and column values from paleo metadata : param dict sections : Metadata : param str crumbs : Crumbs : param dict csvs : Csv : return dict sections : Metadata : return dict csvs : Csv"""
logger_csvs . info ( "enter get_csv_from_section: {}" . format ( crumbs ) ) _idx = 0 try : # Process the tables in section for _name , _section in sections . items ( ) : # Process each entry sub - table below if they exist if "measurementTable" in _section : sections [ _name ] [ "measurementTabl...
async def pre_handle ( self , request : Request , responder : 'Responder' ) : """Start typing right when the message is received ."""
responder . send ( [ lyr . Typing ( ) ] ) await responder . flush ( request ) responder . clear ( ) await self . next ( request , responder )
def send_OS_X_notify ( title , content , img_path ) : '''发送Mac桌面通知'''
try : from Foundation import ( NSDate , NSUserNotification , NSUserNotificationCenter ) from AppKit import NSImage import objc except ImportError : logger . info ( 'failed to init OSX notify!' ) return def swizzle ( cls , SEL , func ) : old_IMP = getattr ( cls , SEL , None ) if old_IMP is No...
def transition_to_execute ( self ) : """Transition to execute"""
assert self . state in [ AQStateMachineStates . add ] self . state = AQStateMachineStates . execute
def state_not_literal ( self , value ) : """Parse not literal ."""
value = negate = chr ( value ) while value == negate : value = choice ( self . literals ) yield value
def data ( self ) : """Data representation of the datasource sent to the frontend"""
order_by_choices = [ ] # self . column _ names return sorted column _ names for s in self . column_names : s = str ( s or '' ) order_by_choices . append ( ( json . dumps ( [ s , True ] ) , s + ' [asc]' ) ) order_by_choices . append ( ( json . dumps ( [ s , False ] ) , s + ' [desc]' ) ) verbose_map = { '__ti...
def helper_list ( access_token , oid , path ) : '''Helper Function to list a URL path . Args : access _ token ( str ) : A valid Azure authentication token . oid ( str ) : An OID . path ( str ) : A URL Path . Returns : HTTP response . JSON body .'''
if oid != "" : path = '' . join ( [ path , "('" , oid , "')" ] ) endpoint = '' . join ( [ ams_rest_endpoint , path ] ) return do_ams_get ( endpoint , path , access_token )
def parse_rst_params ( doc ) : """Parse a reStructuredText docstring and return a dictionary with parameter names and descriptions . > > > doc = ' ' ' . . . : param foo : foo parameter . . . foo parameter . . . : param bar : bar parameter . . . : param baz : baz parameter . . . baz parameter . . . b...
param_re = re . compile ( r"""^([ \t]*):param\ (?P<param>\w+):\ (?P<body>.*\n(\1[ \t]+\w.*\n)*)""" , re . MULTILINE | re . VERBOSE ) params = { } for match in param_re . finditer ( doc ) : parts = match . groupdict ( ) body_lines = parts [ 'body' ] ....
def __get_ssh_credentials ( vm_ ) : '''Get configured SSH credentials .'''
ssh_user = config . get_cloud_config_value ( 'ssh_username' , vm_ , __opts__ , default = os . getenv ( 'USER' ) ) ssh_key = config . get_cloud_config_value ( 'ssh_keyfile' , vm_ , __opts__ , default = os . path . expanduser ( '~/.ssh/google_compute_engine' ) ) return ssh_user , ssh_key
def get_bindings_for_keys ( self , keys ) : """Return a list of key bindings that can handle this key . ( This return also inactive bindings , so the ` filter ` still has to be called , for checking it . ) : param keys : tuple of keys ."""
def get ( ) : result = [ ] for b in self . key_bindings : if len ( keys ) == len ( b . keys ) : match = True any_count = 0 for i , j in zip ( b . keys , keys ) : if i != j and i != Keys . Any : match = False brea...
def almost_equals ( self , other ) : """Compare transforms for approximate equality . : param other : Transform being compared . : type other : Affine : return : True if absolute difference between each element of each respective tranform matrix < ` ` EPSILON ` ` ."""
for i in ( 0 , 1 , 2 , 3 , 4 , 5 ) : if abs ( self [ i ] - other [ i ] ) >= EPSILON : return False return True
def system_methodHelp ( self , method_name : str ) -> str : """将docstring返回 . system . methodHelp ( ' add ' ) = > " Adds two integers together " Return : ( str ) : - 函数的帮助文本"""
method = None if method_name in self . funcs : method = self . funcs [ method_name ] elif self . instance is not None : try : method = resolve_dotted_attribute ( self . instance , method_name , self . allow_dotted_names ) except AttributeError : pass if method is None : return "" else : ...
def plot ( data , output_dir_path = '.' , width = 10 , height = 8 ) : """Create two plots : 1 ) loss 2 ) accuracy . Args : data : Panda dataframe in * the * format ."""
if not isinstance ( data , pd . DataFrame ) : data = pd . DataFrame ( data ) plot_accuracy ( data , output_dir_path = output_dir_path , width = width , height = height ) plot_loss ( data , output_dir_path , width = width , height = height )
def clean_file ( c_source , virtualenv_dirname ) : """Strip trailing whitespace and clean up " local " names in C source . These source files are autogenerated from the ` ` cython ` ` CLI . Args : c _ source ( str ) : Path to a ` ` . c ` ` source file . virtualenv _ dirname ( str ) : The name of the ` ` vir...
with open ( c_source , "r" ) as file_obj : contents = file_obj . read ( ) . rstrip ( ) # Replace the path to the Cython include files . py_version = "python{}.{}" . format ( * sys . version_info [ : 2 ] ) lib_path = os . path . join ( ".nox" , virtualenv_dirname , "lib" , py_version , "site-packages" , "" ) content...
def contour ( c , subsample = 1 , size = 10 , color = 'g' ) : """Draws a contour on the current plot by scattering points . Parameters c : : obj : ` autolab _ core . Contour ` contour to draw subsample : int subsample rate for boundary pixels size : int size of scattered points color : : obj : ` str...
if not isinstance ( c , Contour ) : raise ValueError ( 'Input must be of type Contour' ) for i in range ( c . num_pixels ) [ 0 : : subsample ] : plt . scatter ( c . boundary_pixels [ i , 1 ] , c . boundary_pixels [ i , 0 ] , s = size , c = color )
def get_nameserver_detail_output_show_nameserver_nameserver_xlatedomain ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) get_nameserver_detail = ET . Element ( "get_nameserver_detail" ) config = get_nameserver_detail output = ET . SubElement ( get_nameserver_detail , "output" ) show_nameserver = ET . SubElement ( output , "show-nameserver" ) nameserver_portid_key = ET . SubElement ( show_nameserver , "n...
def push_broks ( self , broks ) : """Send a HTTP request to the satellite ( POST / push _ broks ) Send broks to the satellite : param broks : Brok list to send : type broks : list : return : True on success , False on failure : rtype : bool"""
logger . debug ( "[%s] Pushing %d broks" , self . name , len ( broks ) ) return self . con . post ( '_push_broks' , { 'broks' : broks } , wait = True )
def search ( lines , pattern ) : """return all lines that match the pattern # TODO : we need an example : param lines : : param pattern : : return :"""
p = pattern . replace ( "*" , ".*" ) test = re . compile ( p ) result = [ ] for l in lines : if test . search ( l ) : result . append ( l ) return result
def _parse_shard_list ( shard_list , current_shard_list ) : """parse shard list : param shard _ list : format like : 1,5-10,20 : param current _ shard _ list : current shard list : return :"""
if not shard_list : return current_shard_list target_shards = [ ] for n in shard_list . split ( "," ) : n = n . strip ( ) if n . isdigit ( ) and n in current_shard_list : target_shards . append ( n ) elif n : rng = n . split ( "-" ) if len ( rng ) == 2 : s = rng [ 0 ]...
def FileHacks ( self ) : """Hacks to make the filesystem look normal ."""
if sys . platform == "win32" : import win32api # pylint : disable = g - import - not - at - top # Make the filesystem look like the topmost level are the drive letters . if self . path == "/" : self . files = win32api . GetLogicalDriveStrings ( ) . split ( "\x00" ) # Remove empty strings...
def split_by_fname_file ( self , fname : PathOrStr , path : PathOrStr = None ) -> 'ItemLists' : "Split the data by using the names in ` fname ` for the validation set . ` path ` will override ` self . path ` ."
path = Path ( ifnone ( path , self . path ) ) valid_names = loadtxt_str ( path / fname ) return self . split_by_files ( valid_names )
def find_visible_birthdays ( request , data ) : """Return only the birthdays visible to current user ."""
if request . user and ( request . user . is_teacher or request . user . is_eighthoffice or request . user . is_eighth_admin ) : return data data [ 'today' ] [ 'users' ] = [ u for u in data [ 'today' ] [ 'users' ] if u [ 'public' ] ] data [ 'tomorrow' ] [ 'users' ] = [ u for u in data [ 'tomorrow' ] [ 'users' ] if u...
def namedb_name_update ( cur , opcode , input_opdata , only_if = { } , constraints_ignored = [ ] ) : """Update an existing name in the database . If non - empty , only update the given fields . DO NOT CALL THIS METHOD DIRECTLY ."""
opdata = copy . deepcopy ( input_opdata ) namedb_name_fields_check ( opdata ) mutate_fields = op_get_mutate_fields ( opcode ) if opcode not in OPCODE_CREATION_OPS : assert 'name' not in mutate_fields , "BUG: 'name' listed as a mutate field for '%s'" % ( opcode ) # reduce opdata down to the given fields . . . . must...
def _setup_pailgun ( self ) : """Sets up a PailgunServer instance ."""
# Constructs and returns a runnable PantsRunner . def runner_factory ( sock , arguments , environment ) : return self . _runner_class . create ( sock , arguments , environment , self . services , self . _scheduler_service , ) # Plumb the daemon ' s lifecycle lock to the ` PailgunServer ` to safeguard teardown . # T...
def p_ex_expression ( tok ) : """ex _ expression : OP _ EXISTS cmp _ expression | cmp _ expression"""
if len ( tok ) == 3 : tok [ 0 ] = UnaryOperationRule ( tok [ 1 ] , tok [ 2 ] ) else : tok [ 0 ] = tok [ 1 ]
def ckw03 ( handle , begtim , endtim , inst , ref , avflag , segid , nrec , sclkdp , quats , avvs , nints , starts ) : """Add a type 3 segment to a C - kernel . http : / / naif . jpl . nasa . gov / pub / naif / toolkit _ docs / C / cspice / ckw03 _ c . html : param handle : Handle of an open CK file . : type ...
handle = ctypes . c_int ( handle ) begtim = ctypes . c_double ( begtim ) endtim = ctypes . c_double ( endtim ) inst = ctypes . c_int ( inst ) ref = stypes . stringToCharP ( ref ) avflag = ctypes . c_int ( avflag ) segid = stypes . stringToCharP ( segid ) sclkdp = stypes . toDoubleVector ( sclkdp ) quats = stypes . toDo...
def assert_subclass_of ( typ , allowed_types # type : Union [ Type , Tuple [ Type ] ] ) : """An inlined version of subclass _ of ( var _ types ) ( value ) without ' return True ' : it does not return anything in case of success , and raises a IsWrongType exception in case of failure . Used in validate and valid...
if not issubclass ( typ , allowed_types ) : try : # more than 1 ? allowed_types [ 1 ] raise IsWrongType ( wrong_value = typ , ref_type = allowed_types , help_msg = 'Value should be a subclass of any of {ref_type}' ) except IndexError : allowed_types = allowed_types [ 0 ] except TypeE...
def dirs ( self , pattern = None ) : """D . dirs ( ) - > List of this directory ' s subdirectories . The elements of the list are Path objects . This does not walk recursively into subdirectories ( but see : meth : ` walkdirs ` ) . With the optional ` pattern ` argument , this only lists directories whose...
return [ p for p in self . listdir ( pattern ) if p . isdir ( ) ]
def get_version ( cls , settings : Dict [ str , Any ] , path : str ) -> Optional [ str ] : """Generate the version string to be used in static URLs . ` ` settings ` ` is the ` Application . settings ` dictionary and ` ` path ` ` is the relative location of the requested asset on the filesystem . The returned ...
abs_path = cls . get_absolute_path ( settings [ "static_path" ] , path ) return cls . _get_cached_version ( abs_path )
def reshape_nd ( data_or_shape , ndim ) : """Return image array or shape with at least ndim dimensions . Prepend 1s to image shape as necessary . > > > reshape _ nd ( numpy . empty ( 0 ) , 1 ) . shape > > > reshape _ nd ( numpy . empty ( 1 ) , 2 ) . shape (1 , 1) > > > reshape _ nd ( numpy . empty ( ( 2 ,...
is_shape = isinstance ( data_or_shape , tuple ) shape = data_or_shape if is_shape else data_or_shape . shape if len ( shape ) >= ndim : return data_or_shape shape = ( 1 , ) * ( ndim - len ( shape ) ) + shape return shape if is_shape else data_or_shape . reshape ( shape )
def _check_categorical_option_type ( option_name , option_value , possible_values ) : """Check whether or not the requested option is one of the allowed values ."""
err_msg = '{0} is not a valid option for {1}. ' . format ( option_value , option_name ) err_msg += ' Expected one of: ' . format ( possible_values ) err_msg += ', ' . join ( map ( str , possible_values ) ) if option_value not in possible_values : raise ToolkitError ( err_msg )
def run_it ( ) : """Search and download torrents until the user says it so ."""
initialize ( ) parser = get_parser ( ) args = None first_parse = True while ( True ) : if first_parse is True : first_parse = False args = parser . parse_args ( ) else : print ( textwrap . dedent ( '''\ Search again like in the beginning. -- You can eith...
def render ( self , container , rerender = False ) : """Flow the flowables into the containers that have been added to this chain ."""
if rerender : container . clear ( ) if not self . _rerendering : # restore saved state on this chain ' s 1st container on this page self . _state = copy ( self . _fresh_page_state ) self . _rerendering = True try : self . done = False self . flowables . flow ( container , last_descender ...
def catalog_datacenters ( consul_url = None , token = None ) : '''Return list of available datacenters from catalog . : param consul _ url : The Consul server URL . : return : The list of available datacenters . CLI Example : . . code - block : : bash salt ' * ' consul . catalog _ datacenters'''
ret = { } if not consul_url : consul_url = _get_config ( ) if not consul_url : log . error ( 'No Consul URL found.' ) ret [ 'message' ] = 'No Consul URL found.' ret [ 'res' ] = False return ret function = 'catalog/datacenters' ret = _query ( consul_url = consul_url , function = f...
def _get_query ( self , cursor ) : '''Query tempalte for source Solr , sorts by id by default .'''
query = { 'q' : '*:*' , 'sort' : 'id desc' , 'rows' : self . _rows , 'cursorMark' : cursor } if self . _date_field : query [ 'sort' ] = "{} asc, id desc" . format ( self . _date_field ) if self . _per_shard : query [ 'distrib' ] = 'false' return query
def FromString ( cls , string_rep ) : """Create a DataStream from a string representation . The format for stream designators when encoded as strings is : [ system ] ( buffered | unbuffered | constant | input | count | output ) < integer > Args : string _ rep ( str ) : The string representation to turn into...
rep = str ( string_rep ) parts = rep . split ( ) if len ( parts ) > 3 : raise ArgumentError ( "Too many whitespace separated parts of stream designator" , input_string = string_rep ) elif len ( parts ) == 3 and parts [ 0 ] != u'system' : raise ArgumentError ( "Too many whitespace separated parts of stream desig...
def ensure_readable ( self ) : """Make sure the location exists and is readable ."""
self . ensure_exists ( ) if not self . context . is_readable ( self . directory ) : if self . context . have_superuser_privileges : msg = "The directory %s isn't readable!" raise ValueError ( msg % self ) else : raise ValueError ( compact ( """ The directory {location...
def check_actors ( self , actors ) : """Performs checks on the actors that are to be used . Raises an exception if invalid setup . : param actors : the actors to check : type actors : list"""
super ( Flow , self ) . check_actors ( actors ) actor = self . first_active if ( actor is not None ) and not base . is_source ( actor ) : raise Exception ( "First active actor is not a source: " + actor . full_name )
def acquire ( self ) : '''Returns an available instance . Returns : browser from pool , if available Raises : NoBrowsersAvailable if none available'''
with self . _lock : if len ( self . _in_use ) >= self . size : raise NoBrowsersAvailable browser = self . _fresh_browser ( ) self . _in_use . add ( browser ) return browser
def parse_map_file ( mapFNH ) : """Opens a QIIME mapping file and stores the contents in a dictionary keyed on SampleID ( default ) or a user - supplied one . The only required fields are SampleID , BarcodeSequence , LinkerPrimerSequence ( in that order ) , and Description ( which must be the final field ) . ...
m = OrderedDict ( ) map_header = None with file_handle ( mapFNH ) as mapF : for line in mapF : if line . startswith ( "#SampleID" ) : map_header = line . strip ( ) . split ( "\t" ) if line . startswith ( "#" ) or not line : continue line = line . strip ( ) . split ( "...
def init ( filename , order = 3 , tokenizer = None ) : """Initialize a brain . This brain ' s file must not already exist . Keyword arguments : order - - Order of the forward / reverse Markov chains ( integer ) tokenizer - - One of Cobe , MegaHAL ( default Cobe ) . See documentation for cobe . tokenizers fo...
log . info ( "Initializing a cobe brain: %s" % filename ) if tokenizer is None : tokenizer = "Cobe" if tokenizer not in ( "Cobe" , "MegaHAL" ) : log . info ( "Unknown tokenizer: %s. Using CobeTokenizer" , tokenizer ) tokenizer = "Cobe" graph = Graph ( sqlite3 . connect ( filename ) ) with trace_us ( "Brain....
def reqAccountSummary ( self , reqId , groupName , tags ) : """reqAccountSummary ( EClientSocketBase self , int reqId , IBString const & groupName , IBString const & tags )"""
return _swigibpy . EClientSocketBase_reqAccountSummary ( self , reqId , groupName , tags )
def create_init_path ( init_path , uid = - 1 , gid = - 1 ) : """create the init path if it does not exist"""
if not os . path . exists ( init_path ) : with open ( init_path , 'wb' ) : pass os . chown ( init_path , uid , gid ) ;
def site ( self , action ) : """Returns site query"""
query = None viewdays = 7 hostpath = self . uri + self . endpoint if action == 'siteinfo' : query = hostpath + ( '?action=query' '&meta=siteinfo|siteviews' '&siprop=general|statistics' '&list=mostviewed&pvimlimit=max' ) query += '&pvisdays=%d' % viewdays # meta = siteviews self . set_status ( 'query' , ...
def user_exists ( username , token_manager = None , app_url = defaults . APP_URL ) : """check if the user exists with the specified username"""
headers = token_manager . get_access_token_headers ( ) auth_url = environment . get_auth_url ( app_url = app_url ) url = "%s/api/v1/accounts?username=%s" % ( auth_url , username ) response = requests . get ( url , headers = headers ) if response . status_code == 404 : return False elif response . status_code == 200...
def tree_iterator ( self , visited = None , path = None ) : '''Generator function that traverse the dr tree start from this node ( self ) .'''
if visited is None : visited = set ( ) if self not in visited : if path and isinstance ( path , list ) : path . append ( self ) visited . add ( self ) yield self if not hasattr ( self , 'dterms' ) : yield for dterm in self . dterms : if hasattr ( self , dterm ) : ...
def refresh ( self , props , body ) : """the refresh method called when on demand refresh service receive a message . then call the parent actor sniff method if message is compliant on what is attended : param props : the message properties : param body : the message body : return :"""
LOGGER . debug ( "InjectorCachedComponent.refresh" ) operation = props [ 'OPERATION' ] if operation == "REFRESH" : if self . parent_actor_ref is not None : parent_actor = self . parent_actor_ref . proxy ( ) parent_actor . sniff ( ) . get ( ) else : LOGGER . error ( "InjectorCachedComponent.refre...
def get_instance ( self , payload ) : """Build an instance of ChallengeInstance : param dict payload : Payload response from the API : returns : twilio . rest . authy . v1 . service . entity . factor . challenge . ChallengeInstance : rtype : twilio . rest . authy . v1 . service . entity . factor . challenge ....
return ChallengeInstance ( self . _version , payload , service_sid = self . _solution [ 'service_sid' ] , identity = self . _solution [ 'identity' ] , factor_sid = self . _solution [ 'factor_sid' ] , )
def check_finished ( self ) : """Poll all processes and handle any finished processes ."""
changed = False for key in list ( self . processes . keys ( ) ) : # Poll process and check if it finshed process = self . processes [ key ] process . poll ( ) if process . returncode is not None : # If a process is terminated by ` stop ` or ` kill ` # we want to queue it again instead closing it as fail...
def bootstrap_options ( self ) : """The post - bootstrap options , computed from the env , args , and fully discovered Config . Re - computing options after Config has been fully expanded allows us to pick up bootstrap values ( such as backends ) from a config override file , for example . Because this can be...
return self . parse_bootstrap_options ( self . env , self . bootstrap_args , self . config )
def pretty_print_error ( err_json ) : """Pretty print Flask - Potion error messages for the user ."""
# Special case validation errors if len ( err_json ) == 1 and "validationOf" in err_json [ 0 ] : required_fields = ", " . join ( err_json [ 0 ] [ "validationOf" ] [ "required" ] ) return "Validation error. Requires properties: {}." . format ( required_fields ) # General error handling msg = "; " . join ( err . ...
def helpEvent ( self , event ) : """Displays a tool tip for the given help event . : param event | < QHelpEvent >"""
item = self . itemAt ( event . scenePos ( ) ) if ( item and item and item . toolTip ( ) ) : parent = self . parent ( ) rect = item . path ( ) . boundingRect ( ) point = event . scenePos ( ) point . setY ( item . pos ( ) . y ( ) + rect . bottom ( ) ) point = parent . mapFromScene ( point ) point ...
def run ( bam_file , data , out_dir ) : """Run coverage QC analysis"""
out = dict ( ) out_dir = utils . safe_makedir ( out_dir ) if dd . get_coverage ( data ) and dd . get_coverage ( data ) not in [ "None" ] : merged_bed_file = bedutils . clean_file ( dd . get_coverage_merged ( data ) , data , prefix = "cov-" , simple = True ) target_name = "coverage" elif dd . get_coverage_interv...
def _split_keys_v1 ( joined ) : """Split two keys out a string created by _ join _ keys _ v1."""
left , _ , right = joined . partition ( '::' ) return _decode_v1 ( left ) , _decode_v1 ( right )
def _extract_line_features ( self ) : """Parse raw log lines and convert it to a dictionary with extracted features ."""
for line in self . line_iterator : m = COMPILED_AUTH_LOG_REGEX . match ( line ) data = { 'raw' : line } if m : data . update ( { 'timestamp' : self . _to_epoch ( m . group ( 1 ) ) , 'hostname' : m . group ( 2 ) , 'program' : m . group ( 3 ) , 'processid' : m . group ( 4 ) , 'message' : m . group ( 5...
def run_command ( self , scan_id , host , cmd ) : """Run a single command via SSH and return the content of stdout or None in case of an Error . A scan error is issued in the latter case . For logging into ' host ' , the scan options ' port ' , ' username ' , ' password ' and ' ssh _ timeout ' are used ."""
ssh = paramiko . SSHClient ( ) ssh . set_missing_host_key_policy ( paramiko . AutoAddPolicy ( ) ) options = self . get_scan_options ( scan_id ) port = int ( options [ 'port' ] ) timeout = int ( options [ 'ssh_timeout' ] ) # For backward compatibility , consider the legacy mode to get # credentials as scan _ option . # ...
def parse_value ( self , querydict ) : """extract value extarct value from querydict and convert it to native missing and empty values result to None"""
value = self . field . get_value ( querydict ) if value in ( None , fields . empty , '' ) : return None return self . field . to_internal_value ( value )
def create_client ( self , addr , timeout ) : """Create client ( s ) based on addr"""
def make ( addr ) : c = Client ( addr ) c . socket . _set_recv_timeout ( timeout ) return c if ',' in addr : addrs = addr . split ( ',' ) addrs = [ a . strip ( ) for a in addrs ] return { a : make ( a ) for a in addrs } return make ( addr )
def read_release_version ( ) : """Read the release version from ` ` _ version . py ` ` ."""
import re dirname = os . path . abspath ( os . path . dirname ( __file__ ) ) try : f = open ( os . path . join ( dirname , "_version.py" ) , "rt" ) for line in f . readlines ( ) : m = re . match ( "__version__ = '([^']+)'" , line ) if m : ver = m . group ( 1 ) return ver ...
def reset ( self ) : """Clears ` nick ` and ` own _ ids ` , sets ` center ` to ` world . center ` , and then calls ` cells _ changed ( ) ` ."""
self . own_ids . clear ( ) self . nick = '' self . center = self . world . center self . cells_changed ( )
def _random_ipv4_address_from_subnet ( self , subnet , network = False ) : """Produces a random IPv4 address or network with a valid CIDR from within a given subnet . : param subnet : IPv4Network to choose from within : param network : Return a network address , and not an IP address"""
address = str ( subnet [ self . generator . random . randint ( 0 , subnet . num_addresses - 1 , ) ] , ) if network : address += '/' + str ( self . generator . random . randint ( subnet . prefixlen , subnet . max_prefixlen , ) ) address = str ( ip_network ( address , strict = False ) ) return address
def area ( self ) : """The surface area of the primitive extrusion . Calculated from polygon and height to avoid mesh creation . Returns area : float , surface area of 3D extrusion"""
# area of the sides of the extrusion area = abs ( self . primitive . height * self . primitive . polygon . length ) # area of the two caps of the extrusion area += self . primitive . polygon . area * 2 return area
def logout_service_description ( self ) : """Logout service description ."""
label = 'Logout from ' + self . name if ( self . auth_type ) : label = label + ' (' + self . auth_type + ')' return ( { "@id" : self . logout_uri , "profile" : self . profile_base + 'logout' , "label" : label } )
def inline ( self ) -> str : """Return endpoint string : return :"""
inlined = [ str ( info ) for info in ( self . server , self . port ) if info ] return ESSubscribtionEndpoint . API + " " + " " . join ( inlined )
def add_stats ( self , args ) : """Callback to add motif statistics ."""
bg_name , stats = args logger . debug ( "Stats: %s %s" , bg_name , stats ) for motif_id in stats . keys ( ) : if motif_id not in self . stats : self . stats [ motif_id ] = { } self . stats [ motif_id ] [ bg_name ] = stats [ motif_id ]
def collapse_times ( ) : """Make copies of everything , assign to global shortcuts so functions work on them , extract the times , then restore the running stacks ."""
orig_ts = f . timer_stack orig_ls = f . loop_stack copy_ts = _copy_timer_stack ( ) copy_ls = copy . deepcopy ( f . loop_stack ) f . timer_stack = copy_ts f . loop_stack = copy_ls f . refresh_shortcuts ( ) while ( len ( f . timer_stack ) > 1 ) or f . t . in_loop : _collapse_subdivision ( ) timer_pub . stop ( ) colla...
def lastAnchor ( self , block , column ) : """Find the last open bracket before the current line . Return ( block , column , char ) or ( None , None , None )"""
currentPos = - 1 currentBlock = None currentColumn = None currentChar = None for char in '({[' : try : foundBlock , foundColumn = self . findBracketBackward ( block , column , char ) except ValueError : continue else : pos = foundBlock . position ( ) + foundColumn if pos > cu...
def set_out ( self , que_out , num_followers ) : """Set the queue in output and the number of parallel tasks that follow"""
self . _que_out = que_out self . _num_followers = num_followers
def SetCacheMode ( mode ) : """Set the Configure cache mode . mode must be one of " auto " , " force " , or " cache " ."""
global cache_mode if mode == "auto" : cache_mode = AUTO elif mode == "force" : cache_mode = FORCE elif mode == "cache" : cache_mode = CACHE else : raise ValueError ( "SCons.SConf.SetCacheMode: Unknown mode " + mode )
def permission_required ( perm , login_url = None ) : """Replacement for django . contrib . auth . decorators . permission _ required that returns 403 Forbidden if the user is already logged in ."""
return user_passes_test ( lambda u : u . has_perm ( perm ) , login_url = login_url )
async def connect ( self , server_info , proto_code = None , * , use_tor = False , disable_cert_verify = False , proxy = None , short_term = False ) : '''Start connection process . Destination must be specified in a ServerInfo ( ) record ( first arg ) .'''
self . server_info = server_info if not proto_code : proto_code , * _ = server_info . protocols self . proto_code = proto_code logger . debug ( "Connecting to: %r" % server_info ) if proto_code == 'g' : # websocket # to do this , we ' ll need a websockets implementation that # operates more like a asyncio . Transpo...
def makedirs ( p ) : """A makedirs that avoids a race conditions for multiple processes attempting to create the same directory ."""
try : os . makedirs ( p , settings . FILE_UPLOAD_PERMISSIONS ) except OSError : # Perhaps someone beat us to the punch ? if not os . path . isdir ( p ) : # Nope , must be something else . . . raise
def _parse_udiff ( self ) : """Parse the diff an return data for the template ."""
lineiter = self . lines files = [ ] try : line = lineiter . next ( ) # skip first context skipfirst = True while 1 : # continue until we found the old file if not line . startswith ( '--- ' ) : line = lineiter . next ( ) continue chunks = [ ] filename , ol...
def add ( self , * args ) : """Add a path template and handler . : param name : Optional . If specified , allows reverse path lookup with : meth : ` reverse ` . : param template : A string or : class : ` ~ potpy . template . Template ` instance used to match paths against . Strings will be wrapped in a Te...
if len ( args ) > 2 : name , template = args [ : 2 ] args = args [ 2 : ] else : name = None template = args [ 0 ] args = args [ 1 : ] if isinstance ( template , tuple ) : template , type_converters = template template = Template ( template , ** type_converters ) elif not isinstance ( templat...
def namedtuple ( typename , field_names , verbose = False , rename = False ) : """Returns a new subclass of tuple with named fields . This is a patched version of collections . namedtuple from the stdlib . Unlike the latter , it accepts non - identifier strings as field names . All values are accessible throu...
if isinstance ( field_names , str ) : field_names = field_names . replace ( ',' , ' ' ) . split ( ) field_names = list ( map ( str , field_names ) ) typename = str ( typename ) for name in [ typename ] + field_names : if type ( name ) != str : raise TypeError ( 'Type names and field names must be string...
def get_email_link ( application ) : """Retrieve a link that can be emailed to the applicant ."""
# don ' t use secret _ token unless we have to if ( application . content_type . model == 'person' and application . applicant . has_usable_password ( ) ) : url = '%s/applications/%d/' % ( settings . REGISTRATION_BASE_URL , application . pk ) is_secret = False else : url = '%s/applications/%s/' % ( settings...
def fetch ( self ) : """Fetch a FieldValueInstance : returns : Fetched FieldValueInstance : rtype : twilio . rest . autopilot . v1 . assistant . field _ type . field _ value . FieldValueInstance"""
params = values . of ( { } ) payload = self . _version . fetch ( 'GET' , self . _uri , params = params , ) return FieldValueInstance ( self . _version , payload , assistant_sid = self . _solution [ 'assistant_sid' ] , field_type_sid = self . _solution [ 'field_type_sid' ] , sid = self . _solution [ 'sid' ] , )
def destroy ( self , request , pk = None , parent_lookup_organization = None ) : '''Remove a user from an organization .'''
user = get_object_or_404 ( User , pk = pk ) org = get_object_or_404 ( SeedOrganization , pk = parent_lookup_organization ) self . check_object_permissions ( request , org ) org . users . remove ( user ) return Response ( status = status . HTTP_204_NO_CONTENT )
def requestViewMenu ( self , point ) : """Emits the itemMenuRequested and viewMenuRequested signals for the given item . : param point | < QPoint >"""
vitem = self . uiGanttVIEW . itemAt ( point ) if vitem : glbl_pos = self . uiGanttVIEW . mapToGlobal ( point ) item = vitem . treeItem ( ) self . viewMenuRequested . emit ( vitem , glbl_pos ) self . itemMenuRequested . emit ( item , glbl_pos )
def _persist ( self ) -> None : """Persists the current data group"""
if self . _store : self . _store . save ( self . _key , self . _snapshot )
def get_by_start_id ( self , start_id ) : """: yield : Log entries starting from : start _ id : and ending 200 entries after . In most cases easier to call than the paginate one because there is no need to keep track of the already read entries in a specific page ."""
url = '/scans/%s/log?id=%s' % ( self . scan_id , start_id ) code , page = self . conn . send_request ( url , method = 'GET' ) if code != 200 : message = page . get ( 'message' , 'None' ) args = ( code , message ) raise APIException ( 'Failed to retrieve scan log. Received HTTP' ' response code %s. Message: ...
def get_metrics ( self , reset : bool = False ) -> Dict [ str , float ] : """We track three metrics here : 1 . dpd _ acc , which is the percentage of the time that our best output action sequence is in the set of action sequences provided by DPD . This is an easy - to - compute lower bound on denotation accur...
return { 'dpd_acc' : self . _action_sequence_accuracy . get_metric ( reset ) , 'denotation_acc' : self . _denotation_accuracy . get_metric ( reset ) , 'lf_percent' : self . _has_logical_form . get_metric ( reset ) , }
def preprocess_batch ( images_batch , preproc_func = None ) : """Creates a preprocessing graph for a batch given a function that processes a single image . : param images _ batch : A tensor for an image batch . : param preproc _ func : ( optional function ) A function that takes in a tensor and returns a pr...
if preproc_func is None : return images_batch with tf . variable_scope ( 'preprocess' ) : images_list = tf . split ( images_batch , int ( images_batch . shape [ 0 ] ) ) result_list = [ ] for img in images_list : reshaped_img = tf . reshape ( img , img . shape [ 1 : ] ) processed_img = pr...
def romanize ( text : str ) -> str : """Rendering Thai words in the Latin alphabet or " romanization " , using the Royal Thai General System of Transcription ( RTGS ) , which is the official system published by the Royal Institute of Thailand . ถอดเสียงภาษาไทยเป็นอักษรละติน : param str text : Thai text to b...
words = word_tokenize ( text ) romanized_words = [ _romanize ( word ) for word in words ] return "" . join ( romanized_words )
def dtrajs ( self ) : """get discrete trajectories"""
if not self . _estimated : self . logger . info ( "not yet parametrized, running now." ) self . parametrize ( ) return self . _chain [ - 1 ] . dtrajs
def _check_descendant ( self , item ) : """Check the boxes of item ' s descendants ."""
children = self . get_children ( item ) for iid in children : self . change_state ( iid , "checked" ) self . _check_descendant ( iid )
def get_stats ( self , start = int ( time ( ) ) , stop = int ( time ( ) ) + 10 , step = 10 ) : """Get stats of a monitored machine : param start : Time formatted as integer , from when to fetch stats ( default now ) : param stop : Time formatted as integer , until when to fetch stats ( default + 10 seconds ) ...
payload = { 'v' : 2 , 'start' : start , 'stop' : stop , 'step' : step } data = json . dumps ( payload ) req = self . request ( self . mist_client . uri + "/clouds/" + self . cloud . id + "/machines/" + self . id + "/stats" , data = data ) stats = req . get ( ) . json ( ) return stats
def mongodump ( mongo_user , mongo_password , mongo_dump_directory_path , database = None , silent = False ) : """Runs mongodump using the provided credentials on the running mongod process . WARNING : This function will delete the contents of the provided directory before it runs ."""
if path . exists ( mongo_dump_directory_path ) : # If a backup dump already exists , delete it rmtree ( mongo_dump_directory_path ) if silent : dump_command = ( "mongodump --quiet -u %s -p %s -o %s" % ( mongo_user , mongo_password , mongo_dump_directory_path ) ) else : dump_command = ( "mongodump -u %s -p %...
def forever ( self , key , value ) : """Store an item in the cache indefinitely . : param key : The cache key : type key : str : param value : The value to store : type value : mixed"""
value = self . serialize ( value ) self . _redis . set ( self . _prefix + key , value )
def khash ( * args ) : '''hash arguments . khash handles None in the same way accross runs ( which is good : ) )'''
ksum = sum ( [ hash ( arg if arg is not None else - 13371337 ) for arg in args ] ) return hash ( str ( ksum ) )
def create_translation ( self , context_id , static_ip , remote_ip , notes ) : """Creates an address translation on a tunnel context / : param int context _ id : The id - value representing the context instance . : param string static _ ip : The IP address value representing the internal side of the translati...
return self . context . createAddressTranslation ( { 'customerIpAddress' : remote_ip , 'internalIpAddress' : static_ip , 'notes' : notes } , id = context_id )
def dsc_comment ( self , comment ) : """Emit a comment into the PostScript output for the given surface . The comment is expected to conform to the PostScript Language Document Structuring Conventions ( DSC ) . Please see that manual for details on the available comments and their meanings . In particular...
cairo . cairo_ps_surface_dsc_comment ( self . _pointer , _encode_string ( comment ) ) self . _check_status ( )