signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def create_translations_model ( shared_model , related_name , meta , ** fields ) :
"""Dynamically create the translations model .
Create the translations model for the shared model ' model ' .
: param related _ name : The related name for the reverse FK from the translations model .
: param meta : A ( optiona... | if not meta :
meta = { }
if shared_model . _meta . abstract : # This can ' t be done , because ` master = ForeignKey ( shared _ model ) ` would fail .
raise TypeError ( "Can't create TranslatedFieldsModel for abstract class {0}" . format ( shared_model . __name__ ) )
# Define inner Meta class
meta [ 'app_label'... |
def weighted_choice ( choices ) :
"""Returns a value from choices chosen by weighted random selection
choices should be a list of ( value , weight ) tuples .
eg . weighted _ choice ( [ ( ' val1 ' , 5 ) , ( ' val2 ' , 0.3 ) , ( ' val3 ' , 1 ) ] )""" | values , weights = zip ( * choices )
total = 0
cum_weights = [ ]
for w in weights :
total += w
cum_weights . append ( total )
x = random . uniform ( 0 , total )
i = bisect . bisect ( cum_weights , x )
return values [ i ] |
def AFF4AddChild ( self , subject , child , extra_attributes = None ) :
"""Adds a child to the specified parent .""" | precondition . AssertType ( child , Text )
attributes = { DataStore . AFF4_INDEX_DIR_TEMPLATE % child : [ DataStore . EMPTY_DATA_PLACEHOLDER ] }
if extra_attributes :
attributes . update ( extra_attributes )
self . MultiSet ( subject , attributes ) |
def gassist ( self , dg , dt , dt2 , na = None , nodiag = False , memlimit = - 1 ) :
"""Calculates probability of gene i regulating gene j with genotype data assisted method ,
with the recommended combination of multiple tests .
Probabilities are converted from likelihood ratios separately for each A . This giv... | return _gassist_any ( self , dg , dt , dt2 , "pij_gassist" , na = na , nodiag = nodiag , memlimit = memlimit ) |
def actionAngleTorus_jacobian_c ( pot , jr , jphi , jz , angler , anglephi , anglez , tol = 0.003 , dJ = 0.001 ) :
"""NAME :
actionAngleTorus _ jacobian _ c
PURPOSE :
compute d ( x , v ) / d ( J , theta ) on a single torus , also compute dO / dJ and the frequencies
INPUT :
pot - Potential object or list t... | # Parse the potential
from galpy . orbit . integrateFullOrbit import _parse_pot
npot , pot_type , pot_args = _parse_pot ( pot , potfortorus = True )
# Set up result
R = numpy . empty ( len ( angler ) )
vR = numpy . empty ( len ( angler ) )
vT = numpy . empty ( len ( angler ) )
z = numpy . empty ( len ( angler ) )
vz = ... |
def _initDiskStats ( self ) :
"""Parse and initialize block device I / O stats in / proc / diskstats .""" | self . _diskStats = { }
self . _mapMajorMinor2dev = { }
try :
fp = open ( diskStatsFile , 'r' )
data = fp . read ( )
fp . close ( )
except :
raise IOError ( 'Failed reading disk stats from file: %s' % diskStatsFile )
for line in data . splitlines ( ) :
cols = line . split ( )
dev = cols . pop ( ... |
def remove_imports ( ) :
"""Remove Imports""" | text , ok = QtGui . QInputDialog . getText ( None , 'Remove Import' , 'Enter an import line to remove (example: os.path or from os import path):' )
if ok :
sort_kate_imports ( remove_imports = text . split ( ";" ) ) |
def _return ( self , load ) :
'''Handle the return data sent from the minions .
Takes the return , verifies it and fires it on the master event bus .
Typically , this event is consumed by the Salt CLI waiting on the other
end of the event bus but could be heard by any listener on the bus .
: param dict load... | if self . opts [ 'require_minion_sign_messages' ] and 'sig' not in load :
log . critical ( '_return: Master is requiring minions to sign their ' 'messages, but there is no signature in this payload from ' '%s.' , load [ 'id' ] )
return False
if 'sig' in load :
log . trace ( 'Verifying signed event publish f... |
def store_file ( self , folder , name ) :
"""Stores the uploaded file in the given path .""" | path = os . path . join ( folder , name )
length = self . headers [ 'content-length' ]
with open ( path , 'wb' ) as sample :
sample . write ( self . rfile . read ( int ( length ) ) )
return path |
def serialize ( self , data ) :
"""Determine & invoke the proper serializer method
If data is a list then the serialize _ datas method will
be run otherwise serialize _ data .""" | super ( Serializer , self ) . serialize ( data )
body = { 'jsonapi' : { 'version' : goldman . config . JSONAPI_VERSION , } , 'links' : { 'self' : self . req . path , } , 'meta' : { 'included_count' : 0 , 'primary_count' : 0 , 'total_primary' : self . req . pages . total , } , }
included = data [ 'included' ]
if include... |
def newProp ( self , name , value ) :
"""Create a new property carried by a node .""" | ret = libxml2mod . xmlNewProp ( self . _o , name , value )
if ret is None :
raise treeError ( 'xmlNewProp() failed' )
__tmp = xmlAttr ( _obj = ret )
return __tmp |
def predict_log_proba ( self , X ) :
"""Apply transforms , and predict _ log _ proba of the final estimator
Parameters
X : iterable
Data to predict on . Must fulfill input requirements of first step
of the pipeline .
Returns
y _ score : array - like , shape = [ n _ samples , n _ classes ]""" | Xt , _ , _ = self . _transform ( X )
return self . _final_estimator . predict_log_proba ( Xt ) |
def get_channel_access ( channel = 14 , read_mode = 'non_volatile' , ** kwargs ) :
''': param kwargs : api _ host = ' 127.0.0.1 ' api _ user = ' admin ' api _ pass = ' example ' api _ port = 623
: param channel : number [ 1:7]
: param read _ mode :
- non _ volatile = get non - volatile Channel Access
- vola... | with _IpmiCommand ( ** kwargs ) as s :
return s . get_channel_access ( channel ) |
def obtainInfo ( self ) :
"""Method for obtaining information about the movie .""" | try :
info = self . ytdl . extract_info ( self . yid , download = False )
except youtube_dl . utils . DownloadError :
raise ConnectionError
if not self . preferences [ 'stream' ] :
self . url = ( info [ 'requested_formats' ] [ 0 ] [ 'url' ] , info [ 'requested_formats' ] [ 1 ] [ 'url' ] )
return True
# ... |
def star_stats_table ( self ) :
"""Take the parsed stats from the STAR report and add them to the
basic stats table at the top of the report""" | headers = OrderedDict ( )
headers [ 'uniquely_mapped_percent' ] = { 'title' : '% Aligned' , 'description' : '% Uniquely mapped reads' , 'max' : 100 , 'min' : 0 , 'suffix' : '%' , 'scale' : 'YlGn' }
headers [ 'uniquely_mapped' ] = { 'title' : '{} Aligned' . format ( config . read_count_prefix ) , 'description' : 'Unique... |
def set_unobserved_before ( self , tlen , qlen , nt , p ) :
"""Set the unobservable sequence data before this base
: param tlen : target homopolymer length
: param qlen : query homopolymer length
: param nt : nucleotide
: param p : p is the probability of attributing this base to the unobserved error
: ty... | self . _unobservable . set_before ( tlen , qlen , nt , p ) |
def to_pydatetime ( self ) :
"""Converts datetime2 object into Python ' s datetime . datetime object
@ return : naive datetime . datetime""" | return datetime . datetime . combine ( self . _date . to_pydate ( ) , self . _time . to_pytime ( ) ) |
def cublasChpr2 ( handle , uplo , n , alpha , x , inx , y , incy , AP ) :
"""Rank - 2 operation on Hermitian - packed matrix .""" | status = _libcublas . cublasChpr2_v2 ( handle , _CUBLAS_FILL_MODE [ uplo ] , n , ctypes . byref ( cuda . cuFloatComplex ( alpha . real , alpha . imag ) ) , int ( x ) , incx , int ( y ) , incy , int ( AP ) )
cublasCheckStatus ( status ) |
def rand_zipfian ( true_classes , num_sampled , range_max ) :
"""Draw random samples from an approximately log - uniform or Zipfian distribution .
This operation randomly samples * num _ sampled * candidates the range of integers [ 0 , range _ max ) .
The elements of sampled _ candidates are drawn with replacem... | assert ( isinstance ( true_classes , Symbol ) ) , "unexpected type %s" % type ( true_classes )
log_range = math . log ( range_max + 1 )
rand = uniform ( 0 , log_range , shape = ( num_sampled , ) , dtype = 'float64' )
# make sure sampled _ classes are in the range of [ 0 , range _ max )
sampled_classes = ( rand . exp ( ... |
def i18n ( msg , event = None , lang = 'en' , domain = 'backend' ) :
"""Gettext function wrapper to return a message in a specified language by domain
To use internationalization ( i18n ) on your messages , import it as ' _ ' and use as usual .
Do not forget to supply the client ' s language setting .""" | if event is not None :
language = event . client . language
else :
language = lang
domain = Domain ( domain )
return domain . get ( language , msg ) |
def display ( text , mode = 'exec' , file = None ) :
"""Show ` text ` , rendered as AST and as Bytecode .
Parameters
text : str
Text of Python code to render .
mode : { ' exec ' , ' eval ' } , optional
Mode for ` ast . parse ` and ` compile ` . Default is ' exec ' .
file : None or file - like object , o... | if file is None :
file = sys . stdout
ast_section = StringIO ( )
a ( text , mode = mode , file = ast_section )
code_section = StringIO ( )
d ( text , mode = mode , file = code_section )
rendered = _DISPLAY_TEMPLATE . format ( text = text , ast = ast_section . getvalue ( ) , code = code_section . getvalue ( ) , )
pr... |
def get_attributes ( self , attributes = 'All' , callback = None ) :
"""Retrieves attributes about this queue object and returns
them in an Attribute instance ( subclass of a Dictionary ) .
: type attributes : string
: param attributes : String containing one of :
ApproximateNumberOfMessages ,
Approximate... | return self . connection . get_queue_attributes ( self , attributes , callback = callback ) |
def fetch ( code ) :
"""Fetch keywords by Code""" | ret = { }
code = KeywordFetcher . _remove_strings ( code )
result = KeywordFetcher . prog . findall ( code )
for keyword in result :
if len ( keyword ) <= 1 :
continue
# Ignore single - length word
if keyword . isdigit ( ) :
continue
# Ignore number
if keyword [ 0 ] == '-' or key... |
def _set_ipv6_interface ( self , v , load = False ) :
"""Setter method for ipv6 _ interface , mapped from YANG variable / rbridge _ id / interface / ve / ipv6 / ipv6 _ local _ anycast _ gateway / ipv6 _ track / ipv6 _ interface ( list )
If this variable is read - only ( config : false ) in the
source YANG file ... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = YANGListType ( "ipv6_interface_type ipv6_interface_name" , ipv6_interface . ipv6_interface , yang_name = "ipv6-interface" , rest_name = "interface" , parent = self , is_container = 'list' , user_ordered = False , path_helper ... |
def set_handler ( self , handler ) :
"""设置异步回调处理对象
: param handler : 回调处理对象 , 必须是以下类的子类实例
类名 说明
StockQuoteHandlerBase 报价处理基类
OrderBookHandlerBase 摆盘处理基类
CurKlineHandlerBase 实时k线处理基类
TickerHandlerBase 逐笔处理基类
RTDataHandlerBase 分时数据处理基类
BrokerHandlerBase 经济队列处理基类
: return : RET _ OK : 设置成功
RET _ ER... | with self . _lock :
if self . _handler_ctx is not None :
return self . _handler_ctx . set_handler ( handler )
return RET_ERROR |
def embedding_to_padding ( emb ) :
"""Input embeddings - > is _ padding .""" | emb_sum = tf . reduce_sum ( tf . abs ( emb ) , axis = - 1 , keep_dims = True )
return tf . to_float ( tf . equal ( emb_sum , 0.0 ) ) |
def update ( self , ** kwargs ) :
"""Updates the matching objects for specified fields .
Note :
Post / pre save hooks and signals will NOT triggered .
Unlike RDBMS systems , this method makes individual save calls
to backend DB store . So this is exists as more of a comfortable
utility method and not a pe... | do_simple_update = kwargs . get ( 'simple_update' , True )
no_of_updates = 0
for model in self :
no_of_updates += 1
model . _load_data ( kwargs )
model . save ( internal = True )
return no_of_updates |
def close ( self ) :
"""Close any existing BFD structure before open a new one .""" | if self . _ptr : # try :
# # Release inner BFD files in case we ' re an archive BFD .
# if self . is _ archive :
# [ inner _ bfd . close ( ) for inner _ bfd in self . archive _ files ]
# except TypeError , err :
# pass
try :
_bfd . close ( self . _ptr )
except TypeError , err :
raise BfdExceptio... |
def add_dataset ( self , name = None , label = None , x_column_label = None , y_column_label = None , index = None , control = False ) :
"""Add a dataset to a specific plot .
This method adds a dataset to a plot . Its functional use is imperative
to the plot generation . It handles adding new files as well
as... | if name is None and label is None and index is None :
raise ValueError ( "Attempting to add a dataset without" + "supplying index or file information." )
if index is None :
trans_dict = DataImportContainer ( )
if name is not None :
trans_dict . file_name = name
if label is not None :
tra... |
def delete_virtual_mfa_device ( iam_client , mfa_serial ) :
"""Delete a vritual MFA device given its serial number
: param iam _ client :
: param mfa _ serial :
: return :""" | try :
printInfo ( 'Deleting MFA device %s...' % mfa_serial )
iam_client . delete_virtual_mfa_device ( SerialNumber = mfa_serial )
except Exception as e :
printException ( e )
printError ( 'Failed to delete MFA device %s' % mfa_serial )
pass |
def _log_multivariate_normal_density_spherical ( X , means , covars ) :
"""Compute Gaussian log - density at X for a spherical model .""" | cv = covars . copy ( )
if covars . ndim == 1 :
cv = cv [ : , np . newaxis ]
if cv . shape [ 1 ] == 1 :
cv = np . tile ( cv , ( 1 , X . shape [ - 1 ] ) )
return _log_multivariate_normal_density_diag ( X , means , cv ) |
def remove_directory ( self , directory_name , * args , ** kwargs ) :
""": meth : ` . WNetworkClientProto . remove _ directory ` method implementation""" | client = self . dav_client ( )
remote_path = self . join_path ( self . session_path ( ) , directory_name )
if client . is_dir ( remote_path ) is False :
raise ValueError ( 'Unable to remove non-directory entry' )
client . clean ( remote_path ) |
def add_comment_to_issue ( self , issue , comment , visibility = None ) :
"""Adds a comment to a specified issue from the current user .
Arguments :
| issue ( string ) | A JIRA Issue that a watcher needs added to , can be an issue ID or Key |
| comment ( string ) | A body of text to add as a comment to an iss... | self . jira . add_comment ( issue = issue , body = comment ) |
def prof_pressure ( altitude , z_coef = ( 1.94170e-9 , - 5.14580e-7 , 4.57018e-5 , - 1.55620e-3 , - 4.61994e-2 , 2.99955 ) ) :
"""Return pressure for given altitude .
This function evaluates a polynomial at altitudes values .
Parameters
altitude : array - like
altitude values [ km ] .
z _ coef : array - l... | altitude = np . asarray ( altitude )
pressure = np . power ( 10 , np . polyval ( z_coef , altitude . flatten ( ) ) )
return pressure . reshape ( altitude . shape ) |
def QA_fetch_stock_day_full_adv ( date ) :
'''' 返回全市场某一天的数据 '
: param date :
: return : QA _ DataStruct _ Stock _ day类 型数据''' | # 🛠 todo 检查日期data参数
res = QA_fetch_stock_full ( date , 'pd' )
if res is None :
print ( "QA Error QA_fetch_stock_day_full_adv parameter date=%s call QA_fetch_stock_full return None" % ( date ) )
return None
else :
res_set_index = res . set_index ( [ 'date' , 'code' ] )
# if res _ set _ index is None :
... |
def mark ( self , n = 1 ) :
"""Mark the occurrence of a given number of events .""" | self . tick_if_necessary ( )
self . count += n
self . m1_rate . update ( n )
self . m5_rate . update ( n )
self . m15_rate . update ( n ) |
def cost ( a , b , c , e , f , p_min , p ) :
"""cost : fuel cost based on " standard " parameters
( with valve - point loading effect )""" | return a + b * p + c * p * p + abs ( e * math . sin ( f * ( p_min - p ) ) ) |
def deriv ( * args ) :
"""; Copyright ( c ) 1984-2009 , ITT Visual Information Solutions . All
; rights reserved . Unauthorized reproduction is prohibited .
; NAME :
; DERIV
; PURPOSE :
; Perform numerical differentiation using 3 - point , Lagrangian
; interpolation .
; CATEGORY :
; Numerical analys... | x = args [ 0 ]
n = x . size
if n < 3 :
raise Exception ( 'Parameters must have at least 3 points' )
if ( len ( args ) == 2 ) :
y = args [ 1 ]
if n != y . size :
raise 'Vectors must have same size'
# ; df / dx = y0 * ( 2x - x1 - x2 ) / ( x01 * x02 ) + y1 * ( 2x - x0 - x2 ) / ( x10 * x12 ) + y2 * ... |
def _create_source ( self , src ) :
"""Create a pyLikelihood Source object from a
` ~ fermipy . roi _ model . Model ` object .""" | if src [ 'SpatialType' ] == 'SkyDirFunction' :
pylike_src = pyLike . PointSource ( self . like . logLike . observation ( ) )
pylike_src . setDir ( src . skydir . ra . deg , src . skydir . dec . deg , False , False )
elif src [ 'SpatialType' ] == 'SpatialMap' :
filepath = str ( utils . path_to_xmlpath ( src ... |
def get_default_config ( self ) :
"""Returns the default collector settings""" | config = super ( KVMCollector , self ) . get_default_config ( )
config . update ( { 'path' : 'kvm' , } )
return config |
def accept ( self , visitor : "BaseVisitor[ResultT]" ) -> ResultT :
"""Traverses the game in PGN order using the given * visitor * . Returns
the * visitor * result .""" | if visitor . begin_game ( ) is not SKIP :
for tagname , tagvalue in self . headers . items ( ) :
visitor . visit_header ( tagname , tagvalue )
if visitor . end_headers ( ) is not SKIP :
board = self . board ( )
visitor . visit_board ( board )
if self . comment :
visit... |
def _parse_segments ( self ) :
"""Read the segment output file and parse into an SQLite database .""" | reader = csv . reader ( open ( self . _segment_file , 'rU' ) , delimiter = '\t' )
for row in reader :
if reader . line_num == 1 : # skip header
continue
sql = '''INSERT INTO segments
(id, multiplicon, genome, list, first, last, ord)
VALUES (?,?,?,?,?,?,?)'''
... |
def with_headers ( self , headers = None , ** params ) :
"""Add headers to the request .
: param headers : A dict , or a list of key , value pairs
: param params : A dict of key value pairs""" | if isinstance ( headers , ( tuple , list ) ) :
headers = dict ( headers )
if params :
if isinstance ( headers , dict ) :
headers . update ( params )
elif headers is None :
headers = params
self . _headers . update ( headers )
return self |
def mgmt_nw_id ( cls ) :
"""Returns id of the management network .""" | if cls . _mgmt_nw_uuid is None :
tenant_id = cls . l3_tenant_id ( )
if not tenant_id :
return
net = bc . get_plugin ( ) . get_networks ( bc . context . get_admin_context ( ) , { 'tenant_id' : [ tenant_id ] , 'name' : [ cfg . CONF . general . management_network ] } , [ 'id' , 'subnets' ] )
if len... |
def set_servo ( self , channel , pwm ) :
'''set a servo value''' | self . mav . command_long_send ( self . target_system , self . target_component , mavlink . MAV_CMD_DO_SET_SERVO , 0 , channel , pwm , 0 , 0 , 0 , 0 , 0 ) |
def transform_record ( self , pid , record , links_factory = None ) :
"""Transform record into an intermediate representation .
: param pid : The : class : ` invenio _ pidstore . models . PersistentIdentifier `
instance .
: param record : The : class : ` invenio _ records . api . Record ` instance .
: param... | return self . dump ( self . preprocess_record ( pid , record , links_factory = links_factory ) ) |
def do_counter_reset ( self , element , decl , pseudo ) :
"""Clear specified counters .""" | step = self . state [ self . state [ 'current_step' ] ]
counter_name = ''
for term in decl . value :
if type ( term ) is ast . WhitespaceToken :
continue
elif type ( term ) is ast . IdentToken :
if counter_name :
step [ 'counters' ] [ counter_name ] = 0
counter_name = term . ... |
def getxattr ( self , req , ino , name , size ) :
"""Set an extended attribute
Valid replies :
reply _ buf
reply _ data
reply _ xattr
reply _ err""" | self . reply_err ( req , errno . ENOSYS ) |
def update_items ( self , ocean_backend , enrich_backend ) :
"""Retrieve the commits not present in the original repository and delete
the corresponding documents from the raw and enriched indexes""" | fltr = { 'name' : 'origin' , 'value' : [ self . perceval_backend . origin ] }
logger . debug ( "[update-items] Checking commits for %s." , self . perceval_backend . origin )
git_repo = GitRepository ( self . perceval_backend . uri , self . perceval_backend . gitpath )
try :
current_hashes = set ( [ commit for commi... |
def get_env ( ) :
"""Return the Capitalize environment name
It can be used to retrieve class base config
Default : Development
: returns : str""" | env = "Development"
if _env_key in os . environ :
env = os . environ [ _env_key ] . lower ( ) . capitalize ( )
return env |
def enterbox ( message = 'Enter something.' , title = '' , argDefaultText = '' ) :
"""Original doc : Show a box in which a user can enter some text .
You may optionally specify some default text , which will appear in the
enterbox when it is displayed .
Returns the text that the user entered , or None if he c... | return psidialogs . ask_string ( message = message , title = title , default = argDefaultText ) |
def require_login ( self , view_func ) :
"""Use this to decorate view functions that require a user to be logged
in . If the user is not already logged in , they will be sent to the
Provider to log in , after which they will be returned .
. . versionadded : : 1.0
This was : func : ` check ` before .""" | @ wraps ( view_func )
def decorated ( * args , ** kwargs ) :
if g . oidc_id_token is None :
return self . redirect_to_auth_server ( request . url )
return view_func ( * args , ** kwargs )
return decorated |
def _write_arg_read_code ( builder , arg , args , name ) :
"""Writes the read code for the given argument , setting the
arg . name variable to its read value .
: param builder : The source code builder
: param arg : The argument to write
: param args : All the other arguments in TLObject same on _ send .
... | if arg . generic_definition :
return
# Do nothing , this only specifies a later type
# The argument may be a flag , only write that flag was given !
was_flag = False
if arg . is_flag : # Treat ' true ' flags as a special case , since they ' re true if
# they ' re set , and nothing else needs to actually be read .
... |
def _get_kdjj ( df , n_days ) :
"""Get the J of KDJ
J = 3K - 2D
: param df : data
: param n _ days : calculation range
: return : None""" | k_column = 'kdjk_{}' . format ( n_days )
d_column = 'kdjd_{}' . format ( n_days )
j_column = 'kdjj_{}' . format ( n_days )
df [ j_column ] = 3 * df [ k_column ] - 2 * df [ d_column ] |
async def build_req_creds_json ( self , creds : dict , filt : dict = None , filt_dflt_incl : bool = False ) -> str :
"""Build and return indy - sdk requested credentials json from input indy - sdk creds structure
through specified filter .
: param creds : indy - sdk creds structure
: param filt : filter mappi... | LOGGER . debug ( 'HolderProver.build_req_creds_json >>> creds: %s, filt: %s' , creds , filt )
req_creds = { 'self_attested_attributes' : { } , 'requested_attributes' : { } , 'requested_predicates' : { } }
def _add_cred ( cred , uuid , key ) :
nonlocal req_creds
req_creds [ key ] [ uuid ] = { 'cred_id' : cred [ ... |
def quit ( self , daemononly = False ) :
'''Send quit event to quit the main loop''' | if not self . quitting :
self . quitting = True
self . queue . append ( SystemControlEvent ( SystemControlEvent . QUIT , daemononly = daemononly ) , True ) |
def _StartMonitoringProcess ( self , process ) :
"""Starts monitoring a process .
Args :
process ( MultiProcessBaseProcess ) : process .
Raises :
IOError : if the RPC client cannot connect to the server .
KeyError : if the process is not registered with the engine or
if the process is already being moni... | if process is None :
raise ValueError ( 'Missing process.' )
pid = process . pid
if pid in self . _process_information_per_pid :
raise KeyError ( 'Already monitoring process (PID: {0:d}).' . format ( pid ) )
if pid in self . _rpc_clients_per_pid :
raise KeyError ( 'RPC client (PID: {0:d}) already exists' . ... |
def put ( self , measurementId , deviceId ) :
"""Initialises the measurement session from the given device .
: param measurementId :
: param deviceId :
: return :""" | logger . info ( 'Starting measurement ' + measurementId + ' for ' + deviceId )
if self . _measurementController . startMeasurement ( measurementId , deviceId ) :
logger . info ( 'Started measurement ' + measurementId + ' for ' + deviceId )
return None , 200
else :
logger . warning ( 'Failed to start measure... |
def parse_cluster_pubsub_numpat ( res , ** options ) :
"""Result callback , handles different return types
switchable by the ` aggregate ` flag .""" | aggregate = options . get ( 'aggregate' , True )
if not aggregate :
return res
numpat = 0
for node , node_numpat in res . items ( ) :
numpat += node_numpat
return numpat |
def iskip ( value , iterable ) :
"""Skips all values in ' iterable ' matching the given ' value ' .""" | for e in iterable :
if value is None :
if e is None :
continue
elif e == value :
continue
yield e |
def set ( aadb , cur ) :
"""Sets the values in the config file""" | cfg = Config ( )
edited = False
if aadb :
cfg . set ( ConfigKeys . asset_allocation_database_path , aadb )
print ( f"The database has been set to {aadb}." )
edited = True
if cur :
cfg . set ( ConfigKeys . default_currency , cur )
edited = True
if edited :
print ( f"Changes saved." )
else :
p... |
def conglomerate ( self , messages , ** config ) :
"""Given N messages , return another list that has some of them
grouped together into a common ' item ' .
A conglomeration of messages should be of the following form : :
' subtitle ' : ' relrod pushed commits to ghc and 487 other packages ' ,
' link ' : No... | for conglomerator in self . conglomerator_objects :
messages = conglomerator . conglomerate ( messages , ** config )
return messages |
def remove_child ( self , child ) :
"""Remove a child from this node .""" | assert child in self . children
self . children . remove ( child )
self . index . pop ( child . tax_id )
if child . parent is self :
child . parent = None
if child . index is self . index :
child . index = None
# Remove child subtree from index
for n in child :
if n is child :
continue
self . in... |
def convert_coordinates ( coords , origin , wgs84 , wrapped ) :
"""Convert coordinates from one crs to another""" | if isinstance ( coords , list ) or isinstance ( coords , tuple ) :
try :
if isinstance ( coords [ 0 ] , list ) or isinstance ( coords [ 0 ] , tuple ) :
return [ convert_coordinates ( list ( c ) , origin , wgs84 , wrapped ) for c in coords ]
elif isinstance ( coords [ 0 ] , float ) :
... |
def write_array ( self , outfile , pixels ) :
"""Write an array that holds all the image values
as a PNG file on the output file .
See also : meth : ` write ` method .""" | if self . interlace :
if type ( pixels ) != array : # Coerce to array type
fmt = 'BH' [ self . bitdepth > 8 ]
pixels = array ( fmt , pixels )
self . write_passes ( outfile , self . array_scanlines_interlace ( pixels ) )
else :
self . write_passes ( outfile , self . array_scanlines ( pixels )... |
def to_internal_value ( self , data ) :
"""Convert to internal value .""" | user = getattr ( self . context . get ( 'request' ) , 'user' )
queryset = self . get_queryset ( )
permission = get_full_perm ( 'view' , queryset . model )
try :
return get_objects_for_user ( user , permission , queryset . filter ( ** { self . slug_field : data } ) , ) . latest ( )
except ObjectDoesNotExist :
se... |
def normalizedGraylevelVariance ( img ) :
'''' GLVN ' algorithm ( Santos97)''' | mean , stdev = cv2 . meanStdDev ( img )
s = stdev [ 0 ] ** 2 / mean [ 0 ]
return s [ 0 ] |
def _norm ( self , x ) :
"""Compute the safe norm .""" | return tf . sqrt ( tf . reduce_sum ( tf . square ( x ) , keepdims = True , axis = - 1 ) + 1e-7 ) |
def unpack_binary ( self , offset , length = False ) :
"""Returns raw binary data from the relative offset with the given length .
Arguments :
- ` offset ` : The relative offset from the start of the block .
- ` length ` : The length of the binary blob . If zero , the empty string
zero length is returned . ... | if not length :
return bytes ( "" . encode ( "ascii" ) )
o = self . _offset + offset
try :
return bytes ( struct . unpack_from ( "<{}s" . format ( length ) , self . _buf , o ) [ 0 ] )
except struct . error :
raise OverrunBufferException ( o , len ( self . _buf ) ) |
def restart ( self ) :
"""Restart module""" | # Call stop & start if any of them was overriden
if self . __class__ . stop != Module . stop or self . __class__ . start != Module . start :
self . stop ( )
self . start ( )
else : # If not , restart is better
for daemon in self . daemons ( ) :
daemon . restart ( ) |
def _set_server_known ( cls , host , port ) :
"""Store the host / port combination for this server""" | with PostgreSql . _known_servers_lock :
PostgreSql . _known_servers . add ( ( host , port ) ) |
def _run_gvcfgenotyper ( data , region , vrn_files , out_file ) :
"""Run gvcfgenotyper on a single gVCF region in input file .""" | if not utils . file_exists ( out_file ) :
with file_transaction ( data , out_file ) as tx_out_file :
input_file = "%s-inputs.txt" % utils . splitext_plus ( tx_out_file ) [ 0 ]
with open ( input_file , "w" ) as out_handle :
out_handle . write ( "%s\n" % "\n" . join ( vrn_files ) )
... |
def delete_hosting_device_resources ( self , context , tenant_id , mgmt_port , ** kwargs ) :
"""Deletes resources for a hosting device in a plugin specific way .""" | if mgmt_port is not None :
try :
self . _cleanup_hosting_port ( context , mgmt_port [ 'id' ] )
except n_exc . NeutronException as e :
LOG . error ( "Unable to delete port:%(port)s after %(tries)d" " attempts due to exception %(exception)s. " "Skipping it" , { 'port' : mgmt_port [ 'id' ] , 'tries... |
def unload_modules ( ) :
"""Unload all modules of the jukebox package and all plugin modules
Python provides the ` ` reload ` ` command for reloading modules . The major drawback is , that if this module is loaded in any other module
the source code will not be resourced !
If you want to reload the code becau... | mods = set ( [ ] )
for m in sys . modules :
if m . startswith ( 'jukebox' ) :
mods . add ( m )
pm = PluginManager . get ( )
for p in pm . get_all_plugins ( ) :
mods . add ( p . __module__ )
for m in mods :
del ( sys . modules [ m ] ) |
def _getXrefString ( self , xref , compressed = 1 ) :
"""_ getXrefString ( self , xref , compressed = 1 ) - > PyObject *""" | if self . isClosed :
raise ValueError ( "operation illegal for closed doc" )
return _fitz . Document__getXrefString ( self , xref , compressed ) |
def quaternion_conjugate ( quaternion ) :
"""Return conjugate of quaternion .
> > > q0 = random _ quaternion ( )
> > > q1 = quaternion _ conjugate ( q0)
> > > q1[0 ] = = q0[0 ] and all ( q1[1 : ] = = - q0[1 : ] )
True""" | q = numpy . array ( quaternion , dtype = numpy . float64 , copy = True )
numpy . negative ( q [ 1 : ] , q [ 1 : ] )
return q |
def run ( self ) :
"""Thread main loop""" | retries = 0
try :
while not self . _stopping :
try :
data = self . notifications_api . long_poll_notifications ( )
except mds . rest . ApiException as e : # An HTTP 410 can be raised when stopping so don ' t log anything
if not self . _stopping :
backoff = 2 *... |
def _make_expanded_field_serializer ( self , name , nested_expand , nested_fields , nested_omit ) :
"""Returns an instance of the dynamically created nested serializer .""" | field_options = self . expandable_fields [ name ]
serializer_class = field_options [ 0 ]
serializer_settings = copy . deepcopy ( field_options [ 1 ] )
if name in nested_expand :
serializer_settings [ "expand" ] = nested_expand [ name ]
if name in nested_fields :
serializer_settings [ "fields" ] = nested_fields ... |
def next ( self ) :
"""Return the next match ; raises Exception if no next match available""" | # Check the state and find the next match as a side - effect if necessary .
if not self . has_next ( ) :
raise StopIteration ( "No next match" )
# Don ' t retain that memory any longer than necessary .
result = self . _last_match
self . _last_match = None
self . _state = PhoneNumberMatcher . _NOT_READY
return resul... |
def create_table ( self , name , * columns , ** kwargs ) :
"""Create a new table with the same metadata and info""" | targs = table_args ( ** kwargs )
args , kwargs = targs [ : - 1 ] , targs [ - 1 ]
return Table ( name , self . metadata , * columns , * args , ** kwargs ) |
def validate_config ( config ) :
"""Verify sanity for a : class : ` . Config ` instance .
This will raise an exception in case conditions are not met , otherwise
will complete silently .
: param config : ( : class : ` . Config ` ) Configuration container .""" | non_null_params = [ 'space_id' , 'access_token' ]
for param in non_null_params :
if getattr ( config , param ) is None :
raise Exception ( 'Configuration for \"{0}\" must not be empty.' . format ( param ) )
for clazz in config . custom_entries :
if not issubclass ( clazz , Entry ) :
raise Except... |
def iter_links_by_attrib ( self , element ) :
'''Iterate an element by looking at its attributes for links .''' | for attrib_name in element . attrib . keys ( ) :
attrib_value = element . attrib . get ( attrib_name )
if attrib_name in self . LINK_ATTRIBUTES :
if self . javascript_scraper and attrib_value . lstrip ( ) . startswith ( 'javascript:' ) :
for link in self . iter_links_by_js_attrib ( attrib_na... |
def getStat ( cls , obj , name ) :
"""Gets the stat for the given object with the given name , or None if no such stat exists .""" | objClass = type ( obj )
for theClass in objClass . __mro__ :
if theClass == object :
break
for value in theClass . __dict__ . values ( ) :
if isinstance ( value , Stat ) and value . getName ( ) == name :
return value |
def copy_resource ( self , container , resource , local_filename ) :
"""Identical to : meth : ` dockermap . client . base . DockerClientWrapper . copy _ resource ` with additional logging .""" | self . push_log ( "Receiving tarball for resource '{0}:{1}' and storing as {2}" . format ( container , resource , local_filename ) )
super ( DockerFabricClient , self ) . copy_resource ( container , resource , local_filename ) |
def detach_screens ( self , screen_ids ) :
"""Unplugs monitors from the virtual graphics card .
in screen _ ids of type int""" | if not isinstance ( screen_ids , list ) :
raise TypeError ( "screen_ids can only be an instance of type list" )
for a in screen_ids [ : 10 ] :
if not isinstance ( a , baseinteger ) :
raise TypeError ( "array can only contain objects of type baseinteger" )
self . _call ( "detachScreens" , in_p = [ screen... |
def get_recipients ( self , ** options ) :
"""Figures out the recipients""" | if options [ 'recipients_from_setting' ] :
return settings . TIMELINE_DIGEST_EMAIL_RECIPIENTS
users = get_user_model ( ) . _default_manager . all ( )
if options [ 'staff' ] :
users = users . filter ( is_staff = True )
elif not options [ 'all' ] :
users = users . filter ( is_staff = True , is_superuser = Tru... |
def write_PIA0_B_control ( self , cpu_cycles , op_address , address , value ) :
"""write to 0xff03 - > PIA 0 B side Control reg .
TODO : Handle IRQ
bit 7 | IRQ 1 ( VSYNC ) flag
bit 6 | IRQ 2 flag ( not used )
bit 5 | Control line 2 ( CB2 ) is an output = 1
bit 4 | Control line 2 ( CB2 ) set by bit 3 = 1
... | log . critical ( "%04x| write $%02x (%s) to $%04x -> PIA 0 B side Control reg.\t|%s" , op_address , value , byte2bit_string ( value ) , address , self . cfg . mem_info . get_shortest ( op_address ) )
if is_bit_set ( value , bit = 0 ) :
log . critical ( "%04x| write $%02x (%s) to $%04x -> VSYNC IRQ: enable\t|%s" , o... |
def load ( self , path = None ) :
"""Loads the specified DLL , if any , otherwise re - loads the current DLL .
If ` ` path ` ` is specified , loads the DLL at the given ` ` path ` ` ,
otherwise re - loads the DLL currently specified by this library .
Note :
This creates a temporary DLL file to use for the i... | self . unload ( )
self . _path = path or self . _path
# Windows requires a proper suffix in order to load the library file ,
# so it must be set here .
if self . _windows or self . _cygwin :
suffix = '.dll'
elif sys . platform . startswith ( 'darwin' ) :
suffix = '.dylib'
else :
suffix = '.so'
# Copy the J ... |
def users_with_birthday ( self , month , day ) :
"""Return a list of user objects who have a birthday on a given date .""" | users = User . objects . filter ( properties___birthday__month = month , properties___birthday__day = day )
results = [ ]
for user in users : # TODO : permissions system
results . append ( user )
return results |
def uniquify ( l ) :
"""Uniquify a list ( skip duplicate items ) .""" | result = [ ]
for x in l :
if x not in result :
result . append ( x )
return result |
def create_inputs_to_reference ( job_data , input_files , input_directories ) :
"""Creates a dictionary with the summarized information in job _ data , input _ files and input _ directories
: param job _ data : The job data specifying input parameters other than files and directories .
: param input _ files : A... | return { ** deepcopy ( job_data ) , ** deepcopy ( input_files ) , ** deepcopy ( input_directories ) } |
def define ( self , klass , name = "default" ) :
"""Define a class with a given set of attributes .
: param klass : The class
: type klass : class
: param name : The short name
: type name : str""" | def decorate ( func ) :
@ wraps ( func )
def wrapped ( * args , ** kwargs ) :
return func ( * args , ** kwargs )
self . register ( klass , func , name = name )
return wrapped
return decorate |
def tv_distance ( a , b ) :
'''Get the Total Variation ( TV ) distance between two densities a and b .''' | if len ( a . shape ) == 1 :
return np . sum ( np . abs ( a - b ) )
return np . sum ( np . abs ( a - b ) , axis = 1 ) |
def input_on_stderr ( prompt = '' , default = None , convert = None ) :
"""Output a string to stderr and wait for input .
Args :
prompt ( str ) : the message to display .
default : the default value to return if the user
leaves the field empty
convert ( callable ) : a callable to be used to convert
the ... | print ( prompt , end = '' , file = sys . stderr )
value = builtins . input ( )
return _convert ( value , default , convert ) |
def _get_child_mock ( self , ** kw ) :
"""Create the child mocks for attributes and return value .
By default child mocks will be the same type as the parent .
Subclasses of Mock may want to override this to customize the way
child mocks are made .
For non - callable mocks the callable variant will be used ... | _type = type ( self )
if not issubclass ( _type , CallableMixin ) :
if issubclass ( _type , NonCallableMagicMock ) :
klass = MagicMock
elif issubclass ( _type , NonCallableMock ) :
klass = Mock
else :
klass = _type . __mro__ [ 1 ]
return klass ( ** kw ) |
def lonlat_to_screen ( self , lon , lat ) :
"""Projects geodesic coordinates to screen
: param lon : longitude
: param lat : latitude
: return : x , y screen coordinates""" | if type ( lon ) == list :
lon = np . array ( lon )
if type ( lat ) == list :
lat = np . array ( lat )
lat_rad = np . radians ( lat )
n = 2.0 ** self . zoom
xtile = ( lon + 180.0 ) / 360.0 * n
ytile = ( 1.0 - np . log ( np . tan ( lat_rad ) + ( 1 / np . cos ( lat_rad ) ) ) / math . pi ) / 2.0 * n
x = ( xtile * T... |
def conjugate_gradient_nonlinear ( f , x , line_search = 1.0 , maxiter = 1000 , nreset = 0 , tol = 1e-16 , beta_method = 'FR' , callback = None ) :
r"""Conjugate gradient for nonlinear problems .
Parameters
f : ` Functional `
Functional with ` ` f . gradient ` ` .
x : ` ` op . domain ` ` element
Vector to... | if x not in f . domain :
raise TypeError ( '`x` {!r} is not in the domain of `f` {!r}' '' . format ( x , f . domain ) )
if not callable ( line_search ) :
line_search = ConstantLineSearch ( line_search )
if beta_method not in [ 'FR' , 'PR' , 'HS' , 'DY' ] :
raise ValueError ( 'unknown ``beta_method``' )
for ... |
def __downloadPage ( factory , * args , ** kwargs ) :
"""Start a HTTP download , returning a HTTPDownloader object""" | # The Twisted API is weird :
# 1 ) web . client . downloadPage ( ) doesn ' t give us the HTTP headers
# 2 ) there is no method that simply accepts a URL and gives you back
# a HTTPDownloader object
# TODO : convert getPage ( ) usage to something similar , too
downloader = factory ( * args , ** kwargs )
if downloader . ... |
def anim ( self , duration , offset = 0 , timestep = 1 , label = None , unit = None , time_fn = param . Dynamic . time_fn ) :
"""duration : The temporal duration to animate in the units
defined on the global time function .
offset : The temporal offset from which the animation is
generated given the supplied ... | frames = ( duration // timestep ) + 1
if duration % timestep != 0 :
raise ValueError ( "The duration value must be an exact multiple of the timestep." )
if label is None :
label = time_fn . label if hasattr ( time_fn , 'label' ) else 'Time'
unit = time_fn . unit if ( not unit and hasattr ( time_fn , 'unit' ) ) ... |
def deflate ( f , * args , ** kwargs ) :
"""Deflate Flask Response Decorator .""" | data = f ( * args , ** kwargs )
if isinstance ( data , Response ) :
content = data . data
else :
content = data
deflater = zlib . compressobj ( )
deflated_data = deflater . compress ( content )
deflated_data += deflater . flush ( )
if isinstance ( data , Response ) :
data . data = deflated_data
data . h... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.