signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def hypergeometric_like ( x , n , m , N ) : r"""Hypergeometric log - likelihood . Discrete probability distribution that describes the number of successes in a sequence of draws from a finite population without replacement . . . math : : f ( x \ mid n , m , N ) = \ frac { \ left ( { \ begin { array } { c } ...
return flib . hyperg ( x , n , m , N )
def is_user ( value , min = None , max = None ) : """Check whether username or uid as argument exists . if this function recieved username , convert uid and exec validation ."""
if type ( value ) == str : try : entry = pwd . getpwnam ( value ) value = entry . pw_uid except KeyError : err_message = ( '{0}: No such user.' . format ( value ) ) raise validate . VdtValueError ( err_message ) return value elif type ( value ) == int : try : pwd ...
def fetch_data ( self , stock_no , nowdatetime ) : """Fetch data from gretai . org . tw ( OTC ) return list . 從 gretai . org . tw 下載資料 , 回傳格式為 csv . reader 0 . 日期 1 . 成交股數 2 . 成交金額 3 . 開盤價 4 . 最高價 ( 續 ) 5 . 最低價 6 . 收盤價 7 . 漲跌價差 8 . 成交筆數 : param str stock _ no : 股票代碼 : param datetime nowdat...
url = ( '/ch/stock/aftertrading/' + 'daily_trading_info/st43_download.php?d=%(year)d/%(mon)02d&' + 'stkno=%(stock)s&r=%(rand)s' ) % { 'year' : nowdatetime . year - 1911 , 'mon' : nowdatetime . month , 'stock' : stock_no , 'rand' : random . randrange ( 1 , 1000000 ) } logging . info ( url ) result = GRETAI_CONNECTIONS ....
def replicate_no_merge ( source , model , cache = None ) : '''Replicates the ` source ` object to ` model ` class and returns its reflection .'''
# ` cache ` is used to break circular dependency : we need to replicate # attributes before merging target into the session , but replication of # some attributes may require target to be in session to avoid infinite # loop . if source is None : return None if cache is None : cache = { } elif source in cache : ...
def _compute_style_of_faulting_term ( self , rup , C ) : """Computes the coefficient to scale for reverse or strike - slip events Fault type ( Strike - slip , Normal , Thrust / reverse ) is derived from rake angle . Rakes angles within 30 of horizontal are strike - slip , angles from 30 to 150 are reverse ,...
if np . abs ( rup . rake ) <= 30.0 or ( 180.0 - np . abs ( rup . rake ) ) <= 30.0 : # strike - slip return C [ 'B1ss' ] elif rup . rake > 30.0 and rup . rake < 150.0 : # reverse return C [ 'B1rv' ] else : # unspecified ( also includes Normal faulting ! ) return C [ 'B1all' ]
def variable_names ( self ) : """Get all variable names required for this query"""
if self . _variable_names is None : if self . _operator is None : if self . _operands is None : self . _variable_names = tuple ( ) else : self . _variable_names = self . _get_variable_names ( self . _operands ) elif self . _operator == 'NOT' : self . _variable_nam...
def update ( self ) : "Updates cartesian coordinates for drawing tree graph"
# get new shape and clear for attrs self . edges = np . zeros ( ( self . ttree . nnodes - 1 , 2 ) , dtype = int ) self . verts = np . zeros ( ( self . ttree . nnodes , 2 ) , dtype = float ) self . lines = [ ] self . coords = [ ] # fill with updates self . update_idxs ( ) # get dimensions of tree self . update_fixed_ord...
def normalized_hypergraph_cut ( H , threshold = 0 ) : """Executes the min - cut algorithm described in the paper : Zhou , Dengyong , Jiayuan Huang , and Bernhard Scholkopf . " Learning with hypergraphs : Clustering , classification , and embedding . " Advances in neural information processing systems . 2006. ...
if not isinstance ( H , UndirectedHypergraph ) : raise TypeError ( "Algorithm only applicable to undirected hypergraphs" ) # TODO : make sure that the hypergraph is connected # Get index < - > node mappings and index < - > hyperedge _ id mappings for matrices indices_to_nodes , nodes_to_indices = umat . get_node_ma...
def hamsterday_time_to_datetime ( hamsterday , time ) : """Return the civil datetime corresponding to a given hamster day and time . The hamster day start is taken into account ."""
# work around cyclic imports from hamster . lib . configuration import conf if time < conf . day_start : # early morning , between midnight and day _ start # = > the hamster day is the previous civil day civil_date = hamsterday + dt . timedelta ( days = 1 ) else : civil_date = hamsterday return dt . datetime . ...
def _get_gecos ( name ) : '''Retrieve GECOS field info and return it in dictionary form'''
try : gecos_field = pwd . getpwnam ( name ) . pw_gecos . split ( ',' , 3 ) except KeyError : raise CommandExecutionError ( 'User \'{0}\' does not exist' . format ( name ) ) if not gecos_field : return { } else : # Assign empty strings for any unspecified trailing GECOS fields while len ( gecos_field ) <...
def read_json ( self ) : """read metadata from json and set all the found properties . when overriding remember to wrap your calls in reading _ ancillary _ files : return : the read metadata : rtype : dict"""
with reading_ancillary_files ( self ) : if self . json_uri is None : metadata = self . _read_json_db ( ) else : metadata = self . _read_json_file ( ) if 'properties' in metadata : for name , prop in list ( metadata [ 'properties' ] . items ( ) ) : try : se...
def validators ( self ) : """Gets or creates validator wrapper"""
if not hasattr ( self , "_validators" ) : self . _validators = ValidatorList ( self ) return self . _validators
def get_final_version_string ( release_mode , semver , commit_count = 0 ) : """Generates update dictionary entries for the version string"""
version_string = "." . join ( semver ) maybe_dev_version_string = version_string updates = { } if release_mode : # in production , we have something like ` 1.2.3 ` , as well as a flag e . g . PRODUCTION = True updates [ Constants . RELEASE_FIELD ] = config . RELEASED_VALUE else : # in dev mode , we have a dev marke...
def create ( self , equipments ) : """Method to create equipments : param equipments : List containing equipments desired to be created on database : return : None"""
data = { 'equipments' : equipments } return super ( ApiV4Equipment , self ) . post ( 'api/v4/equipment/' , data )
def name ( self ) : """Name attribute of rule element"""
return self . _meta . name if self . _meta . name else 'Rule @%s' % self . tag
def json_template ( data , template_name , template_context ) : """Old style , use JSONTemplateResponse instead of this ."""
html = render_to_string ( template_name , template_context ) data = data or { } data [ 'html' ] = html return HttpResponse ( json_encode ( data ) , content_type = 'application/json' )
def to_backward_slashes ( data ) : """Converts forward slashes to backward slashes . Usage : : > > > to _ backward _ slashes ( " / Users / JohnDoe / Documents " ) u ' \\ Users \\ JohnDoe \\ Documents ' : param data : Data to convert . : type data : unicode : return : Converted path . : rtype : unicode...
data = data . replace ( "/" , "\\" ) LOGGER . debug ( "> Data: '{0}' to backward slashes." . format ( data ) ) return data
def detach ( self ) : """Detach from parent . @ return : This element removed from its parent ' s child list and I { parent } = I { None } @ rtype : L { Element }"""
if self . parent is not None : if self in self . parent . children : self . parent . children . remove ( self ) self . parent = None return self
def search ( query , stats ) : """Perform issue search for given stats instance"""
log . debug ( "Search query: {0}" . format ( query ) ) issues = [ ] # Fetch data from the server in batches of MAX _ RESULTS issues for batch in range ( MAX_BATCHES ) : response = stats . parent . session . get ( "{0}/rest/api/latest/search?{1}" . format ( stats . parent . url , urllib . urlencode ( { "jql" : query...
def _accept_header ( self ) : """Method for determining correct ` Accept ` header . Different resources and different GoCD version servers prefer a diverse headers . In order to manage all of them , this method tries to help : if ` VERSION _ TO _ ACCEPT _ HEADER ` is not provided , if would simply return de...
if not self . VERSION_TO_ACCEPT_HEADER : return self . ACCEPT_HEADER return YagocdUtil . choose_option ( version_to_options = self . VERSION_TO_ACCEPT_HEADER , default = self . ACCEPT_HEADER , server_version = self . _session . server_version )
def _parse_view_results ( self , rows , factory , options ) : '''rows here should be a list of tuples : - ( key , value ) for reduce views - ( key , value , id ) for nonreduce views without include docs - ( key , value , id , doc ) for nonreduce with with include docs'''
kwargs = dict ( ) kwargs [ 'reduced' ] = factory . use_reduce and options . get ( 'reduce' , True ) kwargs [ 'include_docs' ] = options . get ( 'include_docs' , False ) # Lines below pass extra arguments to the parsing function if they # are expected . These arguments are bound method unserialize ( ) and # unserialize ...
def parse ( self , data ) : """Parse a 17 bytes packet in the Wind format and return a dictionary containing the data extracted . An example of a return value would be : . . code - block : : python ' id ' : " 0x2EB2 " , ' packet _ length ' : 16, ' packet _ type ' : 86, ' packet _ type _ name ' : ' Win...
self . validate_packet ( data ) results = self . parse_header_part ( data ) sub_type = results [ 'packet_subtype' ] id_ = self . dump_hex ( data [ 4 : 6 ] ) direction = data [ 6 ] * 256 + data [ 7 ] if sub_type != 0x05 : av_speed = ( data [ 8 ] * 256 + data [ 9 ] ) * 0.1 else : av_speed = '--??--' gust = ( data...
def median ( self , func = lambda x : x ) : """Return the median value of data elements : param func : lambda expression to project and sort data : return : median value"""
if self . count ( ) == 0 : raise NoElementsError ( u"Iterable contains no elements" ) result = self . order_by ( func ) . select ( func ) . to_list ( ) length = len ( result ) i = int ( length / 2 ) return result [ i ] if length % 2 == 1 else ( float ( result [ i - 1 ] ) + float ( result [ i ] ) ) / float ( 2 )
def multi_component_layout ( data , graph , n_components , component_labels , dim , random_state , metric = "euclidean" , metric_kwds = { } , ) : """Specialised layout algorithm for dealing with graphs with many connected components . This will first fid relative positions for the components by spectrally embeddi...
result = np . empty ( ( graph . shape [ 0 ] , dim ) , dtype = np . float32 ) if n_components > 2 * dim : meta_embedding = component_layout ( data , n_components , component_labels , dim , metric = metric , metric_kwds = metric_kwds , ) else : k = int ( np . ceil ( n_components / 2.0 ) ) base = np . hstack (...
def get_reserved_bindings ( vlan_id , instance_id , switch_ip = None , port_id = None ) : """Lists reserved bindings ."""
LOG . debug ( "get_reserved_bindings() called" ) if port_id : return _lookup_all_nexus_bindings ( vlan_id = vlan_id , switch_ip = switch_ip , instance_id = instance_id , port_id = port_id ) elif switch_ip : return _lookup_all_nexus_bindings ( vlan_id = vlan_id , switch_ip = switch_ip , instance_id = instance_id...
def delete_node ( self , node_name ) : """Deletes this node and all edges referencing it . Args : node _ name ( str ) : The name of the node to delete . Raises : KeyError : Raised if the node does not exist in the graph ."""
graph = self . graph if node_name not in graph : raise KeyError ( 'node %s does not exist' % node_name ) graph . pop ( node_name ) for node , edges in graph . items ( ) : if node_name in edges : edges . remove ( node_name )
def get_nested_exceptions ( self ) : """Traverses the exception record linked list and builds a Python list . Nested exception records are received for nested exceptions . This happens when an exception is raised in the debugee while trying to handle a previous exception . @ rtype : list ( L { ExceptionEven...
# The list always begins with ourselves . # Just put a reference to " self " as the first element , # and start looping from the second exception record . nested = [ self ] raw = self . raw dwDebugEventCode = raw . dwDebugEventCode dwProcessId = raw . dwProcessId dwThreadId = raw . dwThreadId dwFirstChance = raw . u . ...
def has_preview ( self ) : """Returns if the document has real merged data . When True , ` topil ( ) ` returns pre - composed data ."""
version_info = self . image_resources . get_data ( 'version_info' ) if version_info : return version_info . has_composite return True
def list_team_codes ( ) : """List team names in alphabetical order of team ID , per league ."""
# Sort teams by league , then alphabetical by code cleanlist = sorted ( TEAM_DATA , key = lambda k : ( k [ "league" ] [ "name" ] , k [ "code" ] ) ) # Get league names leaguenames = sorted ( list ( set ( [ team [ "league" ] [ "name" ] for team in cleanlist ] ) ) ) for league in leaguenames : teams = [ team for team ...
def register_cmdfinalization_hook ( self , func : Callable [ [ plugin . CommandFinalizationData ] , plugin . CommandFinalizationData ] ) -> None : """Register a hook to be called after a command is completed , whether it completes successfully or not ."""
self . _validate_cmdfinalization_callable ( func ) self . _cmdfinalization_hooks . append ( func )
def _R2deriv ( self , R , z , phi = 0. , t = 0. ) : """NAME : _ Rderiv PURPOSE : evaluate the second radial derivative for this potential INPUT : R - Galactocentric cylindrical radius z - vertical height phi - azimuth t - time OUTPUT : the second radial derivative HISTORY : 2013-04-10 - Writ...
r = numpy . sqrt ( R ** 2. + z ** 2. ) x = r / self . a return - numpy . pi / x ** 3. / r ** 2. * ( - 4. * R ** 2. * r ** 3. / ( self . a ** 2. + r ** 2. ) / ( self . a + r ) + ( z ** 2. - 2. * R ** 2. ) * ( numpy . pi - 2. * numpy . arctan ( 1. / x ) - 2. * numpy . log ( 1. + x ) - numpy . log ( 1. + x ** 2. ) ) )
def to_event ( self ) : """get rid of id , sign , tunnel and update message type Notice : this method will return a deepcopy"""
msg = copy . deepcopy ( self ) for _ in [ "id" , "sign" , "tunnel" , "query" , "param" ] : if not hasattr ( msg , _ ) : continue delattr ( msg , _ ) msg . _type = Message . get_message_type ( msg . __dict__ ) return msg
def description ( self ) : """Grab package verion"""
for line in self . SLACKBUILDS_TXT . splitlines ( ) : if line . startswith ( self . line_name ) : sbo_name = line [ 17 : ] . strip ( ) if line . startswith ( self . line_des ) : if sbo_name == self . name : return line [ 31 : ] . strip ( )
def linkcode_resolve ( domain , info ) : """Determine the URL corresponding to Python object"""
if domain != 'py' : return None modname = info [ 'module' ] fullname = info [ 'fullname' ] submod = sys . modules . get ( modname ) if submod is None : return None obj = submod for part in fullname . split ( '.' ) : try : obj = getattr ( obj , part ) except : return None try : fn = i...
def isrc ( name = None ) : """Creates the grammar for an ISRC code . ISRC stands for International Standard Recording Code , which is the standard ISO 3901 . This stores information identifying a particular recording . : param name : name for the field : return : grammar for an ISRC field"""
if name is None : name = 'ISRC Field' field = _isrc_short ( name ) | _isrc_long ( name ) field . setName ( name ) return field . setResultsName ( 'isrc' )
def wait_for_event ( self , emptybuffer = False ) : """Waits until a joystick event becomes available . Returns the event , as an ` InputEvent ` tuple . If * emptybuffer * is ` True ` ( it defaults to ` False ` ) , any pending events will be thrown away first . This is most useful if you are only interested...
if emptybuffer : while self . _wait ( 0 ) : self . _read ( ) while self . _wait ( ) : event = self . _read ( ) if event : return event
def versional ( a , b ) : """Sorts the inputted items by their natural order , trying to extract a number from them to sort by . : param a < str > b < str > : return < int > 1 | | 0 | | - 1 : usage | > > > from projex import sorting | > > > a = [ ' test - 1.1.2 ' , ' test - 1.02 ' , ' test - 1.2 ' , ' tes...
stra = nstr ( a ) . lower ( ) strb = nstr ( b ) . lower ( ) # look up all the pairs of items aresults = EXPR_VERSIONAL . findall ( stra ) bresults = EXPR_VERSIONAL . findall ( strb ) # make sure we have the same number of results bcount = len ( bresults ) for i in range ( len ( aresults ) ) : # make sure we don ' t exc...
def trimim ( fims , affine = None , scale = 2 , divdim = 8 ** 2 , int_order = 0 , fmax = 0.05 , outpath = '' , fname = '' , fcomment = '' , store_avg = False , store_img_intrmd = False , store_img = False , imdtype = np . float32 , memlim = False , verbose = False ) : '''Trim and upsample PET image ( s ) , e . g . ...
using_multiple_files = False # case when input folder is given if isinstance ( fims , basestring ) and os . path . isdir ( fims ) : # list of input images ( e . g . , PET ) fimlist = [ os . path . join ( fims , f ) for f in os . listdir ( fims ) if f . endswith ( '.nii' ) or f . endswith ( '.nii.gz' ) ] imdic =...
def poll ( self , timeout ) : """: param float timeout : Timeout in seconds . A timeout that is less than the poll _ period will still cause a single read that may take up to poll _ period seconds ."""
now = time . time ( ) end_time = now + float ( timeout ) prev_timeout = self . stream . gettimeout ( ) self . stream . settimeout ( self . _poll_period ) incoming = None try : while ( end_time - now ) >= 0 : try : incoming = self . stream . recv ( self . _max_read ) except socket . timeo...
def box_show ( text , width = 100 , height = 3 , corner = "+" , horizontal = "-" , vertical = "|" ) : """Print a formatted ascii text box ."""
print ( StrTemplate . box ( text = text , width = width , height = height , corner = corner , horizontal = horizontal , vertical = vertical ) )
def uniquified_mesh ( self ) : """This function returns a copy of the mesh in which vertices are copied such that each vertex appears in only one face , and hence has only one texture"""
import numpy as np from lace . mesh import Mesh new_mesh = Mesh ( v = self . v [ self . f . flatten ( ) ] , f = np . array ( range ( len ( self . f . flatten ( ) ) ) ) . reshape ( - 1 , 3 ) ) if self . vn is None : self . reset_normals ( ) new_mesh . vn = self . vn [ self . f . flatten ( ) ] if self . vt is not Non...
def edit_event_view ( request , event_pk ) : '''The view to edit an event .'''
page_name = "Edit Event" profile = UserProfile . objects . get ( user = request . user ) event = get_object_or_404 ( Event , pk = event_pk ) if event . owner != profile and not request . user . is_superuser : return HttpResponseRedirect ( reverse ( 'events:view' , kwargs = { "event_pk" : event_pk } ) , ) event_form...
def get_all_tags_with_auth ( image_name , branch = None ) : """Get the tag information using authentication credentials provided by the user . : param image _ name : The image name to query : param branch : The branch to filter by : return : A list of Version instances , latest first"""
logging . debug ( 'Getting %s with authentication' % image_name ) url = '%s/%s/images' % ( API_URL , image_name ) registry_user = os . environ . get ( 'REGISTRY_USER' ) registry_pass = os . environ . get ( 'REGISTRY_PASS' ) if registry_user is None or registry_pass is None : msg = ( 'The docker image seems to be pr...
def neighbours ( self , word , size = 10 ) : """Get nearest words with KDTree , ranking by cosine distance"""
word = word . strip ( ) v = self . word_vec ( word ) [ distances ] , [ points ] = self . kdt . query ( array ( [ v ] ) , k = size , return_distance = True ) assert len ( distances ) == len ( points ) , "distances and points should be in same shape." words , scores = [ ] , { } for ( x , y ) in zip ( points , distances )...
def get_firmwares ( ) : '''Return ` dmf _ control _ board ` compiled Arduino hex file paths . This function may be used to locate firmware binaries that are available for flashing to [ Arduino Mega2560 ] [ 1 ] boards . [1 ] : http : / / arduino . cc / en / Main / arduinoBoardMega2560'''
return OrderedDict ( [ ( board_dir . name , [ f . abspath ( ) for f in board_dir . walkfiles ( '*.hex' ) ] ) for board_dir in package_path ( ) . joinpath ( 'firmware' ) . dirs ( ) ] )
def remove_file ( profile , branch , file_path , commit_message = None ) : """Remove a file from a branch . Args : profile A profile generated from ` ` simplygithub . authentication . profile ` ` . Such profiles tell this module ( i ) the ` ` repo ` ` to connect to , and ( ii ) the ` ` token ` ` to connec...
branch_sha = get_branch_sha ( profile , branch ) tree = get_files_in_branch ( profile , branch_sha ) new_tree = remove_file_from_tree ( tree , file_path ) data = trees . create_tree ( profile , new_tree ) sha = data . get ( "sha" ) if not commit_message : commit_message = "Deleted " + file_path + "." parents = [ br...
def pop ( self , count = 1 ) : """Return new deque with rightmost element removed . Popping the empty queue will return the empty queue . A optional count can be given to indicate the number of elements to pop . Popping with a negative index is the same as popleft . Executes in amortized O ( k ) where k is th...
if count < 0 : return self . popleft ( - count ) new_right_list , new_left_list = PDeque . _pop_lists ( self . _right_list , self . _left_list , count ) return PDeque ( new_left_list , new_right_list , max ( self . _length - count , 0 ) , self . _maxlen )
def load ( fp , encode_nominal = False , return_type = DENSE ) : '''Load a file - like object containing the ARFF document and convert it into a Python object . : param fp : a file - like object . : param encode _ nominal : boolean , if True perform a label encoding while reading the . arff file . : param...
decoder = ArffDecoder ( ) return decoder . decode ( fp , encode_nominal = encode_nominal , return_type = return_type )
def competition_leaderboard_download ( self , competition , path , quiet = True ) : """Download competition leaderboards Parameters competition : the name of the competition path : a path to download the file to quiet : suppress verbose output ( default is True )"""
response = self . process_response ( self . competition_download_leaderboard_with_http_info ( competition , _preload_content = False ) ) if path is None : effective_path = self . get_default_download_dir ( 'competitions' , competition ) else : effective_path = path file_name = competition + '.zip' outfile = os ...
def _GetAPFSVolumeIdentifiers ( self , scan_node ) : """Determines the APFS volume identifiers . Args : scan _ node ( dfvfs . SourceScanNode ) : scan node . Returns : list [ str ] : APFS volume identifiers . Raises : SourceScannerError : if the format of or within the source is not supported or the th...
if not scan_node or not scan_node . path_spec : raise errors . SourceScannerError ( 'Invalid scan node.' ) volume_system = apfs_volume_system . APFSVolumeSystem ( ) volume_system . Open ( scan_node . path_spec ) volume_identifiers = self . _source_scanner . GetVolumeIdentifiers ( volume_system ) if not volume_ident...
def write_basic_mesh ( Verts , E2V = None , mesh_type = 'tri' , pdata = None , pvdata = None , cdata = None , cvdata = None , fname = 'output.vtk' ) : """Write mesh file for basic types of elements . Parameters fname : { string } file to be written , e . g . ' mymesh . vtu ' Verts : { array } coordinate a...
if E2V is None : mesh_type = 'vertex' map_type_to_key = { 'vertex' : 1 , 'tri' : 5 , 'quad' : 9 , 'tet' : 10 , 'hex' : 12 } if mesh_type not in map_type_to_key : raise ValueError ( 'unknown mesh_type=%s' % mesh_type ) key = map_type_to_key [ mesh_type ] if mesh_type == 'vertex' : uidx = np . arange ( 0 , Ve...
def field ( self , name ) : '''Get the gdb . Value for the given field within the PyObject , coping with some python 2 versus python 3 differences . Various libpython types are defined using the " PyObject _ HEAD " and " PyObject _ VAR _ HEAD " macros . In Python 2 , this these are defined so that " ob _ ty...
if self . is_null ( ) : raise NullPyObjectPtr ( self ) if name == 'ob_type' : pyo_ptr = self . _gdbval . cast ( PyObjectPtr . get_gdb_type ( ) ) return pyo_ptr . dereference ( ) [ name ] if name == 'ob_size' : try : # Python 2: return self . _gdbval . dereference ( ) [ name ] except RuntimeE...
def get_stp_mst_detail_output_cist_port_port_hello_time ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) get_stp_mst_detail = ET . Element ( "get_stp_mst_detail" ) config = get_stp_mst_detail output = ET . SubElement ( get_stp_mst_detail , "output" ) cist = ET . SubElement ( output , "cist" ) port = ET . SubElement ( cist , "port" ) port_hello_time = ET . SubElement ( port , "port-hello-...
async def deactivate ( cls , access_key : str ) -> dict : '''Deactivates this keypair . Deactivated keypairs cannot make any API requests unless activated again by an administrator . You need an admin privilege for this operation .'''
q = 'mutation($access_key: String!, $input: ModifyKeyPairInput!) {' + ' modify_keypair(access_key: $access_key, props: $input) {' ' ok msg' ' }' '}' variables = { 'access_key' : access_key , 'input' : { 'is_active' : False , 'is_admin' : None , 'resource_policy' : None , 'rate_limit' : None , } , } rqst = Request ...
def _system_parameters ( ** kwargs ) : """Returns system keyword arguments removing Nones . Args : kwargs : system keyword arguments . Returns : dict : system keyword arguments ."""
return { key : value for key , value in kwargs . items ( ) if ( value is not None or value == { } ) }
def _compute_needed_metrics ( self , instance , available_metrics ) : """Compare the available metrics for one MOR we have computed and intersect them with the set of metrics we want to report"""
i_key = self . _instance_key ( instance ) if self . in_compatibility_mode ( instance ) : if instance . get ( 'all_metrics' , False ) : return available_metrics wanted_metrics = [ ] # Get only the basic metrics for counter_id in available_metrics : # No cache yet , skip it for now if not ...
def store_net_db ( self , tenant_id , net , net_dict , result ) : """Store service network in DB ."""
network_dict = { 'name' : net_dict . get ( 'name' ) , 'config_profile' : net_dict . get ( 'config_profile' ) , 'segmentation_id' : net_dict . get ( 'segmentation_id' ) , 'tenant_id' : tenant_id , 'fwd_mode' : net_dict . get ( 'fwd_mode' ) , 'vlan' : net_dict . get ( 'vlan_id' ) } self . add_network_db ( net , network_d...
def split ( self ) : """Split a Path2D into multiple Path2D objects where each one has exactly one root curve . Parameters self : trimesh . path . Path2D Input geometry Returns split : list of trimesh . path . Path2D Original geometry as separate paths"""
# avoid a circular import by referencing class of self Path2D = type ( self ) # save the results of the split to an array split = [ ] # get objects from cache to avoid a bajillion # cache checks inside the tight loop paths = self . paths discrete = self . discrete polygons_closed = self . polygons_closed enclosure_dire...
def create_app_multi_region ( regional_options , app_name , src_dir , publish = False , set_default = False , billTo = None , try_versions = None , try_update = True , confirm = True ) : """Creates a new app object from the specified applet ( s ) . : param regional _ options : Region - specific options for the ap...
return _create_app ( dict ( regionalOptions = regional_options ) , app_name , src_dir , publish = publish , set_default = set_default , billTo = billTo , try_versions = try_versions , try_update = try_update , confirm = confirm )
def composition ( mol ) : """Molecular composition in dict format ( ex . Glucose { ' C ' : 6 , ' H ' : 12 , ' O ' : 6 } ) ."""
mol . require ( "Valence" ) c = Counter ( ) for _ , a in mol . atoms_iter ( ) : c += a . composition ( ) return c
def category_filter ( self , category_filter ) : """Sets the category _ filter of this AzureActivityLogConfiguration . A list of Azure ActivityLog categories to pull events for . Allowable values are ADMINISTRATIVE , SERVICEHEALTH , ALERT , AUTOSCALE , SECURITY # noqa : E501 : param category _ filter : The cate...
allowed_values = [ "ADMINISTRATIVE" , "SERVICEHEALTH" , "ALERT" , "AUTOSCALE" , "SECURITY" ] # noqa : E501 if not set ( category_filter ) . issubset ( set ( allowed_values ) ) : raise ValueError ( "Invalid values for `category_filter` [{0}], must be a subset of [{1}]" # noqa : E501 . format ( ", " . join ( map ...
def __parse ( value ) : """Parse the string date . Supports the subset of ISO8601 used by xsd : date , but is lenient with what is accepted , handling most reasonable syntax . Any timezone is parsed but ignored because a ) it is meaningless without a time and b ) B { datetime } . I { date } does not support...
match_result = _RE_DATE . match ( value ) if match_result is None : raise ValueError ( "date data has invalid format '%s'" % ( value , ) ) return _date_from_match ( match_result )
def create ( self , name , data ) : """Create a Job Binary Internal . : param str data : raw data of script text"""
return self . _update ( '/job-binary-internals/%s' % urlparse . quote ( name . encode ( 'utf-8' ) ) , data , 'job_binary_internal' , dump_json = False )
def begin ( self ) : """Start taking temperature measurements . Returns True if the device is intialized , False otherwise ."""
# Check manufacturer and device ID match expected values . mid = self . _device . readU16BE ( MCP9808_REG_MANUF_ID ) did = self . _device . readU16BE ( MCP9808_REG_DEVICE_ID ) self . _logger . debug ( 'Read manufacturer ID: {0:04X}' . format ( mid ) ) self . _logger . debug ( 'Read device ID: {0:04X}' . format ( did ) ...
def DeleteHuntObject ( self , hunt_id , cursor = None ) : """Deletes a given hunt object ."""
query = "DELETE FROM hunts WHERE hunt_id = %s" hunt_id_int = db_utils . HuntIDToInt ( hunt_id ) rows_deleted = cursor . execute ( query , [ hunt_id_int ] ) if rows_deleted == 0 : raise db . UnknownHuntError ( hunt_id ) query = "DELETE FROM hunt_output_plugins_states WHERE hunt_id = %s" cursor . execute ( query , [ ...
def orthogonalization_matrix ( lengths , angles ) : """Return orthogonalization matrix for crystallographic cell coordinates . Angles are expected in degrees . The de - orthogonalization matrix is the inverse . > > > O = orthogonalization _ matrix ( [ 10 , 10 , 10 ] , [ 90 , 90 , 90 ] ) > > > numpy . allclo...
a , b , c = lengths angles = numpy . radians ( angles ) sina , sinb , _ = numpy . sin ( angles ) cosa , cosb , cosg = numpy . cos ( angles ) co = ( cosa * cosb - cosg ) / ( sina * sinb ) return numpy . array ( [ [ a * sinb * math . sqrt ( 1.0 - co * co ) , 0.0 , 0.0 , 0.0 ] , [ - a * sinb * co , b * sina , 0.0 , 0.0 ] ...
def _subs_tree ( cls , tvars = None , args = None ) : """An internal helper function : calculate substitution tree for generic cls after replacing its type parameters with substitutions in tvars - > args ( if any ) . Repeat the same following _ _ origin _ _ ' s . Return a list of arguments with all possible...
if cls . __origin__ is None : return cls # Make of chain of origins ( i . e . cls - > cls . _ _ origin _ _ ) current = cls . __origin__ orig_chain = [ ] while current . __origin__ is not None : orig_chain . append ( current ) current = current . __origin__ # Replace type variables in _ _ args _ _ if asked ....
def _parse_features ( features , new_names ) : """Takes a collection of features structured in a various ways and parses them into one way . If input format is not recognized it raises an error . : return : A collection of features : rtype : collections . OrderedDict ( FeatureType : collections . OrderedDict ...
if isinstance ( features , dict ) : return FeatureParser . _parse_dict ( features , new_names ) if isinstance ( features , list ) : return FeatureParser . _parse_list ( features , new_names ) if isinstance ( features , tuple ) : return FeatureParser . _parse_tuple ( features , new_names ) if features is ......
def get_errors ( audit_results ) : """Args : audit _ results : results of ` AxeCoreAudit . do _ audit ( ) ` . Returns : A dictionary with keys " errors " and " total " ."""
errors = { "errors" : [ ] , "total" : 0 } if audit_results : errors [ "errors" ] . extend ( audit_results ) for i in audit_results : for _node in i [ "nodes" ] : errors [ "total" ] += 1 return errors
def initialize ( cls ) : """Initialize Axes logging and show version information . This method is re - entrant and can be called multiple times . It displays version information exactly once at application startup ."""
if cls . logging_initialized : return cls . logging_initialized = True if not settings . AXES_VERBOSE : return log . info ( 'AXES: BEGIN LOG' ) log . info ( 'AXES: Using django-axes %s' , get_version ( ) ) if settings . AXES_ONLY_USER_FAILURES : log . info ( 'AXES: blocking by username only.' ) elif setting...
def add_provider ( self , cls : Type [ BaseProvider ] ) -> None : """Add a custom provider to Generic ( ) object . : param cls : Custom provider . : return : None : raises TypeError : if cls is not class ."""
if inspect . isclass ( cls ) : if not issubclass ( cls , BaseProvider ) : raise TypeError ( 'The provider must be a ' 'subclass of BaseProvider' ) try : meta = getattr ( cls , 'Meta' ) name = getattr ( meta , 'name' ) except AttributeError : name = cls . __name__ . lower ( ) ...
def verify_exif ( filename ) : '''Check that image file has the required EXIF fields . Incompatible files will be ignored server side .'''
# required tags in IFD name convention required_exif = required_fields ( ) exif = ExifRead ( filename ) required_exif_exist = exif . fields_exist ( required_exif ) return required_exif_exist
def get_reduced_symbols ( symbols ) : """Reduces expanded list of symbols . Args : symbols : list containing any chemical symbols as often as the atom appears in the structure Returns : reduced _ symbols : any symbols appears only once"""
reduced_symbols = [ ] for ss in symbols : if not ( ss in reduced_symbols ) : reduced_symbols . append ( ss ) return reduced_symbols
def to_posix_path ( code_path ) : """Change the code _ path to be of unix - style if running on windows when supplied with an absolute windows path . Parameters code _ path : str Directory in the host operating system that should be mounted within the container . Returns str Posix equivalent of absolute...
return re . sub ( "^([A-Za-z])+:" , lambda match : posixpath . sep + match . group ( ) . replace ( ":" , "" ) . lower ( ) , pathlib . PureWindowsPath ( code_path ) . as_posix ( ) ) if os . name == "nt" else code_path
def get_next_step ( self ) : """Find the proper step when user clicks the Next button . : returns : The step to be switched to : rtype : WizardStep instance or None"""
if self . rbAggLayerFromCanvas . isChecked ( ) : new_step = self . parent . step_fc_agglayer_from_canvas elif self . rbAggLayerFromBrowser . isChecked ( ) : new_step = self . parent . step_fc_agglayer_from_browser else : new_step = self . parent . step_fc_summary return new_step
def to_json ( self ) : """Writes the complete Morse - Smale merge hierarchy to a string object . @ Out , a string object storing the entire merge hierarchy of all minima and maxima ."""
capsule = { } capsule [ "Hierarchy" ] = [ ] for ( dying , ( persistence , surviving , saddle ) , ) in self . merge_sequence . items ( ) : capsule [ "Hierarchy" ] . append ( { "Dying" : dying , "Persistence" : persistence , "Surviving" : surviving , "Saddle" : saddle , } ) capsule [ "Partitions" ] = [ ] base = np . ...
def build_all ( self , verbose = False , hide_base_schemas = True , hide_implicit_types = True , hide_implicit_preds = True ) : """Extract all ontology entities from an RDF graph and construct Python representations of them ."""
if verbose : printDebug ( "Scanning entities..." , "green" ) printDebug ( "----------" , "comment" ) self . build_ontologies ( ) if verbose : printDebug ( "Ontologies.........: %d" % len ( self . all_ontologies ) , "comment" ) self . build_classes ( hide_base_schemas , hide_implicit_types ) if verbose : ...
def __analizar_errores ( self , ret ) : "Comprueba y extrae errores si existen en la respuesta XML"
if 'arrayErrores' in ret : errores = ret [ 'arrayErrores' ] or [ ] self . Errores = [ err [ 'error' ] for err in errores ] self . ErrCode = ' ' . join ( self . Errores ) self . ErrMsg = '\n' . join ( self . Errores )
def delete ( self ) : """Delete this NIC . Authorization requirements : * Object - access permission to the Partition containing this HBA . * Task permission to the " Partition Details " task . Raises : : exc : ` ~ zhmcclient . HTTPError ` : exc : ` ~ zhmcclient . ParseError ` : exc : ` ~ zhmcclient ....
self . manager . session . delete ( self . _uri ) self . manager . _name_uri_cache . delete ( self . properties . get ( self . manager . _name_prop , None ) )
def calculate_sleep_time ( attempt , delay_factor = 5.0 , randomization_factor = .5 , max_delay = 120 ) : """Calculate the sleep time between retries , in seconds . Based off of ` taskcluster . utils . calculateSleepTime ` , but with kwargs instead of constant ` delay _ factor ` / ` randomization _ factor ` / `...
if attempt <= 0 : return 0 # We subtract one to get exponents : 1 , 2 , 3 , 4 , 5 , . . delay = float ( 2 ** ( attempt - 1 ) ) * float ( delay_factor ) # Apply randomization factor . Only increase the delay here . delay = delay * ( randomization_factor * random . random ( ) + 1 ) # Always limit with a maximum delay...
def start ( self ) : '''Starts ( Subscribes ) the client .'''
self . sub = rospy . Subscriber ( self . topic , BumperEvent , self . __callback )
def siblings_after ( self ) : """: return : a list of this node ' s siblings that occur * after * this node in the DOM ."""
impl_nodelist = self . adapter . get_node_children ( self . parent . impl_node ) after_nodelist = [ ] is_after_myself = False for n in impl_nodelist : if is_after_myself : after_nodelist . append ( n ) elif n == self . impl_node : is_after_myself = True return self . _convert_nodelist ( after_no...
def GET ( self ) : """Checks if user is authenticated and calls POST _ AUTH or performs login and calls GET _ AUTH . Otherwise , returns the login template ."""
data = self . user_manager . session_lti_info ( ) if data is None : raise web . notfound ( ) try : course = self . course_factory . get_course ( data [ "task" ] [ 0 ] ) if data [ "consumer_key" ] not in course . lti_keys ( ) . keys ( ) : raise Exception ( ) except : return self . template_helper...
def print_row ( self , row , rstrip = True ) : """Format and print the pre - rendered data to the output device ."""
line = '' . join ( map ( str , row ) ) print ( line . rstrip ( ) if rstrip else line , file = self . table . file )
def del_hparam ( self , name ) : """Removes the hyperparameter with key ' name ' . Does nothing if it isn ' t present . Args : name : Name of the hyperparameter ."""
if hasattr ( self , name ) : delattr ( self , name ) del self . _hparam_types [ name ]
def brunt_vaisala_period ( heights , potential_temperature , axis = 0 ) : r"""Calculate the Brunt - Vaisala period . This function is a helper function for ` brunt _ vaisala _ frequency ` that calculates the period of oscilation as in Exercise 3.13 of [ Hobbs2006 ] _ : . . math : : \ tau = \ frac { 2 \ pi } {...
bv_freq_squared = brunt_vaisala_frequency_squared ( heights , potential_temperature , axis = axis ) bv_freq_squared [ bv_freq_squared . magnitude <= 0 ] = np . nan return 2 * np . pi / np . sqrt ( bv_freq_squared )
def attachmethod ( target ) : '''Reference : https : / / blog . tonyseek . com / post / open - class - in - python / class Spam ( object ) : pass @ attach _ method ( Spam ) def egg1 ( self , name ) : print ( ( self , name ) ) spam1 = Spam ( ) # OpenClass 加入的方法 egg1 可用 spam1 . egg1 ( " Test1 " ) # ...
if isinstance ( target , type ) : def decorator ( func ) : setattr ( target , func . __name__ , func ) else : def decorator ( func ) : setattr ( target , func . __name__ , partial ( func , target ) ) return decorator
def add_dataset ( data_type , val , unit_id = None , metadata = { } , name = "" , user_id = None , flush = False ) : """Data can exist without scenarios . This is the mechanism whereby single pieces of data can be added without doing it through a scenario . A typical use of this would be for setting default val...
d = Dataset ( ) d . type = data_type d . value = val d . set_metadata ( metadata ) d . unit_id = unit_id d . name = name d . created_by = user_id d . hash = d . set_hash ( ) try : existing_dataset = db . DBSession . query ( Dataset ) . filter ( Dataset . hash == d . hash ) . one ( ) if existing_dataset . check_...
def _augment ( self ) : """Finds a minimum cost path and adds it to the matching"""
# build a minimum cost tree _pred , _ready , istar , j , mu = self . _build_tree ( ) # update prices self . _v [ _ready ] += self . _d [ _ready ] - mu # augment the solution with the minimum cost path from the # tree . Follows an alternating path along matched , unmatched # edges from X to Y while True : i = _pred ...
def seed ( self ) : """Seed new initial values for the stochastics ."""
for generation in self . generations : for s in generation : try : if s . rseed is not None : value = s . random ( ** s . parents . value ) except : pass
def replace_store_profile_by_id ( cls , store_profile_id , store_profile , ** kwargs ) : """Replace StoreProfile Replace all attributes of StoreProfile This method makes a synchronous HTTP request by default . To make an asynchronous HTTP request , please pass async = True > > > thread = api . replace _ sto...
kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'async' ) : return cls . _replace_store_profile_by_id_with_http_info ( store_profile_id , store_profile , ** kwargs ) else : ( data ) = cls . _replace_store_profile_by_id_with_http_info ( store_profile_id , store_profile , ** kwargs ) return data
def get_device_by_ain ( self , ain ) : """Returns a device specified by the AIN ."""
devices = self . get_devices ( ) for device in devices : if device . ain == ain : return device
def crpix ( self ) : """The location of the reference coordinate in the pixel frame . First simple respond with the header values , if they don ' t exist try usnig the DETSEC values @ rtype : float , float"""
try : return self . wcs . crpix1 , self . wcs . crpix2 except Exception as ex : logging . debug ( "Couldn't get CRPIX from WCS: {}" . format ( ex ) ) logging . debug ( "Switching to use DATASEC for CRPIX value computation." ) try : ( x1 , x2 ) , ( y1 , y2 ) = util . get_pixel_bounds_from_datasec_keyword...
def get_job_log_url ( self , project , ** params ) : """Gets job log url , filtered by parameters : param project : project ( repository name ) to query data for : param params : keyword arguments to filter results"""
return self . _get_json ( self . JOB_LOG_URL_ENDPOINT , project , ** params )
def _Pcn_zm_crp ( x , dsz , Nv , dimN = 2 , dimC = 1 ) : """Projection onto dictionary update constraint set : support projection , mean subtraction , and normalisation . The result is cropped to the support of the largest filter in the dictionary . Parameters x : array _ like Input array dsz : tuple ...
return normalise ( zeromean ( bcrop ( x , dsz , dimN ) , dsz , dimN ) , dimN + dimC )
def parse_numbering ( document , xmlcontent ) : """Parse numbering document . Numbering is defined in file ' numbering . xml ' ."""
numbering = etree . fromstring ( xmlcontent ) document . abstruct_numbering = { } document . numbering = { } for abstruct_num in numbering . xpath ( './/w:abstractNum' , namespaces = NAMESPACES ) : numb = { } for lvl in abstruct_num . xpath ( './w:lvl' , namespaces = NAMESPACES ) : ilvl = int ( lvl . at...
def com_daltonmaag_check_required_fields ( ufo_font ) : """Check that required fields are present in the UFO fontinfo . ufo2ft requires these info fields to compile a font binary : unitsPerEm , ascender , descender , xHeight , capHeight and familyName ."""
recommended_fields = [ ] for field in [ "unitsPerEm" , "ascender" , "descender" , "xHeight" , "capHeight" , "familyName" ] : if ufo_font . info . __dict__ . get ( "_" + field ) is None : recommended_fields . append ( field ) if recommended_fields : yield FAIL , f"Required field(s) missing: {recommended_...
def cmd_cm ( self , nm = None , ch = None ) : """cm nm = color _ map _ name ch = chname Set a color map ( name ` nm ` ) for the given channel . If no value is given , reports the current color map ."""
viewer = self . get_viewer ( ch ) if viewer is None : self . log ( "No current viewer/channel." ) return if nm is None : rgbmap = viewer . get_rgbmap ( ) cmap = rgbmap . get_cmap ( ) self . log ( cmap . name ) else : viewer . set_color_map ( nm )
def tenant_present ( name , description = None , enabled = True , profile = None , ** connection_args ) : '''Ensures that the keystone tenant exists name The name of the tenant to manage description The description to use for this tenant enabled Availability state for this tenant'''
ret = { 'name' : name , 'changes' : { } , 'result' : True , 'comment' : 'Tenant / project "{0}" already exists' . format ( name ) } _api_version ( profile = profile , ** connection_args ) # Check if tenant is already present tenant = __salt__ [ 'keystone.tenant_get' ] ( name = name , profile = profile , ** connection_a...
def type ( self , name : str ) : """return the first complete definition of type ' name '"""
for f in self . body : if ( hasattr ( f , '_ctype' ) and f . _ctype . _storage == Storages . TYPEDEF and f . _name == name ) : return f