signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def memoize ( f ) :
"""Memoization decorator for a function taking one or more arguments .""" | def _c ( * args , ** kwargs ) :
if not hasattr ( f , 'cache' ) :
f . cache = dict ( )
key = ( args , tuple ( kwargs ) )
if key not in f . cache :
f . cache [ key ] = f ( * args , ** kwargs )
return f . cache [ key ]
return wraps ( f ) ( _c ) |
def _convert_xml_to_queue_messages ( response , decode_function ) :
'''< ? xml version = " 1.0 " encoding = " utf - 8 " ? >
< QueueMessagesList >
< QueueMessage >
< MessageId > string - message - id < / MessageId >
< InsertionTime > insertion - time < / InsertionTime >
< ExpirationTime > expiration - time... | if response is None or response . body is None :
return response
messages = list ( )
list_element = ETree . fromstring ( response . body )
for message_element in list_element . findall ( 'QueueMessage' ) :
message = QueueMessage ( )
message . id = message_element . findtext ( 'MessageId' )
message . deq... |
def codemirror_field_js_bundle ( field ) :
"""Filter to get CodeMirror Javascript bundle name needed for a single field .
Example :
{ % load djangocodemirror _ tags % }
{ { form . myfield | codemirror _ field _ js _ bundle } }
Arguments :
field ( django . forms . fields . Field ) : A form field that conta... | manifesto = CodemirrorAssetTagRender ( )
manifesto . register_from_fields ( field )
try :
bundle_name = manifesto . js_bundle_names ( ) [ 0 ]
except IndexError :
msg = ( "Given field with configuration name '{}' does not have a " "Javascript bundle name" )
raise CodeMirrorFieldBundleError ( msg . format ( f... |
def change_volume ( self , increment ) :
"""调整音量大小""" | if increment == 1 :
self . volume += 5
else :
self . volume -= 5
self . volume = max ( min ( self . volume , 100 ) , 0 ) |
def remove_entity_tags ( self ) :
'''Returns
A new TermDocumentMatrix consisting of only terms in the current TermDocumentMatrix
that aren ' t spaCy entity tags .
Note : Used if entity types are censored using FeatsFromSpacyDoc ( tag _ types _ to _ censor = . . . ) .''' | terms_to_remove = [ term for term in self . _term_idx_store . _i2val if any ( [ word in SPACY_ENTITY_TAGS for word in term . split ( ) ] ) ]
return self . remove_terms ( terms_to_remove ) |
def _ObjectFactory ( obj ) :
"""Parse a python ` ` { name : schema } ` ` dict as an : py : class : ` Object ` instance .
- A property name prepended by " + " is required
- A property name prepended by " ? " is optional
- Any other property is required if : py : attr : ` Object . REQUIRED _ PROPERTIES `
is T... | if isinstance ( obj , dict ) :
optional , required = { } , { }
for key , value in iteritems ( obj ) :
if key . startswith ( "+" ) :
required [ key [ 1 : ] ] = value
elif key . startswith ( "?" ) :
optional [ key [ 1 : ] ] = value
elif Object . REQUIRED_PROPERTIES ... |
def explain_image ( self , labels , instance , column_name = None , num_features = 100000 , num_samples = 300 , batch_size = 200 , hide_color = 0 ) :
"""Explain an image of a prediction .
It analyze the prediction by LIME , and returns a report of which words are most impactful
in contributing to certain labels... | from lime . lime_image import LimeImageExplainer
if len ( self . _image_columns ) > 1 and not column_name :
raise ValueError ( 'There are multiple image columns in the input of the model. ' + 'Please specify "column_name".' )
elif column_name and column_name not in self . _image_columns :
raise ValueError ( 'Sp... |
def destroy ( self , si , logger , session , vcenter_data_model , vm_uuid , vm_name , reservation_id ) :
""": param si :
: param logger :
: param CloudShellAPISession session :
: param vcenter _ data _ model :
: param vm _ uuid :
: param str vm _ name : This is the resource name
: param reservation _ id... | # disconnect
self . _disconnect_all_my_connectors ( session = session , resource_name = vm_name , reservation_id = reservation_id , logger = logger )
# find vm
vm = self . pv_service . find_by_uuid ( si , vm_uuid )
if vm is not None : # destroy vm
result = self . pv_service . destroy_vm ( vm = vm , logger = logger ... |
def get_family_query_session ( self , proxy = None ) :
"""Gets the ` ` OsidSession ` ` associated with the family query service .
arg : proxy ( osid . proxy . Proxy ) : a proxy
return : ( osid . relationship . FamilyQuerySession ) - a
` ` FamilyQuerySession ` `
raise : NullArgument - ` ` proxy ` ` is ` ` nu... | if not self . supports_family_query ( ) :
raise Unimplemented ( )
try :
from . import sessions
except ImportError :
raise OperationFailed ( )
proxy = self . _convert_proxy ( proxy )
try :
session = sessions . FamilyQuerySession ( proxy = proxy , runtime = self . _runtime )
except AttributeError :
ra... |
def iter_alignments ( dataset , cognate_sets , column = 'Segments' , method = 'library' ) :
"""Function computes automatic alignments and writes them to file .""" | if not isinstance ( dataset , lingpy . basic . parser . QLCParser ) :
wordlist = _cldf2wordlist ( dataset )
cognates = { r [ 'Form_ID' ] : r for r in cognate_sets }
wordlist . add_entries ( 'cogid' , 'lid' , lambda x : cognates [ x ] [ 'Cognateset_ID' ] if x in cognates else 0 )
alm = lingpy . Alignment... |
def main ( ) :
"""Sample usage for this python module
This main method simply illustrates sample usage for this python
module .
: return : None""" | log = logging . getLogger ( mod_logger + '.main' )
parser = argparse . ArgumentParser ( description = 'cons3rt deployment CLI' )
parser . add_argument ( 'command' , help = 'Command for the deployment CLI' )
parser . add_argument ( '--network' , help = 'Name of the network' )
parser . add_argument ( '--name' , help = 'N... |
def db_migrate ( ) :
"""Migrate DB""" | print ( "Not ready for use" )
exit ( )
cwd_to_sys_path ( )
alembic = _set_flask_alembic ( )
with application . app . app_context ( ) :
p = db . Model . __subclasses__ ( )
print ( p )
# Auto - generate a migration
alembic . revision ( 'making changes' )
# Upgrade the database
alembic . upgrade ( ... |
def tasks_runner ( request ) :
"""A page that let the admin to run global tasks .""" | # server info
cached_layers_number = 0
cached_layers = cache . get ( 'layers' )
if cached_layers :
cached_layers_number = len ( cached_layers )
cached_deleted_layers_number = 0
cached_deleted_layers = cache . get ( 'deleted_layers' )
if cached_deleted_layers :
cached_deleted_layers_number = len ( cached_deleted... |
def ReadFromDirectory ( self , artifacts_reader , path , extension = 'yaml' ) :
"""Reads artifact definitions into the registry from files in a directory .
This function does not recurse sub directories .
Args :
artifacts _ reader ( ArtifactsReader ) : an artifacts reader .
path ( str ) : path of the direct... | for artifact_definition in artifacts_reader . ReadDirectory ( path , extension = extension ) :
self . RegisterDefinition ( artifact_definition ) |
def _send ( key , value , metric_type ) :
"""Send the specified value to the statsd daemon via UDP without a
direct socket connection .
: param str value : The properly formatted statsd counter value""" | if STATSD_PREFIX :
key = '.' . join ( [ STATSD_PREFIX , key ] )
try :
STATSD_SOCKET . sendto ( '{0}:{1}|{2}' . format ( key , value , metric_type ) . encode ( ) , STATSD_ADDR )
except socket . error :
LOGGER . exception ( SOCKET_ERROR ) |
async def _RPC_handler ( self , request : Dict [ str , Any ] ) :
"""用于调用函数并执行 . 同时如果执行出错也负责将错误转化为对应的调用错误返回给客户端 .
执行成功后根据结果进行不同的处理 , 如果注册的是函数 , 实例中的方法 , 或者协程 , 则获取计算得的结果 , 并返回给客户端 .
如果是异步生成器函数 , 那么返回的就是一个对应的异步生成器 , 我们通过对其包装后循环调用实现流传输 .
Parameters :
request ( Dict [ str , Any ] ) : - python字典形式的请求
Raise :
... | ID = request . get ( "ID" )
method = request . get ( "METHOD" )
with_return = request . get ( "RETURN" )
args = request . get ( "ARGS" ) or [ ]
kwargs = request . get ( "KWARGS" ) or { }
try :
if method is None :
raise RequestError ( "request do not have method" , request . get ( "ID" ) )
if method == "... |
def _onMouseWheel ( self , evt ) :
"""Translate mouse wheel events into matplotlib events""" | # Determine mouse location
x = evt . GetX ( )
y = self . figure . bbox . height - evt . GetY ( )
# Convert delta / rotation / rate into a floating point step size
delta = evt . GetWheelDelta ( )
rotation = evt . GetWheelRotation ( )
rate = evt . GetLinesPerAction ( )
# print " delta , rotation , rate " , delta , rotati... |
def _batch_arguments ( self ) :
"""Arguments specific to Batch API writes .
- - batch _ action action Action for the batch job [ ' Create ' , ' Delete ' ] .
- - batch _ chunk number The maximum number of indicator per batch job .
- - batch _ halt _ on _ error Flag to indicate that the batch job should halt on... | self . add_argument ( '--batch_action' , choices = [ 'Create' , 'Delete' ] , default = self . _batch_action , help = 'Action for the batch job' , )
self . add_argument ( '--batch_chunk' , default = self . _batch_chunk , help = 'Max number of indicators per batch' , type = int , )
self . add_argument ( '--batch_halt_on_... |
def _downsample_array ( col : np . array , target : int , random_state : int = 0 , replace : bool = True , inplace : bool = False ) :
"""Evenly reduce counts in cell to target amount .
This is an internal function and has some restrictions :
* ` dtype ` of col must be an integer ( i . e . satisfy issubclass ( c... | np . random . seed ( random_state )
cumcounts = col . cumsum ( )
if inplace :
col [ : ] = 0
else :
col = np . zeros_like ( col )
total = cumcounts [ - 1 ]
sample = np . random . choice ( total , target , replace = replace )
sample . sort ( )
geneptr = 0
for count in sample :
while count >= cumcounts [ genep... |
def get_vm_status ( self , device = 'FLOPPY' ) :
"""Returns the virtual media drive status .""" | dic = { 'DEVICE' : device . upper ( ) }
data = self . _execute_command ( 'GET_VM_STATUS' , 'RIB_INFO' , 'read' , dic )
return data [ 'GET_VM_STATUS' ] |
def _str2array ( d ) :
"""Reconstructs a numpy array from a plain - text string""" | if type ( d ) == list :
return np . asarray ( [ _str2array ( s ) for s in d ] )
ins = StringIO ( d )
return np . loadtxt ( ins ) |
def calculate_traditional_regressor_output_shapes ( operator ) :
'''Allowed input / output patterns are
1 . [ N , C ] - - - > [ N , C ' ]
The number C ' is the length of prediction vector . It can be a scalar ( C ' = 1 ) or a vector ( C ' > 1)''' | check_input_and_output_types ( operator , good_input_types = [ FloatTensorType , Int64TensorType , FloatType , Int64Type ] )
if any ( len ( variable . type . shape ) != 2 for variable in operator . inputs ) :
raise RuntimeError ( 'Input(s) must be 2-D tensor(s)' )
model_type = operator . raw_operator . WhichOneof (... |
def inverse_gaussian_gradient ( image , alpha = 100.0 , sigma = 5.0 ) :
"""Inverse of gradient magnitude .
Compute the magnitude of the gradients in the image and then inverts the
result in the range [ 0 , 1 ] . Flat areas are assigned values close to 1,
while areas close to borders are assigned values close ... | gradnorm = ndi . gaussian_gradient_magnitude ( image , sigma , mode = 'nearest' )
return 1.0 / np . sqrt ( 1.0 + alpha * gradnorm ) |
def remove_analysis_from_worksheet ( analysis ) :
"""Removes the analysis passed in from the worksheet , if assigned to any""" | worksheet = analysis . getWorksheet ( )
if not worksheet :
return
analyses = filter ( lambda an : an != analysis , worksheet . getAnalyses ( ) )
worksheet . setAnalyses ( analyses )
worksheet . purgeLayout ( )
if analyses : # Maybe this analysis was the only one that was not yet submitted or
# verified , so try to ... |
def decrypt ( self , password_encrypted ) :
"""Decrypt the password .""" | if not password_encrypted or not self . _crypter :
return password_encrypted or b''
return self . _crypter . decrypt ( password_encrypted ) |
def upload_data ( self , file_or_str , chunk_size = analyzere . upload_chunk_size , poll_interval = analyzere . upload_poll_interval , upload_callback = lambda x : None , commit_callback = lambda x : None ) :
"""Accepts a file - like object or string and uploads it . Files are
automatically uploaded in chunks . T... | if not callable ( upload_callback ) :
raise Exception ( 'provided upload_callback is not callable' )
if not callable ( commit_callback ) :
raise Exception ( 'provided commit_callback is not callable' )
file_obj = StringIO ( file_or_str ) if isinstance ( file_or_str , six . string_types ) else file_or_str
# Uplo... |
def max_in_column ( tuple_list : list , index : int ) -> int :
"""Determines the maximum value in a specific column of a given list of tuples .
Args :
tuple _ list : a list of tuples that are assumed to have at least ' index ' elements
index : the 0 - based index for the column to find the maximum value in
... | highest_value = max ( sub [ index ] for sub in tuple_list )
return highest_value |
def File ( name , mode = 'a' , chunk_cache_mem_size = 1024 ** 2 , w0 = 0.75 , n_cache_chunks = None , ** kwds ) :
"""Create h5py File object with cache specification
This function is basically just a wrapper around the usual h5py . File constructor ,
but accepts two additional keywords :
Parameters
name : s... | import sys
import numpy as np
import h5py
name = name . encode ( sys . getfilesystemencoding ( ) )
open ( name , mode ) . close ( )
# Just make sure the file exists
if mode in [ m + b for m in [ 'w' , 'w+' , 'r+' , 'a' , 'a+' ] for b in [ '' , 'b' ] ] :
mode = h5py . h5f . ACC_RDWR
else :
mode = h5py . h5f . AC... |
def intialize ( self ) :
"""initialize the serial port with baudrate , timeout parameters""" | print '%s call intialize' % self . port
try :
self . deviceConnected = False
# init serial port
self . _connect ( )
if self . firmwarePrefix in self . UIStatusMsg :
self . deviceConnected = True
else :
self . UIStatusMsg = "Firmware Not Matching Expecting " + self . firmwarePrefix + ... |
def remove_small_ns ( taus , devs , deverrs , ns ) :
"""Remove results with small number of samples .
If n is small ( = = 1 ) , reject the result
Parameters
taus : array
List of tau values for which deviation were computed
devs : array
List of deviations
deverrs : array or list of arrays
List of est... | ns_big_enough = ns > 1
o_taus = taus [ ns_big_enough ]
o_devs = devs [ ns_big_enough ]
o_ns = ns [ ns_big_enough ]
if isinstance ( deverrs , list ) :
assert len ( deverrs ) < 3
o_deverrs = [ deverrs [ 0 ] [ ns_big_enough ] , deverrs [ 1 ] [ ns_big_enough ] ]
else :
o_deverrs = deverrs [ ns_big_enough ]
if l... |
def parse ( self , buffer , inlineparent = None ) :
'''Compatible to Parser . parse ( )''' | size = 0
v = [ ]
for i in range ( 0 , self . size ) : # @ UnusedVariable
r = self . innerparser . parse ( buffer [ size : ] , None )
if r is None :
return None
v . append ( r [ 0 ] )
size += r [ 1 ]
return ( v , size ) |
def surface ( self , param ) :
"""Return the detector surface point corresponding to ` ` param ` ` .
For parameter value ` ` p ` ` , the surface point is given by : :
surf = p * axis
Parameters
param : float or ` array - like `
Parameter value ( s ) at which to evaluate .
Returns
point : ` numpy . nda... | squeeze_out = ( np . shape ( param ) == ( ) )
param = np . array ( param , dtype = float , copy = False , ndmin = 1 )
if self . check_bounds and not is_inside_bounds ( param , self . params ) :
raise ValueError ( '`param` {} not in the valid range ' '{}' . format ( param , self . params ) )
# Create outer product o... |
def history ( directory = None , rev_range = None , verbose = False , indicate_current = False ) :
"""List changeset scripts in chronological order .""" | config = current_app . extensions [ 'migrate' ] . migrate . get_config ( directory )
if alembic_version >= ( 0 , 9 , 9 ) :
command . history ( config , rev_range , verbose = verbose , indicate_current = indicate_current )
elif alembic_version >= ( 0 , 7 , 0 ) :
command . history ( config , rev_range , verbose =... |
async def wait_for_connection_lost ( self ) -> bool :
"""Wait until the TCP connection is closed or ` ` self . close _ timeout ` ` elapses .
Return ` ` True ` ` if the connection is closed and ` ` False ` ` otherwise .""" | if not self . connection_lost_waiter . done ( ) :
try :
await asyncio . wait_for ( asyncio . shield ( self . connection_lost_waiter ) , self . close_timeout , loop = self . loop , )
except asyncio . TimeoutError :
pass
# Re - check self . connection _ lost _ waiter . done ( ) synchronously becau... |
def submit_background_work_chain ( self , work_chain , parent_workunit_name = None ) :
""": API : public""" | background_root_workunit = self . run_tracker . get_background_root_workunit ( )
if parent_workunit_name : # We have to keep this workunit alive until all its child work is done , so
# we manipulate the context manually instead of using it as a contextmanager .
# This is slightly funky , but the with - context usage is... |
def add_tot_length ( self , qname , sname , value , sym = True ) :
"""Add a total length value to self . alignment _ lengths .""" | self . alignment_lengths . loc [ qname , sname ] = value
if sym :
self . alignment_lengths . loc [ sname , qname ] = value |
async def read ( self , * , decode : bool = False ) -> Any :
"""Reads body part data .
decode : Decodes data following by encoding
method from Content - Encoding header . If it missed
data remains untouched""" | if self . _at_eof :
return b''
data = bytearray ( )
while not self . _at_eof :
data . extend ( ( await self . read_chunk ( self . chunk_size ) ) )
if decode :
return self . decode ( data )
return data |
def add_group ( self , group_id , name , desc ) :
'''Add a new parameter group .
Parameters
group _ id : int
The numeric ID for a group to check or create .
name : str , optional
If a group is created , assign this name to the group .
desc : str , optional
If a group is created , assign this descripti... | if group_id in self . groups :
raise KeyError ( group_id )
name = name . upper ( )
if name in self . groups :
raise KeyError ( name )
group = self . groups [ name ] = self . groups [ group_id ] = Group ( name , desc )
return group |
def cmd_ip_internal ( verbose ) :
"""Get the local IP address ( es ) of the local interfaces .
Example :
$ habu . ip . internal
" lo " : {
" ipv4 " : [
" addr " : " 127.0.0.1 " ,
" netmask " : " 255.0.0.0 " ,
" peer " : " 127.0.0.1"
" link _ layer " : [
" addr " : " 00:00:00:00:00:00 " ,
" peer ... | if verbose :
logging . basicConfig ( level = logging . INFO , format = '%(message)s' )
print ( "Gathering NIC details..." , file = sys . stderr )
result = get_internal_ip ( )
if result :
print ( json . dumps ( result , indent = 4 ) )
else :
print ( "[X] Unable to get detail about the interfaces" )
retur... |
def publish_request ( self , subject , reply , payload ) :
"""Publishes a message tagging it with a reply subscription
which can be used by those receiving the message to respond :
- > > PUB hello _ INBOX . 2007314fe0fcb2cdc2a2914c1 5
- > > MSG _ PAYLOAD : world
< < - MSG hello 2 _ INBOX . 2007314fe0fcb2cdc... | payload_size = len ( payload )
if payload_size > self . _max_payload_size :
raise ErrMaxPayload
if self . is_closed :
raise ErrConnectionClosed
yield self . _publish ( subject , reply , payload , payload_size )
if self . _flush_queue . empty ( ) :
yield self . _flush_pending ( ) |
def loadUi ( modulefile , inst , uifile = None , theme = 'default' , className = None ) :
"""Load the ui file based on the module file location and the inputed class .
: param modulefile | < str >
inst | < subclass of QWidget >
uifile | < str > | | None
: return < QWidget >""" | if className is None :
className = inst . __class__ . __name__
import_qt ( globals ( ) )
currpath = QtCore . QDir . currentPath ( )
# use compiled information vs . dynamic generation
widget = None
if USE_COMPILED : # find the root module
def find_root_module ( cls , name ) :
if cls . __name__ == name :
... |
def calculate_size ( name , overflow_policy , value ) :
"""Calculates the request payload size""" | data_size = 0
data_size += calculate_size_str ( name )
data_size += INT_SIZE_IN_BYTES
data_size += calculate_size_data ( value )
return data_size |
def random ( self , length = 22 ) :
"""Generate and return a cryptographically - secure short random string
of the specified length .""" | random_num = int ( binascii . b2a_hex ( os . urandom ( length ) ) , 16 )
return self . _num_to_string ( random_num , pad_to_length = length ) [ : length ] |
def update_dataset ( self , dataset_id , friendly_name = None , description = None , access = None , project_id = None ) :
"""Updates information in an existing dataset . The update method
replaces the entire dataset resource , whereas the patch method only
replaces fields that are provided in the submitted dat... | project_id = self . _get_project_id ( project_id )
try :
datasets = self . bigquery . datasets ( )
body = self . dataset_resource ( dataset_id , friendly_name = friendly_name , description = description , access = access , project_id = project_id )
request = datasets . update ( projectId = project_id , data... |
def get_days_since_last_modified ( filename ) :
""": param filename : Absolute file path
: return : Number of days since filename ' s last modified time""" | now = datetime . now ( )
last_modified = datetime . fromtimestamp ( os . path . getmtime ( filename ) )
return ( now - last_modified ) . days |
def squawk ( self ) -> Set [ str ] :
"""Returns all the unique squawk values in the trajectory .""" | return set ( self . data . squawk . ffill ( ) . bfill ( ) ) |
def key_map ( f , m , * args , ** kwargs ) :
'''key _ map ( f , m ) is equivalent to { f ( k ) : v for ( k , v ) in m . items ( ) } except that it returns a
persistent mapping object instead of a dict . Additionally , it respects the laziness of maps
and does not evaluate the values of a lazy map that has been ... | if is_lazy_map ( m ) :
from . table import ( is_itable , itable )
def _curry_getval ( k ) :
return lambda : m [ k ]
m0 = { f ( k , * args , ** kwargs ) : _curry_getval ( k ) for k in six . iterkeys ( m ) }
return itable ( m0 ) if is_itable ( m ) else lazy_map ( m0 )
else :
return ps . pmap (... |
def value_is_int ( self ) :
"""Identify whether the value text is an int .""" | try :
a = float ( self . value )
b = int ( a )
except ValueError :
return False
else :
return a == b |
def _work ( self ) :
"""Process the information regarding the available ports .""" | if self . _refresh_cache : # Inconsistent cache might cause exceptions . For example ,
# if a port has been removed , it will be known in the next
# loop . Using the old switch port can cause exceptions .
LOG . debug ( "Refreshing os_win caches..." )
self . _utils . update_cache ( )
self . _refresh_cache = ... |
def acquire ( self , blocking = True , timeout = None ) :
"""Attempt to acquire this lock .
If the optional argument " blocking " is True and " timeout " is None ,
this methods blocks until is successfully acquires the lock . If
" blocking " is False , it returns immediately if the lock could not
be acquire... | if timeout is None :
return self . __lock . acquire ( blocking )
else : # Simulated timeout using progressively longer sleeps .
# This is the same timeout scheme used in the stdlib Condition
# class . If there ' s lots of contention on the lock then there ' s
# a good chance you won ' t get it ; but then again , Py... |
def from_dict ( cls , data ) :
""": type data : dict [ str , str ]
: rtype : satosa . internal . AuthenticationInformation
: param data : A dict representation of an AuthenticationInformation object
: return : An AuthenticationInformation object""" | return cls ( auth_class_ref = data . get ( "auth_class_ref" ) , timestamp = data . get ( "timestamp" ) , issuer = data . get ( "issuer" ) , ) |
def elbow_method ( data , k_min , k_max , distance = 'euclidean' ) :
"""Calculates and plots the plot of variance explained - number of clusters
Implementation reference : https : / / github . com / sarguido / k - means - clustering . rst
: param data : The dataset
: param k _ min : lowerbound of the cluster ... | # Determine your k range
k_range = range ( k_min , k_max )
# Fit the kmeans model for each n _ clusters = k
k_means_var = [ Clustering . kmeans ( k ) . fit ( data ) for k in k_range ]
# Pull out the cluster centers for each model
centroids = [ X . model . cluster_centers_ for X in k_means_var ]
# Calculate the Euclidea... |
def flatten ( obj , isinstance = isinstance , StringTypes = StringTypes , SequenceTypes = SequenceTypes , do_flatten = do_flatten ) :
"""Flatten a sequence to a non - nested list .
Flatten ( ) converts either a single scalar or a nested sequence
to a non - nested list . Note that flatten ( ) considers strings
... | if isinstance ( obj , StringTypes ) or not isinstance ( obj , SequenceTypes ) :
return [ obj ]
result = [ ]
for item in obj :
if isinstance ( item , StringTypes ) or not isinstance ( item , SequenceTypes ) :
result . append ( item )
else :
do_flatten ( item , result )
return result |
def gen_search_article_url ( keyword , page = 1 , timesn = WechatSogouConst . search_article_time . anytime , article_type = WechatSogouConst . search_article_type . all , ft = None , et = None ) :
"""拼接搜索 文章 URL
Parameters
keyword : str or unicode
搜索文字
page : int , optional
页数 the default is 1
timesn :... | assert isinstance ( page , int ) and page > 0
assert timesn in [ WechatSogouConst . search_article_time . anytime , WechatSogouConst . search_article_time . day , WechatSogouConst . search_article_time . week , WechatSogouConst . search_article_time . month , WechatSogouConst . search_article_time . year , WechatSogouC... |
def main ( argv ) :
"""Entry point for command line script to perform OAuth 2.0.""" | p = argparse . ArgumentParser ( )
p . add_argument ( '-s' , '--scope' , nargs = '+' )
p . add_argument ( '-o' , '--oauth-service' , default = 'google' )
p . add_argument ( '-i' , '--client-id' )
p . add_argument ( '-x' , '--client-secret' )
p . add_argument ( '-r' , '--redirect-uri' )
p . add_argument ( '-f' , '--clien... |
def get_fd_qnm ( template = None , ** kwargs ) :
"""Return a frequency domain damped sinusoid .
Parameters
template : object
An object that has attached properties . This can be used to substitute
for keyword arguments . A common example would be a row in an xml table .
f _ 0 : float
The ringdown - freq... | input_params = props ( template , qnm_required_args , ** kwargs )
f_0 = input_params . pop ( 'f_0' )
tau = input_params . pop ( 'tau' )
amp = input_params . pop ( 'amp' )
phi = input_params . pop ( 'phi' )
# the following have defaults , and so will be populated
t_0 = input_params . pop ( 't_0' )
# the following may no... |
def _get ( self , key , parser_result ) :
"""Given a type and a dict of parser results , return
the items as a list .""" | try :
list_data = parser_result [ key ] . asList ( )
if any ( isinstance ( obj , str ) for obj in list_data ) :
txt_lines = [ '' . join ( list_data ) ]
else :
txt_lines = [ '' . join ( f ) for f in list_data ]
except KeyError :
txt_lines = [ ]
return txt_lines |
def getSDSSImage ( ra , dec , radius = 1.0 , xsize = 800 , opt = 'GML' , ** kwargs ) :
"""Download Sloan Digital Sky Survey images
http : / / skyserver . sdss3 . org / dr9 / en / tools / chart / chart . asp
radius ( degrees )
opts : ( G ) Grid , ( L ) Label , P ( PhotoObj ) , S ( SpecObj ) , O ( Outline ) , (... | import subprocess
import tempfile
url = "http://skyservice.pha.jhu.edu/DR10/ImgCutout/getjpeg.aspx?"
scale = 2. * radius * 3600. / xsize
params = dict ( ra = ra , dec = dec , width = xsize , height = xsize , scale = scale , opt = opt )
query = '&' . join ( "%s=%s" % ( k , v ) for k , v in params . items ( ) )
tmp = tem... |
def _solve_forbase_address ( self , function_starts , functions ) :
"""Voting for the most possible base address .
: param function _ starts :
: param functions :
: returns :""" | pseudo_base_addr = self . project . loader . main_object . min_addr
base_addr_ctr = { }
for s in function_starts :
for f in functions :
base_addr = s - f + pseudo_base_addr
ctr = 1
for k in function_starts :
if k - base_addr + pseudo_base_addr in functions :
ctr +... |
def dump_cookie ( key , value = '' , max_age = None , expires = None , path = '/' , domain = None , secure = False , httponly = False , charset = 'utf-8' , sync_expires = True ) :
"""Creates a new Set - Cookie header without the ` ` Set - Cookie ` ` prefix
The parameters are the same as in the cookie Morsel objec... | key = to_bytes ( key , charset )
value = to_bytes ( value , charset )
if path is not None :
path = iri_to_uri ( path , charset )
domain = _make_cookie_domain ( domain )
if isinstance ( max_age , timedelta ) :
max_age = ( max_age . days * 60 * 60 * 24 ) + max_age . seconds
if expires is not None :
if not isi... |
def strptime ( cls , date_string , format ) :
'string , format - > new datetime parsed from a string ( like time . strptime ( ) ) .' | import _strptime
return _strptime . _strptime_datetime ( cls , date_string , format ) |
def validate_split_runs_file ( split_runs_file ) :
"""Check if structure of file is as expected and return dictionary linking names to run _ IDs .""" | try :
content = [ l . strip ( ) for l in split_runs_file . readlines ( ) ]
if content [ 0 ] . upper ( ) . split ( '\t' ) == [ 'NAME' , 'RUN_ID' ] :
return { c . split ( '\t' ) [ 1 ] : c . split ( '\t' ) [ 0 ] for c in content [ 1 : ] if c }
else :
sys . exit ( "ERROR: Mandatory header of --s... |
def open ( self , options = None , mimetype = 'application/octet-stream' ) :
"""open : return a file like object for self .
The method can be used with the ' with ' statment .""" | return self . connection . open ( self , options , mimetype ) |
def crop ( im , r , c , sz_h , sz_w ) :
'''crop image into a square of size sz ,''' | return im [ r : r + sz_h , c : c + sz_w ] |
def get_declared_enums ( metadata , schema , default ) :
"""Return a dict mapping SQLAlchemy enumeration types to the set of their
declared values .
: param metadata :
: param str schema :
Schema name ( e . g . " public " ) .
: returns dict :
" my _ enum " : frozenset ( [ " a " , " b " , " c " ] ) ,""" | types = set ( column . type for table in metadata . tables . values ( ) for column in table . columns if ( isinstance ( column . type , sqlalchemy . Enum ) and schema == ( column . type . schema or default ) ) )
return { t . name : frozenset ( t . enums ) for t in types } |
def get_clear_pin ( pinblock , account_number ) :
"""Calculate the clear PIN from provided PIN block and account _ number , which is the 12 right - most digits of card account number , excluding check digit""" | raw_pinblock = bytes . fromhex ( pinblock . decode ( 'utf-8' ) )
raw_acct_num = bytes . fromhex ( ( b'0000' + account_number ) . decode ( 'utf-8' ) )
pin_str = xor ( raw2B ( raw_pinblock ) , raw2B ( raw_acct_num ) ) . decode ( 'utf-8' )
pin_length = int ( pin_str [ : 2 ] , 16 )
if pin_length >= 4 and pin_length < 9 :
... |
def parse_queue ( self , global_params , region , queue_url ) :
"""Parse a single queue and fetch additional attributes
: param global _ params : Parameters shared for all regions
: param region : Name of the AWS region
: param queue _ url : URL of the AWS queue""" | queue = { 'QueueUrl' : queue_url }
attributes = api_clients [ region ] . get_queue_attributes ( QueueUrl = queue_url , AttributeNames = [ 'CreatedTimestamp' , 'Policy' , 'QueueArn' ] ) [ 'Attributes' ]
queue [ 'arn' ] = attributes . pop ( 'QueueArn' )
for k in [ 'CreatedTimestamp' ] :
queue [ k ] = attributes [ k ]... |
def xmoe_tr_dense_2k ( ) :
"""Series of architectural experiments on Translation .
# run on 8 - core setup
119M params , einsum = 0.95e13
Returns :
a hparams""" | hparams = mtf_transformer2 . mtf_bitransformer_base ( )
hparams . encoder_layers = [ "self_att" , "drd" ] * 4
hparams . decoder_layers = [ "self_att" , "enc_att" , "drd" ] * 4
hparams . batch_size = 64
hparams . shared_embedding_and_softmax_weights = True
hparams . mesh_shape = "batch:8"
return hparams |
def _extract_one_pair ( body ) :
"""Extract one language - text pair from a : class : ` ~ . LanguageMap ` .
This is used for tracking .""" | if not body :
return None , None
try :
return None , body [ None ]
except KeyError :
return min ( body . items ( ) , key = lambda x : x [ 0 ] ) |
def marching_cubes ( self ) :
"""A marching cubes Trimesh representation of the voxels .
No effort was made to clean or smooth the result in any way ;
it is merely the result of applying the scikit - image
measure . marching _ cubes function to self . matrix .
Returns
meshed : Trimesh object representing ... | meshed = matrix_to_marching_cubes ( matrix = self . matrix , pitch = self . pitch , origin = self . origin )
return meshed |
def Register ( self , app_id , challenge , registered_keys ) :
"""Registers app _ id with the security key .
Executes the U2F registration flow with the security key .
Args :
app _ id : The app _ id to register the security key against .
challenge : Server challenge passed to the security key .
registered... | client_data = model . ClientData ( model . ClientData . TYP_REGISTRATION , challenge , self . origin )
challenge_param = self . InternalSHA256 ( client_data . GetJson ( ) )
app_param = self . InternalSHA256 ( app_id )
for key in registered_keys :
try : # skip non U2F _ V2 keys
if key . version != u'U2F_V2' ... |
def _save_stats ( self , epoch_data : EpochData ) -> None :
"""Extend ` ` epoch _ data ` ` by stream : variable : aggreagation data .
: param epoch _ data : data source from which the statistics are computed""" | for stream_name in epoch_data . keys ( ) :
for variable , aggregations in self . _variable_aggregations . items ( ) : # variables are already checked in the AccumulatingHook ; hence , we do not check them here
epoch_data [ stream_name ] [ variable ] = OrderedDict ( { aggr : ComputeStats . _compute_aggregati... |
def apply ( self , root ) :
"""Apply the import ( rule ) to the specified schema .
If the schema does not already contain an import for the
I { namespace } specified here , it is added .
@ param root : A schema root .
@ type root : L { Element }""" | if not self . filter . match ( root , self . ns ) :
return
if self . exists ( root ) :
return
node = Element ( 'import' , ns = self . xsdns )
node . set ( 'namespace' , self . ns )
if self . location is not None :
node . set ( 'schemaLocation' , self . location )
log . debug ( 'inserting: %s' , node )
root ... |
def _get_shard ( self , shard ) :
"""Dynamically Builds methods to query shard with proper with arg and kwargs support""" | @ wraps ( API_WRAPPER . _get_shard )
def get_shard ( * arg , ** kwargs ) :
"""Gets the shard '{}'""" . format ( shard )
return self . get_shards ( Shard ( shard , * arg , ** kwargs ) )
return get_shard |
def set_base_prompt ( self , pri_prompt_terminator = "$" , alt_prompt_terminator = "#" , delay_factor = 1 ) :
"""Determine base prompt .""" | return super ( LinuxSSH , self ) . set_base_prompt ( pri_prompt_terminator = pri_prompt_terminator , alt_prompt_terminator = alt_prompt_terminator , delay_factor = delay_factor , ) |
def create_identity_pool ( IdentityPoolName , AllowUnauthenticatedIdentities = False , SupportedLoginProviders = None , DeveloperProviderName = None , OpenIdConnectProviderARNs = None , region = None , key = None , keyid = None , profile = None ) :
'''Creates a new identity pool . All parameters except for Identity... | SupportedLoginProviders = dict ( ) if SupportedLoginProviders is None else SupportedLoginProviders
OpenIdConnectProviderARNs = list ( ) if OpenIdConnectProviderARNs is None else OpenIdConnectProviderARNs
conn = _get_conn ( region = region , key = key , keyid = keyid , profile = profile )
try :
request_params = dict... |
def get_requirements ( lookup = None ) :
'''get _ requirements reads in requirements and versions from
the lookup obtained with get _ lookup''' | if lookup == None :
lookup = get_lookup ( )
install_requires = [ ]
for module in lookup [ 'INSTALL_REQUIRES' ] :
module_name = module [ 0 ]
module_meta = module [ 1 ]
if "exact_version" in module_meta :
dependency = "%s==%s" % ( module_name , module_meta [ 'exact_version' ] )
elif "min_versi... |
def get_sections ( self ) :
"""Returns an array with the sections to be displayed .
Every section is a dictionary with the following structure :
{ ' id ' : < section _ identifier > ,
' title ' : < section _ title > ,
' panels ' : < array of panels > }""" | sections = [ ]
user = api . user . get_current ( )
if is_panel_visible_for_user ( 'analyses' , user ) :
sections . append ( self . get_analyses_section ( ) )
if is_panel_visible_for_user ( 'analysisrequests' , user ) :
sections . append ( self . get_analysisrequests_section ( ) )
if is_panel_visible_for_user ( ... |
def modified ( self ) :
"""Union [ datetime . datetime , None ] : Datetime at which the model was last
modified ( : data : ` None ` until set from the server ) .
Read - only .""" | value = self . _proto . last_modified_time
if value is not None and value != 0 : # value will be in milliseconds .
return google . cloud . _helpers . _datetime_from_microseconds ( 1000.0 * float ( value ) ) |
def water ( target , temperature = 'pore.temperature' , salinity = 'pore.salinity' ) :
r"""Calculates vapor pressure of pure water or seawater given by [ 1 ] based on
Raoult ' s law . The pure water vapor pressure is given by [ 2]
Parameters
target : OpenPNM Object
The object for which these values are bein... | T = target [ temperature ]
if salinity in target . keys ( ) :
S = target [ salinity ]
else :
S = 0
a1 = - 5.8002206E+03
a2 = 1.3914993E+00
a3 = - 4.8640239E-02
a4 = 4.1764768E-05
a5 = - 1.4452093E-08
a6 = 6.5459673E+00
Pv_w = np . exp ( ( a1 / T ) + a2 + a3 * T + a4 * T ** 2 + a5 * T ** 3 + a6 * np . log ( T ) ... |
def draw_units ( self , surf ) :
"""Draw the units and buildings .""" | for u , p in self . _visible_units ( ) :
if self . _camera . intersects_circle ( p , u . radius ) :
fraction_damage = clamp ( ( u . health_max - u . health ) / ( u . health_max or 1 ) , 0 , 1 )
surf . draw_circle ( colors . PLAYER_ABSOLUTE_PALETTE [ u . owner ] , p , u . radius )
if fraction... |
def _ite ( test : str , in1 : str , in0 : str , output : str = None ) :
r"test - > in1 / \ ~ test - > in0" | assert len ( { test , in0 , in1 } ) == 3
true_out = bit_flipper ( [ test ] ) >> or_gate ( [ test , in1 ] , 'true_out' )
false_out = or_gate ( [ test , in0 ] , 'false_out' )
return ( true_out | false_out ) >> and_gate ( [ 'true_out' , 'false_out' ] , output ) |
def raise_ ( tp , value = None , tb = None ) :
"""A function that matches the Python 2 . x ` ` raise ` ` statement . This
allows re - raising exceptions with the cls value and traceback on
Python 2 and 3.""" | 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 get_group ( self , group_id ) :
"""Get group for the provided group ID .
Args :
group _ id : Group ID for which group is to be determined .
Returns :
Group corresponding to the provided group ID .""" | group = self . group_id_map . get ( group_id )
if group :
return group
self . logger . error ( 'Group ID "%s" is not in datafile.' % group_id )
self . error_handler . handle_error ( exceptions . InvalidGroupException ( enums . Errors . INVALID_GROUP_ID_ERROR ) )
return None |
def request ( url , * args , ** kwargs ) :
"""Do the HTTP Request and return data""" | method = kwargs . get ( 'method' , 'GET' )
timeout = kwargs . pop ( 'timeout' , 10 )
# hass default timeout
req = requests . request ( method , url , * args , timeout = timeout , ** kwargs )
data = req . json ( )
_LOGGER . debug ( json . dumps ( data ) )
return data |
def _split_index ( params ) :
"""Delete index infromation from params""" | if isinstance ( params , list ) :
return [ params [ 0 ] , _split_index ( params [ 1 ] ) ]
elif isinstance ( params , dict ) :
if INDEX in params . keys ( ) :
return _split_index ( params [ VALUE ] )
result = dict ( )
for key in params :
result [ key ] = _split_index ( params [ key ] )
... |
async def get_json ( self , url , timeout = 30 , astext = False , exceptions = False ) :
"""Get URL and parse JSON from text .""" | try :
with async_timeout . timeout ( timeout ) :
res = await self . _aio_session . get ( url )
if res . status != 200 :
_LOGGER . error ( "QSUSB returned %s [%s]" , res . status , url )
return None
res_text = await res . text ( )
except ( aiohttp . client_exceptions .... |
def select_upstream ( self , device : devicetools . Device ) -> 'Selection' :
"""Restrict the current selection to the network upstream of the given
starting point , including the starting point itself .
See the documentation on method | Selection . search _ upstream | for
additional information .""" | upstream = self . search_upstream ( device )
self . nodes = upstream . nodes
self . elements = upstream . elements
return self |
def assemble_common_meta ( common_meta_dfs , fields_to_remove , sources , remove_all_metadata_fields , error_report_file ) :
"""Assemble the common metadata dfs together . Both indices are sorted .
Fields that are not in all the dfs are dropped .
Args :
common _ meta _ dfs ( list of pandas dfs )
fields _ to... | all_meta_df , all_meta_df_with_dups = build_common_all_meta_df ( common_meta_dfs , fields_to_remove , remove_all_metadata_fields )
if not all_meta_df . index . is_unique :
all_report_df = build_mismatched_common_meta_report ( [ x . shape for x in common_meta_dfs ] , sources , all_meta_df , all_meta_df_with_dups )
... |
def run_cmake ( command , build_path , default_build_path ) :
"""Execute CMake command .""" | from subprocess import Popen , PIPE
from shutil import rmtree
topdir = os . getcwd ( )
p = Popen ( command , shell = True , stdin = PIPE , stdout = PIPE , stderr = PIPE )
stdout_coded , stderr_coded = p . communicate ( )
stdout = stdout_coded . decode ( 'UTF-8' )
stderr = stderr_coded . decode ( 'UTF-8' )
# print cmake... |
def merge ( * maps ) :
"""Merge all maps left to right""" | copies = map ( deepcopy , maps )
return reduce ( lambda acc , val : acc . update ( val ) or acc , copies ) |
def column_describe ( table_name , col_name ) :
"""Return summary statistics of a column as JSON .
Uses Pandas ' " split " JSON format .""" | col_desc = orca . get_table ( table_name ) . get_column ( col_name ) . describe ( )
return ( col_desc . to_json ( orient = 'split' ) , 200 , { 'Content-Type' : 'application/json' } ) |
def loss ( params , batch , model_predict , rng ) :
"""Calculate loss .""" | inputs , targets = batch
predictions = model_predict ( inputs , params , rng = rng )
predictions , targets = _make_list ( predictions , targets )
xent = [ ]
for ( pred , target ) in zip ( predictions , targets ) :
xent . append ( np . sum ( pred * layers . one_hot ( target , pred . shape [ - 1 ] ) , axis = - 1 ) )
... |
def to_segwizard ( segs , target , header = True , coltype = LIGOTimeGPS ) :
"""Write the given ` SegmentList ` to a file in SegWizard format .
Parameters
segs : : class : ` ~ gwpy . segments . SegmentList `
The list of segments to write .
target : ` file ` , ` str `
An open file , or file path , to which... | # write file path
if isinstance ( target , string_types ) :
with open ( target , 'w' ) as fobj :
return to_segwizard ( segs , fobj , header = header , coltype = coltype )
# write file object
if header :
print ( '# seg\tstart\tstop\tduration' , file = target )
for i , seg in enumerate ( segs ) :
a = ... |
def post ( self , url , data , proto = 'http' , form_name = None ) :
"""Load an url using the POST method .
Keyword arguments :
url - - the Universal Resource Location
data - - the form to be sent
proto - - the protocol ( default ' http ' )
form _ name - - the form name to search the default values""" | form = self . translator . fill_form ( self . last_response_soup , form_name if form_name else url , data )
self . last_response = self . session . post ( proto + self . base_uri + url , headers = self . headers , cookies = self . cookies , data = form , allow_redirects = True , verify = self . verify )
return self . l... |
def loadXml ( self , xdata , filepath = '' ) :
"""Loads properties from the xml data .
: param xdata | < xml . etree . ElementTree . Element >""" | # build options
opts = { 'platform' : sys . platform }
mkpath = lambda x : _mkpath ( filepath , x , ** opts )
# lookup environment variables
xenv = xdata . find ( 'environment' )
if xenv is not None :
env = { }
log . info ( 'loading environment...' )
for xkey in xenv :
text = xkey . text
if ... |
def _handle_human_connection_event ( self , event : events . HumanConnectionEvent , ) -> None :
"""Not thread - safe .""" | for subscriber in self . _human_connection_subscribers :
try :
subscriber ( event )
except Exception :
LOG . exception ( self . _prefix_log_message ( f"failed to send human connection event {event} to " f"subscriber {subscriber}" ) ) |
def quantize ( self , value ) :
"""Quantize the decimal value to the configured precision .""" | context = decimal . getcontext ( ) . copy ( )
context . prec = self . max_digits
return value . quantize ( decimal . Decimal ( '.1' ) ** self . decimal_places , context = context ) |
def _set_hierarchy_view ( self , session ) :
"""Sets the underlying hierarchy view to match current view""" | if self . _hierarchy_view == FEDERATED :
try :
session . use_federated_hierarchy_view ( )
except AttributeError :
pass
else :
try :
session . use_isolated_hierarchy_view ( )
except AttributeError :
pass |
def set_share_properties ( self , share_name , quota , timeout = None ) :
'''Sets service - defined properties for the specified share .
: param str share _ name :
Name of existing share .
: param int quota :
Specifies the maximum size of the share , in gigabytes . Must be
greater than 0 , and less than o... | _validate_not_none ( 'share_name' , share_name )
_validate_not_none ( 'quota' , quota )
request = HTTPRequest ( )
request . method = 'PUT'
request . host = self . _get_host ( )
request . path = _get_path ( share_name )
request . query = [ ( 'restype' , 'share' ) , ( 'comp' , 'properties' ) , ( 'timeout' , _int_to_str (... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.