signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def _parse_content ( response ) : """parse the response body as JSON , raise on errors"""
if response . status_code != 200 : raise ApiError ( f'unknown error: {response.content.decode()}' ) result = json . loads ( response . content ) if not result [ 'ok' ] : raise ApiError ( f'{result["error"]}: {result.get("detail")}' ) return result
def request_token ( self ) : """Gets OAuth request token"""
client = OAuth1 ( client_key = self . _server_cache [ self . client . server ] . key , client_secret = self . _server_cache [ self . client . server ] . secret , callback_uri = self . callback , ) request = { "auth" : client } response = self . _requester ( requests . post , "oauth/request_token" , ** request ) data = ...
def render_sparkline ( self , ** kwargs ) : """Render a sparkline"""
spark_options = dict ( width = 200 , height = 50 , show_dots = False , show_legend = False , show_x_labels = False , show_y_labels = False , spacing = 0 , margin = 5 , min_scale = 1 , max_scale = 2 , explicit_size = True , no_data_text = '' , js = ( ) , classes = ( _ellipsis , 'pygal-sparkline' ) ) spark_options . upda...
def add_firmware_manifest ( self , name , datafile , key_table_file = None , ** kwargs ) : """Add a new manifest reference . : param str name : Manifest file short name ( Required ) : param str datafile : The file object or path to the manifest file ( Required ) : param str key _ table _ file : The file objec...
kwargs . update ( { 'name' : name , 'url' : datafile , # really it ' s the datafile } ) if key_table_file is not None : kwargs . update ( { 'key_table_url' : key_table_file } ) # really it ' s the key _ table firmware_manifest = FirmwareManifest . _create_request_map ( kwargs ) api = self . _get_api ( update_se...
def make_as ( self , klass , name , ** attributes ) : """Create an instance of the given model and type . : param klass : The class : type klass : class : param name : The type : type name : str : param attributes : The instance attributes : type attributes : dict : return : mixed"""
return self . of ( klass , name ) . make ( ** attributes )
def compute_hash_info ( fd , unit_size = None ) : """Get MediaFireHashInfo structure from the fd , unit _ size fd - - file descriptor - expects exclusive access because of seeking unit _ size - - size of a single unit Returns MediaFireHashInfo : hi . file - - sha256 of the whole file hi . units - - list o...
logger . debug ( "compute_hash_info(%s, unit_size=%s)" , fd , unit_size ) fd . seek ( 0 , os . SEEK_END ) file_size = fd . tell ( ) fd . seek ( 0 , os . SEEK_SET ) units = [ ] unit_counter = 0 file_hash = hashlib . sha256 ( ) unit_hash = hashlib . sha256 ( ) for chunk in iter ( lambda : fd . read ( HASH_CHUNK_SIZE_BYTE...
def add_server ( self , name , prefer = False ) : """Add or update an NTP server entry to the node config Args : name ( string ) : The IP address or FQDN of the NTP server . prefer ( bool ) : Sets the NTP server entry as preferred if True . Returns : True if the operation succeeds , otherwise False ."""
if not name or re . match ( r'^[\s]+$' , name ) : raise ValueError ( 'ntp server name must be specified' ) if prefer : name = '%s prefer' % name cmd = self . command_builder ( 'ntp server' , value = name ) return self . configure ( cmd )
def tidy_html ( html_buffer , cleaning_lib = 'utidylib' ) : """Tidy up the input HTML using one of the installed cleaning libraries . @ param html _ buffer : the input HTML to clean up @ type html _ buffer : string @ param cleaning _ lib : chose the preferred library to clean the HTML . One of : - utidyli...
if CFG_TIDY_INSTALLED and cleaning_lib == 'utidylib' : options = dict ( output_xhtml = 1 , show_body_only = 1 , merge_divs = 0 , wrap = 0 ) try : output = str ( tidy . parseString ( html_buffer , ** options ) ) except : output = html_buffer elif CFG_BEAUTIFULSOUP_INSTALLED and cleaning_lib =...
def __remove_redundant_proper_names ( self , docs , lemma_set ) : """Eemaldame yleliigsed pärisnimeanalüüsid etteantud sõnalemmade loendi ( hulga ) põhjal ;"""
for doc in docs : for word in doc [ WORDS ] : # Vaatame vaid s6nu , millele on pakutud rohkem kui yks analyys : if len ( word [ ANALYSIS ] ) > 1 : # 1 ) Leiame analyysid , mis tuleks loendi järgi eemaldada toDelete = [ ] for analysis in word [ ANALYSIS ] : if analysi...
def get_file_breaks ( self , filename ) : """List all file ` filename ` breakpoints"""
return [ breakpoint for breakpoint in self . breakpoints if breakpoint . on_file ( filename ) ]
def _parse_value ( cls , stream_rdr , offset , value_count , value_offset ) : """Return the ASCII string parsed from * stream _ rdr * at * value _ offset * . The length of the string , including a terminating ' \x00 ' ( NUL ) character , is in * value _ count * ."""
return stream_rdr . read_str ( value_count - 1 , value_offset )
def krylovMethod ( self , tol = 1e-8 ) : """We obtain ` ` pi ` ` by using the : func : ` ` gmres ` ` solver for the system of linear equations . It searches in Krylov subspace for a vector with minimal residual . The result is stored in the class attribute ` ` pi ` ` . Example > > > P = np . array ( [ [ 0.5,0...
P = self . getIrreducibleTransitionMatrix ( ) # if P consists of one element , then set self . pi = 1.0 if P . shape == ( 1 , 1 ) : self . pi = np . array ( [ 1.0 ] ) return size = P . shape [ 0 ] dP = P - eye ( size ) # Replace the first equation by the normalizing condition . A = vstack ( [ np . ones ( size )...
def _check_parameter_range ( s_min , s_max ) : r"""Performs a final check on a clipped parameter range . . . note : : This is a helper for : func : ` clip _ range ` . If both values are unchanged from the " unset " default , this returns the whole interval : math : ` \ left [ 0.0 , 1.0 \ right ] ` . If on...
if s_min == DEFAULT_S_MIN : # Based on the way ` ` _ update _ parameters ` ` works , we know # both parameters must be unset if ` ` s _ min ` ` . return 0.0 , 1.0 if s_max == DEFAULT_S_MAX : return s_min , s_min return s_min , s_max
def get_translations ( self , domain = None , locale = None ) : """Load translations for given or configuration domain . : param domain : Messages domain ( str ) : param locale : Locale object"""
if locale is None : if self . locale is None : return support . NullTranslations ( ) locale = self . locale if domain is None : domain = self . cfg . domain if ( domain , locale . language ) not in self . translations : translations = None for locales_dir in reversed ( self . cfg . locales_d...
def diagnostics ( self , ** kwds ) : """Endpoint : / system / diagnostics . json Runs a set of diagnostic tests on the server . Returns a dictionary containing the results ."""
# Don ' t process the result automatically , since this raises an exception # on failure , which doesn ' t provide the cause of the failure self . _client . get ( "/system/diagnostics.json" , process_response = False , ** kwds ) return self . _client . last_response . json ( ) [ "result" ]
def lint ( ) : """Run flake8 against all py files"""
py_files = subprocess . check_output ( "git ls-files" ) if PY3 : py_files = py_files . decode ( ) py_files = [ x for x in py_files . split ( ) if x . endswith ( '.py' ) ] py_files = ' ' . join ( py_files ) sh ( "%s -m flake8 %s" % ( PYTHON , py_files ) , nolog = True )
def flush ( self , file = str ( ) ) : """Flushes the updated file content to the given * file * . . . note : : Overwrites an existing file . : param str file : name and location of the file . Default is the original file ."""
if file : Path ( file ) . write_bytes ( self . _cache ) else : self . path . write_bytes ( self . _cache )
def is_ancestor_of_repository ( self , id_ , repository_id ) : """Tests if an ` ` Id ` ` is an ancestor of a repository . arg : id ( osid . id . Id ) : an ` ` Id ` ` arg : repository _ id ( osid . id . Id ) : the Id of a repository return : ( boolean ) - ` ` true ` ` if this ` ` id ` ` is an ancestor of ` `...
# Implemented from template for # osid . resource . BinHierarchySession . is _ ancestor _ of _ bin if self . _catalog_session is not None : return self . _catalog_session . is_ancestor_of_catalog ( id_ = id_ , catalog_id = repository_id ) return self . _hierarchy_session . is_ancestor ( id_ = id_ , ancestor_id = re...
def attrput ( self , groupname , attrname , rownr , value , unit = [ ] , meas = [ ] ) : """Put the value and optionally unit and measinfo of an attribute in a row in a group ."""
return self . _attrput ( groupname , attrname , rownr , value , unit , meas )
def identify_vertex_neighbours ( self , vertex ) : """Find the neighbour - vertices in the triangulation for the given vertex Searches self . simplices for vertex entries and sorts neighbours"""
simplices = self . simplices ridx , cidx = np . where ( simplices == vertex ) neighbour_array = np . unique ( np . hstack ( [ simplices [ ridx ] ] ) ) . tolist ( ) neighbour_array . remove ( vertex ) return neighbour_array
def get_id ( self ) : """Gets the Id associated with this instance of this OSID object . Persisting any reference to this object is done by persisting the Id returned from this method . The Id returned may be different than the Id used to query this object . In this case , the new Id should be preferred ove...
return Id ( identifier = str ( self . _my_map [ '_id' ] ) , namespace = self . _namespace , authority = self . _authority )
def open_stream ( self , class_attr_name = None , fn = None ) : """Save an arff structure to a file , leaving the file object open for writing of new data samples . This prevents you from directly accessing the data via Python , but when generating a huge file , this prevents all your data from being stored...
if fn : self . fout_fn = fn else : fd , self . fout_fn = tempfile . mkstemp ( ) os . close ( fd ) self . fout = open ( self . fout_fn , 'w' ) if class_attr_name : self . class_attr_name = class_attr_name self . write ( fout = self . fout , schema_only = True ) self . write ( fout = self . fout , data_on...
def unpurge ( * packages ) : '''Change package selection for each package specified to ' install ' CLI Example : . . code - block : : bash salt ' * ' lowpkg . unpurge curl'''
if not packages : return { } old = __salt__ [ 'pkg.list_pkgs' ] ( purge_desired = True ) ret = { } __salt__ [ 'cmd.run' ] ( [ 'dpkg' , '--set-selections' ] , stdin = r'\n' . join ( [ '{0} install' . format ( x ) for x in packages ] ) , python_shell = False , output_loglevel = 'trace' ) __context__ . pop ( 'pkg.list...
def _jit ( function ) : """Compile a function using a jit compiler . The function is always compiled to check errors , but is only used outside tests , so that code coverage analysis can be performed in jitted functions . The tests set sys . _ called _ from _ test in conftest . py ."""
import sys compiled = numba . jit ( function ) if hasattr ( sys , '_called_from_test' ) : return function else : # pragma : no cover return compiled
def envcontext ( patch , _env = None ) : """In this context , ` os . environ ` is modified according to ` patch ` . ` patch ` is an iterable of 2 - tuples ( key , value ) : ` key ` : string ` value ` : - string : ` environ [ key ] = = value ` inside the context . - UNSET : ` key not in environ ` inside th...
env = os . environ if _env is None else _env before = env . copy ( ) for k , v in patch : if v is UNSET : env . pop ( k , None ) elif isinstance ( v , tuple ) : env [ k ] = format_env ( v , before ) else : env [ k ] = v try : yield finally : env . clear ( ) env . update (...
def summarize ( reintegrate = True , dist_tolerance = 3 , qranges = None , samples = None , raw = False , late_radavg = True , graph_ncols = 3 , std_multiplier = 3 , graph_extension = 'png' , graph_dpi = 80 , correlmatrix_colormap = 'coolwarm' , image_colormap = 'viridis' , correlmatrix_logarithmic = True , cormaptest ...
if qranges is None : qranges = { } ip = get_ipython ( ) data2d = { } data1d = { } headers_tosave = { } rowavg = { } if raw : writemarkdown ( '# Summarizing RAW images.' ) headers = ip . user_ns [ '_headers' ] [ 'raw' ] rawpart = '_raw' # this will be added in the filenames saved else : writemark...
def from_csv ( input_csv , headers = None , schema_file = None ) : """Create a ConfusionMatrix from a csv file . Args : input _ csv : Path to a Csv file ( with no header ) . Can be local or GCS path . headers : Csv headers . If present , it must include ' target ' and ' predicted ' . schema _ file : Path to...
if headers is not None : names = headers elif schema_file is not None : with _util . open_local_or_gcs ( schema_file , mode = 'r' ) as f : schema = json . load ( f ) names = [ x [ 'name' ] for x in schema ] else : raise ValueError ( 'Either headers or schema_file is needed' ) all_files = _util ....
def overlay_gateway_map_vlan_vni_mapping_vni ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) overlay_gateway = ET . SubElement ( config , "overlay-gateway" , xmlns = "urn:brocade.com:mgmt:brocade-tunnels" ) name_key = ET . SubElement ( overlay_gateway , "name" ) name_key . text = kwargs . pop ( 'name' ) map = ET . SubElement ( overlay_gateway , "map" ) vlan_vni_mapping = ET ....
def rotate_orth ( self , quads ) : "Orthographic rotation , quads : 0-3 , number of clockwise rotations"
with _LeptonicaErrorTrap ( ) : return Pix ( lept . pixRotateOrth ( self . _cdata , quads ) )
def privileges ( state , host , user , privileges , user_hostname = 'localhost' , database = '*' , table = '*' , present = True , flush = True , # Details for speaking to MySQL via ` mysql ` CLI mysql_user = None , mysql_password = None , mysql_host = None , mysql_port = None , ) : '''Add / remove MySQL privileges ...
# Ensure we have a list if isinstance ( privileges , six . string_types ) : privileges = [ privileges ] if database != '*' : database = '`{0}`' . format ( database ) if table != '*' : table = '`{0}`' . format ( table ) # We can ' t set privileges on * . tablename as MySQL won ' t allow it if databas...
def click ( self , force_no_call = False , milis = None ) : """Call when the button is pressed . This start the callback function in a thread If : milis is given , will release the button after : milis miliseconds"""
if self . clicked : return False if not force_no_call and self . flags & self . CALL_ON_PRESS : if self . flags & self . THREADED_CALL : start_new_thread ( self . func , ( ) ) else : self . func ( ) super ( ) . click ( ) if milis is not None : start_new_thread ( self . release , ( ) , { ...
def _do_check ( self , obj , check_module , check_str ) : '''Run a check function on obj'''
opts = self . _config [ 'options' ] if check_str in opts : fargs = opts [ check_str ] if isinstance ( fargs , list ) : out = check_wrapper ( getattr ( check_module , check_str ) ) ( obj , * fargs ) else : out = check_wrapper ( getattr ( check_module , check_str ) ) ( obj , fargs ) else : ...
def _load_converted_gssha_data_from_lsm ( self , gssha_var , lsm_var , load_type , time_step = None ) : """This function loads data from LSM and converts to GSSHA format"""
if 'radiation' in gssha_var : conversion_factor = self . netcdf_attributes [ gssha_var ] [ 'conversion_factor' ] [ load_type ] if gssha_var . startswith ( 'direct_radiation' ) and not isinstance ( lsm_var , basestring ) : # direct _ radiation = ( 1 - DIFFUSIVE _ FRACION ) * global _ radiation global_rad...
def add_to_stack ( self , instance , stack ) : """Get the context manager for the service ` instance ` and push it to the context manager ` stack ` . : param instance : The service to get the context manager for . : type instance : : class : ` Service ` : param stack : The context manager stack to push the ...
cm = self . init_cm ( instance ) obj = stack . enter_context ( cm ) self . _data [ instance ] = cm , obj return obj
def make_field ( self , field_name , field_body ) : """Fill content into nodes . : param string field _ name : Field name of the field : param field _ name : Field body if the field : type field _ name : str or instance of docutils . nodes : return : field instance filled with given name and body : rtype ...
name = nodes . field_name ( ) name += nodes . Text ( field_name ) paragraph = nodes . paragraph ( ) if isinstance ( field_body , str ) : # This is the case when field _ body is just a string : paragraph += nodes . Text ( field_body ) else : # This is the case when field _ body is a complex node : # useful when cons...
def _to_dict ( self ) : """Return a json dictionary representing this model ."""
_dict = { } if hasattr ( self , 'environments' ) and self . environments is not None : _dict [ 'environments' ] = [ x . _to_dict ( ) for x in self . environments ] return _dict
def load_shedding ( network , ** kwargs ) : """Implement load shedding in existing network to identify feasibility problems Parameters network : : class : ` pypsa . Network Overall container of PyPSA marginal _ cost : int Marginal costs for load shedding p _ nom : int Installed capacity of load shed...
marginal_cost_def = 10000 # network . generators . marginal _ cost . max ( ) * 2 p_nom_def = network . loads_t . p_set . max ( ) . max ( ) marginal_cost = kwargs . get ( 'marginal_cost' , marginal_cost_def ) p_nom = kwargs . get ( 'p_nom' , p_nom_def ) network . add ( "Carrier" , "load" ) start = network . generators ....
def create_role ( self , ** kwargs ) : """Creates and returns a new role from the given parameters ."""
role = self . role_model ( ** kwargs ) return self . put ( role )
def _apply_serial_port ( serial_device_spec , key , operation = 'add' ) : '''Returns a vim . vm . device . VirtualSerialPort representing a serial port component serial _ device _ spec Serial device properties key Unique key of the device operation Add or edit the given device . . code - block : : b...
log . trace ( 'Creating serial port adapter=%s type=%s connectable=%s yield=%s' , serial_device_spec [ 'adapter' ] , serial_device_spec [ 'type' ] , serial_device_spec [ 'connectable' ] , serial_device_spec [ 'yield' ] ) device_spec = vim . vm . device . VirtualDeviceSpec ( ) device_spec . device = vim . vm . device . ...
def _send_request ( self , method , url , * args , ** kwargs ) : """Send HTTP request . : param str method : The HTTP method to use . : param str url : The URL to make the request to . : return : Deferred firing with the HTTP response ."""
action = LOG_JWS_REQUEST ( url = url ) with action . context ( ) : headers = kwargs . setdefault ( 'headers' , Headers ( ) ) headers . setRawHeaders ( b'user-agent' , [ self . _user_agent ] ) kwargs . setdefault ( 'timeout' , self . timeout ) return ( DeferredContext ( self . _treq . request ( method , ...
def facet_search ( cls , * facets ) : '''Build a FacetSearch for a given list of facets Elasticsearch DSL doesn ' t allow to list facets once and for all and then later select them . They are always all requested As we don ' t use them every time and facet computation can take some time , we build the Fac...
f = dict ( ( k , v ) for k , v in cls . facets . items ( ) if k in facets ) class TempSearch ( SearchQuery ) : adapter = cls analyzer = cls . analyzer boosters = cls . boosters doc_types = cls facets = f fields = cls . fields fuzzy = cls . fuzzy match_type = cls . match_type model = ...
def enable_modules_from_last_session ( seashcommanddict ) : """Enable every module that isn ' t marked as disabled in the modules folder . This function is meant to be called when seash is initializing and nowhere else . A module is marked as disabled when there is a modulename . disabled file ."""
successfully_enabled_modules = [ ] modules_to_enable = get_enabled_modules ( ) for modulename in modules_to_enable : # There are no bad side effects to seash ' s state when we do this # The only thing that should happen is that the modulename . disabled file # gets created ( temporarily ) disable ( seashcommanddict...
def _import_status ( data , item , repo_name , repo_tag ) : '''Process a status update from docker import , updating the data structure'''
status = item [ 'status' ] try : if 'Downloading from' in status : return elif all ( x in string . hexdigits for x in status ) : # Status is an image ID data [ 'Image' ] = '{0}:{1}' . format ( repo_name , repo_tag ) data [ 'Id' ] = status except ( AttributeError , TypeError ) : pass
def get_ca_certs ( environ = os . environ ) : """Retrieve a list of CAs at either the DEFAULT _ CERTS _ PATH or the env override , TXAWS _ CERTS _ PATH . In order to find . pem files , this function checks first for presence of the TXAWS _ CERTS _ PATH environment variable that should point to a directory c...
cert_paths = environ . get ( "TXAWS_CERTS_PATH" , DEFAULT_CERTS_PATH ) . split ( ":" ) certificate_authority_map = { } for path in cert_paths : if not path : continue for cert_file_name in glob ( os . path . join ( path , "*.pem" ) ) : # There might be some dead symlinks in there , so let ' s make sure ...
def run ( self ) : """Use directly check ( ) api from pydocstyle ."""
if self . exclude_from_doctest : for pattern in self . exclude_from_doctest : if fnmatch . fnmatch ( self . filename , pattern ) : return checked_codes = pep257 . conventions . pep257 | { 'D998' , 'D999' } for error in self . _check_source ( ) : if isinstance ( error , pep257 . Error ) and e...
def _init_grpc_publisher ( self ) : """initialize the grpc publisher , builds the stub and then starts the grpc manager : return : None"""
self . _stub = EventHub_pb2_grpc . PublisherStub ( channel = self . _channel ) self . grpc_manager = Eventhub . GrpcManager ( stub_call = self . _stub . send , on_msg_callback = self . _publisher_callback , metadata = self . _generate_publish_headers ( ) . items ( ) )
def append_path_payment_op ( self , destination , send_code , send_issuer , send_max , dest_code , dest_issuer , dest_amount , path , source = None ) : """Append a : class : ` PathPayment < stellar _ base . operation . PathPayment > ` operation to the list of operations . : param str destination : The destinati...
# path : a list of asset tuple which contains asset _ code and asset _ issuer , # [ ( asset _ code , asset _ issuer ) , ( asset _ code , asset _ issuer ) ] for native asset you can deliver # ( ' XLM ' , None ) send_asset = Asset ( send_code , send_issuer ) dest_asset = Asset ( dest_code , dest_issuer ) assets = [ ] for...
def scan_field ( self , measure , target , rate , delay = 1 ) : """Performs a field scan . Measures until the target field is reached . : param measure : A callable called repeatedly until stability at the target field is reached . : param field : The target field in Tesla . : param rate : The field rate ...
if not hasattr ( measure , '__call__' ) : raise TypeError ( 'measure parameter not callable.' ) self . activity = 'hold' self . field . target = target self . field . sweep_rate = rate self . activity = 'to setpoint' while self . status [ 'mode' ] != 'at rest' : measure ( ) time . sleep ( delay )
def read_configs ( __pkg : str , __name : str = 'config' , * , local : bool = True ) -> ConfigParser : """Process configuration file stack . We export the time parsing functionality of ` ` jnrbase ` ` as custom converters for : class : ` configparser . ConfigParser ` : Method Function ` ` . getdatetime ( ) ...
configs = get_configs ( __pkg , __name ) if local : localrc = path . abspath ( '.{}rc' . format ( __pkg ) ) if path . exists ( localrc ) : configs . append ( localrc ) cfg = ConfigParser ( converters = { 'datetime' : parse_datetime , 'humandelta' : parse_timedelta , 'timedelta' : parse_delta , } ) cfg ....
def name ( self , name ) : """This function will take the given name and split it into components weight , width , customName , and possibly the full name . This is what Glyphs 1113 seems to be doing , approximately ."""
weight , width , custom_name = self . _splitName ( name ) self . set_all_name_components ( name , weight , width , custom_name )
def tx ( self , * args , ** kwargs ) : """Executes a raw tx string , or get a new TX object to work with . Passing a raw string or list of strings will immedately transact and return the API response as a dict . > > > resp = tx ( ' { : db / id # db / id [ : db . part / user ] : person / name " Bob " } ' ) {...
if 0 == len ( args ) : return TX ( self ) ops = [ ] for op in args : if isinstance ( op , list ) : ops += op elif isinstance ( op , ( str , unicode ) ) : ops . append ( op ) if 'debug' in kwargs : pp ( ops ) tx_proc = "[ %s ]" % "" . join ( ops ) x = self . rest ( 'POST' , self . uri_db ...
def callRemote ( self , methodName , * args , ** kwargs ) : """Calls the remote method and returns a Deferred instance to the result . DBus does not support passing keyword arguments over the wire . The keyword arguments accepted by this method alter the behavior of the remote call as described in the kwargs ...
expectReply = kwargs . get ( 'expectReply' , True ) autoStart = kwargs . get ( 'autoStart' , True ) timeout = kwargs . get ( 'timeout' , None ) interface = kwargs . get ( 'interface' , None ) m = None for i in self . interfaces : if interface and not interface == i . name : continue m = i . methods . ge...
def send_simple_command ( self , cmd ) : """Send simple mqtt commands ."""
pkt = MqttPkt ( ) pkt . command = cmd pkt . remaining_length = 0 ret = pkt . alloc ( ) if ret != NC . ERR_SUCCESS : return ret return self . packet_queue ( pkt )
def register_a_problem ( self , prob , hosts , services , timeperiods , bi_modulations ) : # pylint : disable = too - many - locals """Call recursively by potentials impacts so they update their source _ problems list . But do not go below if the problem is not a real one for me like If I ' ve got multiple pa...
# Maybe we already have this problem ? If so , bailout too if prob . uuid in self . source_problems : return [ ] now = time . time ( ) was_an_impact = self . is_impact # Our father already look if he impacts us . So if we are here , # it ' s that we really are impacted self . is_impact = True impacts = [ ] # Ok , i...
def osf_crawl ( k , * pths , ** kw ) : '''osf _ crawl ( k ) crawls the osf repository k and returns a lazy nested map structure of the repository ' s files . Folders have values that are maps of their contents while files have values that are their download links . osf _ crawl ( k1 , k2 , . . . ) is equivalen...
from six . moves import reduce base = kw . pop ( 'base' , 'osfstorage' ) root = kw . pop ( 'root' , None ) if len ( kw ) > 0 : raise ValueError ( 'Unknown optional parameters: %s' % ( list ( kw . keys ( ) ) , ) ) if k . lower ( ) . startswith ( 'osf:' ) : k = k [ 4 : ] k = k . lstrip ( '/' ) pths = [ p . lstrip...
def register_signal ( alias : str , signal : pyqtSignal ) : """Used to register signal at the dispatcher . Note that you can not use alias that already exists . : param alias : Alias of the signal . String . : param signal : Signal itself . Usually pyqtSignal instance . : return :"""
if SignalDispatcher . signal_alias_exists ( alias ) : raise SignalDispatcherError ( 'Alias "' + alias + '" for signal already exists!' ) SignalDispatcher . signals [ alias ] = signal
def schema_helper ( self , name , _ , schema = None , ** kwargs ) : """Definition helper that allows using a marshmallow : class : ` Schema < marshmallow . Schema > ` to provide OpenAPI metadata . : param type | Schema schema : A marshmallow Schema class or instance ."""
if schema is None : return None schema_instance = resolve_schema_instance ( schema ) schema_key = make_schema_key ( schema_instance ) self . warn_if_schema_already_in_spec ( schema_key ) self . openapi . refs [ schema_key ] = name json_schema = self . openapi . schema2jsonschema ( schema_instance ) return json_sche...
def relocate_zeros ( array ) : """This function moves all zeroes present in the given list to the end . Examples : > > > relocate _ zeros ( [ 6 , 0 , 8 , 2 , 3 , 0 , 4 , 0 , 1 ] ) [6 , 8 , 2 , 3 , 4 , 1 , 0 , 0 , 0] > > > relocate _ zeros ( [ 4 , 0 , 2 , 7 , 0 , 9 , 0 , 12 , 0 ] ) [4 , 2 , 7 , 9 , 12 , 0 ...
non_zero_index = 0 for i in array : if i != 0 : array [ non_zero_index ] = i non_zero_index += 1 for i in range ( non_zero_index , len ( array ) ) : array [ i ] = 0 return array
def update ( identifiers , nopull , only ) : '''Performs a ` git pull ` in each of the repositories registered with ` homely add ` , runs all of their HOMELY . py scripts , and then performs automatic cleanup as necessary . REPO This should be the path to a local dotfiles repository that has already been ...
mkcfgdir ( ) setallowpull ( not nopull ) cfg = RepoListConfig ( ) if len ( identifiers ) : updatedict = { } for identifier in identifiers : repo = cfg . find_by_any ( identifier , "ilc" ) if repo is None : hint = "Try running %s add /path/to/this/repo first" % CMD raise F...
def validate_endpoint_create_and_update_params ( endpoint_type , managed , params ) : """Given an endpoint type of " shared " " server " or " personal " and option values Confirms the option values are valid for the given endpoint"""
# options only allowed for GCS endpoints if endpoint_type != "server" : # catch params with two option flags if params [ "public" ] is False : raise click . UsageError ( "Option --private only allowed " "for Globus Connect Server endpoints" ) # catch any params only usable with GCS for option in [ "...
def compare ( self , other , r_threshold = 1e-3 ) : """Compare two rotations The RMSD of the rotation matrices is computed . The return value is True when the RMSD is below the threshold , i . e . when the two rotations are almost identical ."""
return compute_rmsd ( self . r , other . r ) < r_threshold
def cr ( A , b , x0 = None , tol = 1e-5 , maxiter = None , xtype = None , M = None , callback = None , residuals = None ) : """Conjugate Residual algorithm . Solves the linear system Ax = b . Left preconditioning is supported . The matrix A must be Hermitian symmetric ( but not necessarily definite ) . Parame...
A , M , x , b , postprocess = make_system ( A , M , x0 , b ) # n = len ( b ) # Ensure that warnings are always reissued from this function import warnings warnings . filterwarnings ( 'always' , module = 'pyamg\.krylov\._cr' ) # determine maxiter if maxiter is None : maxiter = int ( 1.3 * len ( b ) ) + 2 elif maxite...
def connectionLost ( self , reason ) : """Called when the transport loses connection to the bus"""
if self . busName is None : return for cb in self . _dcCallbacks : cb ( self , reason ) for d , timeout in self . _pendingCalls . values ( ) : if timeout : timeout . cancel ( ) d . errback ( reason ) self . _pendingCalls = { } self . objHandler . connectionLost ( reason )
def run ( cmd : str , * paths : str , cwd : str = '.' , mute : bool = False , filters : typing . Optional [ typing . Union [ typing . Iterable [ str ] , str ] ] = None , failure_ok : bool = False , timeout : float = _DEFAULT_PROCESS_TIMEOUT , ) -> typing . Tuple [ str , int ] : """Executes a command and returns the...
filters = _sanitize_filters ( filters ) exe_path , args_list = _parse_cmd ( cmd , * paths ) context = RunContext ( # type : ignore exe_path = exe_path , capture = sarge . Capture ( ) , failure_ok = failure_ok , mute = mute , args_list = args_list , paths = paths , cwd = cwd , timeout = timeout , filters = filters , ) i...
def append_arrays ( many , single ) : """Append an array to another padding with NaNs for constant length . Parameters many : array _ like of rank ( j , k ) values appended to a copy of this array . This may be a 1 - D or 2 - D array . single : array _ like of rank l values to append . This should be a ...
assert np . ndim ( single ) == 1 # Check if the values need to be padded to for equal length diff = single . shape [ 0 ] - many . shape [ 0 ] if diff < 0 : single = np . pad ( single , ( 0 , - diff ) , 'constant' , constant_values = np . nan ) elif diff > 0 : many = np . pad ( many , ( ( 0 , diff ) , ) , 'const...
def _set_BC ( self , pores , bctype , bcvalues = None , mode = 'merge' ) : r"""Apply boundary conditions to specified pores Parameters pores : array _ like The pores where the boundary conditions should be applied bctype : string Specifies the type or the name of boundary condition to apply . The types ...
# Hijack the parse _ mode function to verify bctype argument bctype = self . _parse_mode ( bctype , allowed = [ 'value' , 'rate' ] , single = True ) mode = self . _parse_mode ( mode , allowed = [ 'merge' , 'overwrite' , 'remove' ] , single = True ) pores = self . _parse_indices ( pores ) values = np . array ( bcvalues ...
def object_patch_append_data ( self , multihash , new_data , ** kwargs ) : """Creates a new merkledag object based on an existing one . The new object will have the provided data appended to it , and will thus have a new Hash . . . code - block : : python > > > c . object _ patch _ append _ data ( " QmZZmY ...
args = ( multihash , ) body , headers = multipart . stream_files ( new_data , self . chunk_size ) return self . _client . request ( '/object/patch/append-data' , args , decoder = 'json' , data = body , headers = headers , ** kwargs )
def is_multifile_object_without_children ( self , location : str ) -> bool : """Returns True if an item with this location is present as a multifile object without children . For this implementation , this means that there is a folder without any files in it : param location : : return :"""
return isdir ( location ) and len ( self . find_multifile_object_children ( location ) ) == 0
def parse ( self , data ) : """: return : None"""
# pylint : disable - msg = R0911 , C1801 assert isinstance ( data , bytes ) assert len ( data ) > 0 assert len ( data ) >= velbus . MINIMUM_MESSAGE_SIZE assert data [ 0 ] == velbus . START_BYTE self . logger . debug ( "Processing message %s" , str ( data ) ) if len ( data ) > velbus . MAXIMUM_MESSAGE_SIZE : self . ...
def release_port ( upnp , external_port ) : """Try to release the port mapping for ` external _ port ` . Args : external _ port ( int ) : the port that was previously forwarded to . Returns : success ( boolean ) : if the release was successful ."""
mapping = upnp . getspecificportmapping ( external_port , 'UDP' ) if mapping is None : log . error ( 'could not find a port mapping' , external = external_port ) return False else : log . debug ( 'found existing port mapping' , mapping = mapping ) if upnp . deleteportmapping ( external_port , 'UDP' ) : ...
def fric_rect ( FlowRate , Width , DistCenter , Nu , PipeRough , openchannel ) : """Return the friction factor for a rectangular channel ."""
# Checking input validity - inputs not checked here are checked by # functions this function calls . ut . check_range ( [ PipeRough , "0-1" , "Pipe roughness" ] ) if re_rect ( FlowRate , Width , DistCenter , Nu , openchannel ) >= RE_TRANSITION_PIPE : # Swamee - Jain friction factor adapted for rectangular channel . # D...
def getUrlFromFilename ( self , filename ) : """Construct URL from filename ."""
components = util . splitpath ( util . getRelativePath ( self . basepath , filename ) ) url = '/' . join ( [ url_quote ( component , '' ) for component in components ] ) return self . baseurl + url
def _writeTracebackMessage ( logger , typ , exception , traceback ) : """Write a traceback to the log . @ param typ : The class of the exception . @ param exception : The L { Exception } instance . @ param traceback : The traceback , a C { str } ."""
msg = TRACEBACK_MESSAGE ( reason = exception , traceback = traceback , exception = typ ) msg = msg . bind ( ** _error_extraction . get_fields_for_exception ( logger , exception ) ) msg . write ( logger )
def imported_member ( self , node , member , name ) : """verify this is not an imported class or handle it"""
# / ! \ some classes like ExtensionClass doesn ' t have a _ _ module _ _ # attribute ! Also , this may trigger an exception on badly built module # ( see http : / / www . logilab . org / ticket / 57299 for instance ) try : modname = getattr ( member , "__module__" , None ) except TypeError : modname = None if m...
def div ( computation : BaseComputation ) -> None : """Division"""
numerator , denominator = computation . stack_pop ( num_items = 2 , type_hint = constants . UINT256 ) if denominator == 0 : result = 0 else : result = ( numerator // denominator ) & constants . UINT_256_MAX computation . stack_push ( result )
def dump ( self , cache_file = None ) : """Write dump out to file ` cache _ file ` , defaulting to ` ` self . cache _ file ` `"""
if cache_file is None : cache_file = self . cache_file if cache_file is not None : self . cache_file = cache_file with open ( cache_file , 'wb' ) as pickle_fh : pickle . dump ( ( self . remote , self . backend . name , self . max_sleep_interval , self . job_id , self . _status , self . epilogue , se...
def hrJoin ( items ) : """Joins items together in a human readable string e . g . ' wind , ice and fire '"""
conjuction = " " + _ ( "and" ) + " " if len ( items ) <= 2 : return conjuction . join ( items ) else : return ", " . join ( items [ : - 1 ] ) + conjuction + items [ - 1 ]
def manage_beacons ( self , tag , data ) : '''Manage Beacons'''
func = data . get ( 'func' , None ) name = data . get ( 'name' , None ) beacon_data = data . get ( 'beacon_data' , None ) include_pillar = data . get ( 'include_pillar' , None ) include_opts = data . get ( 'include_opts' , None ) funcs = { 'add' : ( 'add_beacon' , ( name , beacon_data ) ) , 'modify' : ( 'modify_beacon'...
def router_removed_from_hosting_device ( self , context , router ) : """Notify cfg agent about router removed from hosting device ."""
self . _notification ( context , 'router_removed_from_hosting_device' , [ router ] , operation = None , shuffle_agents = False )
def get_object ( self , item ) : """Returns a StorageObject matching the specified item . If no such object exists , a NotFound exception is raised . If ' item ' is not a string , that item is returned unchanged ."""
if isinstance ( item , six . string_types ) : item = self . object_manager . get ( item ) return item
def _pre_suf_fix_filter ( t : List , prefix : str , suffix : str ) -> bool : """Prefix and Suffix filter Args : t : List , list of tokens prefix : str suffix : str Returns : bool"""
if prefix : for a_token in t : if a_token . _ . n_prefix ( len ( prefix ) ) != prefix : return False if suffix : for a_token in t : if a_token . _ . n_suffix ( len ( suffix ) ) != suffix : return False return True
def logout ( token_dir = DEFAULT_CRED_PATH ) : """Remove ALL tokens in the token directory . This will force re - authentication to all services . Arguments : token _ dir ( str ) : The path to the directory to save tokens in and look for credentials by default . If this argument was given to a ` ` login ( )...
for f in os . listdir ( token_dir ) : if f . endswith ( "tokens.json" ) : try : os . remove ( os . path . join ( token_dir , f ) ) except OSError as e : # Eat ENOENT ( no such file / dir , tokens already deleted ) only , # raise any other issue ( bad permissions , etc . ) ...
def to_dict ( self ) : '''Save this configuration set into a dictionary .'''
d = { 'id' : self . id } data = [ ] for c in self . _config_data : data . append ( c . to_dict ( ) ) if data : d [ 'configurationData' ] = data return d
def freeze_script ( script_path , cache = True , temp_path = '_hadoopy_temp' ) : """Freezes a script , puts it on hdfs , and gives you the path ' frozen _ tar _ path ' can be given to launch _ frozen and it will use that instead of making its own , this is useful for repeated calls . If a file with the same m...
script_abspath = os . path . abspath ( script_path ) if not os . path . exists ( script_abspath ) : raise ValueError ( 'Script [%s] does not exist.' % script_abspath ) try : if not cache : raise KeyError # NOTE ( brandyn ) : Don ' t use cache item cmds , frozen_tar_path = FREEZE_CACHE [ scri...
def _order_by_is_valid_or_none ( self , params ) : """Validates that a given order _ by has proper syntax . : param params : Query params . : return : Returns True if either no order _ by is present , or if the order _ by is well - formed ."""
if not "order_by" in params or not params [ "order_by" ] : return True def _order_by_dict_is_not_well_formed ( d ) : if not isinstance ( d , dict ) : # Bad type . return True if "property_name" in d and d [ "property_name" ] : if "direction" in d and not direction . is_valid_direction ( d [ ...
def as_operation ( self ) : """Obtains a single ` Operation ` representing this instances contents . Returns : : class : ` endpoints _ management . gen . servicecontrol _ v1 _ messages . Operation `"""
result = encoding . CopyProtoMessage ( self . _op ) names = sorted ( self . _metric_values_by_name_then_sign . keys ( ) ) for name in names : mvs = self . _metric_values_by_name_then_sign [ name ] result . metricValueSets . append ( sc_messages . MetricValueSet ( metricName = name , metricValues = mvs . values ...
def bzip_blocks_decompress_all ( data ) : """Decompress all of the bzip2 - ed blocks . Returns the decompressed data as a ` bytearray ` ."""
frames = bytearray ( ) offset = 0 while offset < len ( data ) : size_bytes = data [ offset : offset + 4 ] offset += 4 block_cmp_bytes = abs ( Struct ( '>l' ) . unpack ( size_bytes ) [ 0 ] ) try : frames . extend ( bz2 . decompress ( data [ offset : offset + block_cmp_bytes ] ) ) offset +...
def sort ( self , ** parameters ) : """Enhance the default sort method to accept a new parameter " by _ score " , to use instead of " by " if you want to sort by the score of a sorted set . You must pass to " by _ sort " the key of a redis sorted set ( or a sortedSetField attached to an instance )"""
self . _sort_by_sortedset = None is_sortedset = False if parameters . get ( 'by_score' ) : if parameters . get ( 'by' ) : raise ValueError ( "You can't use `by` and `by_score` in the same " "call to `sort`." ) by = parameters . get ( 'by_score' , None ) if isinstance ( by , SortedSetField ) and geta...
def get_kbr_values ( self , searchkey = "" , searchvalue = "" , searchtype = 's' ) : """Return dicts of ' key ' and ' value ' from a knowledge base . : param kb _ name the name of the knowledge base : param searchkey search using this key : param searchvalue search using this value : param searchtype s = su...
import warnings warnings . warn ( "The function is deprecated. Please use the " "`KnwKBRVAL.query_kb_mappings()` instead. " "E.g. [(kval.m_value,) for kval in " "KnwKBRVAL.query_kb_mappings(kb_id).all()]" ) # prepare filters if searchtype == 's' : searchkey = '%' + searchkey + '%' if searchtype == 's' and searchval...
def get_body ( self , msg ) : """Extracts and returns the decoded body from an EmailMessage object"""
body = "" charset = "" if msg . is_multipart ( ) : for part in msg . walk ( ) : ctype = part . get_content_type ( ) cdispo = str ( part . get ( 'Content-Disposition' ) ) # skip any text / plain ( txt ) attachments if ctype == 'text/plain' and 'attachment' not in cdispo : ...
def flush ( bank , key = None ) : '''Remove the key from the cache bank with all the key content .'''
_init_client ( ) query = "DELETE FROM {0} WHERE bank='{1}'" . format ( _table_name , bank ) if key is not None : query += " AND etcd_key='{0}'" . format ( key ) cur , _ = run_query ( client , query ) cur . close ( )
def _view_removed ( self ) : """View packages before removed"""
print ( "\nPackages with name matching [ {0}{1}{2} ]\n" . format ( self . meta . color [ "CYAN" ] , ", " . join ( self . binary ) , self . meta . color [ "ENDC" ] ) ) removed , packages = self . _get_removed ( ) if packages and "--checklist" in self . extra : removed = [ ] text = "Press 'spacebar' to unchoose p...
def reset ( self ) : """Reset the clustering to the original clustering . All changes are lost ."""
self . _undo_stack . clear ( ) self . _spike_clusters = self . _spike_clusters_base self . _new_cluster_id = self . _new_cluster_id_0
def make_association ( self , record ) : """contstruct the association : param record : : return : modeled association of genotype to mammalian ? ? ? phenotype"""
# prep record # remove description and mapp Experiment Type to apo term experiment_type = record [ 'Experiment Type' ] . split ( '(' ) [ 0 ] experiment_type = experiment_type . split ( ',' ) record [ 'experiment_type' ] = list ( ) for exp_type in experiment_type : exp_type = exp_type . lstrip ( ) . rstrip ( ) r...
def update_models ( new_obj , current_table , tables , relations ) : """Update the state of the parsing ."""
_update_check_inputs ( current_table , tables , relations ) _check_no_current_table ( new_obj , current_table ) if isinstance ( new_obj , Table ) : tables_names = [ t . name for t in tables ] _check_not_creating_duplicates ( new_obj . name , tables_names , 'table' , DuplicateTableException ) return new_obj ...
def circuit_to_latex ( circ : Circuit , qubits : Qubits = None , document : bool = True ) -> str : """Create an image of a quantum circuit in LaTeX . Can currently draw X , Y , Z , H , T , S , T _ H , S _ H , RX , RY , RZ , TX , TY , TZ , TH , CNOT , CZ , SWAP , ISWAP , CCNOT , CSWAP , XX , YY , ZZ , CAN , P0 a...
if qubits is None : qubits = circ . qubits N = len ( qubits ) qubit_idx = dict ( zip ( qubits , range ( N ) ) ) layers = _display_layers ( circ , qubits ) layer_code = [ ] code = [ r'\lstick{' + str ( q ) + r'}' for q in qubits ] layer_code . append ( code ) def _two_qubit_gate ( top , bot , label ) : if bot - ...
def redshift ( distance , ** kwargs ) : r"""Returns the redshift associated with the given luminosity distance . If the requested cosmology is one of the pre - defined ones in : py : attr : ` astropy . cosmology . parameters . available ` , : py : class : ` DistToZ ` is used to provide a fast interpolation . ...
cosmology = get_cosmology ( ** kwargs ) try : z = _d2zs [ cosmology . name ] ( distance ) except KeyError : # not a standard cosmology , call the redshift function z = _redshift ( distance , cosmology = cosmology ) return z
def delete_container_instance_group ( access_token , subscription_id , resource_group , container_group_name ) : '''Delete a container group from a resource group . Args : access _ token ( str ) : A valid Azure authentication token . subscription _ id ( str ) : Azure subscription id . resource _ group ( str...
endpoint = '' . join ( [ get_rm_endpoint ( ) , '/subscriptions/' , subscription_id , '/resourcegroups/' , resource_group , '/providers/Microsoft.ContainerInstance/ContainerGroups/' , container_group_name , '?api-version=' , CONTAINER_API ] ) return do_delete ( endpoint , access_token )
def _preprocess_add_items ( self , items ) : """Split the items into two lists of path strings and BaseEntries ."""
paths = [ ] entries = [ ] for item in items : if isinstance ( item , string_types ) : paths . append ( self . _to_relative_path ( item ) ) elif isinstance ( item , ( Blob , Submodule ) ) : entries . append ( BaseIndexEntry . from_blob ( item ) ) elif isinstance ( item , BaseIndexEntry ) : ...
def get_version ( full = False ) : """Returns a string - ified version number . Optionally accepts a ` ` full ` ` parameter , which if ` ` True ` ` , will include any pre - release information . ( Default : ` ` False ` ` )"""
version = '.' . join ( [ str ( bit ) for bit in __version__ [ : 3 ] ] ) if full : version = '-' . join ( [ version ] + list ( __version__ [ 3 : ] ) ) return version