signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def request_system_code ( self ) :
"""Return all system codes that are registered in the card .
A card has one or more system codes that correspond to logical
partitions ( systems ) . Each system has a system code that could
be used in a polling command to activate that system . The
system codes responded b... | log . debug ( "request system code list" )
a , e = self . pmm [ 3 ] & 7 , self . pmm [ 3 ] >> 6
timeout = max ( 302E-6 * ( a + 1 ) * 4 ** e , 0.002 )
data = self . send_cmd_recv_rsp ( 0x0C , '' , timeout , check_status = False )
if len ( data ) != 1 + data [ 0 ] * 2 :
log . debug ( "insufficient data received from ... |
def newton_raphson_sparse ( f , guess , dfdx , x_tol = 1e-10 , lim_iter = 100 ) :
"""Solve f ( x ) = 0 with initial guess for x and dfdx ( x ) . dfdx ( x ) should
return a sparse Jacobian . Terminate if error on norm of f ( x ) is <
x _ tol or there were more than lim _ iter iterations .""" | converged = False
n_iter = 0
F = f ( guess )
diff = norm ( F , np . Inf )
logger . debug ( "Error at iteration %d: %f" , n_iter , diff )
while diff > x_tol and n_iter < lim_iter :
n_iter += 1
guess = guess - spsolve ( dfdx ( guess ) , F )
F = f ( guess )
diff = norm ( F , np . Inf )
logger . debug (... |
def pipeline_simulate ( id , body , verbose = False , hosts = None , profile = None ) :
'''. . versionadded : : 2017.7.0
Simulate existing Ingest pipeline on provided data . Available since Elasticsearch 5.0.
id
Pipeline id
body
Pipeline definition as specified in https : / / www . elastic . co / guide / ... | es = _get_instance ( hosts , profile )
try :
return es . ingest . simulate ( id = id , body = body , verbose = verbose )
except elasticsearch . TransportError as e :
raise CommandExecutionError ( "Cannot simulate pipeline {0}, server returned code {1} with message {2}" . format ( id , e . status_code , e . erro... |
def register_transport_ready_event ( self , user_cb , user_arg ) :
"""Register for transport ready events . The ` transport ready `
event is raised via a user callback . If the endpoint
is configured as a source , then the user may then
call : py : meth : ` write _ transport ` in order to send data to
the a... | self . user_cb = user_cb
self . user_arg = user_arg |
def rollout ( self , ** kwargs ) :
"""Generate x for open loop movements .""" | if kwargs . has_key ( 'tau' ) :
timesteps = int ( self . timesteps / kwargs [ 'tau' ] )
else :
timesteps = self . timesteps
self . x_track = np . zeros ( timesteps )
self . reset_state ( )
for t in range ( timesteps ) :
self . x_track [ t ] = self . x
self . step ( ** kwargs )
return self . x_track |
def get_lock_state_transaction ( self , transaction_id ) :
"""Get lock state transaction status
Args :
transaction _ id : Transaction ID received from set _ lock _ state""" | response = None
try :
response = requests . get ( urls . get_lockstate_transaction ( self . _giid , transaction_id ) , headers = { 'Accept' : 'application/json, text/javascript, */*; q=0.01' , 'Cookie' : 'vid={}' . format ( self . _vid ) } )
except requests . exceptions . RequestException as ex :
raise RequestE... |
def nl_msg_out_handler_debug ( msg , arg ) :
"""https : / / github . com / thom311 / libnl / blob / libnl3_2_25 / lib / handlers . c # L124.""" | ofd = arg or _LOGGER . debug
ofd ( '-- Debug: Sent Message:' )
nl_msg_dump ( msg , ofd )
return NL_OK |
def new ( cls , mode , size , color = 0 , depth = 8 , ** kwargs ) :
"""Create a new PSD document .
: param mode : The color mode to use for the new image .
: param size : A tuple containing ( width , height ) in pixels .
: param color : What color to use for the image . Default is black .
: return : A : py ... | header = cls . _make_header ( mode , size , depth )
image_data = ImageData . new ( header , color = color , ** kwargs )
# TODO : Add default metadata .
return cls ( PSD ( header = header , image_data = image_data , image_resources = ImageResources . new ( ) , ) ) |
async def async_set_state ( self , data ) :
"""Recall scene to group .""" | field = self . _deconz_id + '/recall'
await self . _async_set_state_callback ( field , data ) |
def bind_key ( conn , event_type , wid , key_string , cb ) :
"""Binds a function ` ` cb ` ` to a particular key press ` ` key _ string ` ` on a
window ` ` wid ` ` . Whether it ' s a key release or key press binding is
determined by ` ` event _ type ` ` .
` ` bind _ key ` ` will automatically hook into the ` `... | assert event_type in ( 'KeyPress' , 'KeyRelease' )
mods , kc = parse_keystring ( conn , key_string )
key = ( wid , mods , kc )
if not kc :
print ( "Could not find a keycode for " + key_string )
return False
if not __keygrabs [ key ] and not grab_key ( conn , wid , mods , kc ) :
return False
__keybinds [ key... |
def get_nodes_by_hashes ( self , node_hashes : List [ str ] ) -> List [ Node ] :
"""Look up several nodes by their hashes .""" | return self . session . query ( Node ) . filter ( Node . sha512 . in_ ( node_hashes ) ) . all ( ) |
def _operation_speak_as_spell_out ( self , content , index , children ) :
"""The operation method of _ speak _ as method for spell - out .
: param content : The text content of element .
: type content : str
: param index : The index of pattern in text content of element .
: type index : int
: param child... | children . append ( self . _create_content_element ( content [ 0 : ( index + 1 ) ] , 'spell-out' ) )
children . append ( self . _create_aural_content_element ( ' ' , 'spell-out' ) )
return children |
def log ( ** data ) :
"""RPC method for logging events
Makes entry with new account creating
Return None""" | # Get data from request body
entry = { "module" : data [ "params" ] [ "module" ] , "event" : data [ "params" ] [ "event" ] , "timestamp" : data [ "params" ] [ "timestamp" ] , "arguments" : data [ "params" ] [ "arguments" ] }
# Call create metod for writing data to database
history . create ( entry ) |
def child_removed ( self , child ) :
"""Handle the child removed event from the declaration .
This handler will unparent the child toolkit widget . Subclasses
which need more control should reimplement this method .""" | super ( AndroidViewGroup , self ) . child_removed ( child )
if child . widget is not None :
self . widget . removeView ( child . widget ) |
def _track_tendril ( self , tendril ) :
"""Adds the tendril to the set of tracked tendrils .""" | self . tendrils [ tendril . _tendril_key ] = tendril
# Also add to _ tendrils
self . _tendrils . setdefault ( tendril . proto , weakref . WeakValueDictionary ( ) )
self . _tendrils [ tendril . proto ] [ tendril . _tendril_key ] = tendril |
def _get_sensor_names ( self ) :
"""Join the sensors from all loaded readers .""" | # if the user didn ' t tell us what sensors to work with , let ' s figure it
# out
if not self . attrs . get ( 'sensor' ) : # reader finder could return multiple readers
return set ( [ sensor for reader_instance in self . readers . values ( ) for sensor in reader_instance . sensor_names ] )
elif not isinstance ( se... |
def callback_property ( getter ) :
"""A decorator to build a CallbackProperty .
This is used by wrapping a getter method , similar to the use of @ property : :
class Foo ( object ) :
@ callback _ property
def x ( self ) :
return self . _ x
@ x . setter
def x ( self , value ) :
self . _ x = value
I... | cb = CallbackProperty ( getter = getter )
cb . __doc__ = getter . __doc__
return cb |
def unpack_small_tensors ( tower_grads , packing ) :
"""Undo the structure alterations to tower _ grads done by pack _ small _ tensors .
Args :
tower _ grads : List of List of ( grad , var ) tuples .
packing : A dict generated by pack _ small _ tensors describing the changes
it made to tower _ grads .
Ret... | if not packing :
return tower_grads
new_tower_grads = [ ]
num_devices = len ( tower_grads )
num_packed = len ( packing . keys ( ) ) // num_devices
for dev_idx , gv_list in enumerate ( tower_grads ) :
new_gv_list = gv_list [ num_packed : ]
for i in xrange ( 0 , num_packed ) :
k = "%d:%d" % ( dev_idx ... |
def get_static_folder ( app_or_blueprint ) :
"""Return the static folder of the given Flask app
instance , or module / blueprint .
In newer Flask versions this can be customized , in older
ones ( < = 0.6 ) the folder is fixed .""" | if not hasattr ( app_or_blueprint , 'static_folder' ) : # I believe this is for app objects in very old Flask
# versions that did not support custom static folders .
return path . join ( app_or_blueprint . root_path , 'static' )
if not app_or_blueprint . has_static_folder : # Use an exception type here that is not ... |
def maketrans ( x , y = None , z = None ) :
"""Return a translation table usable for str . translate ( ) .
If there is only one argument , it must be a dictionary mapping Unicode
ordinals ( integers ) or characters to Unicode ordinals , strings or None .
Character keys will be then converted to ordinals .
I... | if y is None :
assert z is None
if not isinstance ( x , dict ) :
raise TypeError ( 'if you give only one argument to maketrans it must be a dict' )
result = { }
for ( key , value ) in x . items ( ) :
if len ( key ) > 1 :
raise ValueError ( 'keys in translate table must be str... |
def get_field ( self , field_name ) :
"""Get property from the Dataset .
Parameters
field _ name : string
The field name of the information .
Returns
info : numpy array
A numpy array with information from the Dataset .""" | if self . handle is None :
raise Exception ( "Cannot get %s before construct Dataset" % field_name )
tmp_out_len = ctypes . c_int ( )
out_type = ctypes . c_int ( )
ret = ctypes . POINTER ( ctypes . c_void_p ) ( )
_safe_call ( _LIB . LGBM_DatasetGetField ( self . handle , c_str ( field_name ) , ctypes . byref ( tmp_... |
def get_arp_output_arp_entry_interface_name ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
get_arp = ET . Element ( "get_arp" )
config = get_arp
output = ET . SubElement ( get_arp , "output" )
arp_entry = ET . SubElement ( output , "arp-entry" )
ip_address_key = ET . SubElement ( arp_entry , "ip-address" )
ip_address_key . text = kwargs . pop ( 'ip_address' )
interface_name... |
def setActions ( self , actions ) :
"""Sets the action options for this widget to the inputed list of actions .
: param actions | { < str > key : < QAction > , . . }""" | self . _actions = actions
self . uiActionTREE . blockSignals ( True )
self . uiActionTREE . setUpdatesEnabled ( False )
self . uiActionTREE . clear ( )
actions = actions . items ( )
actions . sort ( key = lambda x : nativestring ( x [ 1 ] . text ( ) ) . replace ( '&' , '' ) )
for key , action in actions :
item = se... |
def fromDict ( cls , _dict ) :
"""Builds instance from dictionary of properties .""" | obj = cls ( )
obj . __dict__ . update ( _dict )
return obj |
def update_context ( cls , base_context , str_or_dict , template_path = None ) :
"""Helper method to structure initial message context data .
NOTE : updates ` base _ context ` inplace .
: param dict base _ context : context dict to update
: param dict , str str _ or _ dict : text representing a message , or a... | if isinstance ( str_or_dict , dict ) :
base_context . update ( str_or_dict )
base_context [ 'use_tpl' ] = True
else :
base_context [ cls . SIMPLE_TEXT_ID ] = str_or_dict
if cls . SIMPLE_TEXT_ID in str_or_dict :
base_context [ 'use_tpl' ] = False
base_context [ 'tpl' ] = template_path |
def unique_row ( array , use_columns = None , selected_columns_only = False ) :
'''Takes a numpy array and returns the array reduced to unique rows . If columns are defined only these columns are taken to define a unique row .
The returned array can have all columns of the original array or only the columns defin... | if array . dtype . names is None : # normal array has no named dtype
if use_columns is not None :
a_cut = array [ : , use_columns ]
else :
a_cut = array
if len ( use_columns ) > 1 :
b = np . ascontiguousarray ( a_cut ) . view ( np . dtype ( ( np . void , a_cut . dtype . itemsize * a_... |
def _pythonized_comments ( tokens ) :
"""Similar to tokens but converts strings after a colon ( : ) to comments .""" | is_after_colon = True
for token_type , token_text in tokens :
if is_after_colon and ( token_type in pygments . token . String ) :
token_type = pygments . token . Comment
elif token_text == ':' :
is_after_colon = True
elif token_type not in pygments . token . Comment :
is_whitespace =... |
def browse_podcasts ( self , podcast_genre_id = 'JZCpodcasttopchartall' ) :
"""Get the podcasts for a genre from the Podcasts browse tab .
Parameters :
podcast _ genre _ id ( str , Optional ) : A podcast genre ID as found
in : meth : ` browse _ podcasts _ genres ` .
Default : ` ` ' JZCpodcasttopchartall ' `... | response = self . _call ( mc_calls . PodcastBrowse , podcast_genre_id = podcast_genre_id )
podcast_series_list = response . body . get ( 'series' , [ ] )
return podcast_series_list |
def onPeopleAdded ( self , mid = None , added_ids = None , author_id = None , thread_id = None , ts = None , msg = None , ) :
"""Called when the client is listening , and somebody adds people to a group thread
: param mid : The action ID
: param added _ ids : The IDs of the people who got added
: param author... | log . info ( "{} added: {} in {}" . format ( author_id , ", " . join ( added_ids ) , thread_id ) ) |
async def update ( query ) :
"""Perform UPDATE query asynchronously . Returns number of rows updated .""" | assert isinstance ( query , peewee . Update ) , ( "Error, trying to run update coroutine" "with wrong query class %s" % str ( query ) )
cursor = await _execute_query_async ( query )
rowcount = cursor . rowcount
await cursor . release ( )
return rowcount |
def _enforceDataType ( self , data ) :
"""Converts to str so that this CTI always stores that type .""" | qColor = QtGui . QColor ( data )
# TODO : store a RGB string ?
if not qColor . isValid ( ) :
raise ValueError ( "Invalid color specification: {!r}" . format ( data ) )
return qColor |
def shutdown ( self , how = socket . SHUT_RDWR ) :
"""Send a shutdown signal for both reading and writing , or whatever
socket . SHUT _ * constant you like .
Shutdown differs from closing in that it explicitly changes the state of
the socket resource to closed , whereas closing will only decrement the
numbe... | if self . _sock_send is not None :
self . _sock_send . shutdown ( how )
return self . sock . shutdown ( how ) |
def update_default_rules ( self ) :
"""Concatinate application and global security group rules .""" | app_ingress = self . properties [ 'security_group' ] [ 'ingress' ]
ingress = conservative_merger . merge ( DEFAULT_SECURITYGROUP_RULES , app_ingress )
resolved_ingress = self . resolve_self_references ( ingress )
self . log . info ( 'Updated default rules:\n%s' , ingress )
return resolved_ingress |
def get_versions ( self ) :
"""Returns a list of available versions for this item
: return : list of versions
: rtype : list [ DriveItemVersion ]""" | if not self . object_id :
return [ ]
url = self . build_url ( self . _endpoints . get ( 'versions' ) . format ( id = self . object_id ) )
response = self . con . get ( url )
if not response :
return [ ]
data = response . json ( )
# Everything received from cloud must be passed as self . _ cloud _ data _ key
ret... |
def _init_map ( self ) :
"""stub""" | QuestionTextsFormRecord . _init_map ( self )
QuestionFilesFormRecord . _init_map ( self )
super ( QuestionTextsAndFilesMixin , self ) . _init_map ( ) |
def _calculate_feature_stats ( feature_list , prepared , serialization_file ) : # pylint : disable = R0914
"""Calculate min , max and mean for each feature . Store it in object .""" | # Create feature only list
feats = [ x for x , _ in prepared ]
# Label is not necessary
# Calculate all means / mins / maxs
means = numpy . mean ( feats , 0 )
mins = numpy . min ( feats , 0 )
maxs = numpy . max ( feats , 0 )
# Calculate , min , max and mean vector for each feature with
# normalization
start = 0
mode = ... |
def reduce ( self , mapped_props , aggregated , value_type , visitor ) :
"""This reduction is called to combine the mapped slot and collection
item values into a single value for return .
The default implementation tries to behave naturally ; you ' ll almost
always get a dict back when mapping over a record ,... | reduced = None
if mapped_props :
reduced = dict ( ( k . name , v ) for k , v in mapped_props )
if issubclass ( value_type , Collection ) and aggregated is not None :
if all ( visitor . is_filtered ( prop ) for prop in value_type . properties . values ( ) ) :
reduced = aggregated
else :
if re... |
def get_dimension ( geometry ) :
"""Gets the dimension of a Fiona - like geometry element .""" | coordinates = geometry [ "coordinates" ]
type_ = geometry [ "type" ]
if type_ in ( 'Point' , ) :
return len ( coordinates )
elif type_ in ( 'LineString' , 'MultiPoint' ) :
return len ( coordinates [ 0 ] )
elif type_ in ( 'Polygon' , 'MultiLineString' ) :
return len ( coordinates [ 0 ] [ 0 ] )
elif type_ in ... |
def find_needed_input ( input_format ) :
"""Find a needed input class
input _ format - needed input format , see utils . input . dataformats""" | needed_inputs = [ re . cls for re in registry if re . category == RegistryCategories . inputs and re . cls . input_format == input_format ]
if len ( needed_inputs ) > 0 :
return needed_inputs [ 0 ]
return None |
def create_access_token ( self , authorization_request , subject_identifier , scope = None ) : # type : ( oic . oic . message . AuthorizationRequest , str , Optional [ List [ str ] ] ) - > se _ leg _ op . access _ token . AccessToken
"""Creates an access token bound to the authentication request and the authenticat... | if not self . _is_valid_subject_identifier ( subject_identifier ) :
raise InvalidSubjectIdentifier ( '{} unknown' . format ( subject_identifier ) )
scope = scope or authorization_request [ 'scope' ]
return self . _create_access_token ( subject_identifier , authorization_request . to_dict ( ) , ' ' . join ( scope ) ... |
def offload_service_containers ( self , service ) :
""": param service :
: return :""" | def anonymous ( anonymous_service ) :
if not isinstance ( anonymous_service , Service ) :
raise TypeError ( "service must be an instance of Service." )
if anonymous_service . containers :
logger . info ( "Deleting service: {0} containers." . format ( anonymous_service . name ) )
for cont... |
def _maybe_set_current_user_vars ( method , api_info = None , request = None ) :
"""Get user information from the id _ token or oauth token in the request .
Used internally by Endpoints to set up environment variables for user
authentication .
Args :
method : The class method that ' s handling this request ... | if _is_auth_info_available ( ) :
return
# By default , there ' s no user .
os . environ [ _ENV_AUTH_EMAIL ] = ''
os . environ [ _ENV_AUTH_DOMAIN ] = ''
# Choose settings on the method , if specified . Otherwise , choose settings
# from the API . Specifically check for None , so that methods can override
# with empt... |
def violinplot ( x = None , y = None , data = None , bw = 0.2 , scale = 'width' , inner = None , ax = None , ** kwargs ) :
"""Wrapper around Seaborn ' s Violinplot specifically for [ 0 , 1 ] ranged data
What ' s different :
- bw = 0.2 : Sets bandwidth to be small and the same between datasets
- scale = ' widt... | if ax is None :
ax = plt . gca ( )
sns . violinplot ( x , y , data = data , bw = bw , scale = scale , inner = inner , ax = ax , ** kwargs )
ax . set ( ylim = ( 0 , 1 ) , yticks = ( 0 , 0.5 , 1 ) )
return ax |
def _simplify ( elements ) :
"""Simplifies and normalizes the list of elements removing
redundant / repeated elements and normalising upper / lower case
so case sensitivity is resolved here .""" | simplified = [ ]
previous = None
for element in elements :
if element == ".." :
raise FormicError ( "Invalid glob:" " Cannot have '..' in a glob: {0}" . format ( "/" . join ( elements ) ) )
elif element == "." : # . in a path does not do anything
pass
elif element == "**" and previous == "**... |
def slice_by_size ( seq , size ) :
"""Slice a sequence into chunks , return as a generation of chunks with ` size ` .""" | filling = null
for it in zip ( * ( itertools_chain ( seq , [ filling ] * size ) , ) * size ) :
if filling in it :
it = tuple ( i for i in it if i is not filling )
if it :
yield it |
def links ( self ) :
"""Links parsed from HTTP Link header""" | ret = [ ]
linkheader = self . getheader ( 'link' )
if not linkheader :
return ret
for i in linkheader . split ( ',' ) :
try :
url , params = i . split ( ';' , 1 )
except ValueError :
url , params = i , ''
link = { }
link [ 'url' ] = url . strip ( '''<> '"''' )
for param in params... |
def list_packets ( self , name = None , start = None , stop = None , page_size = 500 , descending = False ) :
"""Reads packet information between the specified start and stop
time .
Packets are sorted by generation time and sequence number .
: param ~ datetime . datetime start : Minimum generation time of the... | params = { 'order' : 'desc' if descending else 'asc' , }
if name is not None :
params [ 'name' ] = name
if page_size is not None :
params [ 'limit' ] = page_size
if start is not None :
params [ 'start' ] = to_isostring ( start )
if stop is not None :
params [ 'stop' ] = to_isostring ( stop )
return pagi... |
def combine_info ( self , all_infos ) :
"""Combine metadata for multiple datasets .
When loading data from multiple files it can be non - trivial to combine
things like start _ time , end _ time , start _ orbit , end _ orbit , etc .
By default this method will produce a dictionary containing all values
that... | combined_info = combine_metadata ( * all_infos )
new_dict = self . _combine ( all_infos , min , 'start_time' , 'start_orbit' )
new_dict . update ( self . _combine ( all_infos , max , 'end_time' , 'end_orbit' ) )
new_dict . update ( self . _combine ( all_infos , np . mean , 'satellite_longitude' , 'satellite_latitude' ,... |
def registerItem ( self , itemName , description = None ) :
"""creates an entry for a given item . Once the entry is created , then
the item can be uploaded by parts . Once finished , a commit call is
made to merge the parts together .
Inputs :
itemName - name of the item to upload
description - optional ... | url = self . _url + "/register"
params = { "f" : "json" , "itemName" : itemName , "description" : "" }
if description is not None :
params [ 'description' ] = description
return self . _post ( url = url , param_dict = params , proxy_url = self . _proxy_url , proxy_port = self . _proxy_port , securityHandler = self ... |
def list_str ( list_ , ** listkw ) :
r"""Makes a pretty list string
Args :
list _ ( list ) : input list
* * listkw : nl , newlines , packed , truncate , nobr , nobraces , itemsep ,
trailing _ sep , truncatekw , strvals , recursive ,
indent _ , precision , use _ numpy , with _ dtype , force _ dtype ,
str... | import utool as ut
newlines = listkw . pop ( 'nl' , listkw . pop ( 'newlines' , 1 ) )
packed = listkw . pop ( 'packed' , False )
truncate = listkw . pop ( 'truncate' , False )
listkw [ 'nl' ] = _rectify_countdown_or_bool ( newlines )
listkw [ 'truncate' ] = _rectify_countdown_or_bool ( truncate )
listkw [ 'packed' ] = ... |
def get_stencil ( self , stencil_name , ** options ) :
"""Return a Stencil instance given a stencil name .""" | if stencil_name not in self . manifest . get ( 'stencils' , { } ) :
raise ValueError ( "Stencil '%s' not declared in StencilSet " "manifest." % stencil_name )
stencil = copy . deepcopy ( self . manifest )
allstencils = stencil . pop ( 'stencils' )
stencil . pop ( 'default_stencil' , None )
override = allstencils [ ... |
def join_time_series ( serieses , ignore_year = False , T_s = None , aggregator = 'mean' ) :
"""Combine a dict of pd . Series objects into a single pd . DataFrame with optional downsampling
FIXME :
For ignore _ year and multi - year data , the index ( in seconds ) is computed assuming
366 days per year ( leap... | if ignore_year :
df = pd . DataFrame ( )
for name , ts in serieses . iteritems ( ) : # FIXME : deal with leap years
sod = np . array ( map ( lambda x : ( x . hour * 3600 + x . minute * 60 + x . second ) , ts . index . time ) )
# Coerce soy to an integer so that merge / join operations identify s... |
def on_quit ( self , event , wind = None ) :
"""shut down application if in the main frame .
otherwise , destroy the top window ( wind ) and restore
the main frame .""" | if wind :
wind . Destroy ( )
if not self . parent . IsShown ( ) :
self . on_show_mainframe ( None )
# re - do the quit binding
self . parent . Bind ( wx . EVT_MENU , self . on_quit , self . file_quit )
else :
self . parent . Close ( ) |
def setLabel ( self , edfsignal , label ) :
"""Sets the label ( name ) of signal edfsignal ( " FP1 " , " SaO2 " , etc . ) .
Parameters
edfsignal : int
signal number on which the label should be changed
label : str
signal label
Notes
This function is recommended for every signal and can be called only ... | if ( edfsignal < 0 or edfsignal > self . n_channels ) :
raise ChannelDoesNotExist ( edfsignal )
self . channels [ edfsignal ] [ 'label' ] = label
self . update_header ( ) |
def folderitem ( self , obj , item , index ) :
"""Augment folder listing item""" | url = item . get ( "url" )
title = item . get ( "Title" )
item [ "getDownFrom" ] = self . localize_date ( obj . getDownFrom ( ) )
item [ "getDownTo" ] = self . localize_date ( obj . getDownTo ( ) )
item [ "getValidator" ] = obj . getValidator ( )
item [ "replace" ] [ "Title" ] = get_link ( url , value = title )
# valid... |
def get_relative_error ( self ) :
"""Returns the relative error statistic ( e _ rel ) , defined by Frohlich &
Davis ( 1999 ) : ` e _ rel = sqrt ( ( U : U ) / ( M : M ) ) ` where M is the moment
tensor , U is the uncertainty tensor and : is the tensor dot product""" | if not self . moment_tensor :
raise ValueError ( 'Moment tensor not defined!' )
numer = np . tensordot ( self . moment_tensor . tensor_sigma , self . moment_tensor . tensor_sigma )
denom = np . tensordot ( self . moment_tensor . tensor , self . moment_tensor . tensor )
self . e_rel = sqrt ( numer / denom )
return s... |
def config ( self ) :
"""Get a Configuration object from the file contents .""" | conf = config . Configuration ( )
for namespace in self . namespaces :
if not hasattr ( conf , namespace ) :
if not self . _strict :
continue
raise exc . NamespaceNotRegistered ( "The namespace {0} is not registered." . format ( namespace ) )
name = getattr ( conf , namespace )
f... |
def getFrameTiming ( self , unFramesAgo ) :
"""Returns true if timing data is filled it . Sets oldest timing info if nFramesAgo is larger than the stored history .
Be sure to set timing . size = sizeof ( Compositor _ FrameTiming ) on struct passed in before calling this function .""" | fn = self . function_table . getFrameTiming
pTiming = Compositor_FrameTiming ( )
result = fn ( byref ( pTiming ) , unFramesAgo )
return result , pTiming |
def logout_view ( request ) :
"""Clear the Kerberos cache and logout .""" | do_logout ( request )
app_redirects = { "collegerecs" : "https://apps.tjhsst.edu/collegerecs/logout?ion_logout=1" }
app = request . GET . get ( "app" , "" )
if app and app in app_redirects :
return redirect ( app_redirects [ app ] )
return redirect ( "index" ) |
def set_priority ( self , priority ) :
"""Sets the priority .
arg : priority ( osid . type . Type ) : the new priority
raise : InvalidArgument - ` ` priority ` ` is invalid
raise : NoAccess - ` ` Metadata . isReadOnly ( ) ` ` is ` ` true ` `
raise : NullArgument - ` ` priority ` ` is ` ` null ` `
* compli... | # Implemented from template for osid . logging . LogEntryForm . set _ priority
if self . get_priority_metadata ( ) . is_read_only ( ) :
raise errors . NoAccess ( )
if not self . _is_valid_type ( priority ) :
raise errors . InvalidArgument ( )
self . _my_map [ 'priority' ] = str ( priority ) |
def generate_binding_permissions ( self , binding , permissions ) :
"""Generate Users pemissions on the database
Defining roles to the database for the users .
We can pass extra information into parameters of the binding if needed ( see binding . parameters ) .
Args :
binding ( AtlasServiceBinding . Binding... | permissions . add_roles ( binding . instance . get_dbname ( ) , [ RoleSpecs . dbAdmin , RoleSpecs . readWrite ] )
return permissions |
def _handle_array_decl ( self , node , scope , ctxt , stream ) :
"""Handle ArrayDecl nodes
: node : TODO
: scope : TODO
: ctxt : TODO
: stream : TODO
: returns : TODO""" | self . _dlog ( "handling array declaration '{}'" . format ( node . type . declname ) )
if node . dim is None : # will be used
array_size = None
else :
array_size = self . _handle_node ( node . dim , scope , ctxt , stream )
self . _dlog ( "array size = {}" . format ( array_size ) )
# TODO node . dim _ quals
# no... |
def init ( ) :
"Initialize the current directory with base starting files and database ." | if not os . path . exists ( 'site.cfg' ) :
f = open ( 'site.cfg' , 'w' )
f . write ( SITECFG )
f . close ( )
try :
os . mkdir ( 'queries' )
except OSError :
pass
try :
os . mkdir ( 'templates' )
except OSError :
pass
htmlfile = os . path . join ( 'templates' , 'homepage.html' )
if not os . p... |
def _health_check_thread ( self ) :
"""Health checker thread that pings the service every 30 seconds
: return : None""" | while self . _run_health_checker :
response = self . _health_check ( Health_pb2 . HealthCheckRequest ( service = 'predix-event-hub.grpc.health' ) )
logging . debug ( 'received health check: ' + str ( response ) )
time . sleep ( 30 )
return |
def init_gpg ( self ) :
"""Initialize gpg object and check if repository signing key is trusted""" | if self . gpg_verify :
logger . debug ( "gpg verification enabled, initializing gpg" )
gpg_home = os . path . expanduser ( '~/.gnupg' )
self . gpg = gnupg . GPG ( gnupghome = gpg_home )
self . key_path , self . key_info = self . get_signing_key ( )
logger . debug ( "{0} {1}" . format ( self . key_pa... |
def readmission ( aFileName ) :
"""Load a mission from a file into a list . The mission definition is in the Waypoint file
format ( http : / / qgroundcontrol . org / mavlink / waypoint _ protocol # waypoint _ file _ format ) .
This function is used by upload _ mission ( ) .""" | print ( "\nReading mission from file: %s" % aFileName )
cmds = vehicle . commands
missionlist = [ ]
with open ( aFileName ) as f :
for i , line in enumerate ( f ) :
if i == 0 :
if not line . startswith ( 'QGC WPL 110' ) :
raise Exception ( 'File is not supported WP version' )
... |
def set_size ( self , width , height ) :
"""Set the widget size .
Args :
width ( int or str ) : An optional width for the widget ( es . width = 10 or width = ' 10px ' or width = ' 10 % ' ) .
height ( int or str ) : An optional height for the widget ( es . height = 10 or height = ' 10px ' or height = ' 10 % ' ... | if width is not None :
try :
width = to_pix ( int ( width ) )
except ValueError : # now we know w has ' px or % in it '
pass
self . style [ 'width' ] = width
if height is not None :
try :
height = to_pix ( int ( height ) )
except ValueError : # now we know w has ' px or % in ... |
def stop ( self ) :
"""Stop this process .
Once closed , it should not , and cannot be used again .
: return : : py : attr : ` ~ exitcode ` .""" | self . child . terminate ( )
self . _cleanup ( )
return self . child . exitcode |
def shift ( self , periods , freq = None ) :
"""Shift index by desired number of time frequency increments .
This method is for shifting the values of datetime - like indexes
by a specified time increment a given number of times .
Parameters
periods : int
Number of periods ( or increments ) to shift by , ... | result = self . _data . _time_shift ( periods , freq = freq )
return type ( self ) ( result , name = self . name ) |
def _patched_pep257 ( ) :
"""Monkey - patch pep257 after imports to avoid info logging .""" | import pep257
if getattr ( pep257 , "log" , None ) :
def _dummy ( * args , ** kwargs ) :
del args
del kwargs
old_log_info = pep257 . log . info
pep257 . log . info = _dummy
# suppress ( unused - attribute )
try :
yield
finally :
if getattr ( pep257 , "log" , None ) :
pep2... |
def save_model ( model_folder : str , model_name : str , model : Model , compiler_options : Dict [ str , str ] ) -> None :
"""Saves a CasADi model to disk .
: param model _ folder : Folder where the precompiled CasADi model will be stored .
: param model _ name : Name of the model .
: param model : Model inst... | objects = { 'dae_residual' : None , 'initial_residual' : None , 'variable_metadata' : None , 'delay_arguments' : None }
for o in objects . keys ( ) :
f = getattr ( model , o + '_function' )
if compiler_options . get ( 'codegen' , False ) :
objects [ o ] = _codegen_model ( model_folder , f , '{}_{}' . fo... |
def _elements_to_dict ( data , position , obj_end , opts ) :
"""Decode a BSON document .""" | result = opts . document_class ( )
pos = position
for key , value , pos in _iterate_elements ( data , position , obj_end , opts ) :
result [ key ] = value
if pos != obj_end :
raise InvalidBSON ( 'bad object or element length' )
return result |
def addPrivateCertificate ( self , subjectName , existingCertificate = None ) :
"""Add a PrivateCertificate object to this store for this subjectName .
If existingCertificate is None , add a new self - signed certificate .""" | if existingCertificate is None :
assert '@' not in subjectName , "Don't self-sign user certs!"
mainDN = DistinguishedName ( commonName = subjectName )
mainKey = KeyPair . generate ( )
mainCertReq = mainKey . certificateRequest ( mainDN )
mainCertData = mainKey . signCertificateRequest ( mainDN , mai... |
def lev_bounds ( self ) :
"""Pressure levels at grid interfaces ( hPa or mb )
: getter : Returns the bounds of axis ` ` ' lev ' ` ` if availible in the
process ' s domains .
: type : array
: raises : : exc : ` ValueError `
if no ` ` ' lev ' ` ` axis can be found .""" | try :
for domname , dom in self . domains . items ( ) :
try :
thislev = dom . axes [ 'lev' ] . bounds
except :
pass
return thislev
except :
raise ValueError ( 'Can\'t resolve a lev axis.' ) |
def execute ( self , command , istream = None , with_keep_cwd = False , with_extended_output = False , with_exceptions = True , as_process = False , output_stream = None , ** subprocess_kwargs ) :
"""Handles executing the command on the shell and consumes and returns
the returned information ( stdout )
: param ... | if GIT_PYTHON_TRACE and not GIT_PYTHON_TRACE == 'full' :
print ' ' . join ( command )
# Allow the user to have the command executed in their working dir .
if with_keep_cwd or self . _working_dir is None :
cwd = os . getcwd ( )
else :
cwd = self . _working_dir
# Start the process
proc = Popen ( command , cwd... |
def recalc_concurrency ( self ) :
'''Call to recalculate sleeps and concurrency for the session . Called automatically if
cost has drifted significantly . Otherwise can be called at regular intervals if
desired .''' | # Refund resource usage proportionally to elapsed time ; the bump passed is negative
now = time . time ( )
self . cost = max ( 0 , self . cost - ( now - self . _cost_time ) * self . cost_decay_per_sec )
self . _cost_time = now
self . _cost_last = self . cost
# Setting cost _ hard _ limit < = 0 means to not limit concur... |
def from_path ( cls , spec_path ) :
"""Load a specification from a path .
: param FilePath spec _ path : The location of the specification to read .""" | with spec_path . open ( ) as spec_file :
return cls . from_document ( load ( spec_file ) ) |
def on_same_fs ( request ) :
"""Accept a POST request to check access to a FS available by a client .
: param request :
` django . http . HttpRequest ` object , containing mandatory parameters
filename and checksum .""" | filename = request . POST [ 'filename' ]
checksum_in = request . POST [ 'checksum' ]
checksum = 0
try :
data = open ( filename , 'rb' ) . read ( 32 )
checksum = zlib . adler32 ( data , checksum ) & 0xffffffff
if checksum == int ( checksum_in ) :
return HttpResponse ( content = json . dumps ( { 'succ... |
def next_page ( self , max_ = None ) :
"""Return a query set which requests the page after this response .
: param max _ : Maximum number of items to return .
: type max _ : : class : ` int ` or : data : ` None `
: rtype : : class : ` ResultSetMetadata `
: return : A new request set up to request the next p... | result = type ( self ) ( )
result . after = After ( self . last . value )
result . max_ = max_
return result |
def __proxy_password ( self ) :
"""Returning the password and immediately destroying it""" | passwd = copy ( self . _inp_proxy_password . value )
self . _inp_proxy_password . value = ''
return passwd |
def simplify ( self , eps , max_dist_error , max_speed_error , topology_only = False ) :
"""In - place simplification of segments
Args :
max _ dist _ error ( float ) : Min distance error , in meters
max _ speed _ error ( float ) : Min speed error , in km / h
topology _ only : Boolean , optional . True to ke... | for segment in self . segments :
segment . simplify ( eps , max_dist_error , max_speed_error , topology_only )
return self |
def patch_namespaced_stateful_set ( self , name , namespace , body , ** kwargs ) : # noqa : E501
"""patch _ namespaced _ stateful _ set # noqa : E501
partially update the specified StatefulSet # noqa : E501
This method makes a synchronous HTTP request by default . To make an
asynchronous HTTP request , please... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'async_req' ) :
return self . patch_namespaced_stateful_set_with_http_info ( name , namespace , body , ** kwargs )
# noqa : E501
else :
( data ) = self . patch_namespaced_stateful_set_with_http_info ( name , namespace , body , ** kwargs )
# no... |
def showGrid ( self ) :
"""Returns whether or not this delegate should draw its grid lines .
: return < bool >""" | delegate = self . itemDelegate ( )
if ( isinstance ( delegate , XTreeWidgetDelegate ) ) :
return delegate . showGrid ( )
return False |
def commit_analyzer ( commits , label_pattern , label_position = "footer" ) :
"""Analyzes a list of : class : ` ~ braulio . git . Commit ` objects searching for
messages that match a given message convention and extract metadata from
them .
A message convention is determined by ` ` label _ pattern ` ` , which... | # Internally , a real regular expression pattern is used
pattern_string = re . escape ( label_pattern )
# Capturing group patterns
action_cgp = r"(?P<type>\w+)"
scope_cgp = r"(?P<scope>\w*)"
subject_cgp = r"(?P<subject>.+)"
pattern_string = pattern_string . replace ( r"\{type\}" , action_cgp ) . replace ( r"\{scope\}" ... |
async def request ( self , method : base . String , data : Optional [ Dict ] = None , files : Optional [ Dict ] = None , ** kwargs ) -> Union [ List , Dict , base . Boolean ] :
"""Make an request to Telegram Bot API
https : / / core . telegram . org / bots / api # making - requests
: param method : API method
... | return await api . make_request ( self . session , self . __token , method , data , files , proxy = self . proxy , proxy_auth = self . proxy_auth , timeout = self . timeout , ** kwargs ) |
def DeserializeExclusiveData ( self , reader ) :
"""Deserialize full object .
Args :
reader ( neo . IO . BinaryReader ) :""" | self . Type = TransactionType . IssueTransaction
if self . Version > 1 :
raise Exception ( 'Invalid TX Type' ) |
def _set_fcoe_map_fabric_map ( self , v , load = False ) :
"""Setter method for fcoe _ map _ fabric _ map , mapped from YANG variable / fcoe / fcoe _ map / fcoe _ map _ fabric _ map ( container )
If this variable is read - only ( config : false ) in the
source YANG file , then _ set _ fcoe _ map _ fabric _ map ... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = fcoe_map_fabric_map . fcoe_map_fabric_map , is_container = 'container' , presence = False , yang_name = "fcoe-map-fabric-map" , rest_name = "fabric-map" , parent = self , path_helper = self . _path_helper , extmethods = self ... |
def rec_new ( self , zone , record_type , name , content , ttl = 1 , priority = None , service = None , service_name = None , protocol = None , weight = None , port = None , target = None ) :
"""Create a DNS record for the given zone
: param zone : domain name
: type zone : str
: param record _ type : Type of... | params = { 'a' : 'rec_new' , 'z' : zone , 'type' : record_type , 'name' : name , 'content' : content , 'ttl' : ttl }
if priority is not None :
params [ 'prio' ] = priority
if service is not None :
params [ 'service' ] = service
if service_name is not None :
params [ 'srvname' ] = service_name
if protocol is... |
def enable_marathon_basic_authentication ( principal , password ) :
"""configures marathon to start with authentication""" | upstart_file = '/etc/init/marathon.conf'
with hide ( 'running' , 'stdout' ) :
sudo ( 'echo -n "{}" > /etc/marathon-mesos.credentials' . format ( password ) )
boot_args = ' ' . join ( [ 'exec' , '/usr/bin/marathon' , '--http_credentials' , '"{}:{}"' . format ( principal , password ) , '--mesos_authentication_princip... |
def add_static_path ( prefix : str , path : str , no_watch : bool = False ) -> None :
"""Add directory to serve static files .
First argument ` ` prefix ` ` is a URL prefix for the ` ` path ` ` . ` ` path ` ` must
be a directory . If ` ` no _ watch ` ` is True , any change of the files in the
path do not trig... | app = get_app ( )
app . add_static_path ( prefix , path )
if not no_watch :
watch_dir ( path ) |
def cfg_to_dot ( self , filename ) :
"""Export the function to a dot file
Args :
filename ( str )""" | with open ( filename , 'w' , encoding = 'utf8' ) as f :
f . write ( 'digraph{\n' )
for node in self . nodes :
f . write ( '{}[label="{}"];\n' . format ( node . node_id , str ( node ) ) )
for son in node . sons :
f . write ( '{}->{};\n' . format ( node . node_id , son . node_id ) )
... |
def StyleFactory ( style_elm ) :
"""Return a style object of the appropriate | BaseStyle | subclass , according
to the type of * style _ elm * .""" | style_cls = { WD_STYLE_TYPE . PARAGRAPH : _ParagraphStyle , WD_STYLE_TYPE . CHARACTER : _CharacterStyle , WD_STYLE_TYPE . TABLE : _TableStyle , WD_STYLE_TYPE . LIST : _NumberingStyle } [ style_elm . type ]
return style_cls ( style_elm ) |
def add ( cls , zone_id , version_id , record ) :
"""Add record to a zone .""" | return cls . call ( 'domain.zone.record.add' , zone_id , version_id , record ) |
def set_font ( self , pango_layout ) :
"""Sets the font for draw _ text""" | wx2pango_weights = { wx . FONTWEIGHT_BOLD : pango . WEIGHT_BOLD , wx . FONTWEIGHT_LIGHT : pango . WEIGHT_LIGHT , wx . FONTWEIGHT_NORMAL : None , # Do not set a weight by default
}
wx2pango_styles = { wx . FONTSTYLE_NORMAL : None , # Do not set a style by default
wx . FONTSTYLE_SLANT : pango . STYLE_OBLIQUE , wx . FONTS... |
def numerator ( self , value ) :
"""Sets a new numerator and generates the ETA . Must be greater than or equal to previous numerator .""" | # If ETA is every iteration , don ' t do anything fancy .
if self . eta_every <= 1 :
self . _eta . numerator = value
self . _eta_string = self . _generate_eta ( self . _eta . eta_seconds )
return
# If ETA is not every iteration , unstable rate is used . If this bar is undefined , no point in calculating eve... |
def open ( self ) :
"""\~english Trun on device and with all sensors at same time
\~chinese 开启全部传感器""" | self . _sendCmd ( self . REG_PWR_MGMT_1 , 0x00 )
self . _sendCmd ( self . REG_PWR_MGMT_2 , 0x00 ) |
def _verify_parsed_token ( parsed_token , issuers , audiences , allowed_client_ids , is_legacy_google_auth = True ) :
"""Verify a parsed user ID token .
Args :
parsed _ token : The parsed token information .
issuers : A list of allowed issuers
audiences : The allowed audiences .
allowed _ client _ ids : T... | # Verify the issuer .
if parsed_token . get ( 'iss' ) not in issuers :
_logger . warning ( 'Issuer was not valid: %s' , parsed_token . get ( 'iss' ) )
return False
# Check audiences .
aud = parsed_token . get ( 'aud' )
if not aud :
_logger . warning ( 'No aud field in token' )
return False
# Special leg... |
def publish ( tgt , fun , arg = None , tgt_type = 'glob' , returner = '' , timeout = 5 , via_master = None ) :
'''Publish a command from the minion out to other minions .
Publications need to be enabled on the Salt master and the minion
needs to have permission to publish the command . The Salt master
will al... | return _publish ( tgt , fun , arg = arg , tgt_type = tgt_type , returner = returner , timeout = timeout , form = 'clean' , wait = True , via_master = via_master ) |
def no_gaps ( curve ) :
"""Check for gaps , after ignoring any NaNs at the top and bottom .""" | tnt = utils . top_and_tail ( curve )
return not any ( np . isnan ( tnt ) ) |
def get_signature ( payment_request ) :
"""Returns the signature for the transaction .
To compute the signature , first you have to get the value of all
the fields that starts by ' vads _ ' , ordering them alphabetically .
All the values are separated by the ' + ' character . Then you add
the value of the p... | vads_args = { }
for field in payment_request . _meta . fields :
if field . name [ : 5 ] == 'vads_' :
field_value = field . value_from_object ( payment_request )
if field_value :
vads_args . update ( { field . name : field_value } )
base_str = ''
for key in sorted ( vads_args ) :
base... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.