signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def get_direct_command ( self , command_url ) : """Send raw command via get"""
self . logger . info ( "get_direct_command: %s" , command_url ) req = requests . get ( command_url , timeout = self . timeout , auth = requests . auth . HTTPBasicAuth ( self . username , self . password ) ) self . http_code = req . status_code req . raise_for_status ( ) return req
def openQuickSettingsSettings ( self ) : '''Opens the Quick Settings shade and then tries to open Settings from there .'''
STATUS_BAR_SETTINGS_SETTINGS_BUTTON = [ u"Settings" , u"Cài đặt" , u"Instellingen" , u"Կարգավորումներ" , u"设置" , u"Nastavitve" , u"සැකසීම්" , u"Ayarlar" , u"Setelan" , u"Настройки" , u"تنظیمات" , u"Mga Setting" , u"Тохиргоо" , u"Configuració" , u"Setări" , u"Налады" , u"Einstellungen" , u"პარამეტრები" , u"सेटिङहरू" , u...
def create ( self , domain_name , partner_id = None ) : """Register a domain you control with netki as a Gem - managed domain . Note : After registering a domain , unless you have already set up its DNSSEC / DS Records , you ' ll need to do so : http : / / docs . netki . apiary . io The information required w...
params = dict ( domain_name = domain_name ) if partner_id : params [ 'partner_id' ] = partner_id domain = self . wrap ( self . resource . create ( params ) ) self . add ( domain ) return domain
def future_raise ( self , tp , value = None , tb = None ) : """raise _ implementation from future . utils"""
if value is not None and isinstance ( tp , Exception ) : raise TypeError ( "instance exception may not have a separate value" ) if value is not None : exc = tp ( value ) else : exc = tp if exc . __traceback__ is not tb : raise exc . with_traceback ( tb ) raise exc
def parse ( yaml , validate = True ) : """Parse the given YAML data into a ` Config ` object , optionally validating it first . : param yaml : YAML data ( either a string , a stream , or pre - parsed Python dict / list ) : type yaml : list | dict | str | file : param validate : Whether to validate the data be...
data = read_yaml ( yaml ) if validate : # pragma : no branch from . validation import validate validate ( data , raise_exc = True ) return Config . parse ( data )
def get_dictionary ( self ) : """Returns the list of parameters and a dictionary of values ( good for writing to a databox header ! ) Return format is sorted _ keys , dictionary"""
# output k = list ( ) d = dict ( ) # loop over the root items for i in range ( self . _widget . topLevelItemCount ( ) ) : # grab the parameter item , and start building the name x = self . _widget . topLevelItem ( i ) . param # now start the recursive loop self . _get_parameter_dictionary ( '' , d , k , x )...
def freeze_variables ( stop_gradient = True , skip_collection = False ) : """Return a context to freeze variables , by wrapping ` ` tf . get _ variable ` ` with a custom getter . It works by either applying ` ` tf . stop _ gradient ` ` on the variables , or by keeping them out of the ` ` TRAINABLE _ VARIABLES...
def custom_getter ( getter , * args , ** kwargs ) : trainable = kwargs . get ( 'trainable' , True ) name = args [ 0 ] if len ( args ) else kwargs . get ( 'name' ) if skip_collection : kwargs [ 'trainable' ] = False v = getter ( * args , ** kwargs ) if skip_collection : tf . add_to_co...
def add_indicators ( self , indicators = list ( ) , private = False , tags = list ( ) ) : """Add indicators to the remote instance ."""
if len ( indicators ) == 0 : raise Exception ( "No indicators were identified." ) self . logger . debug ( "Checking {} indicators" . format ( len ( indicators ) ) ) cleaned = clean_indicators ( indicators ) self . logger . debug ( "Cleaned {} indicators" . format ( len ( cleaned ) ) ) whitelisted = check_whitelist ...
def cache_last_modified ( request , * argz , ** kwz ) : '''Last modification date for a cached page . Intended for usage in conditional views ( @ condition decorator ) .'''
response , site , cachekey = kwz . get ( '_view_data' ) or initview ( request ) if not response : return None return response [ 1 ]
def iterGet ( self , objectType , * args , ** coolArgs ) : """Same as get . But retuns the elements one by one , much more efficient for large outputs"""
for e in self . _makeLoadQuery ( objectType , * args , ** coolArgs ) . iterRun ( ) : if issubclass ( objectType , pyGenoRabaObjectWrapper ) : yield objectType ( wrapped_object_and_bag = ( e , self . bagKey ) ) else : yield e
def SetStorageProfiler ( self , storage_profiler ) : """Sets the storage profiler . Args : storage _ profiler ( StorageProfiler ) : storage profiler ."""
self . _storage_profiler = storage_profiler if self . _storage_file : self . _storage_file . SetStorageProfiler ( storage_profiler )
def set_contents_from_filename ( self , filename , headers = None , replace = True , cb = None , num_cb = 10 , policy = None , md5 = None , reduced_redundancy = False , encrypt_key = False ) : """Store an object in S3 using the name of the Key object as the key in S3 and the contents of the file named by ' filena...
fp = open ( filename , 'rb' ) self . set_contents_from_file ( fp , headers , replace , cb , num_cb , policy , md5 , reduced_redundancy , encrypt_key = encrypt_key ) fp . close ( )
def _save_file ( self , data , path ) : """Save an file to the specified path . : param data : binary data of the file : param path : path to save the file to"""
with open ( path , 'wb' ) as tfile : for chunk in data : tfile . write ( chunk )
def ShlexSplit ( string ) : """A wrapper for ` shlex . split ` that works with unicode objects . Args : string : A unicode string to split . Returns : A list of unicode strings representing parts of the input string ."""
precondition . AssertType ( string , Text ) if PY2 : string = string . encode ( "utf-8" ) parts = shlex . split ( string ) if PY2 : # TODO ( hanuszczak ) : https : / / github . com / google / pytype / issues / 127 # pytype : disable = attribute - error parts = [ part . decode ( "utf-8" ) for part in parts ] ...
def EMAIL_REQUIRED ( self ) : """The user is required to hand over an e - mail address when signing up"""
from allauth . account import app_settings as account_settings return self . _setting ( "EMAIL_REQUIRED" , account_settings . EMAIL_REQUIRED )
def query_by_slug ( slug ) : '''查询全部章节'''
cat_rec = MCategory . get_by_slug ( slug ) if cat_rec : cat_id = cat_rec . uid else : return None if cat_id . endswith ( '00' ) : cat_con = TabPost2Tag . par_id == cat_id else : cat_con = TabPost2Tag . tag_id == cat_id recs = TabPost . select ( ) . join ( TabPost2Tag , on = ( TabPost . uid == TabPost2Ta...
def emoticons_filter ( content , exclude = '' , autoescape = None ) : """Filter for rendering emoticons ."""
esc = autoescape and conditional_escape or ( lambda x : x ) content = mark_safe ( replace_emoticons ( esc ( content ) , exclude ) ) return content
def setSpeedFactor ( self , typeID , factor ) : """setSpeedFactor ( string , double ) - > None"""
self . _connection . _sendDoubleCmd ( tc . CMD_SET_VEHICLETYPE_VARIABLE , tc . VAR_SPEED_FACTOR , typeID , factor )
def do_create ( self , line ) : "create { tablename } [ - c rc , wc ] { hkey } [ : { type } { rkey } : { type } ]"
args = self . getargs ( line ) rc = wc = 5 name = args . pop ( 0 ) # tablename if args [ 0 ] == "-c" : # capacity args . pop ( 0 ) # skyp - c capacity = args . pop ( 0 ) . strip ( ) rc , _ , wc = capacity . partition ( "," ) rc = int ( rc ) wc = int ( wc ) if wc != "" else rc schema = [ ] hkey ,...
def new_from_list ( cls , content , fill_title = True , ** kwargs ) : """Populates the Table with a list of tuples of strings . Args : content ( list ) : list of tuples of strings . Each tuple is a row . fill _ title ( bool ) : if true , the first tuple in the list will be set as title"""
obj = cls ( ** kwargs ) obj . append_from_list ( content , fill_title ) return obj
def dynamic_content_item_variant_delete ( self , item_id , id , ** kwargs ) : "https : / / developer . zendesk . com / rest _ api / docs / core / dynamic _ content # delete - variant"
api_path = "/api/v2/dynamic_content/items/{item_id}/variants/{id}.json" api_path = api_path . format ( item_id = item_id , id = id ) return self . call ( api_path , method = "DELETE" , ** kwargs )
def deserialize_footer ( stream , verifier = None ) : """Deserializes a footer . : param stream : Source data stream : type stream : io . BytesIO : param verifier : Signature verifier object ( optional ) : type verifier : aws _ encryption _ sdk . internal . crypto . Verifier : returns : Deserialized foote...
_LOGGER . debug ( "Starting footer deserialization" ) signature = b"" if verifier is None : return MessageFooter ( signature = signature ) try : ( sig_len , ) = unpack_values ( ">H" , stream ) ( signature , ) = unpack_values ( ">{sig_len}s" . format ( sig_len = sig_len ) , stream ) except SerializationError...
def docCopyNodeList ( self , doc ) : """Do a recursive copy of the node list ."""
if doc is None : doc__o = None else : doc__o = doc . _o ret = libxml2mod . xmlDocCopyNodeList ( doc__o , self . _o ) if ret is None : raise treeError ( 'xmlDocCopyNodeList() failed' ) __tmp = xmlNode ( _obj = ret ) return __tmp
def topics_in ( self , d , topn = 5 ) : """List the top ` ` topn ` ` topics in document ` ` d ` ` ."""
return self . theta . features [ d ] . top ( topn )
def build_request ( headers : Headers ) -> str : """Build a handshake request to send to the server . Return the ` ` key ` ` which must be passed to : func : ` check _ response ` ."""
raw_key = bytes ( random . getrandbits ( 8 ) for _ in range ( 16 ) ) key = base64 . b64encode ( raw_key ) . decode ( ) headers [ "Upgrade" ] = "websocket" headers [ "Connection" ] = "Upgrade" headers [ "Sec-WebSocket-Key" ] = key headers [ "Sec-WebSocket-Version" ] = "13" return key
def _callbackPlaceFillOrders ( self , d ) : """This method distringuishes notifications caused by Matched orders from those caused by placed orders"""
if isinstance ( d , FilledOrder ) : self . onOrderMatched ( d ) elif isinstance ( d , Order ) : self . onOrderPlaced ( d ) elif isinstance ( d , UpdateCallOrder ) : self . onUpdateCallOrder ( d ) else : pass
def _open_all_rings ( self ) : """Having already generated all unique fragments that did not require ring opening , now we want to also obtain fragments that do require opening . We achieve this by looping through all unique fragments and opening each bond present in any ring we find . We also temporarily add...
self . unique_fragments . insert ( 0 , self . mol_graph ) for fragment in self . unique_fragments : ring_edges = fragment . find_rings ( ) if ring_edges != [ ] : for bond in ring_edges [ 0 ] : new_fragment = open_ring ( fragment , [ bond ] , self . opt_steps ) found = False ...
def format_name ( self , name , indent_size = 4 ) : """Format the name of this verifier The name will be formatted as : < name > : < short description > long description if one is given followed by \n otherwise no long description Args : name ( string ) : A name for this validator indent _ size ( int ...
name_block = '' if self . short_desc is None : name_block += name + '\n' else : name_block += name + ': ' + self . short_desc + '\n' if self . long_desc is not None : name_block += self . wrap_lines ( self . long_desc , 1 , indent_size = indent_size ) name_block += '\n' return name_block
def restore ( file_name , jail = None , chroot = None , root = None ) : '''Reads archive created by pkg backup - d and recreates the database . CLI Example : . . code - block : : bash salt ' * ' pkg . restore / tmp / pkg jail Restore database to the specified jail . Note that this will run the command w...
return __salt__ [ 'cmd.run' ] ( _pkg ( jail , chroot , root ) + [ 'backup' , '-r' , file_name ] , output_loglevel = 'trace' , python_shell = False )
def delete ( self ) : """Delete this cluster . For example : . . literalinclude : : snippets . py : start - after : [ START bigtable _ delete _ cluster ] : end - before : [ END bigtable _ delete _ cluster ] Marks a cluster and all of its tables for permanent deletion in 7 days . Immediately upon complet...
client = self . _instance . _client client . instance_admin_client . delete_cluster ( self . name )
def get_subject ( self , lang = None ) : """Get the subject of the object : param lang : Lang to retrieve : return : Subject string representation : rtype : Literal"""
return self . metadata . get_single ( key = DC . subject , lang = lang )
def plot ( self , minx = - 1.5 , maxx = 1.2 , miny = - 0.2 , maxy = 2 , ** kwargs ) : """Helper function to plot the Muller potential"""
import matplotlib . pyplot as pp grid_width = max ( maxx - minx , maxy - miny ) / 200.0 ax = kwargs . pop ( 'ax' , None ) xx , yy = np . mgrid [ minx : maxx : grid_width , miny : maxy : grid_width ] V = self . potential ( xx , yy ) # clip off any values greater than 200 , since they mess up # the color scheme if ax is ...
def upload_segmentation_image ( self , mapobject_type_name , plate_name , well_name , well_pos_y , well_pos_x , tpoint , zplane , image ) : '''Uploads a segmentation image . Parameters mapobject _ type _ name : str name of the segmented objects plate _ name : str name of the plate well _ name : str na...
if not isinstance ( image , np . ndarray ) : raise TypeError ( 'Image must be provided in form of a numpy array.' ) if image . dtype != np . int32 : raise ValueError ( 'Image must have 32-bit integer data type.' ) self . _upload_segmentation_image ( mapobject_type_name , plate_name , well_name , well_pos_y , we...
def frombase ( path1 , path2 ) : # type : ( Text , Text ) - > Text """Get the final path of ` ` path2 ` ` that isn ' t in ` ` path1 ` ` . Arguments : path1 ( str ) : A PyFilesytem path . path2 ( str ) : A PyFilesytem path . Returns : str : the final part of ` ` path2 ` ` . Example : > > > frombase ( '...
if not isparent ( path1 , path2 ) : raise ValueError ( "path1 must be a prefix of path2" ) return path2 [ len ( path1 ) : ]
def flush ( self , timeout = None ) : """Invoking this method makes all buffered records immediately available to send ( even if linger _ ms is greater than 0 ) and blocks on the completion of the requests associated with these records . The post - condition of : meth : ` ~ kafka . KafkaProducer . flush ` is ...
log . debug ( "Flushing accumulated records in producer." ) # trace self . _accumulator . begin_flush ( ) self . _sender . wakeup ( ) self . _accumulator . await_flush_completion ( timeout = timeout )
def get_cidr_name ( cidr , ip_ranges_files , ip_ranges_name_key ) : """Read display name for CIDRs from ip - ranges files : param cidr : : param ip _ ranges _ files : : param ip _ ranges _ name _ key : : return :"""
for filename in ip_ranges_files : ip_ranges = read_ip_ranges ( filename , local_file = True ) for ip_range in ip_ranges : ip_prefix = netaddr . IPNetwork ( ip_range [ 'ip_prefix' ] ) cidr = netaddr . IPNetwork ( cidr ) if cidr in ip_prefix : return ip_range [ ip_ranges_name_k...
def _add_model ( self , model_list_or_dict , core_element , model_class , model_key = None , load_meta_data = True ) : """Adds one model for a given core element . The method will add a model for a given core object and checks if there is a corresponding model object in the future expected model list . The meth...
found_model = self . _get_future_expected_model ( core_element ) if found_model : found_model . parent = self if model_class is IncomeModel : self . income = found_model if found_model else IncomeModel ( core_element , self ) return if model_key is None : model_list_or_dict . append ( found_model if fou...
def update_args ( self , override_args ) : """Update the arguments used to invoke the application Note that this will also update the dictionary of input and output files Parameters override _ args : dict dictionary of arguments to override the current values"""
self . args = extract_arguments ( override_args , self . args ) self . _job_configs = self . build_job_configs ( self . args ) if not self . _scatter_link . jobs : self . _build_job_dict ( ) self . _latch_file_info ( )
def fnd_unq_rws ( A , return_index = False , return_inverse = False ) : """Find unique rows in 2D array . Parameters A : 2d numpy array Array for which unique rows should be identified . return _ index : bool Bool to decide whether I is returned . return _ inverse : bool Bool to decide whether J is re...
A = np . require ( A , requirements = 'C' ) assert A . ndim == 2 , "array must be 2-dim'l" B = np . unique ( A . view ( [ ( '' , A . dtype ) ] * A . shape [ 1 ] ) , return_index = return_index , return_inverse = return_inverse ) if return_index or return_inverse : return ( B [ 0 ] . view ( A . dtype ) . reshape ( (...
def create_basic_op_node ( op_name , node , kwargs ) : """Helper function to create a basic operator node that doesn ' t contain op specific attrs"""
name , input_nodes , _ = get_inputs ( node , kwargs ) node = onnx . helper . make_node ( op_name , input_nodes , [ name ] , name = name ) return [ node ]
def p_node_expression ( self , t ) : '''node _ expression : IDENT'''
if len ( t ) < 3 : t [ 0 ] = t [ 1 ] # print ( t [ 1] self . accu . add ( Term ( 'vertex' , [ "gen(\"" + t [ 1 ] + "\")" ] ) ) else : t [ 0 ] = "unknown"
def _add_default_options ( self ) -> None : """Add default command line options to the parser ."""
# Updating the trust stores update_stores_group = OptionGroup ( self . _parser , 'Trust stores options' , '' ) update_stores_group . add_option ( '--update_trust_stores' , help = 'Update the default trust stores used by SSLyze. The latest stores will be downloaded from ' 'https://github.com/nabla-c0d3/trust_stores_obse...
def _load_json_config ( self ) : """Load the configuration file in JSON format : rtype : dict"""
try : return json . loads ( self . _read_config ( ) ) except ValueError as error : raise ValueError ( 'Could not read configuration file: {}' . format ( error ) )
def replace_apply_state ( meta_graph , state_ops , feed_map ) : """Replaces state ops with non state Placeholder ops for the apply graph ."""
for node in meta_graph . graph_def . node : keys_to_purge = [ ] tensor_name = node . name + ":0" # Verify that the node is a state op and that its due to be rewired # in the feedmap . if node . op in state_ops and tensor_name in feed_map : node . op = "Placeholder" for key in node . ...
def setup_logging ( ** kwargs ) : # type : ( Any ) - > None """Setup logging configuration Args : * * kwargs : See below logging _ config _ dict ( dict ) : Logging configuration dictionary OR logging _ config _ json ( str ) : Path to JSON Logging configuration OR logging _ config _ yaml ( str ) : Path to ...
smtp_config_found = False smtp_config_dict = kwargs . get ( 'smtp_config_dict' , None ) if smtp_config_dict : smtp_config_found = True print ( 'Loading smtp configuration customisations from dictionary' ) smtp_config_json = kwargs . get ( 'smtp_config_json' , '' ) if smtp_config_json : if smtp_config_found ...
def saveWallet ( self , wallet , fpath ) : """Save wallet into specified localtion . Returns the canonical path for the ` ` fpath ` ` where ` ` wallet ` ` has been stored . Error cases : - ` ` fpath ` ` is not inside the keyrings base dir - ValueError raised - directory part of ` ` fpath ` ` exists and it...
if not fpath : raise ValueError ( "empty path" ) _fpath = self . _normalize ( fpath ) _dpath = _fpath . parent try : _dpath . relative_to ( self . _baseDir ) except ValueError : raise ValueError ( "path {} is not is not relative to the keyrings {}" . format ( fpath , self . _baseDir ) ) self . _createDirIfN...
def show_hydrophobic ( self ) : """Visualizes hydrophobic contacts ."""
hydroph = self . plcomplex . hydrophobic_contacts if not len ( hydroph . bs_ids ) == 0 : self . select_by_ids ( 'Hydrophobic-P' , hydroph . bs_ids , restrict = self . protname ) self . select_by_ids ( 'Hydrophobic-L' , hydroph . lig_ids , restrict = self . ligname ) for i in hydroph . pairs_ids : cm...
def send_document ( url , data , timeout = 10 , * args , ** kwargs ) : """Helper method to send a document via POST . Additional ` ` * args ` ` and ` ` * * kwargs ` ` will be passed on to ` ` requests . post ` ` . : arg url : Full url to send to , including protocol : arg data : Dictionary ( will be form - en...
logger . debug ( "send_document: url=%s, data=%s, timeout=%s" , url , data , timeout ) headers = CaseInsensitiveDict ( { 'User-Agent' : USER_AGENT , } ) if "headers" in kwargs : # Update from kwargs headers . update ( kwargs . get ( "headers" ) ) kwargs . update ( { "data" : data , "timeout" : timeout , "headers" :...
def sign_with_privkey ( digest : bytes , privkey : Ed25519PrivateKey , global_pubkey : Ed25519PublicPoint , nonce : int , global_commit : Ed25519PublicPoint , ) -> Ed25519Signature : """Create a CoSi signature of ` digest ` with the supplied private key . This function needs to know the global public key and glob...
h = _ed25519 . H ( privkey ) a = _ed25519 . decodecoord ( h ) S = ( nonce + _ed25519 . Hint ( global_commit + global_pubkey + digest ) * a ) % _ed25519 . l return Ed25519Signature ( _ed25519 . encodeint ( S ) )
def mouseMoveEvent ( self , event ) : """Determines if a drag is taking place , and initiates it"""
super ( AbstractDragView , self ) . mouseMoveEvent ( event ) if self . dragStartPosition is None or ( event . pos ( ) - self . dragStartPosition ) . manhattanLength ( ) < QtGui . QApplication . startDragDistance ( ) : # change cursor to reflect actions for what its hovering on index = self . indexAt ( event . pos (...
def do_mumble ( self , args ) : """Mumbles what you tell me to ."""
repetitions = args . repeat or 1 for i in range ( min ( repetitions , self . maxrepeats ) ) : output = [ ] if random . random ( ) < .33 : output . append ( random . choice ( self . MUMBLE_FIRST ) ) for word in args . words : if random . random ( ) < .40 : output . append ( random...
def load ( self , callback = None , errback = None , reload = False ) : """Load record data from the API ."""
if not reload and self . data : raise RecordException ( 'record already loaded' ) def success ( result , * args ) : self . _parseModel ( result ) if callback : return callback ( self ) else : return self return self . _rest . retrieve ( self . parentZone . zone , self . domain , self . t...
def get_setupcfg_version ( ) : """As get _ setup _ version ( ) , but configure via setup . cfg . If your project uses setup . cfg to configure setuptools , and hence has at least a " name " key in the [ metadata ] section , you can set the version as follows : [ metadata ] name = mypackage version = att...
try : import configparser except ImportError : import ConfigParser as configparser # python2 ( also prevents dict - like access ) import re cfg = "setup.cfg" autover_section = 'tool:autover' config = configparser . ConfigParser ( ) config . read ( cfg ) pkgname = config . get ( 'metadata' , 'name' ) reponam...
def _temp_filename ( contents ) : """Make a temporary file with ` contents ` . The file will be cleaned up on exit ."""
fp = tempfile . NamedTemporaryFile ( prefix = 'codequalitytmp' , delete = False ) name = fp . name fp . write ( contents ) fp . close ( ) _files_to_cleanup . append ( name ) return name
def _init_equiv ( self ) : """Add equivalent GO IDs to go2color , if necessary ."""
gocolored_all = set ( self . go2color ) go2obj_usr = self . gosubdag . go2obj go2color_add = { } for gocolored_cur , color in self . go2color . items ( ) : # Ignore GOs in go2color that are not in the user set if gocolored_cur in go2obj_usr : goobj = go2obj_usr [ gocolored_cur ] goids_equiv = goobj ...
def _create_matrix ( self , document , dictionary ) : """Creates matrix of shape | unique words | × | sentences | where cells contains number of occurences of words ( rows ) in senteces ( cols ) ."""
sentences = document . sentences words_count = len ( dictionary ) sentences_count = len ( sentences ) if words_count < sentences_count : message = ( "Number of words (%d) is lower than number of sentences (%d). " "LSA algorithm may not work properly." ) warn ( message % ( words_count , sentences_count ) ) # cre...
def num_samples ( self , sr = None ) : """Return the number of samples . Args : sr ( int ) : Calculate the number of samples with the given sampling - rate . If None use the native sampling - rate . Returns : int : Number of samples"""
native_sr = self . sampling_rate num_samples = units . seconds_to_sample ( self . duration , native_sr ) if sr is not None : ratio = float ( sr ) / native_sr num_samples = int ( np . ceil ( num_samples * ratio ) ) return num_samples
def element_sub_sketch ( self , keys = None ) : """Returns the sketch summary for the given set of keys . This is only applicable for sketch summary created from SArray of sarray or dict type . For dict SArray , the keys are the keys in dict value . For array Sarray , the keys are indexes into the array value...
single_val = False if keys is None : keys = [ ] else : if not isinstance ( keys , list ) : single_val = True keys = [ keys ] value_types = set ( [ type ( i ) for i in keys ] ) if ( len ( value_types ) > 1 ) : raise ValueError ( "All keys should have the same type." ) with cython_...
def fill_A ( A , right_eigenvectors ) : """Construct feasible initial guess for transformation matrix A . Parameters A : ndarray Possibly non - feasible transformation matrix . right _ eigenvectors : ndarray Right eigenvectors of transition matrix Returns A : ndarray Feasible transformation matrix ....
num_micro , num_eigen = right_eigenvectors . shape A = A . copy ( ) # compute 1st column of A by row sum condition A [ 1 : , 0 ] = - 1 * A [ 1 : , 1 : ] . sum ( 1 ) # compute 1st row of A by maximum condition A [ 0 ] = - 1 * dot ( right_eigenvectors [ : , 1 : ] . real , A [ 1 : ] ) . min ( 0 ) # rescale A to be in the ...
def import_util ( imp ) : '''Lazily imports a utils ( class , function , or variable ) from a module ) from a string . @ param imp :'''
mod_name , obj_name = imp . rsplit ( '.' , 1 ) mod = importlib . import_module ( mod_name ) return getattr ( mod , obj_name )
def summarize_mutation_io ( name , type , required = False ) : """This function returns the standard summary for mutations inputs and outputs"""
return dict ( name = name , type = type , required = required )
def add_child ( self , parent , title = "" , level = "" , start_date = "" , end_date = "" , date_expression = "" , notes = [ ] , ) : """Adds a new resource component parented within ` parent ` . : param str parent : The ID to a resource or a resource component . : param str title : A title for the record . : ...
parent_record = self . get_record ( parent ) record_type = self . resource_type ( parent ) repository = parent_record [ "repository" ] [ "ref" ] if record_type == "resource" : resource = parent else : resource = parent_record [ "resource" ] [ "ref" ] new_object = { "title" : title , "level" : level , "jsonmodel...
def is_promisc ( ip , fake_bcast = "ff:ff:00:00:00:00" , ** kargs ) : """Try to guess if target is in Promisc mode . The target is provided by its ip ."""
# noqa : E501 responses = srp1 ( Ether ( dst = fake_bcast ) / ARP ( op = "who-has" , pdst = ip ) , type = ETH_P_ARP , iface_hint = ip , timeout = 1 , verbose = 0 , ** kargs ) # noqa : E501 return responses is not None
def deploy ( self , target , overwrite = False ) : '''deploy this contract : param target : : param account : the account address to use : return : address , err'''
name = self . name . replace ( '<stdin>:' , "" ) key = DB . pkey ( [ EZO . DEPLOYED , name , target , self . hash ] ) if not target : return None , "target network must be set with -t or --target" password = os . environ [ 'EZO_PASSWORD' ] if 'EZO_PASSWORD' in os . environ else None # see if a deployment already ex...
def GetLocation ( session = None ) : """Return specified location or if none the default location associated with the provided credentials and alias . > > > clc . v2 . Account . GetLocation ( ) u ' WA1'"""
if session is not None : return session [ 'location' ] if not clc . LOCATION : clc . v2 . API . _Login ( ) return ( clc . LOCATION )
def faces_to_edges ( faces , return_index = False ) : """Given a list of faces ( n , 3 ) , return a list of edges ( n * 3,2) Parameters faces : ( n , 3 ) int Vertex indices representing faces Returns edges : ( n * 3 , 2 ) int Vertex indices representing edges"""
faces = np . asanyarray ( faces ) # each face has three edges edges = faces [ : , [ 0 , 1 , 1 , 2 , 2 , 0 ] ] . reshape ( ( - 1 , 2 ) ) if return_index : # edges are in order of faces due to reshape face_index = np . tile ( np . arange ( len ( faces ) ) , ( 3 , 1 ) ) . T . reshape ( - 1 ) return edges , face_in...
def _close_generator ( g ) : """PyPy 3 generator has a bug that calling ` close ` caused memory leak . Before it is fixed , use ` throw ` instead"""
if isinstance ( g , generatorwrapper ) : g . close ( ) elif _get_frame ( g ) is not None : try : g . throw ( GeneratorExit_ ) except ( StopIteration , GeneratorExit_ ) : return else : raise RuntimeError ( "coroutine ignored GeneratorExit" )
def absent ( name , ip ) : # pylint : disable = C0103 '''Ensure that the named host is absent name The host to remove ip The ip addr ( s ) of the host to remove'''
ret = { 'name' : name , 'changes' : { } , 'result' : None , 'comment' : '' } if not isinstance ( ip , list ) : ip = [ ip ] comments = [ ] for _ip in ip : if not __salt__ [ 'hosts.has_pair' ] ( _ip , name ) : ret [ 'result' ] = True comments . append ( 'Host {0} ({1}) already absent' . format ( n...
def get_python ( cls ) : """returns the python and pip version : return : python version , pip version"""
python_version = sys . version_info [ : 3 ] v_string = [ str ( i ) for i in python_version ] python_version_s = '.' . join ( v_string ) # pip _ version = pip . _ _ version _ _ pip_version = Shell . pip ( "--version" ) . split ( ) [ 1 ] return python_version_s , pip_version
def _process_dimension_kwargs ( direction , kwargs ) : """process kwargs for AxDimension instances by stripping off the prefix for the appropriate direction"""
acceptable_keys = [ 'unit' , 'pad' , 'lim' , 'label' ] # if direction in [ ' s ' ] : # acceptable _ keys + = [ ' mode ' ] processed_kwargs = { } for k , v in kwargs . items ( ) : if k . startswith ( direction ) : processed_key = k . lstrip ( direction ) else : processed_key = k if processed_...
def is_unitless ( ds , variable ) : '''Returns true if the variable is unitless Note units of ' 1 ' are considered whole numbers or parts but still represent physical units and not the absence of units . : param netCDF4 . Dataset ds : An open netCDF dataset : param str variable : Name of the variable'''
units = getattr ( ds . variables [ variable ] , 'units' , None ) return units is None or units == ''
def set_ghost_file ( self , ghost_file ) : """Sets ghost RAM file : ghost _ file : path to ghost file"""
yield from self . _hypervisor . send ( 'vm set_ghost_file "{name}" {ghost_file}' . format ( name = self . _name , ghost_file = shlex . quote ( ghost_file ) ) ) log . info ( 'Router "{name}" [{id}]: ghost file set to {ghost_file}' . format ( name = self . _name , id = self . _id , ghost_file = ghost_file ) ) self . _gho...
def _set_port ( self , v , load = False ) : """Setter method for port , mapped from YANG variable / system _ monitor / port ( container ) If this variable is read - only ( config : false ) in the source YANG file , then _ set _ port is considered as a private method . Backends looking to populate this variabl...
if hasattr ( v , "_utype" ) : v = v . _utype ( v ) try : t = YANGDynClass ( v , base = port . port , is_container = 'container' , presence = True , yang_name = "port" , rest_name = "port" , parent = self , path_helper = self . _path_helper , extmethods = self . _extmethods , register_paths = True , extensions =...
def load_checkpoint ( prefix , epoch ) : """Load model checkpoint from file . Parameters prefix : str Prefix of model name . epoch : int Epoch number of model we would like to load . Returns symbol : Symbol The symbol configuration of computation network . arg _ params : dict of str to NDArray M...
symbol = sym . load ( '%s-symbol.json' % prefix ) save_dict = nd . load ( '%s-%04d.params' % ( prefix , epoch ) ) arg_params = { } aux_params = { } for k , v in save_dict . items ( ) : tp , name = k . split ( ':' , 1 ) if tp == 'arg' : arg_params [ name ] = v if tp == 'aux' : aux_params [ na...
def run_powerflow_onthefly ( components , components_data , grid , export_pypsa_dir = None , debug = False ) : """Run powerflow to test grid stability Two cases are defined to be tested here : i ) load case ii ) feed - in case Parameters components : dict of pandas . DataFrame components _ data : dict o...
scenario = cfg_ding0 . get ( "powerflow" , "test_grid_stability_scenario" ) start_hour = cfg_ding0 . get ( "powerflow" , "start_hour" ) end_hour = cfg_ding0 . get ( "powerflow" , "end_hour" ) # choose temp _ id temp_id_set = 1 timesteps = 2 start_time = datetime ( 1970 , 1 , 1 , 00 , 00 , 0 ) resolution = 'H' # inspect...
def add ( self , model ) : """Add a index method . This method is used to add index algorithms . If multiple algorithms are added , the union of the record pairs from the algorithm is taken . Parameters model : list , class A ( list of ) index algorithm ( s ) from : mod : ` recordlinkage . index ` ."""
if isinstance ( model , list ) : self . algorithms = self . algorithms + model else : self . algorithms . append ( model )
def use_trump_data ( self , symbols ) : """Use trump data to build conversion table symbols : list of symbols : will attempt to use units to build the conversion table , strings represent symbol names ."""
dfs = { sym . units : sym . df [ sym . name ] for sym in symbols } self . build_conversion_table ( dfs )
def match_path ( entry , opts ) : """Return True if ` path ` matches ` match ` and ` exclude ` options ."""
if entry . name in ALWAYS_OMIT : return False # TODO : currently we use fnmatch syntax and match against names . # We also might allow glob syntax and match against the whole relative path instead # path = entry . get _ rel _ path ( ) path = entry . name ok = True match = opts . get ( "match" ) exclude = opts . get...
def concrete_descendents ( parentclass ) : """Return a dictionary containing all subclasses of the specified parentclass , including the parentclass . Only classes that are defined in scripts that have been run or modules that have been imported are included , so the caller will usually first do ` ` from pa...
return dict ( ( c . __name__ , c ) for c in descendents ( parentclass ) if not _is_abstract ( c ) )
def parse ( requirements ) : """Parses given requirements line - by - line ."""
transformer = RTransformer ( ) return map ( transformer . transform , filter ( None , map ( _parse , requirements . splitlines ( ) ) ) )
def txt ( self , txt , h = None , at_x = None , to_x = None , change_style = None , change_size = None ) : """print string to defined ( at _ x ) position to _ x can apply only if at _ x is None and if used then forces align = ' R '"""
h = h or self . height self . _change_props ( change_style , change_size ) align = 'L' w = None if at_x is None : if to_x is not None : align = 'R' self . oPdf . set_x ( 0 ) w = to_x else : self . oPdf . set_x ( at_x ) if w is None : w = self . oPdf . get_string_width ( txt ) self . ...
def setParams ( self , estimator = None , estimatorParamMaps = None , evaluator = None , trainRatio = 0.75 , parallelism = 1 , collectSubModels = False , seed = None ) : """setParams ( self , estimator = None , estimatorParamMaps = None , evaluator = None , trainRatio = 0.75 , parallelism = 1 , collectSubModels = F...
kwargs = self . _input_kwargs return self . _set ( ** kwargs )
def to_json ( self ) : """Returns the JSON representation of the space membership ."""
result = super ( SpaceMembership , self ) . to_json ( ) result . update ( { 'admin' : self . admin , 'roles' : self . roles } ) return result
def is_installed ( self ) : """Check if the tool is installed . Returns is _ installed : bool True if the tool is installed ."""
return self . is_configured ( ) and os . access ( self . bin ( ) , os . X_OK )
def import_locations ( self , gpx_file ) : """Import GPX data files . ` ` import _ locations ( ) ` ` returns a list with : class : ` ~ gpx . Waypoint ` objects . It expects data files in GPX format , as specified in ` GPX 1.1 Schema Documentation ` _ , which is XML such as : : < ? xml version = " 1.0 " en...
self . _gpx_file = gpx_file data = utils . prepare_xml_read ( gpx_file , objectify = True ) try : self . metadata . import_metadata ( data . metadata ) except AttributeError : pass for waypoint in data . wpt : latitude = waypoint . get ( 'lat' ) longitude = waypoint . get ( 'lon' ) try : nam...
def avail_locations ( call = None ) : '''returns a list of locations available to you'''
creds = get_creds ( ) clc . v1 . SetCredentials ( creds [ "token" ] , creds [ "token_pass" ] ) locations = clc . v1 . Account . GetLocations ( ) return locations
def maybe_download ( directory , filename , uri ) : """Download filename from uri unless it ' s already in directory . Copies a remote file to local if that local file does not already exist . If the local file pre - exists this function call , it does not check that the local file is a copy of the remote . ...
tf . gfile . MakeDirs ( directory ) filepath = os . path . join ( directory , filename ) if tf . gfile . Exists ( filepath ) : tf . logging . info ( "Not downloading, file already found: %s" % filepath ) return filepath tf . logging . info ( "Downloading %s to %s" % ( uri , filepath ) ) try : tf . gfile . C...
def cudnnCreatePoolingDescriptor ( ) : """Create pooling descriptor . This function creates a pooling descriptor object by allocating the memory needed to hold its opaque structure , Returns poolingDesc : cudnnPoolingDescriptor Newly allocated pooling descriptor ."""
poolingDesc = ctypes . c_void_p ( ) status = _libcudnn . cudnnCreatePoolingDescriptor ( ctypes . byref ( poolingDesc ) ) cudnnCheckStatus ( status ) return poolingDesc . value
def write_cell ( self , x , y , value ) : """Writing value in the cell of x + 1 and y + 1 position : param x : line index : param y : coll index : param value : value to be written : return :"""
x += 1 y += 1 self . _sheet . update_cell ( x , y , value )
def get_timesheet_collection_for_context ( ctx , entries_file = None ) : """Return a : class : ` ~ taxi . timesheet . TimesheetCollection ` object with the current timesheet ( s ) . Since this depends on the settings ( to get the entries files path , the number of previous files , etc ) this uses the settings obj...
if not entries_file : entries_file = ctx . obj [ 'settings' ] . get_entries_file_path ( False ) parser = TimesheetParser ( date_format = ctx . obj [ 'settings' ] [ 'date_format' ] , add_date_to_bottom = ctx . obj [ 'settings' ] . get_add_to_bottom ( ) , flags_repr = ctx . obj [ 'settings' ] . get_flags ( ) , ) retu...
def update_pass ( user_id , newpass ) : '''Update the password of a user .'''
out_dic = { 'success' : False , 'code' : '00' } entry = TabMember . update ( user_pass = tools . md5 ( newpass ) ) . where ( TabMember . uid == user_id ) entry . execute ( ) out_dic [ 'success' ] = True return out_dic
def prevSolarReturn ( date , lon ) : """Returns the previous date when sun is at longitude ' lon ' ."""
jd = eph . prevSolarReturn ( date . jd , lon ) return Datetime . fromJD ( jd , date . utcoffset )
def subscribe ( self , stream ) : """Subscribe to a stream . : param stream : stream to subscribe to : type stream : str : raises : : class : ` ~ datasift . exceptions . StreamSubscriberNotStarted ` , : class : ` ~ datasift . exceptions . DeleteRequired ` , : class : ` ~ datasift . exceptions . StreamNotConne...
if not self . _stream_process_started : raise StreamSubscriberNotStarted ( ) def real_decorator ( func ) : if not self . _on_delete : raise DeleteRequired ( """An on_delete function is required. You must process delete messages and remove them from your system (if stored) in order to re...
def get_error_page ( self , loadbalancer ) : """Load Balancers all have a default error page that is shown to an end user who is attempting to access a load balancer node that is offline / unavailable ."""
uri = "/loadbalancers/%s/errorpage" % utils . get_id ( loadbalancer ) resp , body = self . api . method_get ( uri ) return body
def getDate ( self ) : "returns the GMT response datetime or None"
date = self . headers . get ( 'date' ) if date : date = self . convertTimeString ( date ) return date
def convert_dms_to_dd ( degree_num , degree_den , minute_num , minute_den , second_num , second_den ) : """Convert the degree / minute / Second formatted GPS data to decimal degrees . @ param degree _ num : the numerator of the degree object . @ param degree _ den : the denominator of the degree object . @ ...
degree = float ( degree_num ) / float ( degree_den ) minute = float ( minute_num ) / float ( minute_den ) / 60 second = float ( second_num ) / float ( second_den ) / 3600 return degree + minute + second
def args_priority ( args , environ ) : '''priority of token 1 ) as argumment : - t 2 ) as environ variable priority of as _ user 1 ) as argument : - a 2 ) as environ variable'''
arg_token = args . token arg_as_user = args . as_user slack_token_var_name = 'SLACK_TOKEN' if slack_token_var_name in environ . keys ( ) : token = environ [ slack_token_var_name ] else : token = None if arg_token : token = arg_token # slack as _ user slack_as_user_var_name = 'SLACK_AS_USER' as_user = bool (...
def ask_for_confirm_with_message ( cls , ui , prompt = 'Do you agree?' , message = '' , ** options ) : """Returns True if user agrees , False otherwise"""
return cls . get_appropriate_helper ( ui ) . ask_for_confirm_with_message ( prompt , message )
def fetcher_with_object ( cls , parent_object , relationship = "child" ) : """Register the fetcher for a served object . This method will fill the fetcher with ` managed _ class ` instances Args : parent _ object : the instance of the parent object to serve Returns : It returns the fetcher instance ."""
fetcher = cls ( ) fetcher . parent_object = parent_object fetcher . relationship = relationship rest_name = cls . managed_object_rest_name ( ) parent_object . register_fetcher ( fetcher , rest_name ) return fetcher
def ra ( self , * args , ** kwargs ) : """NAME : ra PURPOSE : return the right ascension INPUT : t - ( optional ) time at which to get ra ( can be Quantity ) obs = [ X , Y , Z ] - ( optional ) position of observer ( in kpc ; entries can be Quantity ) ( default = [ 8.0,0 . , 0 . ] ) OR Orbit object tha...
out = self . _orb . ra ( * args , ** kwargs ) if len ( out ) == 1 : return out [ 0 ] else : return out