signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def cumulative_before_during_after ( self , start : datetime . datetime , when : datetime . datetime ) -> Tuple [ datetime . timedelta , datetime . timedelta , datetime . timedelta ] :
"""For a given time , ` ` when ` ` , returns the cumulative time
- after ` ` start ` ` but before ` ` self ` ` begins , prior to ... | assert self . no_overlap , ( "Only implemented for IntervalList objects with no_overlap == True" )
no_time = datetime . timedelta ( )
earliest_interval_start = self . start_datetime ( )
# Easy special cases
if when <= start :
return no_time , no_time , no_time
if self . is_empty ( ) or when <= earliest_interval_sta... |
def set_joystick ( self , x , y , n ) :
"""Receives joystick values from the SnakeBoard
x , y Coordinates
n Robot number to give it to""" | self . robots [ n ] . set_joystick ( x , y ) |
def get_auth_string ( self ) :
"""Create auth string from credentials .""" | auth_info = '{}:{}' . format ( self . sauce_username , self . sauce_access_key )
return base64 . b64encode ( auth_info . encode ( 'utf-8' ) ) . decode ( 'utf-8' ) |
def merge_bins ( self , bin_ranges , axis = 0 ) :
"""Merge bins in bin ranges
Parameters
bin _ ranges : list of tuples
A list of tuples of bin indices for each bin range to be merged
into one bin .
axis : int ( default = 1)
The integer identifying the axis to merge bins along .
Returns
hist : TH1
... | ndim = self . GetDimension ( )
if axis > ndim - 1 :
raise ValueError ( "axis is out of range" )
axis_bins = self . nbins ( axis = axis , overflow = True )
# collect the indices along this axis to be merged
# support negative indices via slicing
windows = [ ]
for window in bin_ranges :
if len ( window ) != 2 :
... |
def add ( from_user , from_id , to_user , to_id , type ) :
"adds a relation to the graph" | if options . users and to_user :
G . add_node ( from_user , screen_name = from_user )
G . add_node ( to_user , screen_name = to_user )
if G . has_edge ( from_user , to_user ) :
weight = G [ from_user ] [ to_user ] [ 'weight' ] + 1
else :
weight = 1
G . add_edge ( from_user , to_user ... |
def absent ( name , version = - 1 , recursive = False , profile = None , hosts = None , scheme = None , username = None , password = None , default_acl = None ) :
'''Make sure znode is absent
name
path to znode
version
Specify the version which should be deleted
Default : - 1 ( always match )
recursive ... | ret = { 'name' : name , 'result' : False , 'comment' : 'Failed to delete znode {0}' . format ( name ) , 'changes' : { } }
connkwargs = { 'profile' : profile , 'hosts' : hosts , 'scheme' : scheme , 'username' : username , 'password' : password , 'default_acl' : default_acl }
if __salt__ [ 'zookeeper.exists' ] ( name , *... |
def getNextSample ( self , V ) :
"""Generate the next sample for the condorcet model . This algorithm is described in " Computing
Optimal Bayesian Decisions for Rank Aggregation via MCMC Sampling , " and is adapted from
code written by Lirong Xia .
: ivar list < list < int > V : A two - dimensional list that ... | cands = range ( len ( self . wmg ) )
W = copy . deepcopy ( V )
allPairs = itertools . combinations ( cands , 2 )
for pair in allPairs :
a = pair [ 0 ]
b = pair [ 1 ]
if random . random ( ) < 1.0 / ( 1.0 + pow ( self . phi , self . wmg [ a + 1 ] [ b + 1 ] ) ) :
W [ a ] [ b ] = 1
W [ b ] [ a ]... |
def cli ( ctx , pattern , arguments , safe ) :
"""Executes a saved command .""" | matches = utils . grep_commands ( pattern )
if matches :
selected = utils . select_command ( matches )
if selected >= 0 :
cmd , desc = matches [ selected ]
pcmd = utils . create_pcmd ( cmd )
raw_params , params , defaults = utils . get_params_in_pcmd ( pcmd )
arguments = list ( a... |
def setCurrentIndex ( self , index ) :
"""Sets the current index on self and on the tab bar to keep the two insync .
: param index | < int >""" | super ( XViewPanel , self ) . setCurrentIndex ( index )
self . tabBar ( ) . setCurrentIndex ( index ) |
def _validate_filters ( cls , filters ) :
"""Raise a TypeError if ` ` filters ` ` contains any keys inappropriate to
this event class .""" | for k in iterkeys ( filters ) :
if k not in cls . filters : # Mirror " unexpected keyword argument " message :
raise TypeError ( "%s got an unsupported filter type '%s'" % ( cls . __name__ , k ) ) |
def format_json_api_response ( self , data , many ) :
"""Post - dump hook that formats serialized data as a top - level JSON API object .
See : http : / / jsonapi . org / format / # document - top - level""" | ret = self . format_items ( data , many )
ret = self . wrap_response ( ret , many )
ret = self . render_included_data ( ret )
ret = self . render_meta_document ( ret )
return ret |
def _FormatSocketInet128Token ( self , token_data ) :
"""Formats an Internet socket token as a dictionary of values .
Args :
token _ data ( bsm _ token _ data _ sockinet64 ) : AUT _ SOCKINET128 token data .
Returns :
dict [ str , str ] : token values .""" | protocol = bsmtoken . BSM_PROTOCOLS . get ( token_data . socket_family , 'UNKNOWN' )
ip_address = self . _FormatPackedIPv6Address ( token_data . ip_addresss )
return { 'protocols' : protocol , 'family' : token_data . socket_family , 'port' : token_data . port_number , 'address' : ip_address } |
def splitext ( path ) : # type : ( str ) - > Tuple [ str , str ]
"""Like os . path . splitext , but take off . tar too""" | base , ext = posixpath . splitext ( path )
if base . lower ( ) . endswith ( '.tar' ) :
ext = base [ - 4 : ] + ext
base = base [ : - 4 ]
return base , ext |
def solveBinPacking ( s , B ) :
"""solveBinPacking : use an IP model to solve the in Packing Problem .
Parameters :
- s : list with item widths
- B : bin capacity
Returns a solution : list of lists , each of which with the items in a roll .""" | n = len ( s )
U = len ( FFD ( s , B ) )
# upper bound of the number of bins
model = bpp ( s , B )
x , y = model . data
model . optimize ( )
bins = [ [ ] for i in range ( U ) ]
for ( i , j ) in x :
if model . getVal ( x [ i , j ] ) > .5 :
bins [ j ] . append ( s [ i ] )
for i in range ( bins . count ( [ ] ) ... |
async def set_power ( self , value : bool ) :
"""Toggle the device on and off .""" | if value :
status = "active"
else :
status = "off"
# TODO WoL works when quickboot is not enabled
return await self . services [ "system" ] [ "setPowerStatus" ] ( status = status ) |
def record ( self , tags = None ) :
"""records all the measures at the same time with a tag _ map .
tag _ map could either be explicitly passed to the method , or implicitly
read from current runtime context .""" | if tags is None :
tags = TagContext . get ( )
if self . _invalid :
logger . warning ( "Measurement map has included negative value " "measurements, refusing to record" )
return
for measure , value in self . measurement_map . items ( ) :
if value < 0 :
self . _invalid = True
logger . warn... |
def extract_suffix ( self , name ) :
"""Returns a tuple of ( name , suffix ) , or ( name , None ) if no suffix could be found .
As the method name indicates , the name is returned without the suffix .
Suffixes deemed to be degrees are discarded .""" | # don ' t extract suffixes if we can ' t reasonably suspect we have enough parts to the name for there to be one
if len ( name . strip ( ) . split ( ) ) > 2 :
name , suffix = self . extract_matching_portion ( r'\b(?P<suffix>{})(?=\b|\s|\Z|\W)' . format ( SUFFIX_RE ) , name )
suffix , degree = self . extract_mat... |
def merge_instances ( cls , inst1 , inst2 ) :
"""Merges the two datasets ( side - by - side ) .
: param inst1 : the first dataset
: type inst1 : Instances or str
: param inst2 : the first dataset
: type inst2 : Instances
: return : the combined dataset
: rtype : Instances""" | return Instances ( javabridge . static_call ( "weka/core/Instances" , "mergeInstances" , "(Lweka/core/Instances;Lweka/core/Instances;)Lweka/core/Instances;" , inst1 . jobject , inst2 . jobject ) ) |
def on_cloud_download_item_activated ( self , menu_item ) :
'''创建离线下载任务 , 下载选中的BT种子 .''' | tree_paths = self . iconview . get_selected_items ( )
if not tree_paths :
return
self . app . cloud_page . add_cloud_bt_task ( self . liststore [ tree_paths [ 0 ] ] [ PATH_COL ] ) |
def traverse_frozen_data ( data_structure ) :
"""Yields the leaves of the frozen data - structure pre - order .
It will produce the same order as one would write the data - structure .""" | parent_stack = [ data_structure ]
while parent_stack :
node = parent_stack . pop ( 0 )
# We don ' t iterate strings
tlen = - 1
if not isinstance ( node , _string_types ) : # If item has a length we freeze it
try :
tlen = len ( node )
except :
pass
if tlen == -... |
def search_for_port ( port_glob , req , expected_res ) :
'''Find the serial port the arm is connected to .''' | # Check that the USB port actually exists , based on the known vendor and
# product ID .
if usb . core . find ( idVendor = 0x0403 , idProduct = 0x6001 ) is None :
return None
# Find ports matching the supplied glob .
ports = glob . glob ( port_glob )
if len ( ports ) == 0 :
return None
for port in ports :
w... |
def animation_control ( object , sequence_length = None , add = True , interval = 200 ) :
"""Animate scatter , quiver or mesh by adding a slider and play button .
: param object : : any : ` Scatter ` or : any : ` Mesh ` object ( having an sequence _ index property ) , or a list of these to
control multiple .
... | if isinstance ( object , ( list , tuple ) ) :
objects = object
else :
objects = [ object ]
del object
if sequence_length is None : # get all non - None arrays
sequence_lengths = [ ]
for object in objects :
sequence_lengths_previous = list ( sequence_lengths )
values = [ getattr ( object ... |
def gap_index_map ( sequence , gap_chars = '-' ) :
"""Opposite of ungap _ index _ map : returns mapping from gapped index to ungapped
index .
> > > gap _ index _ map ( ' AC - TG - ' )
{0 : 0 , 1 : 1 , 3 : 2 , 4 : 3}""" | return dict ( ( v , k ) for k , v in list ( ungap_index_map ( sequence , gap_chars ) . items ( ) ) ) |
def istrue ( self , * args ) :
"""Strict test for ' true ' value test . If multiple args are provided it will
test them all .
ISTRUE : true
% { ISTRUE : true } - > ' True '""" | def is_true ( val ) :
if val is True :
return True
val = str ( val ) . lower ( ) . strip ( )
return val in ( 'true' , 'yes' , '1' )
return all ( self . _arg_factory ( is_true , args ) ) |
def spher_harms ( l , m , inclination ) :
"""Return spherical harmonic polarizations""" | # FIXME : we are using spin - 2 weighted spherical harmonics for now ,
# when possible switch to spheroidal harmonics .
Y_lm = lal . SpinWeightedSphericalHarmonic ( inclination , 0. , - 2 , l , m ) . real
Y_lminusm = lal . SpinWeightedSphericalHarmonic ( inclination , 0. , - 2 , l , - m ) . real
Y_plus = Y_lm + ( - 1 )... |
def disable_tracing ( self ) :
"""Disable tracing if it is disabled and debugged program is running ,
else do nothing .
: return : False if tracing has been disabled , True else .""" | _logger . x_debug ( "disable_tracing()" )
# self . dump _ tracing _ state ( " before disable _ tracing ( ) " )
if self . tracing_enabled and self . execution_started :
threading . settrace ( None )
# don ' t trace threads to come
iksettrace3 . _set_trace_off ( )
self . tracing_enabled = False
# self . d... |
def from_string ( cls , string , exists = False , asynchronous = False , verbose = False ) :
"""if exists is bool , then check it either exists or it doesn ' t .
if exists is None , we don ' t care .""" | result = cls . parse ( string )
if result . scheme not in cls . TYPES :
raise CopyError ( "Invalid scheme: %s" % ( result . scheme ) )
return cls . TYPES [ result . scheme ] ( result , exists , asynchronous , verbose ) |
def nextStationJD ( ID , jd ) :
"""Finds the aproximate julian date of the
next station of a planet .""" | speed = swe . sweObject ( ID , jd ) [ 'lonspeed' ]
for i in range ( 2000 ) :
nextjd = jd + i / 2
nextspeed = swe . sweObject ( ID , nextjd ) [ 'lonspeed' ]
if speed * nextspeed <= 0 :
return nextjd
return None |
def _exec_check ( self , check : FontbakeryCallable , args : Dict [ str , Any ] ) :
"""Yields check sub results .
Each check result is a tuple of : ( < Status > , mixed message )
` status ` : must be an instance of Status .
If one of the ` status ` entries in one of the results
is FAIL , the whole check is ... | try : # A check can be either a normal function that returns one Status or a
# generator that yields one or more . The latter will return a generator
# object that we can detect with types . GeneratorType .
result = check ( ** args )
# Might raise .
if isinstance ( result , types . GeneratorType ) : # Itera... |
def put ( self , instance , errors ) :
"""Update a model instance .
: param instance : The model instance .
: param errors : Any errors .
: return : The updated model instance , or a dictionary of errors .""" | if errors :
return self . errors ( errors )
return self . updated ( instance ) |
def set_color ( self , ipaddr , hue , sat , bri , kel , fade ) :
"""Send SETCOLOR message .""" | cmd = { "payloadtype" : PayloadType . SETCOLOR , "target" : ipaddr , "hue" : hue , "sat" : sat , "bri" : bri , "kel" : kel , "fade" : fade }
self . _send_command ( cmd ) |
def _CheckAttribute ( self , attribute , value ) :
"""Check that the value is of the expected type .
Args :
attribute : An instance of Attribute ( ) .
value : An instance of RDFValue .
Raises :
ValueError : when the value is not of the expected type .
AttributeError : When the attribute is not of type A... | if not isinstance ( attribute , Attribute ) :
raise AttributeError ( "Attribute %s must be of type aff4.Attribute()" % attribute )
if not isinstance ( value , attribute . attribute_type ) :
raise ValueError ( "Value for attribute %s must be of type %s()" % ( attribute , attribute . attribute_type . __name__ ) ) |
def infer_transition_matrix_coefficient_from_data ( self , source : str , target : str , state : Optional [ str ] = None , crop : Optional [ str ] = None , ) :
"""Infer the distribution of a particular transition matrix
coefficient from data .
Args :
source : The source of the edge corresponding to the matrix... | rows = engine . execute ( f"select * from dssat where `Crop` like '{crop}'" f" and `State` like '{state}'" )
xs , ys = lzip ( * [ ( r [ "Rainfall" ] , r [ "Production" ] ) for r in rows ] )
xs_scaled , ys_scaled = xs / np . mean ( xs ) , ys / np . mean ( ys )
p , V = np . polyfit ( xs_scaled , ys_scaled , 1 , cov = Tru... |
def shell_call ( command , ** kwargs ) :
"""Calls shell command with parameter substitution .
Args :
command : command to run as a list of tokens
* * kwargs : dirctionary with substitutions
Returns :
whether command was successful , i . e . returned 0 status code
Example of usage :
shell _ call ( [ ' ... | command = list ( command )
for i in range ( len ( command ) ) :
m = CMD_VARIABLE_RE . match ( command [ i ] )
if m :
var_id = m . group ( 1 )
if var_id in kwargs :
command [ i ] = kwargs [ var_id ]
return subprocess . call ( command ) == 0 |
def envCheckFlag ( self , name , default = False ) :
"""Check graph flag for enabling / disabling attributes through
the use of < name > environment variable .
@ param name : Name of flag .
( Also determines the environment variable name . )
@ param default : Boolean ( True or False ) . Default value for fl... | if self . _flags . has_key ( name ) :
return self . _flags [ name ]
else :
val = self . _env . get ( name )
if val is None :
return default
elif val . lower ( ) in [ 'yes' , 'on' ] :
self . _flags [ name ] = True
return True
elif val . lower ( ) in [ 'no' , 'off' ] :
... |
def access_token ( self ) :
"""Get access _ token .""" | if self . cache_token :
return self . access_token_ or self . _resolve_credential ( 'access_token' )
return self . access_token_ |
def service_info ( self , name ) :
"""Pull descriptive info of a service by name .
Information returned includes the service ' s user friendly
name and whether it was preregistered or added dynamically .
Returns :
dict : A dictionary of service information with the following keys
set :
long _ name ( str... | return self . _loop . run_coroutine ( self . _client . service_info ( name ) ) |
def getPinProperties ( cardConnection , featureList = None , controlCode = None ) :
"""return the PIN _ PROPERTIES structure
@ param cardConnection : L { CardConnection } object
@ param featureList : feature list as returned by L { getFeatureRequest ( ) }
@ param controlCode : control code for L { FEATURE _ I... | if controlCode is None :
if featureList is None :
featureList = getFeatureRequest ( cardConnection )
controlCode = hasFeature ( featureList , FEATURE_IFD_PIN_PROPERTIES )
if controlCode is None :
return { 'raw' : [ ] }
response = cardConnection . control ( controlCode , [ ] )
d = { 'raw' : response ... |
def openfile ( filename , mode = "rt" , * args , expanduser = False , expandvars = False , makedirs = False , ** kwargs ) :
"""Open filename and return a corresponding file object .""" | if filename in ( "-" , None ) :
return sys . stdin if "r" in mode else sys . stdout
if expanduser :
filename = os . path . expanduser ( filename )
if expandvars :
filename = os . path . expandvars ( filename )
if makedirs and ( "a" in mode or "w" in mode ) :
parentdir = os . path . dirname ( filename )
... |
def fastqIterate ( infile ) :
'''iterate over contents of fastq file .''' | def convert2string ( b ) :
if type ( b ) == str :
return b
else :
return b . decode ( "utf-8" )
while 1 :
line1 = convert2string ( infile . readline ( ) )
if not line1 :
break
if not line1 . startswith ( '@' ) :
U . error ( "parsing error: expected '@' in line %s" % l... |
def offset_overlays ( self , text , offset = 0 , ** kw ) :
"""Generate overlays after offset .
: param text : The text to be searched .
: param offset : Match starting that index . If none just search .
: returns : An overlay or None""" | # This may be a bit slower but overlayedtext takes care of
# unicode issues .
if not isinstance ( text , OverlayedText ) :
text = OverlayedText ( text )
for m in self . regex . finditer ( unicode ( text ) [ offset : ] ) :
yield Overlay ( text , ( offset + m . start ( ) , offset + m . end ( ) ) , props = self . ... |
def list_space_systems ( self , page_size = None ) :
"""Lists the space systems visible to this client .
Space systems are returned in lexicographical order .
: rtype : : class : ` . SpaceSystem ` iterator""" | params = { }
if page_size is not None :
params [ 'limit' ] = page_size
return pagination . Iterator ( client = self . _client , path = '/mdb/{}/space-systems' . format ( self . _instance ) , params = params , response_class = mdb_pb2 . ListSpaceSystemsResponse , items_key = 'spaceSystem' , item_mapper = SpaceSystem... |
def set_iscsi_initiator_info ( self , initiator_iqn ) :
"""Set iSCSI initiator information in iLO .
: param initiator _ iqn : Initiator iqn for iLO .
: raises : IloError , on an error from iLO .
: raises : IloCommandNotSupportedInBiosError , if the system is
in the BIOS boot mode .""" | sushy_system = self . _get_sushy_system ( PROLIANT_SYSTEM_ID )
if ( self . _is_boot_mode_uefi ( ) ) :
iscsi_data = { 'iSCSIInitiatorName' : initiator_iqn }
try :
( sushy_system . bios_settings . iscsi_resource . iscsi_settings . update_iscsi_settings ( iscsi_data ) )
except sushy . exceptions . Sush... |
def getfragment ( self , default = None , encoding = 'utf-8' , errors = 'strict' ) :
"""Return the decoded fragment identifier , or ` default ` if the
original URI did not contain a fragment component .""" | fragment = self . fragment
if fragment is not None :
return uridecode ( fragment , encoding , errors )
else :
return default |
def from_payload ( self , payload ) :
"""Init frame from binary data .""" | number_of_objects = payload [ 0 ]
self . remaining_scenes = payload [ - 1 ]
predicted_len = number_of_objects * 65 + 2
if len ( payload ) != predicted_len :
raise PyVLXException ( 'scene_list_notification_wrong_length' )
self . scenes = [ ]
for i in range ( number_of_objects ) :
scene = payload [ ( i * 65 + 1 )... |
def login ( self , username = None , password = None ) :
"""Before doing any remote operation , the user has to login to the GMQL serivice .
This can be done in the two following ways :
* Guest mode : the user has no credentials and uses the system only as a temporary guest
* Authenticated mode : the users ha... | if ( username is None ) and ( password is None ) :
auth_token = self . __login_guest ( )
elif ( username is not None ) and ( password is not None ) :
auth_token , fullName = self . __login_credentials ( username , password )
self . logger . info ( "You are logged as {}" . format ( fullName ) )
else :
ra... |
def URem ( a : BitVec , b : BitVec ) -> BitVec :
"""Create an unsigned remainder expression .
: param a :
: param b :
: return :""" | return _arithmetic_helper ( a , b , z3 . URem ) |
def _assert_explicit_vr ( dicom_input ) :
"""Assert that explicit vr is used""" | if settings . validate_multiframe_implicit :
header = dicom_input [ 0 ]
if header . file_meta [ 0x0002 , 0x0010 ] . value == '1.2.840.10008.1.2' :
raise ConversionError ( 'IMPLICIT_VR_ENHANCED_DICOM' ) |
def handle_new_user ( self , provider , access , info ) :
"Create a shell auth . User and redirect ." | user = self . get_or_create_user ( provider , access , info )
access . user = user
AccountAccess . objects . filter ( pk = access . pk ) . update ( user = user )
user = authenticate ( provider = access . provider , identifier = access . identifier )
login ( self . request , user )
return redirect ( self . get_login_red... |
def _get_from_cache ( self , expr ) :
"""Obtain cached result , prepend with the keyname if necessary , and
indent for the current level""" | is_cached , res = super ( ) . _get_from_cache ( expr )
if is_cached :
indent_str = " " * self . _print_level
return True , indent ( res , indent_str )
else :
return False , None |
def minver_error ( pkg_name ) :
"""Report error about missing minimum version constraint and exit .""" | print ( 'ERROR: specify minimal version of "{}" using ' '">=" or "=="' . format ( pkg_name ) , file = sys . stderr )
sys . exit ( 1 ) |
def run ( self ) :
"""Sends contents of a local file to a remote data service .""" | processes = [ ]
progress_queue = ProgressQueue ( Queue ( ) )
num_chunks = ParallelChunkProcessor . determine_num_chunks ( self . config . upload_bytes_per_chunk , self . local_file . size )
work_parcels = ParallelChunkProcessor . make_work_parcels ( self . config . upload_workers , num_chunks )
for ( index , num_items ... |
def broadcast ( self , clients , msg ) :
"""Optimized C { broadcast } implementation . Depending on type of the
session , will json - encode message once and will call either
C { send _ message } or C { send _ jsonifed } .
@ param clients : Clients iterable
@ param msg : Message to send""" | json_msg = None
count = 0
for c in clients :
sess = c . session
if not sess . is_closed :
if sess . send_expects_json :
if json_msg is None :
json_msg = proto . json_encode ( msg )
sess . send_jsonified ( json_msg , stats = False )
else :
sess ... |
def lambda_tilde ( mass1 , mass2 , lambda1 , lambda2 ) :
"""The effective lambda parameter
The mass - weighted dominant effective lambda parameter defined in
https : / / journals . aps . org / prd / pdf / 10.1103 / PhysRevD . 91.043002""" | m1 , m2 , lambda1 , lambda2 , input_is_array = ensurearray ( mass1 , mass2 , lambda1 , lambda2 )
lsum = lambda1 + lambda2
ldiff , _ = ensurearray ( lambda1 - lambda2 )
mask = m1 < m2
ldiff [ mask ] = - ldiff [ mask ]
eta = eta_from_mass1_mass2 ( m1 , m2 )
p1 = ( lsum ) * ( 1 + 7. * eta - 31 * eta ** 2.0 )
p2 = ( 1 - 4 ... |
def register ( self , service , name = '' ) :
"""Exposes a given service to this API .""" | # expose a sub - factory
if isinstance ( service , ApiFactory ) :
self . services [ name ] = ( service . factory , None )
# expose a module dynamically as a service
elif inspect . ismodule ( service ) :
name = name or service . __name__ . split ( '.' ) [ - 1 ]
# exclude endpoints with patterns
for obj i... |
def custom ( self , payload ) :
""": param payload :
a key / value object containing the scimeta you want to store
e . g . { " weather " : " sunny " , " temperature " : " 80C " }
: return :
empty ( 200 status code )""" | url = "{url_base}/resource/{pid}/scimeta/custom/" . format ( url_base = self . hs . url_base , pid = self . pid )
r = self . hs . _request ( 'POST' , url , data = payload )
return r |
def plot ( self , channel_names , kind = 'histogram' , gates = None , gate_colors = None , gate_lw = 1 , ** kwargs ) :
"""Plot the flow cytometry data associated with the sample on the current axis .
To produce the plot , follow up with a call to matplotlib ' s show ( ) function .
Parameters
{ graph _ plotFCM... | ax = kwargs . get ( 'ax' )
channel_names = to_list ( channel_names )
gates = to_list ( gates )
plot_output = graph . plotFCM ( self . data , channel_names , kind = kind , ** kwargs )
if gates is not None :
if gate_colors is None :
gate_colors = cycle ( ( 'b' , 'g' , 'r' , 'm' , 'c' , 'y' ) )
if not isin... |
def conforms_to_template_filter ( self , template_filter ) :
"""Check AttributeFilter conforms to the rules set by the template
- If self , has attributes that template _ filter does not contain , throw Exception
- If sub list found , perform the first check
- If self has a value for an attribute , assign to ... | if not isinstance ( template_filter , self . __class__ ) :
raise TypeError ( "AttributeFilter can only check conformance against \
another template filter, %s provided" % template_filter . __class__ . __name__ )
# keys from the template
template_filter_keys = template_filter . keys ( )
# Keys from t... |
def show ( self ) :
"""Display ( with a pretty print ) this object""" | off = 0
for n , i in enumerate ( self . get_instructions ( ) ) :
print ( "{:8d} (0x{:08x}) {:04x} {:30} {}" . format ( n , off , i . get_op_value ( ) , i . get_name ( ) , i . get_output ( self . idx ) ) )
off += i . get_length ( ) |
def __postCallAction_hwbp ( self , event ) :
"""Handles hardware breakpoint events on return from the function .
@ type event : L { ExceptionEvent }
@ param event : Single step event .""" | # Remove the one shot hardware breakpoint
# at the return address location in the stack .
tid = event . get_tid ( )
address = event . breakpoint . get_address ( )
event . debug . erase_hardware_breakpoint ( tid , address )
# Call the " post " callback .
try :
self . __postCallAction ( event )
# Forget the parameter... |
def fixed_values ( self ) :
"""A flat tuple of all values corresponding to ` scipy _ data _ fitting . Fit . fixed _ parameters `
and ` scipy _ data _ fitting . Fit . constants ` after applying any prefixes .
The values mimic the order of those lists .""" | values = [ ]
values . extend ( [ prefix_factor ( param ) * param [ 'value' ] for param in self . fixed_parameters ] )
values . extend ( [ prefix_factor ( const ) * get_constant ( const [ 'value' ] ) for const in self . constants ] )
return tuple ( values ) |
def _get_api_sig ( args ) :
"""Flickr API need a hash string which made using post arguments
: param args : Arguments of the flickr request
: type args : list of sets
: return : api _ sig , ex : ( ' api _ sig ' , ' abcdefg ' )
: rtype : tuple""" | tmp_sig = api_secret
for i in args :
tmp_sig = tmp_sig + i [ 0 ] + i [ 1 ]
api_sig = hashlib . md5 ( tmp_sig . encode ( 'utf-8' ) ) . hexdigest ( )
return 'api_sig' , api_sig |
def resize ( img , width , height ) :
"""更改图片大小 , 只能更改磁盘空间的大小 。
: param img :
: param width :
: param height :
: return : 更改后的图片""" | return img . resize ( ( width , height ) , Image . ANTIALIAS ) |
def __x_product_aux ( property_sets , seen_features ) :
"""Returns non - conflicting combinations of property sets .
property _ sets is a list of PropertySet instances . seen _ features is a set of Property
instances .
Returns a tuple of :
- list of lists of Property instances , such that within each list ,... | assert is_iterable_typed ( property_sets , property_set . PropertySet )
assert isinstance ( seen_features , set )
if not property_sets :
return ( [ ] , set ( ) )
properties = property_sets [ 0 ] . all ( )
these_features = set ( )
for p in property_sets [ 0 ] . non_free ( ) :
these_features . add ( p . feature )... |
def diffmap ( adata , ** kwargs ) -> Union [ Axes , List [ Axes ] , None ] :
"""Scatter plot in Diffusion Map basis .
Parameters
{ adata _ color _ etc }
{ scatter _ bulk }
{ show _ save _ ax }
Returns
If ` show = = False ` a : class : ` ~ matplotlib . axes . Axes ` or a list of it .""" | return plot_scatter ( adata , 'diffmap' , ** kwargs ) |
def wait_for_initial_conf ( self , timeout = 1.0 ) :
"""Wait initial configuration from the arbiter .
Basically sleep 1.0 and check if new _ conf is here
: param timeout : timeout to wait
: type timeout : int
: return : None""" | logger . info ( "Waiting for initial configuration" )
# Arbiter do not already set our have _ conf param
_ts = time . time ( )
while not self . new_conf and not self . interrupted : # Make a pause and check if the system time changed
_ , _ = self . make_a_pause ( timeout , check_time_change = True )
if not self . i... |
def setup ( ) :
"""Walk the user though the Wallace setup .""" | # Create the Wallace config file if it does not already exist .
config_name = ".wallaceconfig"
config_path = os . path . join ( os . path . expanduser ( "~" ) , config_name )
if os . path . isfile ( config_path ) :
log ( "Wallace config file already exists." , chevrons = False )
else :
log ( "Creating Wallace c... |
def serialize ( element , strip = False ) :
"""A handy way to serialize an element to text .""" | text = etree . tostring ( element , method = 'text' , encoding = 'utf-8' )
if strip :
text = text . strip ( )
return str ( text , encoding = 'utf-8' ) |
def canonicalize ( self , include_nodes = True , sorted = False ) :
"""Generates a canonical : class : ` etc . Node ` object from this mock node .""" | node_class = Directory if self . dir else Value
kwargs = { attr : getattr ( self , attr ) for attr in node_class . __slots__ }
if self . dir :
if include_nodes :
nodes = [ node . canonicalize ( ) for node in six . viewvalues ( kwargs [ 'nodes' ] ) ]
if sorted :
nodes . sort ( key = lambd... |
def luhn_calc ( number , chars = DIGITS ) :
'''Calculate the Luhn check digit for ` ` number ` ` .
: param number : string
: param chars : string
> > > luhn _ calc ( ' 42 ' )''' | checksum = luhn_checksum ( str ( number ) + chars [ 0 ] , chars )
return chars [ - checksum ] |
def register ( self , name , option ) :
"""Register a new option with the namespace .
Args :
name ( str ) : The name to register the option under .
option ( option . Option ) : The option object to register .
Raises :
TypeError : If the option is not an option . Option object .
ValueError : If the name ... | if name in self . _options :
raise ValueError ( "Option {0} already exists." . format ( name ) )
if not isinstance ( option , opt . Option ) :
raise TypeError ( "Options must be of type Option." )
self . _options [ name ] = option |
def create_or_edit ( self , id , seq , resource ) : # pylint : disable = invalid - name , redefined - builtin
"""Create or edit a highlight .
: param id : Result ID as an int .
: param seq : TestResult sequence ID as an int .
: param resource : : class : ` highlights . Highlight < highlights . Highlight > ` o... | schema = HighlightSchema ( exclude = ( 'id' , 'seq' ) )
json = self . service . encode ( schema , resource )
schema = HighlightSchema ( )
resp = self . service . edit ( self . _base ( id , seq ) , resource . line , json )
return self . service . decode ( schema , resp ) |
def get_read_buffers ( self , size ) :
"""Get buffer ( s ) from which we can read data .
When done reading , use : meth : ` advance _ read _ index ` to make the
memory available for writing again .
: param size : The number of elements desired .
: type size : int
: returns :
* The number of elements ava... | ptr1 = self . _ffi . new ( 'void**' )
ptr2 = self . _ffi . new ( 'void**' )
size1 = self . _ffi . new ( 'ring_buffer_size_t*' )
size2 = self . _ffi . new ( 'ring_buffer_size_t*' )
return ( self . _lib . PaUtil_GetRingBufferReadRegions ( self . _ptr , size , ptr1 , size1 , ptr2 , size2 ) , self . _ffi . buffer ( ptr1 [ ... |
def add_observer ( self , signal , observer ) :
"""Add an observer to the object .
Raise an exception if the signal is not allowed .
Parameters
signal : str
a valid signal .
observer : @ func
a function that will be called when the signal is emitted .""" | self . _is_allowed_signal ( signal )
self . _add_observer ( signal , observer ) |
def get_multi_q ( self , sentinel = 'STOP' ) :
'''This helps indexq operate in multiprocessing environment without each process having to have it ' s own IndexQ . It also is a handy way to deal with thread / process safety .
This method will create and return a JoinableQueue object . Additionally , it will kick o... | self . in_q = JoinableQueue ( )
self . indexer_process = Process ( target = self . _indexer_process , args = ( self . in_q , sentinel ) )
self . indexer_process . daemon = False
self . indexer_process . start ( )
return self . in_q |
def local_filename ( self , url = None , filename = None , decompress = False ) :
"""What local filename will we use within the cache directory
for the given URL / filename / decompress options .""" | return common . build_local_filename ( url , filename , decompress ) |
def _value_format ( self , value , serie , index ) :
"""Display value and cumulation""" | sum_ = serie . points [ index ] [ 1 ]
if serie in self . series and ( self . stack_from_top and self . series . index ( serie ) == self . _order - 1 or not self . stack_from_top and self . series . index ( serie ) == 0 ) :
return super ( StackedLine , self ) . _value_format ( value )
return '%s (+%s)' % ( self . _y... |
def remove_notification_listener ( self , notification_id ) :
"""Remove a previously added notification callback .
Args :
notification _ id : The numeric id passed back from add _ notification _ listener
Returns :
The function returns boolean true if found and removed , false otherwise .""" | for v in self . notifications . values ( ) :
toRemove = list ( filter ( lambda tup : tup [ 0 ] == notification_id , v ) )
if len ( toRemove ) > 0 :
v . remove ( toRemove [ 0 ] )
return True
return False |
def get_error_message ( exception , context = None , suggestion = None ) :
"""Convert exception into an ErrorMessage containing a stack trace .
: param exception : Exception object .
: type exception : Exception
: param context : Optional context message .
: type context : str
: param suggestion : Optiona... | name , trace = humanise_exception ( exception )
problem = m . Message ( name )
if exception is None or exception == '' :
problem . append = m . Text ( tr ( 'No details provided' ) )
else :
if hasattr ( exception , 'message' ) and isinstance ( exception . message , Message ) :
problem . append = m . Text... |
def FILER_STORAGES ( self ) :
"""Filer config to set custom private media path
http : / / django - filer . readthedocs . org / en / 0.9.4 / settings . html # filer - storages""" | if not self . FILER_CUSTOM_NGINX_SERVER :
return { }
return { 'public' : { 'main' : { 'ENGINE' : self . default_file_storage , 'OPTIONS' : { } , 'UPLOAD_TO' : 'filer.utils.generate_filename.by_date' , 'UPLOAD_TO_PREFIX' : 'filer_public' , } , 'thumbnails' : { 'ENGINE' : self . default_file_storage , 'OPTIONS' : { }... |
def build_permuted_index ( self , lshash , buckets , num_permutation , beam_size , num_neighbour ) :
"""Build a permutedIndex and store it into the dict self . permutedIndexs .
lshash : the binary lshash object ( nearpy . hashes . lshash ) .
buckets : the buckets object corresponding to lshash . It ' s a dict o... | # Init a PermutedIndex
pi = PermutedIndex ( lshash , buckets , num_permutation , beam_size , num_neighbour )
# get hash _ name
hash_name = lshash . hash_name
self . permutedIndexs [ hash_name ] = pi |
def format ( self , record ) :
"""Format log record .""" | format_orig = self . _fmt
self . _fmt = self . get_level_fmt ( record . levelno )
record . prefix = self . prefix
record . plugin_id = self . plugin_id
result = logging . Formatter . format ( self , record )
self . _fmt = format_orig
return result |
def uptime ( ) :
"""Uptime of the host machine""" | from datetime import timedelta
with open ( '/proc/uptime' , 'r' ) as f :
uptime_seconds = float ( f . readline ( ) . split ( ) [ 0 ] )
uptime_string = str ( timedelta ( seconds = uptime_seconds ) )
bob . says ( uptime_string ) |
def __load_settings_from_dict ( self , settings ) :
"""Loads settings info from a settings Dict
: param settings : SAML Toolkit Settings
: type settings : dict
: returns : True if the settings info is valid
: rtype : boolean""" | errors = self . check_settings ( settings )
if len ( errors ) == 0 :
self . __errors = [ ]
self . __sp = settings [ 'sp' ]
self . __idp = settings . get ( 'idp' , { } )
self . __strict = settings . get ( 'strict' , False )
self . __debug = settings . get ( 'debug' , False )
self . __security = s... |
def write_properties_from_env ( cls , path ) :
'''Uses environmental variables to write a * . properties file for KCL ' s MultiLangDaemon''' | with open ( path , 'w' ) as f :
f . write ( "# Autogenerated by kclboot v%s on %s\n\n" % ( PACKAGE_VERSION , datetime . now ( ) ) )
for env_var , prop_var in ENV_TO_PROPERTY . items ( ) :
env_value = os . environ . get ( env_var )
if env_value :
f . write ( "%s=%s\n" % ( prop_var , e... |
def _operate ( self , other , operation , inplace = True ) :
"""Gives the CanonicalDistribution operation ( product or divide ) with
the other factor .
Parameters
other : CanonicalDistribution
The CanonicalDistribution to be multiplied .
operation : String
' product ' for multiplication operation and
... | phi = self . to_canonical_factor ( ) . _operate ( other . to_canonical_factor ( ) , operation , inplace = False ) . to_joint_gaussian ( )
if not inplace :
return phi |
def _default_key_normalizer ( key_class , request_context ) :
"""Create a pool key out of a request context dictionary .
According to RFC 3986 , both the scheme and host are case - insensitive .
Therefore , this function normalizes both before constructing the pool
key for an HTTPS request . If you wish to ch... | # Since we mutate the dictionary , make a copy first
context = request_context . copy ( )
context [ 'scheme' ] = context [ 'scheme' ] . lower ( )
context [ 'host' ] = context [ 'host' ] . lower ( )
# These are both dictionaries and need to be transformed into frozensets
for key in ( 'headers' , '_proxy_headers' , '_soc... |
def _convert ( x , factor1 , factor2 ) :
"""Converts mixing ratio x in comp1 - comp2 tie line to that in
c1 - c2 tie line .
Args :
x ( float ) : Mixing ratio x in comp1 - comp2 tie line , a float
between 0 and 1.
factor1 ( float ) : Compositional ratio between composition c1 and
processed composition co... | return x * factor2 / ( ( 1 - x ) * factor1 + x * factor2 ) |
def read_mash_output ( result_file ) :
""": param result _ file : Tab - delimited result file generated by mash dist .
: return : mash _ results : A list with each entry in the result file as an entry , with attributes reference , query ,
distance , pvalue , and matching _ hash""" | with open ( result_file ) as handle :
lines = handle . readlines ( )
mash_results = list ( )
for line in lines :
result = MashResult ( line )
mash_results . append ( result )
return mash_results |
def install ( self , paths , maker , ** kwargs ) :
"""Install a wheel to the specified paths . If kwarg ` ` warner ` ` is
specified , it should be a callable , which will be called with two
tuples indicating the wheel version of this software and the wheel
version in the file , if there is a discrepancy in th... | dry_run = maker . dry_run
warner = kwargs . get ( 'warner' )
lib_only = kwargs . get ( 'lib_only' , False )
bc_hashed_invalidation = kwargs . get ( 'bytecode_hashed_invalidation' , False )
pathname = os . path . join ( self . dirname , self . filename )
name_ver = '%s-%s' % ( self . name , self . version )
data_dir = '... |
def context_serve ( context , configfile , listen_addr , listen_port , logfile , debug , daemon , uid , gid , pidfile , umask , rundir ) :
"""Takes a context object , which implements the _ _ enter _ _ / _ _ exit _ _ " with " interface
and starts a server within that context .
This method is a refactored single... | global global_config
server = None
try :
with context : # There ' s a possibility here that init _ logging ( ) will throw an exception . If it does ,
# AND we ' re in a daemon context , then we ' re not going to be able to do anything with it .
# We ' ve got no stderr / stdout here ; and so ( to my knowledg... |
def reset ( self ) :
'''Reset Stan model and all tracked distributions and parameters .''' | self . parameters = [ ]
self . transformed_parameters = [ ]
self . expressions = [ ]
self . data = [ ]
self . transformed_data = [ ]
self . X = { }
self . model = [ ]
self . mu_cont = [ ]
self . mu_cat = [ ]
self . _original_names = { }
# variables to suppress in output . Stan uses limited set for variable
# names , so... |
def get_graph_by_ids ( self , network_ids : List [ int ] ) -> BELGraph :
"""Get a combine BEL Graph from a list of network identifiers .""" | if len ( network_ids ) == 1 :
return self . get_graph_by_id ( network_ids [ 0 ] )
log . debug ( 'getting graph by identifiers: %s' , network_ids )
graphs = self . get_graphs_by_ids ( network_ids )
log . debug ( 'getting union of graphs: %s' , network_ids )
rv = union ( graphs )
return rv |
def _ScopesFromMetadataServer ( self , scopes ) :
"""Returns instance scopes based on GCE metadata server .""" | if not util . DetectGce ( ) :
raise exceptions . ResourceUnavailableError ( 'GCE credentials requested outside a GCE instance' )
if not self . GetServiceAccount ( self . __service_account_name ) :
raise exceptions . ResourceUnavailableError ( 'GCE credentials requested but service account ' '%s does not exist.'... |
def service ( ctx , opts ) :
"""Check the status of the Cloudsmith service .""" | click . echo ( "Retrieving service status ... " , nl = False )
context_msg = "Failed to retrieve status!"
with handle_api_exceptions ( ctx , opts = opts , context_msg = context_msg ) :
with maybe_spinner ( opts ) :
status , version = get_status ( with_version = True )
click . secho ( "OK" , fg = "green" )
c... |
def stop_pipeline ( url , pipeline_id , auth , verify_ssl ) :
"""Stop a running pipeline . The API waits for the pipeline to be ' STOPPED ' before returning .
Args :
url ( str ) : the host url in the form ' http : / / host : port / ' .
pipeline _ id ( str ) : the ID of of the exported pipeline .
auth ( tupl... | stop_result = requests . post ( url + '/' + pipeline_id + '/stop' , headers = X_REQ_BY , auth = auth , verify = verify_ssl )
stop_result . raise_for_status ( )
logging . info ( "Pipeline stop requested." )
poll_pipeline_status ( STATUS_STOPPED , url , pipeline_id , auth , verify_ssl )
logging . info ( 'Pipeline stopped... |
def _sum_by_samples ( seqs_freq , samples_order ) :
"""Sum sequences of a metacluster by samples .""" | n = len ( seqs_freq [ seqs_freq . keys ( ) [ 0 ] ] . freq . keys ( ) )
y = np . array ( [ 0 ] * n )
for s in seqs_freq :
x = seqs_freq [ s ] . freq
exp = [ seqs_freq [ s ] . freq [ sam ] for sam in samples_order ]
y = list ( np . array ( exp ) + y )
return y |
def _set_cid_card ( self , v , load = False ) :
"""Setter method for cid _ card , mapped from YANG variable / system _ monitor / cid _ card ( container )
If this variable is read - only ( config : false ) in the
source YANG file , then _ set _ cid _ card is considered as a private
method . Backends looking to... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = cid_card . cid_card , is_container = 'container' , presence = False , yang_name = "cid-card" , rest_name = "cid-card" , parent = self , path_helper = self . _path_helper , extmethods = self . _extmethods , register_paths = Tr... |
def demo ( nums = [ ] ) :
"Print a few usage examples on stdout ." | nums = nums or [ 3 , 1 , 4 , 1 , 5 , 9 , 2 , 6 ]
fmt = lambda num : '{0:g}' . format ( num ) if isinstance ( num , ( float , int ) ) else 'None'
nums1 = list ( map ( fmt , nums ) )
if __name__ == '__main__' :
prog = sys . argv [ 0 ]
else :
prog = 'sparklines'
result = [ ]
result . append ( 'Usage examples (comm... |
def prob_classify ( self , text ) :
"""Return the label probability distribution for classifying a string
of text .
Example :
> > > classifier = MaxEntClassifier ( train _ data )
> > > prob _ dist = classifier . prob _ classify ( " I feel happy this morning . " )
> > > prob _ dist . max ( )
' positive '... | feats = self . extract_features ( text )
return self . classifier . prob_classify ( feats ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.