signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def insertDataset ( self , dataset ) :
"""Inserts the specified dataset into this repository .""" | try :
models . Dataset . create ( id = dataset . getId ( ) , name = dataset . getLocalId ( ) , description = dataset . getDescription ( ) , attributes = json . dumps ( dataset . getAttributes ( ) ) )
except Exception :
raise exceptions . DuplicateNameException ( dataset . getLocalId ( ) ) |
def recenter ( positions ) :
'''Returns a list of new positions centered around the origin .''' | ( x0 , y0 , z0 ) , ( x1 , y1 , z1 ) = bounding_box ( positions )
dx = x1 - ( x1 - x0 ) / 2.0
dy = y1 - ( y1 - y0 ) / 2.0
dz = z1 - ( z1 - z0 ) / 2.0
result = [ ]
for x , y , z in positions :
result . append ( ( x - dx , y - dy , z - dz ) )
return result |
def versions_request ( self ) :
"""List Available REST API Versions""" | ret = self . handle_api_exceptions ( 'GET' , '' , api_ver = '' )
return [ str_dict ( x ) for x in ret . json ( ) ] |
def afw_nonemptiness_check ( afw : dict ) -> bool :
"""Checks if the input AFW reads any language other than the
empty one , returning True / False .
The afw is translated into a nfa and then its nonemptiness is
checked .
: param dict afw : input AFW .
: return : * ( bool ) * , True if input afw is nonemp... | nfa = afw_to_nfa_conversion ( afw )
return NFA . nfa_nonemptiness_check ( nfa ) |
def _special_value_autocomplete ( em ) :
'''handle " autocomplete " property , which has different behaviour for form vs input "''' | if em . tagName == 'form' :
return convertPossibleValues ( em . getAttribute ( 'autocomplete' , 'on' ) , POSSIBLE_VALUES_ON_OFF , invalidDefault = 'on' , emptyValue = EMPTY_IS_INVALID )
# else : input
return convertPossibleValues ( em . getAttribute ( 'autocomplete' , '' ) , POSSIBLE_VALUES_ON_OFF , invalidDefault ... |
def stats ( self ) :
"""The current status of the positions .
Returns
stats : PositionStats
The current stats position stats .
Notes
This is cached , repeated access will not recompute the stats until
the stats may have changed .""" | if self . _dirty_stats :
calculate_position_tracker_stats ( self . positions , self . _stats )
self . _dirty_stats = False
return self . _stats |
def validate_row_lengths ( fields , # type : Sequence [ FieldSpec ]
data # type : Sequence [ Sequence [ str ] ]
) : # type : ( . . . ) - > None
"""Validate the ` data ` row lengths according to the specification
in ` fields ` .
: param fields : The ` FieldSpec ` objects forming the
specification .
: param d... | for i , row in enumerate ( data ) :
if len ( fields ) != len ( row ) :
msg = 'Row {} has {} entries when {} are expected.' . format ( i , len ( row ) , len ( fields ) )
raise FormatError ( msg ) |
def find_model_dat ( ) :
"""Find the file containing the definition of all the models in Xspec
( model . dat ) and return its path""" | # model . dat is in $ HEADAS / . . / spectral
headas_env = os . environ . get ( "HEADAS" )
assert headas_env is not None , ( "You need to setup the HEADAS variable before importing this module." " See Heasoft documentation." )
# Expand all variables and other things like ~
headas_env = os . path . expandvars ( os . pat... |
def signature ( secret , parts ) :
"""Generates a signature . All strings are assumed to be utf - 8""" | if not isinstance ( secret , six . binary_type ) :
secret = secret . encode ( 'utf-8' )
newparts = [ ]
for part in parts :
if not isinstance ( part , six . binary_type ) :
part = part . encode ( 'utf-8' )
newparts . append ( part )
parts = newparts
if sys . version_info >= ( 2 , 5 ) :
csum = hma... |
def deleteDenylistAddress ( self , * args , ** kwargs ) :
"""Delete Denylisted Address
Delete the specified address from the notification denylist .
This method takes input : ` ` v1 / notification - address . json # ` `
This method is ` ` experimental ` `""" | return self . _makeApiCall ( self . funcinfo [ "deleteDenylistAddress" ] , * args , ** kwargs ) |
def registerAccountResponse ( self , person , vendorSpecific = None ) :
"""CNIdentity . registerAccount ( session , person ) → Subject
https : / / releases . dataone . org / online / api -
documentation - v2.0.1 / apis / CN _ APIs . html # CNIdentity . registerAccount .
Args :
person :
vendorSpecific :
... | mmp_dict = { 'person' : ( 'person.xml' , person . toxml ( 'utf-8' ) ) }
return self . POST ( 'accounts' , fields = mmp_dict , headers = vendorSpecific ) |
def _download_extract_archive ( self , url ) :
"""Returns dict with 2 extracted filenames""" | self . logger . info ( 'Downloading zipfile from ipgeobase.ru...' )
temp_dir = tempfile . mkdtemp ( )
archive = zipfile . ZipFile ( self . _download_url_to_string ( url ) )
self . logger . info ( 'Extracting files...' )
file_cities = archive . extract ( settings . IPGEOBASE_CITIES_FILENAME , path = temp_dir )
file_cidr... |
def drawdowns ( returns , geometric = True ) :
"""compute the drawdown series for the period return series
return : periodic return Series or DataFrame""" | wealth = 1. + returns_cumulative ( returns , geometric = geometric , expanding = True )
values = wealth . values
if values . ndim == 2 :
ncols = values . shape [ - 1 ]
values = np . vstack ( ( [ 1. ] * ncols , values ) )
maxwealth = pd . expanding_max ( values ) [ 1 : ]
dds = wealth / maxwealth - 1.
... |
def keypress ( self , event ) :
"""Allow keys typed in widget to select items""" | try :
self . choice . set ( self . shortcuts [ event . keysym ] )
except KeyError : # key not found ( probably a bug , since we intend to catch
# only events from shortcut keys , but ignore it anyway )
pass |
async def connect ( self , retry = 2 ) :
"""Connect to Mill .""" | # pylint : disable = too - many - return - statements
url = API_ENDPOINT_1 + 'login'
headers = { "Content-Type" : "application/x-zc-object" , "Connection" : "Keep-Alive" , "X-Zc-Major-Domain" : "seanywell" , "X-Zc-Msg-Name" : "millService" , "X-Zc-Sub-Domain" : "milltype" , "X-Zc-Seq-Id" : "1" , "X-Zc-Version" : "1" , ... |
def fbeta ( y_pred : Tensor , y_true : Tensor , thresh : float = 0.2 , beta : float = 2 , eps : float = 1e-9 , sigmoid : bool = True ) -> Rank0Tensor :
"Computes the f _ beta between ` preds ` and ` targets `" | beta2 = beta ** 2
if sigmoid :
y_pred = y_pred . sigmoid ( )
y_pred = ( y_pred > thresh ) . float ( )
y_true = y_true . float ( )
TP = ( y_pred * y_true ) . sum ( dim = 1 )
prec = TP / ( y_pred . sum ( dim = 1 ) + eps )
rec = TP / ( y_true . sum ( dim = 1 ) + eps )
res = ( prec * rec ) / ( prec * beta2 + rec + eps ... |
def getScreenRGB ( self , screen_data = None ) :
"""This function fills screen _ data with the data
screen _ data MUST be a numpy array of uint32 / int32 . This can be initialized like so :
screen _ data = np . array ( w * h , dtype = np . uint32)
Notice , it must be width * height in size also
If it is Non... | if ( screen_data is None ) :
width = ale_lib . getScreenWidth ( self . obj )
height = ale_lib . getScreenWidth ( self . obj )
screen_data = np . zeros ( width * height , dtype = np . uint32 )
ale_lib . getScreenRGB ( self . obj , as_ctypes ( screen_data ) )
return screen_data |
def tree_to_nodes ( tree , context = None , metadata = None ) :
"""Assembles ` ` tree ` ` nodes into object models .
If ` ` context ` ` is supplied , it will be used to contextualize
the contents of the nodes . Metadata will pass non - node identifying
values down to child nodes , if not overridden ( license ... | nodes = [ ]
for item in tree [ 'contents' ] :
if 'contents' in item :
sub_nodes = tree_to_nodes ( item , context = context , metadata = metadata )
if metadata is None :
metadata = { }
else :
metadata = metadata . copy ( )
for key in ( 'title' , 'id' , 'sho... |
def unicode_body ( self , ignore_errors = True , fix_special_entities = True ) :
"""Return response body as unicode string .""" | if not self . _unicode_body :
self . _unicode_body = self . convert_body_to_unicode ( body = self . body , bom = self . bom , charset = self . charset , ignore_errors = ignore_errors , fix_special_entities = fix_special_entities , )
return self . _unicode_body |
def calculate_checksum ( self ) :
"""Calculate ISBN checksum .
Returns :
` ` str ` ` : ISBN checksum value""" | if len ( self . isbn ) in ( 9 , 12 ) :
return calculate_checksum ( self . isbn )
else :
return calculate_checksum ( self . isbn [ : - 1 ] ) |
def __get_query_filters ( cls , filters = { } , inverse = False ) :
"""Convert a dict with the filters to be applied ( { " name1 " : " value1 " , " name2 " : " value2 " } )
to a list of query objects which can be used together in a query using boolean
combination logic .
: param filters : dict with the filter... | query_filters = [ ]
for name in filters :
if name [ 0 ] == '*' and not inverse : # An inverse filter and not inverse mode
continue
if name [ 0 ] != '*' and inverse : # A direct filter and inverse mode
continue
field_name = name [ 1 : ] if name [ 0 ] == '*' else name
params = { field_name... |
def mim2reg ( mimfile , regfile ) :
"""Convert a MIMAS region ( . mim ) file into a DS9 region ( . reg ) file .
Parameters
mimfile : str
Input file in MIMAS format .
regfile : str
Output file .""" | region = Region . load ( mimfile )
region . write_reg ( regfile )
logging . info ( "Converted {0} -> {1}" . format ( mimfile , regfile ) )
return |
def format_search ( q , ** kwargs ) :
'''Formats the results of a search''' | m = search ( q , ** kwargs )
count = m [ 'count' ]
if not count :
raise DapiCommError ( 'Could not find any DAP packages for your query.' )
return
for mdap in m [ 'results' ] :
mdap = mdap [ 'content_object' ]
return _format_dap_with_description ( mdap ) |
def save ( self , path_info , checksum ) :
"""Save checksum for the specified path info .
Args :
path _ info ( dict ) : path _ info to save checksum for .
checksum ( str ) : checksum to save .""" | assert path_info [ "scheme" ] == "local"
assert checksum is not None
path = path_info [ "path" ]
assert os . path . exists ( path )
actual_mtime , actual_size = get_mtime_and_size ( path )
actual_inode = get_inode ( path )
existing_record = self . get_state_record_for_inode ( actual_inode )
if not existing_record :
... |
def notify ( self , * args , ** kwargs ) :
"See signal" | loop = kwargs . pop ( 'loop' , self . loop )
return self . signal . prepare_notification ( subscribers = self . subscribers , instance = self . instance , loop = loop ) . run ( * args , ** kwargs ) |
def umi_consensus ( data ) :
"""Convert UMI grouped reads into fastq pair for re - alignment .""" | align_bam = dd . get_work_bam ( data )
umi_method , umi_tag = _check_umi_type ( align_bam )
f1_out = "%s-cumi-1.fq.gz" % utils . splitext_plus ( align_bam ) [ 0 ]
f2_out = "%s-cumi-2.fq.gz" % utils . splitext_plus ( align_bam ) [ 0 ]
avg_coverage = coverage . get_average_coverage ( "rawumi" , dd . get_variant_regions (... |
def rfc2822_format ( val ) :
"""Takes either a date , a datetime , or a string , and returns a string that
represents the value in RFC 2822 format . If a string is passed it is
returned unchanged .""" | if isinstance ( val , six . string_types ) :
return val
elif isinstance ( val , ( datetime . datetime , datetime . date ) ) : # Convert to a timestamp
val = time . mktime ( val . timetuple ( ) )
if isinstance ( val , numbers . Number ) :
return email . utils . formatdate ( val )
else : # Bail
return val |
def drop_empty ( arr ) :
"""Drop empty array element
: param arr :
: return :""" | return [ x for x in arr if not isinstance ( x , list ) or len ( x ) > 0 ] |
def rpc ( self , address , rpc_id ) :
"""Call an RPC and receive the result as an integer .
If the RPC does not properly return a 32 bit integer , raise a warning
unless it cannot be converted into an integer at all , in which case
a HardwareError is thrown .
Args :
address ( int ) : The address of the ti... | # Always allow mocking an RPC to override whatever the defaul behavior is
if address in self . mock_rpcs and rpc_id in self . mock_rpcs [ address ] :
value = self . mock_rpcs [ address ] [ rpc_id ]
return value
result = self . _call_rpc ( address , rpc_id , bytes ( ) )
if len ( result ) != 4 :
self . warn (... |
def is_valid_embedding ( emb , source , target ) :
"""A simple ( bool ) diagnostic for minor embeddings .
See : func : ` diagnose _ embedding ` for a more detailed diagnostic / more information .
Args :
emb ( dict ) : a dictionary mapping source nodes to arrays of target nodes
source ( graph or edgelist ) :... | for _ in diagnose_embedding ( emb , source , target ) :
return False
return True |
def GetBalance ( self , asset_id , watch_only = 0 ) :
"""Get the balance of a specific token by its asset id .
Args :
asset _ id ( NEP5Token | TransactionOutput ) : an instance of type neo . Wallets . NEP5Token or neo . Core . TX . Transaction . TransactionOutput to get the balance from .
watch _ only ( bool ... | total = Fixed8 ( 0 )
if type ( asset_id ) is NEP5Token . NEP5Token :
return self . GetTokenBalance ( asset_id , watch_only )
for coin in self . GetCoins ( ) :
if coin . Output . AssetId == asset_id :
if coin . State & CoinState . Confirmed > 0 and coin . State & CoinState . Spent == 0 and coin . State &... |
def fit ( self , counts_df , val_set = None ) :
"""Fit Hierarchical Poisson Model to sparse count data
Fits a hierarchical Poisson model to count data using mean - field approximation with either
full - batch coordinate - ascent or mini - batch stochastic coordinate - ascent .
Note
DataFrames and arrays pas... | # # a basic check
if self . stop_crit == 'val-llk' :
if val_set is None :
raise ValueError ( "If 'stop_crit' is set to 'val-llk', must provide a validation set." )
# # running each sub - process
if self . verbose :
self . _print_st_msg ( )
self . _process_data ( counts_df )
if self . verbose :
self ... |
def merge_sketches ( outdir , sketch_paths ) :
"""Merge new Mash sketches with current Mash sketches
Args :
outdir ( str ) : output directory to write merged Mash sketch file
sketch _ paths ( list of str ) : Mash sketch file paths for input fasta files
Returns :
str : output path for Mash sketch file with... | merge_sketch_path = os . path . join ( outdir , 'sistr.msh' )
args = [ 'mash' , 'paste' , merge_sketch_path ]
for x in sketch_paths :
args . append ( x )
args . append ( MASH_SKETCH_FILE )
logging . info ( 'Running Mash paste with command: %s' , ' ' . join ( args ) )
p = Popen ( args )
p . wait ( )
assert os . path... |
def warn_for_geometry_collections ( self ) :
"""Checks for GeoJson GeometryCollection features to warn user about incompatibility .""" | geom_collections = [ feature . get ( 'properties' ) if feature . get ( 'properties' ) is not None else key for key , feature in enumerate ( self . _parent . data [ 'features' ] ) if feature [ 'geometry' ] [ 'type' ] == 'GeometryCollection' ]
if any ( geom_collections ) :
warnings . warn ( "GeoJsonTooltip is not con... |
def fix_config ( self , options ) :
"""Fixes the options , if necessary . I . e . , it adds all required elements to the dictionary .
: param options : the options to fix
: type options : dict
: return : the ( potentially ) fixed options
: rtype : dict""" | opt = "db_url"
if opt not in options :
options [ opt ] = "jdbc:mysql://somehost:3306/somedatabase"
if opt not in self . help :
self . help [ opt ] = "The JDBC database URL to connect to (str)."
opt = "user"
if opt not in options :
options [ opt ] = "user"
if opt not in self . help :
self . help [ opt ] ... |
def pack_column_flat ( self , value , components = None , offset = False ) :
"""TODO : add documentation""" | if components :
if isinstance ( components , str ) :
components = [ components ]
elif isinstance ( components , list ) :
components = components
else :
raise TypeError ( "components should be list or string, not {}" . format ( type ( components ) ) )
elif isinstance ( value , dict ) ... |
def to_column_format ( self , high_density_vertical = True ) :
"""Extract slices of an image as equal - sized blobs of column - format data .
: param high _ density _ vertical : Printed line height in dots""" | im = self . _im . transpose ( Image . ROTATE_270 ) . transpose ( Image . FLIP_LEFT_RIGHT )
line_height = 24 if high_density_vertical else 8
width_pixels , height_pixels = im . size
top = 0
left = 0
while left < width_pixels :
box = ( left , top , left + line_height , top + height_pixels )
im_slice = im . transf... |
def read_legacy_cfg_files ( self , cfg_files , alignak_env_files = None ) : # pylint : disable = too - many - nested - blocks , too - many - statements
# pylint : disable = too - many - branches , too - many - locals
"""Read and parse the Nagios legacy configuration files
and store their content into a StringIO o... | cfg_buffer = ''
if not cfg_files :
return cfg_buffer
# Update configuration with the first legacy configuration file name and path
# This will update macro properties
self . alignak_env = 'n/a'
if alignak_env_files is not None :
self . alignak_env = alignak_env_files
if not isinstance ( alignak_env_files , ... |
def get_stft_kernels ( n_dft ) :
"""[ np ] Return dft kernels for real / imagnary parts assuming
the input . is real .
An asymmetric hann window is used ( scipy . signal . hann ) .
Parameters
n _ dft : int > 0 and power of 2 [ scalar ]
Number of dft components .
Returns
| dft _ real _ kernels : np . n... | assert n_dft > 1 and ( ( n_dft & ( n_dft - 1 ) ) == 0 ) , ( 'n_dft should be > 1 and power of 2, but n_dft == %d' % n_dft )
nb_filter = int ( n_dft // 2 + 1 )
# prepare DFT filters
timesteps = np . array ( range ( n_dft ) )
w_ks = np . arange ( nb_filter ) * 2 * np . pi / float ( n_dft )
dft_real_kernels = np . cos ( w... |
def apply_scopes ( self ) :
"""Get the underlying query builder instance with applied global scopes .
: type : Builder""" | if not self . _scopes :
return self
builder = copy . copy ( self )
query = builder . get_query ( )
# We will keep track of how many wheres are on the query before running the
# scope so that we can properly group the added scope constraints in the
# query as their own isolated nested where statement and avoid issue... |
def note_revert ( self , note_id , version_id ) :
"""Function to revert a specific note ( Requires login ) ( UNTESTED ) .
Parameters :
note _ id ( int ) : Where note _ id is the note id .
version _ id ( int ) : The note version id to revert to .""" | return self . _get ( 'notes/{0}/revert.json' . format ( note_id ) , { 'version_id' : version_id } , method = 'PUT' , auth = True ) |
def get_per_channel_mean ( self , names = ( 'train' , 'test' ) ) :
"""Args :
names ( tuple [ str ] ) : the names ( ' train ' or ' test ' ) of the datasets
Returns :
An array of three values as mean of each channel , for all images in the given datasets .""" | mean = self . get_per_pixel_mean ( names )
return np . mean ( mean , axis = ( 0 , 1 ) ) |
def deltafmt ( delta , decimals = None ) :
"""Returns a human readable representation of a time with the format :
[ [ [ Ih ] Jm ] K [ . L ] s
For example : 6h5m23s
If " decimals " is specified , the seconds will be output with that many decimal places .
If not , there will be two places for times less than ... | try :
delta = float ( delta )
except :
return '(bad delta: %s)' % ( str ( delta ) , )
if delta < 60 :
if decimals is None :
decimals = 2
return ( "{0:." + str ( decimals ) + "f}s" ) . format ( delta )
mins = int ( delta / 60 )
secs = delta - mins * 60
if delta < 600 :
if decimals is None :
... |
def _set_ignored_version ( version ) :
"""Private helper function that writes the most updated
API version that was ignored by a user in the app
: param version : Most recent ignored API update""" | data = { 'version' : version }
with open ( filepath , 'w' ) as data_file :
json . dump ( data , data_file ) |
def update ( self , truth , guess , features ) :
"""Update the feature weights .""" | def upd_feat ( c , f , w , v ) :
param = ( f , c )
self . _totals [ param ] += ( self . i - self . _tstamps [ param ] ) * w
self . _tstamps [ param ] = self . i
self . weights [ f ] [ c ] = w + v
self . i += 1
if truth == guess :
return None
for f in features :
weights = self . weights . setdefa... |
def loadFeatures ( self , path_to_fc ) :
"""loads a feature class features to the object""" | from . . common . spatial import featureclass_to_json
v = json . loads ( featureclass_to_json ( path_to_fc ) )
self . value = v |
def _init_metadata ( self ) :
"""stub""" | QuestionTextFormRecord . _init_metadata ( self )
QuestionFilesFormRecord . _init_metadata ( self )
super ( QuestionTextAndFilesMixin , self ) . _init_metadata ( ) |
def init_net_params ( scale , layer_sizes , rs = npr . RandomState ( 0 ) ) :
"""Build a ( weights , biases ) tuples for all layers .""" | return [ ( scale * rs . randn ( m , n ) , # weight matrix
scale * rs . randn ( n ) ) # bias vector
for m , n in zip ( layer_sizes [ : - 1 ] , layer_sizes [ 1 : ] ) ] |
def disableIndexing ( self ) :
'''disableIndexing - Disables indexing . Consider using plain AdvancedHTMLParser class .
Maybe useful in some scenarios where you want to parse , add a ton of elements , then index
and do a bunch of searching .''' | self . indexIDs = self . indexNames = self . indexClassNames = self . indexTagNames = False
self . _resetIndexInternal ( ) |
def assemble ( self ) :
"""Mangle self into an argument array""" | self . canonify ( )
args = [ sys . argv and sys . argv [ 0 ] or "python" ]
if self . mountpoint :
args . append ( self . mountpoint )
for m , v in self . modifiers . items ( ) :
if v :
args . append ( self . fuse_modifiers [ m ] )
opta = [ ]
for o , v in self . optdict . items ( ) :
opta . append ( ... |
def create ( self , quality_score , issue = values . unset ) :
"""Create a new FeedbackInstance
: param unicode quality _ score : The call quality expressed as an integer from 1 to 5
: param FeedbackInstance . Issues issue : Issues experienced during the call
: returns : Newly created FeedbackInstance
: rty... | data = values . of ( { 'QualityScore' : quality_score , 'Issue' : serialize . map ( issue , lambda e : e ) , } )
payload = self . _version . create ( 'POST' , self . _uri , data = data , )
return FeedbackInstance ( self . _version , payload , account_sid = self . _solution [ 'account_sid' ] , call_sid = self . _solutio... |
def next ( self , timeout = 0 ) :
"""Return empty unless new data is ready for the client .
Arguments :
timeout : Default timeout = 0 range zero to float specifies a time - out as a floating point
number in seconds . Will sit and wait for timeout seconds . When the timeout argument is omitted
the function b... | try :
waitin , _waitout , _waiterror = select . select ( ( self . streamSock , ) , ( ) , ( ) , timeout )
if not waitin :
return
else :
gpsd_response = self . streamSock . makefile ( )
# ' . makefile ( buffering = 4096 ) ' In strictly Python3
self . response = gpsd_response . ... |
def diff ( self , filename , wildcard = '*' ) :
'''show differences with another parameter file''' | other = MAVParmDict ( )
if not other . load ( filename ) :
return
keys = sorted ( list ( set ( self . keys ( ) ) . union ( set ( other . keys ( ) ) ) ) )
for k in keys :
if not fnmatch . fnmatch ( str ( k ) . upper ( ) , wildcard . upper ( ) ) :
continue
if not k in other :
print ( "%-16.16s... |
def created ( filename ) :
'''Retrieve how long ago a file has been created .
: param filename : name of the file
> > > print created ( ' / ' ) # doctest : + SKIP
8 weeks ago''' | if isinstance ( filename , file ) :
filename = filename . name
return duration ( os . stat ( filename ) [ stat . ST_CTIME ] ) |
def about_time ( fn = None , it = None ) :
"""Measures the execution time of a block of code , and even counts iterations
and the throughput of them , always with a beautiful " human " representation .
There ' s three modes of operation : context manager , callable handler and
iterator metrics .
1 . Use it ... | # has to be here to be mockable .
if sys . version_info >= ( 3 , 3 ) :
timer = time . perf_counter
else : # pragma : no cover
timer = time . time
@ contextmanager
def context ( ) :
timings [ 0 ] = timer ( )
yield handle
timings [ 1 ] = timer ( )
timings = [ 0.0 , 0.0 ]
handle = Handle ( timings )
if... |
def set_matrix ( self , matrix ) :
"""Sets the pattern ’ s transformation matrix to : obj : ` matrix ` .
This matrix is a transformation from user space to pattern space .
When a pattern is first created
it always has the identity matrix for its transformation matrix ,
which means that pattern space is init... | cairo . cairo_pattern_set_matrix ( self . _pointer , matrix . _pointer )
self . _check_status ( ) |
def gate_angle ( gate0 : Gate , gate1 : Gate ) -> bk . BKTensor :
"""The Fubini - Study angle between gates""" | return fubini_study_angle ( gate0 . vec , gate1 . vec ) |
def close ( self ) :
"""Iterate through all of the connections and close each one .""" | if not self . _closed :
self . _closed = True
self . _stop_multi_pools ( )
if self . _http_pool is not None :
self . _http_pool . clear ( )
self . _http_pool = None
if self . _tcp_pool is not None :
self . _tcp_pool . clear ( )
self . _tcp_pool = None |
def list_csi_driver ( self , ** kwargs ) :
"""list or watch objects of kind CSIDriver
This method makes a synchronous HTTP request by default . To make an
asynchronous HTTP request , please pass async _ req = True
> > > thread = api . list _ csi _ driver ( async _ req = True )
> > > result = thread . get ( ... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'async_req' ) :
return self . list_csi_driver_with_http_info ( ** kwargs )
else :
( data ) = self . list_csi_driver_with_http_info ( ** kwargs )
return data |
def data ( self , column , role ) :
"""Return the data for the column and role
: param column : the data column
: type column : int
: param role : the data role
: type role : QtCore . Qt . ItemDataRole
: returns : data depending on the role
: rtype :
: raises : None""" | if self . _data is not None and ( column >= 0 or column < self . _data . column_count ( ) ) :
return self . _data . data ( column , role ) |
def _account_table ( accounts ) :
"""creates a lookup table ( emailaddress - > account ) for a given list of
accounts
: param accounts : list of accounts
: type accounts : list of ` alot . account . Account `
: returns : hashtable
: rvalue : dict ( str - > ` alot . account . Account ` )""" | accountmap = { }
for acc in accounts :
accountmap [ acc . address ] = acc
for alias in acc . aliases :
accountmap [ alias ] = acc
return accountmap |
def remove_attr ( self , attr_name ) :
"""Remove cookie attribute . Cookie attribute couldn ' t be removed if cookie is in read - only mode
( RuntimeError exception is raised ) .
: param attr _ name : name of attribute to remove
: return : None""" | if self . __ro_flag :
raise RuntimeError ( 'Read-only cookie changing attempt' )
name = self . __attr_name ( attr_name )
if name in self . __attrs . keys ( ) :
self . __attrs . pop ( attr_name ) |
def colorMap ( value , name = "jet" , vmin = None , vmax = None ) :
"""Map a real value in range [ vmin , vmax ] to a ( r , g , b ) color scale .
: param value : scalar value to transform into a color
: type value : float , list
: param name : color map name
: type name : str , matplotlib . colors . LinearS... | if not _mapscales :
print ( "-------------------------------------------------------------------" )
print ( "WARNING : cannot import matplotlib.cm (colormaps will show up gray)." )
print ( "Try e.g.: sudo apt-get install python3-matplotlib" )
print ( " or : pip install matplotlib" )
print ( " ... |
def disassociate_environment_option_pool ( self , environment_option_id ) :
"""Remove a relationship of optionpool with Environment .
: param id _ option _ pool : Identifier of the Option Pool . Integer value and greater than zero .
: param id _ environment : Identifier of the Environment Pool . Integer value a... | if not is_valid_int_param ( environment_option_id ) :
raise InvalidParameterError ( u'The identifier of Option Pool is invalid or was not informed.' )
if not is_valid_int_param ( environment_option_id ) :
raise InvalidParameterError ( u'The identifier of Environment Pool is invalid or was not informed.' )
url =... |
def arguments ( self ) :
"""Get an iterable object providing each argument in the
command line for the compiler invocation as a _ CXString .
Invariant : the first argument is the compiler executable""" | length = conf . lib . clang_CompileCommand_getNumArgs ( self . cmd )
for i in xrange ( length ) :
yield str ( conf . lib . clang_CompileCommand_getArg ( self . cmd , i ) ) |
def get_hosts_from_csv ( filename , default_protocol = 'telnet' , default_domain = '' , encoding = 'utf-8' ) :
"""Reads a list of hostnames and variables from the tab - separated . csv file
with the given name . The first line of the file must contain the column
names , e . g . : :
addresstestvar1testvar2
1... | # Open the file .
if not os . path . exists ( filename ) :
raise IOError ( 'No such file: %s' % filename )
with codecs . open ( filename , 'r' , encoding ) as file_handle : # Read and check the header .
header = file_handle . readline ( ) . rstrip ( )
if re . search ( r'^(?:hostname|address)\b' , header ) i... |
def circular_hough ( img , radius , nangles = None , mask = None ) :
'''Circular Hough transform of an image
img - image to be transformed .
radius - radius of circle
nangles - # of angles to measure , e . g . nangles = 4 means accumulate at
0 , 90 , 180 and 270 degrees .
Return the Hough transform of the... | a = np . zeros ( img . shape )
m = np . zeros ( img . shape )
if nangles is None : # if no angle specified , take the circumference
# Round to a multiple of 4 to make it bilaterally stable
nangles = int ( np . pi * radius + 3.5 ) & ( ~ 3 )
for i in range ( nangles ) :
theta = 2 * np . pi * float ( i ) / float (... |
def cyl_to_rect ( R , phi , Z ) :
"""NAME :
cyl _ to _ rect
PURPOSE :
convert from cylindrical to rectangular coordinates
INPUT :
R , phi , Z - cylindrical coordinates
OUTPUT :
X , Y , Z
HISTORY :
2011-02-23 - Written - Bovy ( NYU )""" | return ( R * sc . cos ( phi ) , R * sc . sin ( phi ) , Z ) |
def _compile_references ( self , url , tree ) :
'''Returns a list of catalog reference URLs for the current catalog
: param str url : URL for the current catalog
: param lxml . etree . Eleemnt tree : Current XML Tree''' | references = [ ]
for ref in tree . findall ( './/{%s}catalogRef' % INV_NS ) : # Check skips
title = ref . get ( "{%s}title" % XLINK_NS )
if any ( [ x . match ( title ) for x in self . skip ] ) :
logger . info ( "Skipping catalogRef based on 'skips'. Title: %s" % title )
continue
references ... |
def apply ( filter ) :
"""Manufacture decorator that filters return value with given function .
` ` filter ` ` :
Callable that takes a single parameter .""" | def decorator ( callable ) :
return lambda * args , ** kwargs : filter ( callable ( * args , ** kwargs ) )
return decorator |
def _process_mrk_marker_view ( self , limit ) :
"""This is the definition of markers
( as in genes , but other genomic loci types as well ) .
It looks up the identifiers in the hashmap
This includes their labels , specific class , and identifiers
TODO should we use the mrk _ mouse _ view instead ?
Triples... | if self . test_mode :
graph = self . testgraph
else :
graph = self . graph
model = Model ( graph )
geno = Genotype ( graph )
line_counter = 0
raw = '/' . join ( ( self . rawdir , 'mrk_marker_view' ) )
LOG . info ( "getting markers and assigning types" )
with open ( raw , 'r' ) as f :
f . readline ( )
# ... |
def demote ( self , mode ) :
"""Demote PostgreSQL running as master .
: param mode : One of offline , graceful or immediate .
offline is used when connection to DCS is not available .
graceful is used when failing over to another node due to user request . May only be called running async .
immediate is use... | mode_control = { 'offline' : dict ( stop = 'fast' , checkpoint = False , release = False , offline = True , async_req = False ) , 'graceful' : dict ( stop = 'fast' , checkpoint = True , release = True , offline = False , async_req = False ) , 'immediate' : dict ( stop = 'immediate' , checkpoint = False , release = True... |
def thin ( image , mask = None , iterations = 1 ) :
'''Thin an image to lines , preserving Euler number
Implements thinning as described in algorithm # 1 from
Guo , " Parallel Thinning with Two Subiteration Algorithms " ,
Communications of the ACM , Vol 32 # 3 page 359.''' | global thin_table , eight_connect
if thin_table is None :
thin_table = np . zeros ( ( 2 , 512 ) , bool )
for i in range ( 512 ) :
if ( i & 16 ) == 0 : # All zeros - > 0
continue
pat = pattern_of ( i & ~ 16 )
ipat = pat . astype ( int )
if scind . label ( pat , eight_c... |
async def load_kube_config ( config_file = None , context = None , client_configuration = None , persist_config = True ) :
"""Loads authentication and cluster information from kube - config file
and stores them in kubernetes . client . configuration .
: param config _ file : Name of the kube - config file .
:... | if config_file is None :
config_file = KUBE_CONFIG_DEFAULT_LOCATION
loader = _get_kube_config_loader_for_yaml_file ( config_file , active_context = context , persist_config = persist_config )
if client_configuration is None :
config = type . __call__ ( Configuration )
await loader . load_and_set ( config )
... |
def addRnaQuantMetadata ( self , fields ) :
"""data elements are :
Id , annotations , description , name , readGroupId
where annotations is a comma separated list""" | self . _featureSetIds = fields [ "feature_set_ids" ] . split ( ',' )
self . _description = fields [ "description" ]
self . _name = fields [ "name" ]
self . _biosampleId = fields . get ( "biosample_id" , "" )
if fields [ "read_group_ids" ] == "" :
self . _readGroupIds = [ ]
else :
self . _readGroupIds = fields [... |
def update_config ( self , config , timeout = - 1 ) :
"""Updates the remote server configuration and the automatic backup schedule for backup .
Args :
config ( dict ) : Object to update .
timeout :
Timeout in seconds . Wait for task completion by default . The timeout does not abort the operation
in OneVi... | return self . _client . update ( config , uri = self . URI + "/config" , timeout = timeout ) |
def __upload_chunk ( self , resource , chunk_size , bytes , bytes_start , bytes_read ) :
"""Uploads a single chunk of a multi - chunk upload .""" | # note : string conversion required here due to open encoding bug in requests - oauthlib .
headers = { 'content-type' : self . content_type , 'content-length' : str ( min ( [ chunk_size , self . _file_size - bytes_read ] ) ) , 'content-range' : "bytes {0}-{1}/{2}" . format ( bytes_start , bytes_read - 1 , self . _file_... |
def _connect ( self ) :
"""Establish connection to MySQL Database .""" | if self . _connParams :
self . _conn = MySQLdb . connect ( ** self . _connParams )
else :
self . _conn = MySQLdb . connect ( '' ) |
def _call ( self , x , out = None ) :
"""Implement ` ` self ( x [ , out ] ) ` ` .""" | if out is None :
return self . operator ( x * self . vector )
else :
tmp = self . domain . element ( )
x . multiply ( self . vector , out = tmp )
self . operator ( tmp , out = out ) |
def render_alert ( content , alert_type = None , dismissable = True ) :
"""Render a Bootstrap alert""" | button = ""
if not alert_type :
alert_type = "info"
css_classes = [ "alert" , "alert-" + text_value ( alert_type ) ]
if dismissable :
css_classes . append ( "alert-dismissable" )
button = ( '<button type="button" class="close" ' + 'data-dismiss="alert" aria-hidden="true">×</button>' )
button_placehold... |
def key ( string ) :
"""Return a Czech sort key for the given string
: param string : string ( unicode in Python 2)
Comparing the sort keys of two strings will give the result according
to how the strings would compare in Czech collation order , i . e .
` ` key ( s1 ) < key ( s2 ) ` ` < = > ` ` s1 ` ` comes... | # The multi - level key is a nested tuple containing strings and ints .
# The tuple contains sub - keys that roughly correspond to levels in
# UTS # 10 ( http : / / unicode . org / reports / tr10 / ) . Except for fallback strings
# at the end , each contains a tuple of typically one key per element / letter .
# - Alpha... |
def get_link ( self , task_id ) :
"""Get a ` ` LinkOfTrust ` ` by task id .
Args :
task _ id ( str ) : the task id to find .
Returns :
LinkOfTrust : the link matching the task id .
Raises :
CoTError : if no ` ` LinkOfTrust ` ` matches .""" | links = [ x for x in self . links if x . task_id == task_id ]
if len ( links ) != 1 :
raise CoTError ( "No single Link matches task_id {}!\n{}" . format ( task_id , self . dependent_task_ids ( ) ) )
return links [ 0 ] |
def getGUA ( self , filterByPrefix = None ) :
"""get expected global unicast IPv6 address of Thread device
Args :
filterByPrefix : a given expected global IPv6 prefix to be matched
Returns :
a global IPv6 address""" | print '%s call getGUA' % self . port
print filterByPrefix
globalAddrs = [ ]
try : # get global addrs set if multiple
globalAddrs = self . getGlobal ( )
if filterByPrefix is None :
return globalAddrs [ 0 ]
else :
for line in globalAddrs :
fullIp = ModuleHelper . GetFullIpv6Address... |
def _cli ( cls , opts ) :
"""Setup logging via CLI options
If ` - - background ` - - set INFO level for root logger .
If ` - - logdir ` - - set logging with next params :
default Luigi ' s formatter ,
INFO level ,
output in logdir in ` luigi - server . log ` file""" | if opts . background :
logging . getLogger ( ) . setLevel ( logging . INFO )
return True
if opts . logdir :
logging . basicConfig ( level = logging . INFO , format = cls . _log_format , filename = os . path . join ( opts . logdir , "luigi-server.log" ) )
return True
return False |
def _MapLegacyArgs ( nt , message , ref ) :
"""Maps UserNotification object to legacy GRRUser . Notify arguments .""" | unt = rdf_objects . UserNotification . Type
if nt == unt . TYPE_CLIENT_INTERROGATED :
return [ "Discovery" , aff4 . ROOT_URN . Add ( ref . client . client_id ) , _HostPrefix ( ref . client . client_id ) + message , "" , ]
elif nt == unt . TYPE_CLIENT_APPROVAL_REQUESTED :
return [ "GrantAccess" , aff4 . ROOT_URN... |
def memsize ( self ) :
"""Total array cell + indexes size""" | return self . size + 1 + TYPE . size ( gl . BOUND_TYPE ) * len ( self . bounds ) |
def get_search_fields ( cls ) :
"""Returns search fields in sfdict""" | sfdict = { }
for klass in tuple ( cls . __bases__ ) + ( cls , ) :
if hasattr ( klass , 'search_fields' ) :
sfdict . update ( klass . search_fields )
return sfdict |
def handle ( self , * args , ** options ) :
"""Create Customer objects for Subscribers without Customer objects associated .""" | for subscriber in get_subscriber_model ( ) . objects . filter ( djstripe_customers = None ) : # use get _ or _ create in case of race conditions on large subscriber bases
Customer . get_or_create ( subscriber = subscriber )
print ( "Created subscriber for {0}" . format ( subscriber . email ) ) |
def subscribe ( self , subject , callback , queue = '' ) :
"""Subscribe will express interest in the given subject . The subject can
have wildcards ( partial : * , full : > ) . Messages will be delivered to the
associated callback .
Args :
subject ( string ) : a string with the subject
callback ( function... | s = Subscription ( sid = self . _next_sid , subject = subject , queue = queue , callback = callback , connetion = self )
self . _subscriptions [ s . sid ] = s
self . _send ( 'SUB %s %s %d' % ( s . subject , s . queue , s . sid ) )
self . _next_sid += 1
return s |
def sky_to_image ( shape_list , header ) :
"""Converts a ` ShapeList ` into shapes with coordinates in image coordinates
Parameters
shape _ list : ` pyregion . ShapeList `
The ShapeList to convert
header : ` ~ astropy . io . fits . Header `
Specifies what WCS transformations to use .
Yields
shape , co... | for shape , comment in shape_list :
if isinstance ( shape , Shape ) and ( shape . coord_format not in image_like_coordformats ) :
new_coords = convert_to_imagecoord ( shape , header )
l1n = copy . copy ( shape )
l1n . coord_list = new_coords
l1n . coord_format = "image"
yield... |
def do_up ( self , arg ) :
"""u ( p ) [ count ]
Move the current frame count ( default one ) levels up in the
stack trace ( to an older frame ) .""" | if self . curindex == 0 :
self . error ( 'Oldest frame' )
return
try :
count = int ( arg or 1 )
except ValueError :
self . error ( 'Invalid frame count (%s)' % arg )
return
if count < 0 :
newframe = 0
else :
newframe = max ( 0 , self . curindex - count )
self . _select_frame ( newframe ) |
def _parse_header_params ( self , header_param_lines ) :
'''解析头部参数''' | headers = { }
for line in header_param_lines :
if line . strip ( ) : # 跳过空行
key , val = line . split ( ':' , 1 )
headers [ key . lower ( ) ] = val . strip ( )
return headers |
def iter_files ( root , exts = None , recursive = False ) :
"""Iterate over file paths within root filtered by specified extensions .
: param compat . string _ types root : Root folder to start collecting files
: param iterable exts : Restrict results to given file extensions
: param bool recursive : Wether t... | if exts is not None :
exts = set ( ( x . lower ( ) for x in exts ) )
def matches ( e ) :
return ( exts is None ) or ( e in exts )
if recursive is False :
for entry in compat . scandir ( root ) :
if compat . has_scandir :
ext = splitext ( entry . name ) [ - 1 ] . lstrip ( '.' ) . lower ( ... |
def print_inheritance ( doc , stream ) : # type : ( List [ Dict [ Text , Any ] ] , IO ) - > None
"""Write a Grapviz inheritance graph for the supplied document .""" | stream . write ( "digraph {\n" )
for entry in doc :
if entry [ "type" ] == "record" :
label = name = shortname ( entry [ "name" ] )
fields = entry . get ( "fields" , [ ] )
if fields :
label += "\\n* %s\\l" % ( "\\l* " . join ( shortname ( field [ "name" ] ) for field in fields ) ... |
def redo ( self ) :
"""Redo the last action .
This will call ` redo ( ) ` on all controllers involved in this action .""" | controllers = self . forward ( )
if controllers is None :
ups = ( )
else :
ups = tuple ( [ controller . redo ( ) for controller in controllers ] )
if self . process_ups is not None :
return self . process_ups ( ups )
else :
return ups |
def get_lines ( command ) :
"""Run a command and return lines of output
: param str command : the command to run
: returns : list of whitespace - stripped lines output by command""" | stdout = get_output ( command )
return [ line . strip ( ) . decode ( 'utf-8' ) for line in stdout . splitlines ( ) ] |
def p_expr_LE_expr ( p ) :
"""expr : expr LE expr""" | p [ 0 ] = make_binary ( p . lineno ( 2 ) , 'LE' , p [ 1 ] , p [ 3 ] , lambda x , y : x <= y ) |
def add_method ( self , pattern ) :
"""Decorator to add new dispatch functions .""" | def wrap ( f ) :
def frozen_function ( class_instance , f ) :
def _ ( pattern , * args , ** kwargs ) :
return f ( class_instance , pattern , * args , ** kwargs )
return _
self . functions . append ( ( frozen_function ( self , f ) , pattern ) )
return f
return wrap |
def valuetype_class ( self ) :
"""Return the valuetype class , if one is defined , or a built - in type if it isn ' t""" | from ambry . valuetype import resolve_value_type
if self . valuetype :
return resolve_value_type ( self . valuetype )
else :
return resolve_value_type ( self . datatype ) |
def get_miller_index_from_site_indexes ( self , site_ids , round_dp = 4 , verbose = True ) :
"""Get the Miller index of a plane from a set of sites indexes .
A minimum of 3 sites are required . If more than 3 sites are given
the best plane that minimises the distance to all points will be
calculated .
Args ... | return self . lattice . get_miller_index_from_coords ( self . frac_coords [ site_ids ] , coords_are_cartesian = False , round_dp = round_dp , verbose = verbose ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.