signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def getComic ( number , silent = True ) : """Produces a : class : ` Comic ` object with index equal to the provided argument . Prints an error in the event of a failure ( i . e . the number is less than zero or greater than the latest comic number ) and returns an empty Comic object . Arguments : an integer...
numComics = getLatestComicNum ( ) if type ( number ) is str and number . isdigit ( ) : number = int ( number ) if number > numComics or number <= 0 : if not silent : print ( "Error: You have requested an invalid comic." ) return Comic ( - 1 ) return Comic ( number )
def _fetch_router_info ( self , router_ids = None , device_ids = None , all_routers = False ) : """Fetch router dict from the routing plugin . : param router _ ids : List of router _ ids of routers to fetch : param device _ ids : List of device _ ids whose routers to fetch : param all _ routers : If True fetc...
try : if all_routers : LOG . debug ( 'Fetching all routers' ) router_ids = self . plugin_rpc . get_router_ids ( self . context ) routers = self . _fetch_router_chunk_data ( router_ids ) elif router_ids : routers = self . _fetch_router_chunk_data ( router_ids ) elif device_ids...
def refund ( self , callerReference , transactionId , refundAmount = None , callerDescription = None ) : """Refund a transaction . This refunds the full amount by default unless ' refundAmount ' is specified ."""
params = { } params [ 'CallerReference' ] = callerReference params [ 'TransactionId' ] = transactionId if ( refundAmount != None ) : params [ 'RefundAmount' ] = refundAmount if ( callerDescription != None ) : params [ 'CallerDescription' ] = callerDescription response = self . make_request ( "Refund" , params )...
def combine_dicts ( dict1 , dict2 ) : """This function combines two dictionaries into a single dictionary . If a key exists in both dictionaries , the value from the second dictionary is used . Examples : > > > combine _ dicts ( { ' a ' : 100 , ' b ' : 200 } , { ' x ' : 300 , ' y ' : 200 } ) { ' a ' : 100 ,...
combined_dict = dict1 . copy ( ) combined_dict . update ( dict2 ) return combined_dict
def network_sub_create_notif ( self , tenant_id , tenant_name , cidr ) : """Network create notification ."""
if not self . fw_init : return self . network_create_notif ( tenant_id , tenant_name , cidr )
def stylize ( text , styles , reset = True ) : """conveniently styles your text as and resets ANSI codes at its end ."""
terminator = attr ( "reset" ) if reset else "" return "{}{}{}" . format ( "" . join ( styles ) , text , terminator )
def get_gradebook_column_query_session_for_gradebook ( self , gradebook_id , proxy ) : """Gets the ` ` OsidSession ` ` associated with the gradebook column query service for the given gradebook . arg : gradebook _ id ( osid . id . Id ) : the ` ` Id ` ` of the gradebook arg : proxy ( osid . proxy . Proxy ) : a p...
if not self . supports_gradebook_column_query ( ) : raise errors . Unimplemented ( ) # Also include check to see if the catalog Id is found otherwise raise errors . NotFound # pylint : disable = no - member return sessions . GradebookColumnQuerySession ( gradebook_id , proxy , self . _runtime )
def _put ( self , url , data = { } ) : """Wrapper around request . put ( ) to use the API prefix . Returns a JSON response ."""
r = requests . put ( self . _api_prefix + url , data = json . dumps ( data ) , headers = self . headers , auth = self . auth , allow_redirects = False , ) return self . _action ( r )
def p_DEFS ( p ) : # Define bytes """asm : DEFS number _ list"""
if len ( p [ 2 ] ) > 2 : error ( p . lineno ( 1 ) , "too many arguments for DEFS" ) if len ( p [ 2 ] ) < 2 : num = Expr . makenode ( Container ( 0 , p . lineno ( 1 ) ) ) # Defaults to 0 p [ 2 ] = p [ 2 ] + ( num , ) p [ 0 ] = Asm ( p . lineno ( 1 ) , 'DEFS' , p [ 2 ] )
def build_views ( self ) : """Bake out specified buildable views ."""
# Then loop through and run them all for view_str in self . view_list : logger . debug ( "Building %s" % view_str ) if self . verbosity > 1 : self . stdout . write ( "Building %s" % view_str ) view = get_callable ( view_str ) self . get_view_instance ( view ) . build_method ( )
def vars ( self ) : """return all the variables in a PS"""
# cache _ var _ params if self . _var_params is None : self . _var_params = ParameterSet ( [ var . get_parameter ( ) for var in self . _vars ] ) return self . _var_params
def toVerticesAndPolygons ( self ) : """Return list of vertices , polygons ( cells ) , and the total number of vertex indices in the polygon connectivity list ( count ) ."""
offset = 1.234567890 verts = [ ] polys = [ ] vertexIndexMap = { } count = 0 for poly in self . polygons : verts = poly . vertices cell = [ ] for v in poly . vertices : p = v . pos # use string key to remove degeneracy associated # very close points . The format % . 10e ensures that ...
def update ( self , * sources , follow_symlinks : bool = False , maximum_depth : int = 20 ) : """Add one or more ClassFile sources to the class loader . If a given source is a directory path , it is traversed up to the maximum set depth and all files under it are added to the class loader lookup table . If ...
for source in sources : if isinstance ( source , self . klass ) : self . path_map [ source . this . name . value ] = source self . class_cache [ source . this . name . value ] = source continue # Explicit cast to str to support Path objects . source = str ( source ) if source . l...
def pack_nbt ( s ) : """Pack a native Python data structure into an NBT tag . Only the following structures and types are supported : * int * float * str * unicode * dict Additionally , arbitrary iterables are supported . Packing is not lossless . In order to avoid data loss , TAG _ Long and TAG _...
if isinstance ( s , int ) : return TAG_Long ( s ) elif isinstance ( s , float ) : return TAG_Double ( s ) elif isinstance ( s , ( str , unicode ) ) : return TAG_String ( s ) elif isinstance ( s , dict ) : tag = TAG_Compound ( ) for k , v in s : v = pack_nbt ( v ) v . name = str ( k )...
def resolve_label_conflict ( mapping , old_labels = None , new_labels = None ) : """Resolve a self - labeling conflict by creating an intermediate labeling . Args : mapping ( dict ) : A dict mapping the current variable labels to new ones . old _ labels ( set , optional , default = None ) : The keys of ma...
if old_labels is None : old_labels = set ( mapping ) if new_labels is None : new_labels = set ( itervalues ( mapping ) ) # counter will be used to generate the intermediate labels , as an easy optimization # we start the counter with a high number because often variables are labeled by # integers starting from ...
def watch ( self , flag ) : """Whether or not the Template is being watched ."""
lib . EnvSetDeftemplateWatch ( self . _env , int ( flag ) , self . _tpl )
def release ( self , job : Job , priority : int = DEFAULT_PRIORITY , delay : int = DEFAULT_DELAY ) -> None : """Releases a reserved job . : param job : The job to release . : param priority : An integer between 0 and 4,294,967,295 where 0 is the most urgent . : param delay : The number of seconds to delay t...
self . _send_cmd ( b'release %d %d %d' % ( job . id , priority , delay ) , b'RELEASED' )
def set_token ( self , token ) : """Validate and set token : param token : the token ( dict ) to set"""
if not token : self . token = None return expected_keys = [ 'token_type' , 'refresh_token' , 'access_token' , 'scope' , 'expires_in' , 'expires_at' ] if not isinstance ( token , dict ) or not set ( token ) >= set ( expected_keys ) : raise InvalidUsage ( "Expected a token dictionary containing the following ...
def get_config ( path = os . getcwd ( ) ) : """Search for settings file in root of project and its parents ."""
config = default tries = 0 current_dir = path while current_dir and tries < MAX_CONFIG_SEARCH_DEPTH : potential_path = os . path . join ( current_dir , ".fonduer-config.yaml" ) if os . path . exists ( potential_path ) : with open ( potential_path , "r" ) as f : config = _merge ( config , yam...
def parse_segdict_key ( self , key ) : """Return ifo and name from the segdict key ."""
splt = key . split ( ':' ) if len ( splt ) == 2 : return splt [ 0 ] , splt [ 1 ] else : err_msg = "Key should be of the format 'ifo:name', got %s." % ( key , ) raise ValueError ( err_msg )
def StreamMetrics ( self , request_iterator , context ) : """Dispatches metrics streamed by collector"""
LOG . debug ( "StreamMetrics called" ) # set up arguments collect_args = ( next ( request_iterator ) ) max_metrics_buffer = 0 max_collect_duration = 0 cfg = Metric ( pb = collect_args . Metrics_Arg . metrics [ 0 ] ) try : max_metrics_buffer = int ( cfg . config [ "max-metrics-buffer" ] ) except Exception as ex : ...
def fix_subparsers ( subparsers ) : """Workaround for bug in Python 3 . See more info at : https : / / bugs . python . org / issue16308 https : / / github . com / iterative / dvc / issues / 769 Args : subparsers : subparsers to fix ."""
from dvc . utils . compat import is_py3 if is_py3 : # pragma : no cover subparsers . required = True subparsers . dest = "cmd"
def absent ( name , bridge = None ) : '''Ensures that the named port exists on bridge , eventually deletes it . If bridge is not set , port is removed from whatever bridge contains it . Args : name : The name of the port . bridge : The name of the bridge .'''
ret = { 'name' : name , 'changes' : { } , 'result' : False , 'comment' : '' } bridge_exists = False if bridge : bridge_exists = __salt__ [ 'openvswitch.bridge_exists' ] ( bridge ) if bridge_exists : port_list = __salt__ [ 'openvswitch.port_list' ] ( bridge ) else : port_list = ( ) else : ...
def search ( self , input_statement , ** additional_parameters ) : """Search for close matches to the input . Confidence scores for subsequent results will order of increasing value . : param input _ statement : A statement . : type input _ statement : chatterbot . conversation . Statement : param * * addit...
self . chatbot . logger . info ( 'Beginning search for close text match' ) input_search_text = input_statement . search_text if not input_statement . search_text : self . chatbot . logger . warn ( 'No value for search_text was available on the provided input' ) input_search_text = self . chatbot . storage . tag...
async def withdraw ( self , * args , ** kwargs ) : """Withdraw funds to user wallet Accepts : - coinid [ string ] ( blockchain id ( example : BTCTEST , LTCTEST ) ) - address [ string ] withdrawal address ( in hex for tokens ) - amount [ int ] withdrawal amount multiplied by decimals _ k ( 10 * * 8) Return...
try : super ( ) . reload_connections ( ) except Exception as e : return WithdrawValidator . error_500 ( str ( e ) ) coinid = kwargs . get ( "coinid" ) address = kwargs . get ( "address" ) amount = int ( kwargs . get ( "amount" ) ) txid = None connection = self . connections [ coinid ] if coinid in [ 'BTCTEST' ,...
def process_IN_MOVE_SELF ( self , raw_event ) : """STATUS : the following bug has been fixed in recent kernels ( FIXME : which version ? ) . Now it raises IN _ DELETE _ SELF instead . Old kernels were bugged , this event raised when the watched item were moved , so we had to update its path , but under some c...
watch_ = self . _watch_manager . get_watch ( raw_event . wd ) src_path = watch_ . path mv_ = self . _mv . get ( src_path ) if mv_ : dest_path = mv_ [ 0 ] watch_ . path = dest_path # add the separator to the source path to avoid overlapping # path issue when testing with startswith ( ) src_path += os...
def enqueue ( self , function , name = None , times = 1 , data = None ) : """Appends a function to the queue for execution . The times argument specifies the number of attempts if the function raises an exception . If the name argument is None it defaults to whatever id ( function ) returns . : type functio...
self . _check_if_ready ( ) return self . main_loop . enqueue ( function , name , times , data )
def example_point ( self ) : """Returns any single point guaranteed to be in the domain , but no other guarantees ; useful for testing purposes . This is given as a size 1 ` ` np . array ` ` of type ` ` dtype ` ` . : type : ` ` np . ndarray ` `"""
if not np . isinf ( self . min ) : return np . array ( [ self . min ] , dtype = self . dtype ) if not np . isinf ( self . max ) : return np . array ( [ self . max ] , dtype = self . dtype ) else : return np . array ( [ 0 ] , dtype = self . dtype )
def format_page ( text ) : """Format the text for output adding ASCII frame around the text . Args : text ( str ) : Text that needs to be formatted . Returns : str : Formatted string ."""
width = max ( map ( len , text . splitlines ( ) ) ) page = "+-" + "-" * width + "-+\n" for line in text . splitlines ( ) : page += "| " + line . ljust ( width ) + " |\n" page += "+-" + "-" * width + "-+\n" return page
def human_to_seconds ( string ) : """Convert internal string like 1M , 1Y3M , 3W to seconds . : type string : str : param string : Interval string like 1M , 1W , 1M3W4h2s . . . ( s = > seconds , m = > minutes , h = > hours , D = > days , W = > weeks , M = > months , Y = > Years ) . : rtype : int : return ...
interval_exc = "Bad interval format for {0}" . format ( string ) interval_regex = re . compile ( "^(?P<value>[0-9]+)(?P<unit>[{0}])" . format ( "" . join ( interval_dict . keys ( ) ) ) ) seconds = 0 if string is None : return None while string : match = interval_regex . match ( string ) if match : v...
def _move_cursor_to_column ( self , column ) : """Moves the cursor to the specified column , if possible ."""
last_col = len ( self . _cursor . block ( ) . text ( ) ) self . _cursor . movePosition ( self . _cursor . EndOfBlock ) to_insert = '' for i in range ( column - last_col ) : to_insert += ' ' if to_insert : self . _cursor . insertText ( to_insert ) self . _cursor . movePosition ( self . _cursor . StartOfBlock ) s...
def _GetDecodedStreamSize ( self ) : """Retrieves the decoded stream size . Returns : int : decoded stream size ."""
self . _file_object . seek ( 0 , os . SEEK_SET ) self . _decoder = self . _GetDecoder ( ) self . _decoded_data = b'' encoded_data_offset = 0 encoded_data_size = self . _file_object . get_size ( ) decoded_stream_size = 0 while encoded_data_offset < encoded_data_size : read_count = self . _ReadEncodedData ( self . _E...
def add ( self , fact ) : """Create a VALID token and send it to all children ."""
token = Token . valid ( fact ) MATCHER . debug ( "<BusNode> added %r" , token ) for child in self . children : child . callback ( token )
def random_letters ( count ) : """Get a series of pseudo - random letters with no repeats ."""
rv = random . choice ( string . ascii_uppercase ) while len ( rv ) < count : l = random . choice ( string . ascii_uppercase ) if not l in rv : rv += l return rv
def get ( self , varname , idx = 0 , units = None ) : '''get a variable value'''
if not varname in self . mapping . vars : raise fgFDMError ( 'Unknown variable %s' % varname ) if idx >= self . mapping . vars [ varname ] . arraylength : raise fgFDMError ( 'index of %s beyond end of array idx=%u arraylength=%u' % ( varname , idx , self . mapping . vars [ varname ] . arraylength ) ) value = se...
def create_sockets ( self ) : """create zmq sockets"""
ports = self . ports context = zmq . Context ( ) poller = zmq . Poller ( ) # Socket to handle init data rep = context . socket ( zmq . REP ) # this was inconsequent : here REQ is for the client , we reply with REP . # PULL and PUB is seen from here , not from the client . # Is now renamed to PUSH and SUB : everything i...
def fit ( self , method = None , ** kwargs ) : """Fits a model Parameters method : str A fitting method ( e . g ' MLE ' ) . Defaults to model specific default method . Returns None ( stores fit information )"""
cov_matrix = kwargs . get ( 'cov_matrix' , None ) iterations = kwargs . get ( 'iterations' , 1000 ) nsims = kwargs . get ( 'nsims' , 10000 ) optimizer = kwargs . get ( 'optimizer' , 'RMSProp' ) batch_size = kwargs . get ( 'batch_size' , 12 ) mini_batch = kwargs . get ( 'mini_batch' , None ) map_start = kwargs . get ( '...
def _convert_bases_to_mixins ( self , mcs_args : McsArgs ) : """For each base class in bases that the _ ModelRegistry knows about , create a replacement class containing the methods and attributes from the base class : - the mixin should only extend object ( not db . Model ) - if any of the attributes are M...
def _mixin_name ( name ) : return f'{name}_FSQLAConvertedMixin' new_base_names = set ( ) new_bases = [ ] for b in reversed ( mcs_args . bases ) : if b . __name__ not in self . _registry : if b not in new_bases : new_bases . append ( b ) continue _ , base_name , base_bases , base_...
def get_attr_text ( self ) : """Get html attr text to render in template"""
return ' ' . join ( [ '{}="{}"' . format ( key , value ) for key , value in self . attr . items ( ) ] )
def create_widget ( self ) : """Create the underlying widget ."""
d = self . declaration self . widget = CalendarView ( self . get_context ( ) , None , d . style or "@attr/calendarViewStyle" )
def write_spmatrix_to_sparse_tensor ( file , array , labels = None ) : """Writes a scipy sparse matrix to a sparse tensor"""
if not issparse ( array ) : raise TypeError ( "Array must be sparse" ) # Validate shape of array and labels , resolve array and label types if not len ( array . shape ) == 2 : raise ValueError ( "Array must be a Matrix" ) if labels is not None : if not len ( labels . shape ) == 1 : raise ValueError ...
def respond_static ( self , environ ) : """Serves a static file when Django isn ' t being used ."""
path = os . path . normpath ( environ [ "PATH_INFO" ] ) if path == "/" : content = self . index ( ) content_type = "text/html" else : path = os . path . join ( os . path . dirname ( __file__ ) , path . lstrip ( "/" ) ) try : with open ( path , "r" ) as f : content = f . read ( ) ...
def df ( self , src ) : '''Perform ` ` df ` ` on a path'''
return self . _getStdOutCmd ( [ self . _hadoop_cmd , 'fs' , '-df' , self . _full_hdfs_path ( src ) ] , True )
def applied ( ) : """Command for showing all upgrades already applied ."""
upgrader = InvenioUpgrader ( ) logger = upgrader . get_logger ( ) try : upgrades = upgrader . get_history ( ) if not upgrades : logger . info ( "No upgrades have been applied." ) return logger . info ( "Following upgrade(s) have been applied:" ) for u_id , applied in upgrades : l...
def getGroundResolution ( self , latitude , level ) : '''returns the ground resolution for based on latitude and zoom level .'''
latitude = self . clipValue ( latitude , self . min_lat , self . max_lat ) ; mapSize = self . getMapDimensionsByZoomLevel ( level ) return math . cos ( latitude * math . pi / 180 ) * 2 * math . pi * self . earth_radius / mapSize
def start ( self , aug = 'EventLoopThread' ) : """Ensure the background loop is running . This method is safe to call multiple times . If the loop is already running , it will not do anything ."""
if self . stopping : raise LoopStoppingError ( "Cannot perform action while loop is stopping." ) if not self . loop : self . _logger . debug ( "Starting event loop" ) self . loop = asyncio . new_event_loop ( ) self . thread = threading . Thread ( target = self . _loop_thread_main , name = aug , daemon =...
def get_encounter ( self , ehr_username , patient_id ) : """invokes TouchWorksMagicConstants . ACTION _ GET _ ENCOUNTER action : return : JSON response"""
magic = self . _magic_json ( action = TouchWorksMagicConstants . ACTION_GET_ENCOUNTER , app_name = self . _app_name , user_id = ehr_username , token = self . _token . token , patient_id = patient_id ) response = self . _http_request ( TouchWorksEndPoints . MAGIC_JSON , data = magic ) result = self . _get_results_or_rai...
def update_value ( self , key , value ) : """Parse key value pairs to update their values"""
if key == "Status" : self . _inhibited = value != "Enabled" elif key == "Color temperature" : self . _temperature = int ( value . rstrip ( "K" ) , 10 ) elif key == "Period" : self . _period = value elif key == "Brightness" : self . _brightness = value elif key == "Location" : location = [ ] for ...
def __vCmdConnectCameras ( self , args ) : '''ToDo : Validate the argument as a valid port'''
if len ( args ) >= 1 : self . WirelessPort = args [ 0 ] print ( "Connecting to Cameras on %s" % self . WirelessPort ) self . __vRegisterCameras ( )
def _proxy ( self ) : """Generate an instance context for the instance , the context is capable of performing various actions . All instance actions are proxied to the context : returns : CountryContext for this CountryInstance : rtype : twilio . rest . pricing . v2 . voice . country . CountryContext"""
if self . _context is None : self . _context = CountryContext ( self . _version , iso_country = self . _solution [ 'iso_country' ] , ) return self . _context
def re_flags ( flags , custom = ReFlags ) : """Parse regexp flag string . Parameters flags : ` str ` Flag string . custom : ` IntEnum ` , optional Custom flag enum ( default : None ) . Returns ( ` int ` , ` int ` ) ( flags for ` re . compile ` , custom flags ) Raises ValueError"""
re_ , custom_ = 0 , 0 for flag in flags . upper ( ) : try : re_ |= getattr ( re , flag ) except AttributeError : if custom is not None : try : custom_ |= getattr ( custom , flag ) except AttributeError : raise ValueError ( 'Invalid custom f...
def help ( self , args = None , userlevel = 9 ) : """Make a string from the option list"""
out = [ main . __file__ + "\n" ] if args is not None : parsed = self . parse ( args , ignore_help = True ) else : parsed = self . _default_dict ( ) for thing in self . options : if type ( thing ) == str : out . append ( " " + thing ) elif thing [ 0 ] <= userlevel : out . append ( " ...
def _convert_to_dict ( self , setting ) : '''Converts a settings file into a dictionary , ignoring python defaults @ param setting : A loaded setting module'''
the_dict = { } set = dir ( setting ) for key in set : if key in self . ignore : continue value = getattr ( setting , key ) the_dict [ key ] = value return the_dict
def get_migrations_applied ( engine , connection ) : """Get list of migrations already applied"""
try : # Get cursor based on engine if engine == 'postgresql' : cursor = connection . cursor ( cursor_factory = psycopg2 . extras . RealDictCursor ) else : cursor = connection . cursor ( ) sql = "SELECT id, name, date FROM migrations_applied" cursor . execute ( sql ) rows = cursor . f...
def dist_grid ( grid , source , target = None ) : """Distances in a grid by BFS : param grid : matrix with 4 - neighborhood : param ( int , int ) source : pair of row , column indices : param ( int , int ) target : exploration stops if target is reached : complexity : linear in grid size"""
rows = len ( grid ) cols = len ( grid [ 0 ] ) dirs = [ ( 0 , + 1 , '>' ) , ( 0 , - 1 , '<' ) , ( + 1 , 0 , 'v' ) , ( - 1 , 0 , '^' ) ] i , j = source grid [ i ] [ j ] = 's' Q = deque ( ) Q . append ( source ) while Q : i1 , j1 = Q . popleft ( ) for di , dj , symbol in dirs : # explore all directions i2 ...
def fields ( * fields , ** keys ) : """Factory for for L { MessageType } and L { ActionType } field definitions . @ param * fields : A L { tuple } of L { Field } instances . @ param * * keys : A L { dict } mapping key names to the expected type of the field ' s values . @ return : A L { list } of L { Field ...
return list ( fields ) + [ Field . forTypes ( key , [ value ] , "" ) for key , value in keys . items ( ) ]
def close ( self , code = None , reason = '' ) : """Close the socket by sending a CLOSE frame and waiting for a response close message , unless such a message has already been received earlier ( prior to calling this function , for example ) . The onclose ( ) handler is called after the response has been rece...
self . send_close_frame ( code , reason ) frame = self . sock . recv ( ) if frame . opcode != OPCODE_CLOSE : raise ValueError ( 'expected CLOSE frame, got %s' % frame ) self . handle_control_frame ( frame )
def getItemTrace ( self ) : """Returns a node trace up to the < schema > item ."""
item , path , name , ref = self , [ ] , 'name' , 'ref' while not isinstance ( item , XMLSchema ) and not isinstance ( item , WSDLToolsAdapter ) : attr = item . getAttribute ( name ) if not attr : attr = item . getAttribute ( ref ) if not attr : path . append ( '<%s>' % ( item . tag )...
def _current_select ( ) : """Function to calculate the current " predicate " in the current context . Returns a tuple of information : ( predicate , pred _ set ) . The value pred _ set is a set ( [ ( predicate , bool ) , . . . ] ) as described in the _ reset _ conditional _ state"""
# helper to create the conjuction of predicates def and_with_possible_none ( a , b ) : assert ( a is not None or b is not None ) if a is None : return b if b is None : return a return a & b def between_otherwise_and_current ( predlist ) : lastother = None for i , p in enumerate (...
def assignrepr ( self , prefix : str = '' ) -> str : """Return a | repr | string with a prefixed assignment ."""
lines = [ '%sNode("%s", variable="%s",' % ( prefix , self . name , self . variable ) ] if self . keywords : subprefix = '%skeywords=' % ( ' ' * ( len ( prefix ) + 5 ) ) with objecttools . repr_ . preserve_strings ( True ) : with objecttools . assignrepr_tuple . always_bracketed ( False ) : l...
def unglobbed_prefix ( glob ) : '''Returns all the path components , starting from the beginning , up to the first one with any kind of glob . So for example , if glob is ' a / b / c * / d ' , return ' a / b ' .'''
parts = [ ] for part in PurePosixPath ( glob ) . parts : if contains_unescaped_stars ( part ) : break else : parts . append ( part ) return str ( PurePosixPath ( * parts ) ) if parts else ''
def property ( self , name , default = MISSING ) : """Get the value of the given property for this chip , using the default value if not found and one is provided . If not found and default is None , raise an Exception ."""
if name in self . settings : return self . settings [ name ] if default is not MISSING : return default raise ArgumentError ( "property %s not found for target '%s' and no default given" % ( name , self . name ) )
def _get_series_result_type ( result , objs = None ) : """return appropriate class of Series concat input is either dict or array - like"""
from pandas import SparseSeries , SparseDataFrame , DataFrame # concat Series with axis 1 if isinstance ( result , dict ) : # concat Series with axis 1 if all ( isinstance ( c , ( SparseSeries , SparseDataFrame ) ) for c in result . values ( ) ) : return SparseDataFrame else : return DataFrame #...
def add_feature ( self , kind , component = None , ** kwargs ) : """Add a new feature ( spot , etc ) to a component in the system . If not provided , ' feature ' ( the name of the new feature ) will be created for you and can be accessed by the ' feature ' attribute of the returned ParameterSet > > > b . ad...
func = _get_add_func ( _feature , kind ) if kwargs . get ( 'feature' , False ) is None : # then we want to apply the default below , so let ' s pop for now _ = kwargs . pop ( 'feature' ) kwargs . setdefault ( 'feature' , self . _default_label ( func . func_name , ** { 'context' : 'feature' , 'kind' : func . func_na...
def _has_ipv6 ( host ) : """Returns True if the system can bind an IPv6 address ."""
sock = None has_ipv6 = False # App Engine doesn ' t support IPV6 sockets and actually has a quota on the # number of sockets that can be used , so just early out here instead of # creating a socket needlessly . # See https : / / github . com / urllib3 / urllib3 / issues / 1446 if _appengine_environ . is_appengine_sandb...
def prevmonday ( num ) : """Return unix SECOND timestamp of " num " mondays ago"""
today = get_today ( ) lastmonday = today - timedelta ( days = today . weekday ( ) , weeks = num ) return lastmonday
def _unknown_data_size_handler ( self , cfg , irsb , irsb_addr , stmt_idx , data_addr , max_size ) : # pylint : disable = unused - argument """Return the maximum number of bytes until a potential pointer or a potential sequence is found . : param angr . analyses . CFG cfg : The control flow graph . : param pyve...
sequence_offset = None for offset in range ( 1 , max_size ) : if self . _is_sequence ( cfg , data_addr + offset , 5 ) : # a potential sequence is found sequence_offset = offset break if sequence_offset is not None : if self . project . arch . bits == 32 : max_size = min ( max_size , sequ...
def commit ( self , offset = None , limit = None , dryrun = False ) : """Start the rsync download"""
self . stream . command = "rsync -avRK --files-from={path} {source} {destination}" self . stream . append_tasks_to_streamlets ( offset = offset , limit = limit ) self . stream . commit_streamlets ( ) self . stream . run_streamlets ( ) self . stream . reset_streamlet ( )
def _max_p2t ( data , delta ) : """Finds the maximum peak - to - trough amplitude and period . Originally designed to be used to calculate magnitudes ( by taking half of the peak - to - trough amplitude as the peak amplitude ) . : type data : numpy . ndarray : param data : waveform trace to find the peak - to...
turning_points = [ ] # A list of tuples of ( amplitude , sample ) for i in range ( 1 , len ( data ) - 1 ) : if ( data [ i ] < data [ i - 1 ] and data [ i ] < data [ i + 1 ] ) or ( data [ i ] > data [ i - 1 ] and data [ i ] > data [ i + 1 ] ) : turning_points . append ( ( data [ i ] , i ) ) if len ( turning_...
def post_create_app ( cls , app , ** settings ) : """Init the extension for our chosen ORM Backend , if possible . This method will ensure that the ` ` db ` ` proxy is set to the right extension and that that extension is properly created and configured . Since it needs to call ` ` init _ app ` ` it MUST be a...
global _SELECTED_BACKEND backend = settings . pop ( 'orm_backend' , None ) backend = _discover_ideal_backend ( backend ) # did not specify a backend , bail early if backend is MISSING : return app _swap_backends_error = ( 'Cannot swap ORM backends after one is ' 'declared!' ) if backend == _PEEWEE_BACKEND : if ...
def _setup_adc ( self , flags ) : '''Initialize ADC'''
self . _intf . write ( self . _base_addr + self . MAX_1239_ADD , array ( 'B' , pack ( 'B' , flags ) ) )
def read ( self ) : r"""Coroutine that reads the next packet . ( Packets are \ 0 separated . )"""
# Read until we have a \ 0 in our buffer . while b'\0' not in self . _recv_buffer : self . _recv_buffer += yield From ( _read_chunk_from_socket ( self . socket ) ) # Split on the first separator . pos = self . _recv_buffer . index ( b'\0' ) packet = self . _recv_buffer [ : pos ] self . _recv_buffer = self . _recv_b...
def join_path ( a , * p ) : """Join path tokens together similar to osp . join , but always use ' / ' instead of possibly ' \' on windows ."""
path = a for b in p : if len ( b ) == 0 : continue if b . startswith ( '/' ) : path += b [ 1 : ] elif path == '' or path . endswith ( '/' ) : path += b else : path += '/' + b # END for each path token to add return path
def message ( self , value ) : """Setter for * * self . _ _ message * * attribute . : param value : Attribute value . : type value : unicode"""
if value is not None : assert type ( value ) in ( unicode , QString ) , "'{0}' attribute: '{1}' type is not 'unicode' or 'QString'!" . format ( "message" , value ) self . __message = value
def experiments_list ( self , limit = - 1 , offset = - 1 ) : """Retrieve list of all experiments in the data store . Parameters limit : int Limit number of results in returned object listing offset : int Set offset in list ( order as defined by object store ) Returns ObjectListing Listing of experim...
return self . experiments . list_objects ( limit = limit , offset = offset )
def _ProcessTask ( self , task ) : """Processes a task . Args : task ( Task ) : task ."""
logger . debug ( 'Started processing task: {0:s}.' . format ( task . identifier ) ) if self . _tasks_profiler : self . _tasks_profiler . Sample ( task , 'processing_started' ) self . _task = task storage_writer = self . _storage_writer . CreateTaskStorage ( task ) if self . _serializers_profiler : storage_write...
def assignFtypeToPyFile ( extension , args = ( ) , mimetype = None , showTerminal = True ) : """Connect a file extension to a python script Example : We created a python file that can open ' . da ' files The command we need to execute to open that is is : ' python MY _ PYTH _ FILE . py - o MY _ DA _ FILE . ...
# WINDOWS if os . name == 'nt' : if not isAdmin ( ) : raise Exception ( 'need to have admin rights to connect a file extension to program' ) if getattr ( sys , 'frozen' , False ) : # in case we run from an executable e . g . created with pyinstaller : py_exec = sys . executable else : ...
def activate_minion_cachedir ( minion_id , base = None ) : '''Moves a minion from the requested / cachedir into the active / cachedir . This means that Salt Cloud has verified that a requested instance properly exists , and should be expected to exist from here on out .'''
if base is None : base = __opts__ [ 'cachedir' ] fname = '{0}.p' . format ( minion_id ) src = os . path . join ( base , 'requested' , fname ) dst = os . path . join ( base , 'active' ) shutil . move ( src , dst )
def _select_list ( self , model = None , queryview = None , queryform = None , auto_condition = True , post_view = None , post_run = None , ** kwargs ) : """SelectListView wrap method : param auto _ condition : if using queryview to create condition"""
from uliweb import request , json from uliweb . utils . generic import get_sort_field import copy condition = None if queryview and auto_condition : queryview . run ( ) if hasattr ( queryview , 'get_condition' ) : condition = queryview . get_condition ( ) if 'condition' in kwargs : condition = kwarg...
async def stderr_handler ( self , line ) : """Handler for this class for stderr ."""
await self . queue . put ( self . clean_bytes ( b'[stderr] ' + line ) )
def user_getmedia ( userids = None , ** kwargs ) : '''. . versionadded : : 2016.3.0 Retrieve media according to the given parameters . . note : : This function accepts all standard usermedia . get properties : keyword argument names differ depending on your zabbix version , see here _ _ . . . _ _ : https ...
conn_args = _login ( ** kwargs ) ret = { } try : if conn_args : method = 'usermedia.get' if userids : params = { "userids" : userids } else : params = { } params = _params_extend ( params , ** kwargs ) ret = _query ( method , params , conn_args [ 'url'...
def _http_request ( url , headers = None , data = None ) : '''Make the HTTP request and return the body as python object .'''
if not headers : headers = _get_headers ( ) session = requests . session ( ) log . debug ( 'Querying %s' , url ) req = session . post ( url , headers = headers , data = salt . utils . json . dumps ( data ) ) req_body = req . json ( ) ret = _default_ret ( ) log . debug ( 'Status code: %d' , req . status_code ) log ....
def __ensure_provisioning_alarm ( table_name , table_key , gsi_name , gsi_key ) : """Ensure that provisioning alarm threshold is not exceeded : type table _ name : str : param table _ name : Name of the DynamoDB table : type table _ key : str : param table _ key : Table configuration option key name : typ...
lookback_window_start = get_gsi_option ( table_key , gsi_key , 'lookback_window_start' ) lookback_period = get_gsi_option ( table_key , gsi_key , 'lookback_period' ) consumed_read_units_percent = gsi_stats . get_consumed_read_units_percent ( table_name , gsi_name , lookback_window_start , lookback_period ) consumed_wri...
def share ( self , auth , resource , options = { } , defer = False ) : """Generates a share code for the given resource . Args : auth : < cik > resource : The identifier of the resource . options : Dictonary of options ."""
return self . _call ( 'share' , auth , [ resource , options ] , defer )
def delete ( self , path , data = None , params = None ) : """Generic DELETE with headers"""
uri = self . config . get_target ( ) + path headers = { 'Authorization' : self . config . get_access_token ( ) } logging . debug ( "URI=DELETE " + str ( uri ) ) logging . debug ( "HEADERS=" + str ( headers ) ) response = self . session . delete ( uri , headers = headers , params = params , data = json . dumps ( data ) ...
def send ( self , obj ) : """Prepend a 4 - byte length to the string"""
assert isinstance ( obj , ProtocolBase ) string = pickle . dumps ( obj ) length = len ( string ) self . sock . sendall ( struct . pack ( "<I" , length ) + string )
def create_et ( self ) : """Create a et file for this BAM file ( mapping information about read tuples ) . raises : ValueError"""
with ( gzip . open ( self . _es_fn , "tr" ) if self . compress_intermediate_files else open ( self . _es_fn , "r" ) ) as es_fo : with ( gzip . open ( self . _et_fn , "tw+" ) if self . compress_intermediate_files else open ( self . _et_fn , "w+" ) ) as et_fo : self . es2et ( es_fo = es_fo , et_fo = et_fo , )
def get ( self , timeout = None ) : """Get the value of the promise , waiting if necessary ."""
self . wait ( timeout ) if self . _state == self . FULFILLED : return self . value else : raise ValueError ( "Calculation didn't yield a value" )
def to_subject_id ( s ) : '''to _ subject _ id ( s ) coerces the given string or number into an integer subject id . If s is not a valid subejct id , raises an exception .'''
if not pimms . is_number ( s ) and not pimms . is_str ( s ) : raise ValueError ( 'invalid type for subject id: %s' % str ( type ( s ) ) ) if pimms . is_str ( s ) : try : s = os . path . expanduser ( s ) except Exception : pass if os . path . isdir ( s ) : s = s . split ( os . sep...
def prepare ( query , params ) : """For every match of the form " : param _ name " , call marshal on kwargs [ ' param _ name ' ] and replace that section of the query with the result"""
def repl ( match ) : name = match . group ( 1 ) [ 1 : ] if name in params : return marshal ( params [ name ] ) return ":%s" % name new , count = re . subn ( _param_re , repl , query ) if len ( params ) > count : raise cql . ProgrammingError ( "More keywords were provided " "than parameters" ) re...
def slice_tree ( tree , start_refs , end_refs , slice_tuple , html_copy = None ) : """Slices the HTML tree with the given start _ refs and end _ refs ( obtained via get _ line _ info ) at the given slice _ tuple , a tuple ( start , end ) containing the start and end of the slice ( or None , to start from the st...
start_ref = None end_ref = None if slice_tuple : slice_start , slice_end = slice_tuple if ( ( slice_start is not None and slice_start >= len ( start_refs ) ) or ( slice_end is not None and slice_end <= 0 ) ) : return get_html_tree ( '' ) if slice_start != None and slice_start <= 0 : slice_st...
def angle_between_vectors ( x , y ) : """Calculate the angle between two vectors x and y ."""
first_step = abs ( x [ 0 ] * y [ 0 ] + x [ 1 ] * y [ 1 ] + x [ 2 ] * y [ 2 ] ) / ( np . sqrt ( x [ 0 ] ** 2 + x [ 1 ] ** 2 + x [ 2 ] ** 2 ) * np . sqrt ( y [ 0 ] ** 2 + y [ 1 ] ** 2 + y [ 2 ] ** 2 ) ) second_step = np . arccos ( first_step ) return ( second_step )
def length_of_associated_transcript ( effect ) : """Length of spliced mRNA sequence of transcript associated with effect , if there is one ( otherwise return 0 ) ."""
return apply_to_transcript_if_exists ( effect = effect , fn = lambda t : len ( t . sequence ) , default = 0 )
def mkCompoundFilter ( parts ) : """Create a filter out of a list of filter - like things Used by mkFilter @ param parts : list of filter , endpoint , callable or list of any of these"""
# Separate into a list of callables and a list of filter objects transformers = [ ] filters = [ ] for subfilter in parts : try : subfilter = list ( subfilter ) except TypeError : # If it ' s not an iterable if hasattr ( subfilter , 'getServiceEndpoints' ) : # It ' s a full filter fil...
def drop_tip ( self , location = None , home_after = True ) : """Drop the pipette ' s current tip Notes If no location is passed , the pipette defaults to its ` trash _ container ` ( see : any : ` Pipette ` ) Parameters location : : any : ` Placeable ` or tuple ( : any : ` Placeable ` , : any : ` Vector `...
if not self . tip_attached : log . warning ( "Cannot drop tip without a tip attached." ) if not location and self . trash_container : location = self . trash_container if isinstance ( location , Placeable ) : # give space for the drop - tip mechanism # @ TODO ( Laura & Andy 2018261) # When container typing is i...
def get_resolve_url ( self , did_bytes ) : """Return a did value and value type from the block chain event record using ' did ' . : param did _ bytes : DID , hex - str : return url : Url , str"""
data = self . _did_registry . get_registered_attribute ( did_bytes ) if not ( data and data . get ( 'value' ) ) : return None return data [ 'value' ]
def _sign ( self , data ) : """Compute a signature string according to the CloudStack signature method ( hmac / sha1 ) ."""
# Python2/3 urlencode aren ' t good enough for this task . params = "&" . join ( "=" . join ( ( key , cs_encode ( value ) ) ) for key , value in sorted ( data . items ( ) ) ) digest = hmac . new ( self . secret . encode ( 'utf-8' ) , msg = params . lower ( ) . encode ( 'utf-8' ) , digestmod = hashlib . sha1 ) . digest ...
def create ( ) : """Create a new post for the current user ."""
if request . method == "POST" : title = request . form [ "title" ] body = request . form [ "body" ] error = None if not title : error = "Title is required." if error is not None : flash ( error ) else : db . session . add ( Post ( title = title , body = body , author = g ...
def create_dm_pkg ( secret , username ) : '''create ikuai dm message'''
secret = tools . EncodeString ( secret ) username = tools . EncodeString ( username ) pkg_format = '>HHHH32sHH32s' pkg_vals = [ IK_RAD_PKG_VER , IK_RAD_PKG_AUTH , IK_RAD_PKG_USR_PWD_TAG , len ( secret ) , secret . ljust ( 32 , '\x00' ) , IK_RAD_PKG_CMD_ARGS_TAG , len ( username ) , username . ljust ( 32 , '\x00' ) ] re...
def convert ( self , expr ) : # pylint : disable = R0201 """Resolves a claripy . ast . Base into something usable by the backend . : param expr : The expression . : param save : Save the result in the expression ' s object cache : return : A backend object ."""
ast_queue = [ [ expr ] ] arg_queue = [ ] op_queue = [ ] try : while ast_queue : args_list = ast_queue [ - 1 ] if args_list : ast = args_list . pop ( 0 ) if type ( ast ) in { bool , int , str , float } or not isinstance ( ast , Base ) : converted = self . _conv...