signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def _condense ( self , data ) :
'''Condense by adding together all of the lists .''' | rval = { }
for resolution , histogram in data . items ( ) :
for value , count in histogram . items ( ) :
rval [ value ] = count + rval . get ( value , 0 )
return rval |
def append_seeding_induction ( self , nodes : Union [ BaseEntity , List [ BaseEntity ] , List [ Dict ] ] ) -> Seeding :
"""Add a seed induction method .
: returns : seeding container for fluid API""" | return self . seeding . append_induction ( nodes ) |
def describe_volumes ( self , * volume_ids ) :
"""Describe available volumes .""" | volumeset = { }
for pos , volume_id in enumerate ( volume_ids ) :
volumeset [ "VolumeId.%d" % ( pos + 1 ) ] = volume_id
query = self . query_factory ( action = "DescribeVolumes" , creds = self . creds , endpoint = self . endpoint , other_params = volumeset )
d = query . submit ( )
return d . addCallback ( self . pa... |
def prime_event ( event , source , ** kwargs ) :
"""Returns the event ready to be triggered .
If the given event is a string an Event instance is generated from it .""" | if not isinstance ( event , Event ) :
event = Event ( event , source = source , ** kwargs )
return event |
def GET_AUTH ( self , courseid ) : # pylint : disable = arguments - differ
"""GET request""" | course , _ = self . get_course_and_check_rights ( courseid )
return self . page ( course ) |
def _parseExpression ( self , src , returnList = False ) :
"""expr
: term [ operator term ] *""" | src , term = self . _parseExpressionTerm ( src )
operator = None
while src [ : 1 ] not in ( '' , ';' , '{' , '}' , '[' , ']' , ')' ) :
for operator in self . ExpressionOperators :
if src . startswith ( operator ) :
src = src [ len ( operator ) : ]
break
else :
operator = ... |
def from_filepath ( filepath , strict = True , parse_ligands = False ) :
'''A function to replace the old constructor call where a filename was passed in .''' | return PDB ( read_file ( filepath ) , strict = strict , parse_ligands = parse_ligands ) |
def update ( self ) :
"""Update the HVAC state .""" | self . _controller . update ( self . _id , wake_if_asleep = False )
data = self . _controller . get_climate_params ( self . _id )
if data :
if time . time ( ) - self . __manual_update_time > 60 :
self . __is_auto_conditioning_on = ( data [ 'is_auto_conditioning_on' ] )
self . __is_climate_on = data ... |
def endpoints ( self ) :
"""Get all the endpoints under this node in a tree like structure .
Returns :
( tuple ) :
name ( str ) : This node ' s name .
endpoint ( str ) : Endpoint name relative to root .
children ( list ) : ` ` child . endpoints for each child""" | children = [ item . endpoints ( ) for item in self . items ]
return self . name , self . endpoint , children |
def page ( self ) :
"""Get current page .
: return int : page number""" | if not self . _page :
try :
self . _page = self . paginator . page ( self . query_dict . get ( 'page' , 1 ) )
except InvalidPage :
raise HttpError ( "Invalid page" , status = HTTP_400_BAD_REQUEST )
return self . _page |
def _provision_network ( self , port_id , net_uuid , network_type , physical_network , segmentation_id ) :
"""Provision the network with the received information .""" | LOG . info ( "Provisioning network %s" , net_uuid )
vswitch_name = self . _get_vswitch_name ( network_type , physical_network )
vswitch_map = { 'network_type' : network_type , 'vswitch_name' : vswitch_name , 'ports' : [ ] , 'vlan_id' : segmentation_id }
self . _network_vswitch_map [ net_uuid ] = vswitch_map |
def get_extract_method ( path ) :
"""Returns ` ExtractMethod ` to use on resource at path . Cannot be None .""" | info_path = _get_info_path ( path )
info = _read_info ( info_path )
fname = info . get ( 'original_fname' , path ) if info else path
return _guess_extract_method ( fname ) |
def scatter_single ( ax , Y , * args , ** kwargs ) :
"""Plot scatter plot of data .
Parameters
ax : matplotlib . axis
Axis to plot on .
Y : np . array
Data array , data to be plotted needs to be in the first two columns .""" | if 's' not in kwargs :
kwargs [ 's' ] = 2 if Y . shape [ 0 ] > 500 else 10
if 'edgecolors' not in kwargs :
kwargs [ 'edgecolors' ] = 'face'
ax . scatter ( Y [ : , 0 ] , Y [ : , 1 ] , ** kwargs , rasterized = settings . _vector_friendly )
ax . set_xticks ( [ ] )
ax . set_yticks ( [ ] ) |
def save_publication ( pub ) :
"""Save ` pub ` into database and into proper indexes .
Attr :
pub ( obj ) : Instance of the : class : ` . DBPublication ` .
Returns :
obj : : class : ` . DBPublication ` without data .
Raises :
InvalidType : When the ` pub ` is not instance of : class : ` . DBPublication ... | _assert_obj_type ( pub )
_get_handler ( ) . store_object ( pub )
return pub . to_comm ( light_request = True ) |
def fromScratch ( self ) :
"""Start a fresh experiment , from scratch .
Returns ` self ` .""" | assert ( not os . path . lexists ( self . latestLink ) or os . path . islink ( self . latestLink ) )
self . rmR ( self . latestLink )
return self |
def _apply_mask ( self , p , mat ) :
"""Create ( if necessary ) and apply the mask to the given matrix mat .""" | mask = p . mask
ms = p . mask_shape
if ms is not None :
mask = ms ( x = p . x + p . size * ( ms . x * np . cos ( p . orientation ) - ms . y * np . sin ( p . orientation ) ) , y = p . y + p . size * ( ms . x * np . sin ( p . orientation ) + ms . y * np . cos ( p . orientation ) ) , orientation = ms . orientation + p... |
def sanitize_host ( host ) :
'''Sanitize host string .
https : / / tools . ietf . org / html / rfc1123 # section - 2.1''' | RFC952_characters = ascii_letters + digits + ".-"
return "" . join ( [ c for c in host [ 0 : 255 ] if c in RFC952_characters ] ) |
def consume_results ( self ) : # pylint : disable = too - many - branches
"""Handle results waiting in waiting _ results list .
Check ref will call consume result and update their status
: return : None""" | # All results are in self . waiting _ results
# We need to get them first
queue_size = self . waiting_results . qsize ( )
for _ in range ( queue_size ) :
self . manage_results ( self . waiting_results . get ( ) )
# Then we consume them
for chk in list ( self . checks . values ( ) ) :
if chk . status == ACT_STAT... |
def get_default_config_file ( argparser , suppress = None , default_override = None ) :
"""Turn an ArgumentParser into a ConfigObj compatible configuration file .
This method will take the given argparser , and loop over all options contained . The configuration file is formatted
as follows :
# < option help ... | if not suppress :
suppress = [ ]
if not default_override :
default_override = { }
lines = [ ]
seen_arguments = [ ]
for arg in argparser . _actions :
if arg . dest in suppress :
continue
if arg . dest in seen_arguments :
continue
default = arg . default
if arg . dest in default_ov... |
def delete ( self ) :
"""Deletes the Indicator / Group / Victim or Security Label""" | if not self . can_delete ( ) :
self . _tcex . handle_error ( 915 , [ self . type ] )
return self . tc_requests . delete ( self . api_type , self . api_sub_type , self . unique_id , owner = self . owner ) |
def invoke ( * args , ** kwargs ) :
"""Invokes a command callback in exactly the way it expects . There
are two ways to invoke this method :
1 . the first argument can be a callback and all other arguments and
keyword arguments are forwarded directly to the function .
2 . the first argument is a click comma... | self , callback = args [ : 2 ]
ctx = self
# It ' s also possible to invoke another command which might or
# might not have a callback . In that case we also fill
# in defaults and make a new context for this command .
if isinstance ( callback , Command ) :
other_cmd = callback
callback = other_cmd . callback
... |
def has_reg ( self , reg_name ) :
"""Check if a register is used in the instruction .""" | return any ( operand . has_reg ( reg_name ) for operand in self . operands ) |
def simulate_list ( nwords = 16 , nrec = 10 , ncats = 4 ) :
"""A function to simulate a list""" | # load wordpool
wp = pd . read_csv ( 'data/cut_wordpool.csv' )
# get one list
wp = wp [ wp [ 'GROUP' ] == np . random . choice ( list ( range ( 16 ) ) , 1 ) [ 0 ] ] . sample ( 16 )
wp [ 'COLOR' ] = [ [ int ( np . random . rand ( ) * 255 ) for i in range ( 3 ) ] for i in range ( 16 ) ] |
def complete_node ( arg ) :
"""Complete node hostname
This function is currently a bit special as it looks in the config file
for a command to use to complete a node hostname from an external
system .
It is configured by setting the config attribute " complete _ node _ cmd " to
a shell command . The strin... | # get complete command from config
try :
cmd = cfg . get ( 'global' , 'complete_node_cmd' )
except configparser . NoOptionError :
return [ '' , ]
cmd = re . sub ( '%search_string%' , pipes . quote ( arg ) , cmd )
args = shlex . split ( cmd )
p = subprocess . Popen ( args , stdout = subprocess . PIPE )
res , err... |
def selector_to_xpath ( cls , selector , xmlns = None ) :
"""convert a css selector into an xpath expression .
xmlns is option single - item dict with namespace prefix and href""" | selector = selector . replace ( ' .' , ' *.' )
if selector [ 0 ] == '.' :
selector = '*' + selector
log . debug ( selector )
if '#' in selector :
selector = selector . replace ( '#' , '*#' )
log . debug ( selector )
if xmlns is not None :
prefix = list ( xmlns . keys ( ) ) [ 0 ]
href = xmlns [ p... |
def pack ( self , ** kw ) :
"""Pack a widget in the parent widget .
: param after : pack it after you have packed widget
: type after : widget
: param anchor : position anchor according to given direction
( " n " , " s " , " e " , " w " or combinations )
: type anchor : str
: param before : pack it befo... | ttk . Scrollbar . pack ( self , ** kw )
try :
self . _pack_kw = self . pack_info ( )
except TypeError : # bug in some tkinter versions
self . _pack_kw = self . _get_info ( "pack" )
self . _layout = 'pack' |
def encode_list ( data , encoding = None , errors = 'strict' , keep = False , preserve_dict_class = False , preserve_tuples = False ) :
'''Encode all string values to bytes''' | rv = [ ]
for item in data :
if isinstance ( item , list ) :
item = encode_list ( item , encoding , errors , keep , preserve_dict_class , preserve_tuples )
elif isinstance ( item , tuple ) :
item = encode_tuple ( item , encoding , errors , keep , preserve_dict_class ) if preserve_tuples else enco... |
def confd_state_loaded_data_models_data_model_namespace ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
confd_state = ET . SubElement ( config , "confd-state" , xmlns = "http://tail-f.com/yang/confd-monitoring" )
loaded_data_models = ET . SubElement ( confd_state , "loaded-data-models" )
data_model = ET . SubElement ( loaded_data_models , "data-model" )
name_key = ET . SubElement ( data... |
def add ( self , years = 0 , months = 0 , weeks = 0 , days = 0 , hours = 0 , minutes = 0 , seconds = 0 , microseconds = 0 , ) : # type : ( int , int , int , int , int , int , int ) - > DateTime
"""Add a duration to the instance .
If we ' re adding units of variable length ( i . e . , years , months ) ,
move for... | units_of_variable_length = any ( [ years , months , weeks , days ] )
current_dt = datetime . datetime ( self . year , self . month , self . day , self . hour , self . minute , self . second , self . microsecond , )
if not units_of_variable_length :
offset = self . utcoffset ( )
if offset :
current_dt = ... |
def _connect ( self ) :
"""Connect to the serial port .""" | try :
while True :
_LOGGER . info ( 'Trying to connect to %s' , self . port )
try :
yield from serial_asyncio . create_serial_connection ( self . loop , lambda : self . protocol , self . port , self . baud )
return
except serial . SerialException :
_LOGGER... |
def _recordAndPrintHeadline ( self , test , error_class , artifact ) :
"""Record that an error - like thing occurred , and print a summary .
Store ` ` artifact ` ` with the record .
Return whether the test result is any sort of failure .""" | # We duplicate the errorclass handling from super rather than calling
# it and monkeying around with showAll flags to keep it from printing
# anything .
is_error_class = False
for cls , ( storage , label , is_failure ) in self . errorClasses . items ( ) :
if isclass ( error_class ) and issubclass ( error_class , cl... |
def _normalize ( number ) :
"""Normalizes a string of characters representing a phone number .
This performs the following conversions :
- Punctuation is stripped .
- For ALPHA / VANITY numbers :
- Letters are converted to their numeric representation on a telephone
keypad . The keypad used here is the on... | m = fullmatch ( _VALID_ALPHA_PHONE_PATTERN , number )
if m :
return _normalize_helper ( number , _ALPHA_PHONE_MAPPINGS , True )
else :
return normalize_digits_only ( number ) |
def configure ( self , rhsm = None , repositories = None ) :
"""This method will configure the host0 and run the hypervisor .""" | if rhsm is not None :
self . rhsm_register ( rhsm )
if repositories is not None :
self . enable_repositories ( repositories )
self . create_stack_user ( )
self . deploy_hypervisor ( ) |
def http_signature ( message , key_id , signature ) :
"""Return a tuple ( message signature , HTTP header message signature ) .""" | template = ( 'Signature keyId="%(keyId)s",algorithm="hmac-sha256",' 'headers="%(headers)s",signature="%(signature)s"' )
headers = [ '(request-target)' , 'host' , 'accept' , 'date' ]
return template % { 'keyId' : key_id , 'signature' : signature , 'headers' : ' ' . join ( headers ) , } |
def _create_dir_path ( self , file_hash , path = None , hash_list = None ) :
"""Create proper filesystem paths for given ` file _ hash ` .
Args :
file _ hash ( str ) : Hash of the file for which the path should be
created .
path ( str , default None ) : Recursion argument , don ' t set this .
hash _ list ... | # first , non - recursive call - parse ` file _ hash `
if hash_list is None :
hash_list = list ( file_hash )
if not hash_list :
raise IOError ( "Directory structure is too full!" )
# first , non - recursive call - look for subpath of ` self . path `
if not path :
path = os . path . join ( self . path , hash... |
def get_cursor_time ( self , project_name , logstore_name , shard_id , cursor ) :
"""Get cursor time from log service
Unsuccessful opertaion will cause an LogException .
: type project _ name : string
: param project _ name : the Project name
: type logstore _ name : string
: param logstore _ name : the l... | headers = { 'Content-Type' : 'application/json' }
params = { 'type' : 'cursor_time' , 'cursor' : cursor }
resource = "/logstores/" + logstore_name + "/shards/" + str ( shard_id )
( resp , header ) = self . _send ( "GET" , project_name , None , resource , params , headers )
return GetCursorTimeResponse ( resp , header ) |
def process ( self ) :
"""Collects , processes & reports metrics""" | if self . agent . machine . fsm . current is "wait4init" : # Test the host agent if we ' re ready to send data
if self . agent . is_agent_ready ( ) :
self . agent . machine . fsm . ready ( )
else :
return
if self . agent . can_send ( ) :
self . snapshot_countdown = self . snapshot_countdown ... |
def open_fast ( self ) :
"""Turn the device ON Fast .""" | open_command = StandardSend ( self . _address , COMMAND_LIGHT_ON_FAST_0X12_NONE , cmd2 = 0xff )
self . _send_method ( open_command , self . _open_message_received ) |
def command ( self ) :
"""This is used to write a snippet message in the status bar .
A cursor is appended at the end .""" | msg = self . gui . status_message
n = len ( msg )
n_cur = len ( self . cursor )
return msg [ : n - n_cur ] |
def _dataframe_fields ( self ) :
"""Creates a dictionary of all fields to include with DataFrame .
With the result of the calls to class properties changing based on the
class index value , the dictionary should be regenerated every time the
index is changed when the dataframe property is requested .
Return... | fields_to_include = { 'adjusted_assists' : self . adjusted_assists , 'adjusted_goals' : self . adjusted_goals , 'adjusted_goals_against_average' : self . adjusted_goals_against_average , 'adjusted_goals_created' : self . adjusted_goals_created , 'adjusted_points' : self . adjusted_points , 'age' : self . age , 'assists... |
def get_in_segmentlistdict ( self , process_ids = None ) :
"""Return a segmentlistdict mapping instrument to in segment
list . If process _ ids is a sequence of process IDs , then
only rows with matching IDs are included otherwise all rows
are included .
Note : the result is not coalesced , each segmentlist... | seglists = segments . segmentlistdict ( )
for row in self :
ifos = row . instruments or ( None , )
if process_ids is None or row . process_id in process_ids :
seglists . extend ( dict ( ( ifo , segments . segmentlist ( [ row . in_segment ] ) ) for ifo in ifos ) )
return seglists |
def update ( self , d ) :
"""This function make update according provided target
and the last used input vector .
* * Args : * *
* ` d ` : target ( float or 1 - dimensional array ) .
Size depends on number of MLP outputs .
* * Returns : * *
* ` e ` : error used for update ( float or 1 - diemnsional arra... | # update output layer
e = d - self . y
error = np . copy ( e )
if self . outputs == 1 :
dw = self . mu * e * self . x
w = np . copy ( self . w ) [ 1 : ]
else :
dw = self . mu * np . outer ( e , self . x )
w = np . copy ( self . w ) [ : , 1 : ]
self . w += dw
# update hidden layers
for l in reversed ( se... |
def x_frame2D ( X , plot_limits = None , resolution = None ) :
"""Internal helper function for making plots , returns a set of input values to plot as well as lower and upper limits""" | assert X . shape [ 1 ] == 2 , "x_frame2D is defined for two-dimensional inputs"
if plot_limits is None :
xmin , xmax = X . min ( 0 ) , X . max ( 0 )
xmin , xmax = xmin - 0.2 * ( xmax - xmin ) , xmax + 0.2 * ( xmax - xmin )
elif len ( plot_limits ) == 2 :
xmin , xmax = plot_limits
else :
raise ValueError... |
def cublasDsymv ( handle , uplo , n , alpha , A , lda , x , incx , beta , y , incy ) :
"""Matrix - vector product for real symmetric matrix .""" | status = _libcublas . cublasDsymv_v2 ( handle , _CUBLAS_FILL_MODE [ uplo ] , n , ctypes . byref ( ctypes . c_double ( alpha ) ) , int ( A ) , lda , int ( x ) , incx , ctypes . byref ( ctypes . c_double ( beta ) ) , int ( y ) , incy )
cublasCheckStatus ( status ) |
def check_solver ( self , image_x , image_y , kwargs_lens ) :
"""returns the precision of the solver to match the image position
: param kwargs _ lens : full lens model ( including solved parameters )
: param image _ x : point source in image
: param image _ y : point source in image
: return : precision of... | source_x , source_y = self . _lensModel . ray_shooting ( image_x , image_y , kwargs_lens )
dist = np . sqrt ( ( source_x - source_x [ 0 ] ) ** 2 + ( source_y - source_y [ 0 ] ) ** 2 )
return dist |
def input_validation ( group_idx , a , size = None , order = 'C' , axis = None , ravel_group_idx = True , check_bounds = True ) :
"""Do some fairly extensive checking of group _ idx and a , trying to
give the user as much help as possible with what is wrong . Also ,
convert ndim - indexing to 1d indexing .""" | if not isinstance ( a , ( int , float , complex ) ) :
a = np . asanyarray ( a )
group_idx = np . asanyarray ( group_idx )
if not np . issubdtype ( group_idx . dtype , np . integer ) :
raise TypeError ( "group_idx must be of integer type" )
# This check works for multidimensional indexing as well
if check_bounds... |
def read ( self , file_or_filename ) :
"""Returns a case from a version 30 PSS / E raw file .
@ param file _ or _ filename : File name or file like object with PSS / E data
@ return : Case object""" | t0 = time . time ( )
self . init ( )
if isinstance ( file_or_filename , basestring ) :
fname = os . path . basename ( file_or_filename )
logger . info ( "Loading PSS/E Raw file [%s]." % fname )
file = None
try :
file = open ( file_or_filename , "rb" )
except :
logger . error ( "Error... |
def get_raw_index ( self , i ) :
"""Get index into base array ' s raw data , given the index into this
segment""" | if self . is_indexed :
return int ( self . order [ i ] )
if self . data . base is None :
return int ( i )
return int ( self . data_start - self . base_start + i ) |
def pack ( self , message_type , client_id , client_storage , args , kwargs ) :
"""Packs a message""" | return pickle . dumps ( ( message_type , client_id , client_storage , args , kwargs ) , protocol = 2 ) |
def feed ( self , data_len , feed_time = None ) :
'''Update the bandwidth meter .
Args :
data _ len ( int ) : The number of bytes transfered since the last
call to : func : ` feed ` .
feed _ time ( float ) : Current time .''' | self . _bytes_transferred += data_len
self . _collected_bytes_transferred += data_len
time_now = feed_time or time . time ( )
time_diff = time_now - self . _last_feed_time
if time_diff < self . _sample_min_time :
return
self . _last_feed_time = time . time ( )
if data_len == 0 and time_diff >= self . _stall_time :
... |
def create_repo ( self , repo_name = None , feed = None , envs = [ ] , checksum_type = "sha256" , query = '/repositories/' ) :
"""` repo _ name ` - Name of repository to create
` feed ` - Repo URL to feed from
` checksum _ type ` - Used for generating meta - data
Create repository in specified environments , ... | data = { 'display_name' : repo_name , 'notes' : { '_repo-type' : 'rpm-repo' , } }
juicer . utils . Log . log_debug ( "Create Repo: %s" , repo_name )
for env in envs :
if juicer . utils . repo_exists_p ( repo_name , self . connectors [ env ] , env ) :
juicer . utils . Log . log_info ( "repo `%s` already exis... |
def get_audits ( ) :
"""Get OS hardening access audits .
: returns : dictionary of audits""" | audits = [ ]
settings = utils . get_settings ( 'os' )
# Remove write permissions from $ PATH folders for all regular users .
# This prevents changing system - wide commands from normal users .
path_folders = { '/usr/local/sbin' , '/usr/local/bin' , '/usr/sbin' , '/usr/bin' , '/bin' }
extra_user_paths = settings [ 'envi... |
def get_branch_refs ( self , scope_path , project = None , include_deleted = None , include_links = None ) :
"""GetBranchRefs .
Get branch hierarchies below the specified scopePath
: param str scope _ path : Full path to the branch . Default : $ / Examples : $ / , $ / MyProject , $ / MyProject / SomeFolder .
... | route_values = { }
if project is not None :
route_values [ 'project' ] = self . _serialize . url ( 'project' , project , 'str' )
query_parameters = { }
if scope_path is not None :
query_parameters [ 'scopePath' ] = self . _serialize . query ( 'scope_path' , scope_path , 'str' )
if include_deleted is not None :
... |
def is_valid ( self ) :
"""Test if the matrix is positive definite Hermitian .
If the matrix decomposition is available , this test checks
if all eigenvalues are positive .
Otherwise , the test tries to calculate a Cholesky decomposition ,
which can be very time - consuming for large matrices . Sparse
mat... | # Lazy import to improve ` import odl ` time
import scipy . sparse
if scipy . sparse . isspmatrix ( self . matrix ) :
raise NotImplementedError ( 'validation not supported for sparse ' 'matrices' )
elif self . _eigval is not None :
return np . all ( np . greater ( self . _eigval , 0 ) )
else :
try :
... |
def is_app ( command , * app_names , ** kwargs ) :
"""Returns ` True ` if command is call to one of passed app names .""" | at_least = kwargs . pop ( 'at_least' , 0 )
if kwargs :
raise TypeError ( "got an unexpected keyword argument '{}'" . format ( kwargs . keys ( ) ) )
if len ( command . script_parts ) > at_least :
return command . script_parts [ 0 ] in app_names
return False |
def camel_to_snake_case ( camel_input ) :
'''Converts camelCase ( or CamelCase ) to snake _ case .
From https : / / codereview . stackexchange . com / questions / 185966 / functions - to - convert - camelcase - strings - to - snake - case
: param str camel _ input : The camelcase or CamelCase string to convert ... | res = camel_input [ 0 ] . lower ( )
for i , letter in enumerate ( camel_input [ 1 : ] , 1 ) :
if letter . isupper ( ) :
if camel_input [ i - 1 ] . islower ( ) or ( i != len ( camel_input ) - 1 and camel_input [ i + 1 ] . islower ( ) ) :
res += '_'
res += letter . lower ( )
return res |
def get_selected_tab ( self ) :
"""Returns the tab specific by the GET request parameter .
In the event that there is no GET request parameter , the value
of the query parameter is invalid , or the tab is not allowed / enabled ,
the return value of this function is None .""" | selected = self . request . GET . get ( self . param_name , None )
if selected :
try :
tab_group , tab_name = selected . split ( SEPARATOR )
except ValueError :
return None
if tab_group == self . get_id ( ) :
self . _selected = self . get_tab ( tab_name )
return self . _selected |
def view ( self , repo ) :
"""View repository information""" | status = "{0}disabled{1}" . format ( self . meta . color [ "RED" ] , self . meta . color [ "ENDC" ] )
self . form [ "Status:" ] = status
self . form [ "Default:" ] = "no"
if repo in self . meta . default_repositories :
self . form [ "Default:" ] = "yes"
if ( repo in self . meta . repositories and os . path . isfile... |
def register_frame_to_skip ( cls , file_name , function_name , line_number = None ) :
"""Registers a function name to skip when walking the stack .
The ABSLLogger sometimes skips method calls on the stack
to make the log messages meaningful in their appropriate context .
This method registers a function from ... | if line_number is not None :
cls . _frames_to_skip . add ( ( file_name , function_name , line_number ) )
else :
cls . _frames_to_skip . add ( ( file_name , function_name ) ) |
def StartingKey ( self , evt ) :
"""If the editor is enabled by pressing keys on the grid , this will be
called to let the editor do something about that first key if desired .""" | key = evt . GetKeyCode ( )
ch = None
if key in [ wx . WXK_NUMPAD0 , wx . WXK_NUMPAD1 , wx . WXK_NUMPAD2 , wx . WXK_NUMPAD3 , wx . WXK_NUMPAD4 , wx . WXK_NUMPAD5 , wx . WXK_NUMPAD6 , wx . WXK_NUMPAD7 , wx . WXK_NUMPAD8 , wx . WXK_NUMPAD9 ] :
ch = ch = chr ( ord ( '0' ) + key - wx . WXK_NUMPAD0 )
elif key < 256 and k... |
def get_cursor_position ( self ) :
"""Returns the terminal ( row , column ) of the cursor
0 - indexed , like blessings cursor positions""" | # TODO would this be cleaner as a parameter ?
in_stream = self . in_stream
query_cursor_position = u"\x1b[6n"
self . write ( query_cursor_position )
def retrying_read ( ) :
while True :
try :
c = in_stream . read ( 1 )
if c == '' :
raise ValueError ( "Stream should be... |
def _send ( self , messages ) :
"""A helper method that does the actual sending .""" | if len ( messages ) == 1 :
to_send = self . _build_message ( messages [ 0 ] )
if to_send is False : # The message was missing recipients .
# Bail .
return False
else :
pm_messages = list ( map ( self . _build_message , messages ) )
pm_messages = [ m for m in pm_messages if m ]
if len ( p... |
def elements ( self ) :
"""Return the identifier ' s elements as tuple .""" | offset = self . EXTRA_DIGITS
if offset :
return ( self . _id [ : offset ] , self . company_prefix , self . _reference , self . check_digit )
else :
return ( self . company_prefix , self . _reference , self . check_digit ) |
def build_report ( self , op_file , tpe = 'md' ) :
"""create a report showing all project details""" | if tpe == 'md' :
res = self . get_report_md ( )
elif tpe == 'rst' :
res = self . get_report_rst ( )
elif tpe == 'html' :
res = self . get_report_html ( )
else :
res = 'Unknown report type passed to project.build_report'
with open ( op_file , 'w' ) as f :
f . write ( res ) |
def get_timestats_str ( unixtime_list , newlines = 1 , full = True , isutc = True ) :
r"""Args :
unixtime _ list ( list ) :
newlines ( bool ) :
Returns :
str : timestat _ str
CommandLine :
python - m utool . util _ time - - test - get _ timestats _ str
Example :
> > > # ENABLE _ DOCTEST
> > > from... | import utool as ut
datetime_stats = get_timestats_dict ( unixtime_list , full = full , isutc = isutc )
timestat_str = ut . repr4 ( datetime_stats , newlines = newlines )
return timestat_str |
def margin_rate ( self ) :
"""[ float ] 合约最低保证金率 ( 期货专用 )""" | try :
return self . __dict__ [ "margin_rate" ]
except ( KeyError , ValueError ) :
raise AttributeError ( "Instrument(order_book_id={}) has no attribute 'margin_rate' " . format ( self . order_book_id ) ) |
def create_email ( filepaths , collection_name ) :
"""Create an email message object which implements the
email . message . Message interface and which has the files to be shared
uploaded to min . us and links placed in the message body .""" | gallery = minus . CreateGallery ( )
if collection_name is not None :
gallery . SaveGallery ( collection_name )
interface = TerminalInterface ( )
interface . new_section ( )
interface . message ( 'Uploading files to http://min.us/m%s...' % ( gallery . reader_id , ) )
item_map = { }
for path in filepaths :
interf... |
def sort ( self , key , by = None , external = None , offset = 0 , limit = None , order = None , alpha = False , store_as = None ) :
"""Returns or stores the elements contained in the list , set or sorted
set at key . By default , sorting is numeric and elements are compared by
their value interpreted as double... | if order and order not in [ b'ASC' , b'DESC' , 'ASC' , 'DESC' ] :
raise ValueError ( 'invalid sort order "{}"' . format ( order ) )
command = [ b'SORT' , key ]
if by :
command += [ b'BY' , by ]
if external and isinstance ( external , list ) :
for entry in external :
command += [ b'GET' , entry ]
eli... |
def save_index ( self , filename ) :
'''Save the current Layout ' s index to a . json file .
Args :
filename ( str ) : Filename to write to .
Note : At the moment , this won ' t serialize directory - specific config
files . This means reconstructed indexes will only work properly in
cases where there aren... | data = { }
for f in self . files . values ( ) :
entities = { v . entity . id : v . value for k , v in f . tags . items ( ) }
data [ f . path ] = { 'domains' : f . domains , 'entities' : entities }
with open ( filename , 'w' ) as outfile :
json . dump ( data , outfile ) |
def handler ( event , context ) : # pylint : disable = W0613
"""Historical security group event differ .
Listens to the Historical current table and determines if there are differences that need to be persisted in the
historical record .""" | # De - serialize the records :
records = deserialize_records ( event [ 'Records' ] )
for record in records :
process_dynamodb_differ_record ( record , CurrentVPCModel , DurableVPCModel ) |
def getPrefixDirectories ( self , engineRoot , delimiter = ' ' ) :
"""Returns the list of prefix directories for this library , joined using the specified delimiter""" | return delimiter . join ( self . resolveRoot ( self . prefixDirs , engineRoot ) ) |
def cli ( ctx , group_id , users = None ) :
"""Update the group ' s membership
Output :
dictionary of group information""" | return ctx . gi . groups . update_membership ( group_id , users = users ) |
def _open_tracing_interface ( self , connection_id , callback ) :
"""Enable the tracing interface for this IOTile device
Args :
connection _ id ( int ) : The unique identifier for the connection
callback ( callback ) : Callback to be called when this command finishes
callback ( conn _ id , adapter _ id , su... | try :
context = self . connections . get_context ( connection_id )
except ArgumentError :
callback ( connection_id , self . id , False , "Could not find connection information" )
return
self . _logger . info ( "Attempting to enable tracing" )
self . connections . begin_operation ( connection_id , 'open_inte... |
def baffle_thickness ( Dshell , L_unsupported , service = 'C' ) :
r'''Determines the thickness of baffles and support plates in TEMA HX
[1 ] _ . Applies to latitudinal baffles along the diameter of the HX , but
not longitudinal baffles parallel to the tubes .
Parameters
Dshell : float
Shell inner diameter... | if Dshell < 0.381 :
j = 0
elif 0.381 <= Dshell < 0.737 :
j = 1
elif 0.737 <= Dshell < 0.991 :
j = 2
elif 0.991 <= Dshell < 1.524 :
j = 3
else :
j = 4
if service == 'R' :
if L_unsupported <= 0.61 :
i = 0
elif 0.61 < L_unsupported <= 0.914 :
i = 1
elif 0.914 < L_unsupported... |
def select ( cls , * args , ** kwargs ) :
"""Support read slaves .""" | query = super ( Model , cls ) . select ( * args , ** kwargs )
query . database = cls . _get_read_database ( )
return query |
def subprocess_check_output ( * args , cwd = None , env = None , stderr = False ) :
"""Run a command and capture output
: param * args : List of command arguments
: param cwd : Current working directory
: param env : Command environment
: param stderr : Read on stderr
: returns : Command output""" | if stderr :
proc = yield from asyncio . create_subprocess_exec ( * args , stderr = asyncio . subprocess . PIPE , cwd = cwd , env = env )
output = yield from proc . stderr . read ( )
else :
proc = yield from asyncio . create_subprocess_exec ( * args , stdout = asyncio . subprocess . PIPE , cwd = cwd , env = ... |
def loadFile ( self , fileName : str = None ) :
"""Overload this method with applet specific code that can make
sense of the passed ` ` fileName ` ` argument . In many case this
will literally mean a file name , but could equally well be a
URL ( eg . ` ` QWebView ` ` based applets ) or any other resource
de... | msg = ( 'The <b>{}</b> applet has not implemented the ' '<b>LoadFile</b> method' )
self . qteLogger . info ( msg . format ( self . qteAppletSignature ( ) ) ) |
def on_event_pre ( self , e : Event ) -> None :
"""Set values set on browser before calling event listeners .""" | super ( ) . on_event_pre ( e )
ct_msg = e . init . get ( 'currentTarget' , dict ( ) )
if e . type in ( 'input' , 'change' ) : # Update user inputs
if self . type . lower ( ) == 'checkbox' :
self . _set_attribute ( 'checked' , ct_msg . get ( 'checked' ) )
elif self . type . lower ( ) == 'radio' :
... |
def execute_tool ( self , stream , interval ) :
"""Executes the stream ' s tool over the given time interval
: param stream : the stream reference
: param interval : the time interval
: return : None""" | if interval . end > self . up_to_timestamp :
raise ValueError ( 'The stream is not available after ' + str ( self . up_to_timestamp ) + ' and cannot be calculated' )
required_intervals = TimeIntervals ( [ interval ] ) - stream . calculated_intervals
if not required_intervals . is_empty :
for interval in require... |
def install_cmd ( argv ) :
'''Use Pythonz to download and build the specified Python version''' | installer = InstallCommand ( )
options , versions = installer . parser . parse_args ( argv )
if len ( versions ) != 1 :
installer . parser . print_help ( )
sys . exit ( 1 )
else :
try :
actual_installer = PythonInstaller . get_installer ( versions [ 0 ] , options )
return actual_installer . ... |
def parameter_blocks ( self ) :
'''Compute the size ( in 512B blocks ) of the parameter section .''' | bytes = 4. + sum ( g . binary_size ( ) for g in self . groups . values ( ) )
return int ( np . ceil ( bytes / 512 ) ) |
def write_toplevel ( self ) :
"""Traverse a template structure for module - level directives and
generate the start of module - level code .""" | inherit = [ ]
namespaces = { }
module_code = [ ]
self . compiler . pagetag = None
class FindTopLevel ( object ) :
def visitInheritTag ( s , node ) :
inherit . append ( node )
def visitNamespaceTag ( s , node ) :
namespaces [ node . name ] = node
def visitPageTag ( s , node ) :
self .... |
def from_image_to_file ( img_path , file_path ) :
"""Expects images created by from _ from _ file _ to _ image""" | img = Image . open ( img_path )
data = numpy . array ( img )
data = numpy . reshape ( data , len ( img . getdata ( ) ) * 3 )
to_remove = data [ len ( data ) - 1 ]
data = numpy . delete ( data , xrange ( len ( data ) - to_remove , len ( data ) ) )
data . tofile ( file_path ) |
def get_industry ( symbol ) :
'''Uses BeautifulSoup to scrape stock industry from Yahoo ! Finance website''' | url = 'http://finance.yahoo.com/q/pr?s=%s+Profile' % symbol
soup = BeautifulSoup ( urlopen ( url ) . read ( ) )
try :
industry = soup . find ( 'td' , text = 'Industry:' ) . find_next_sibling ( ) . string . encode ( 'utf-8' )
except :
industry = ''
return industry |
def get_result_figure ( result , show_title = False , title = None , show_inset = True , plot_fold_enrichment = False , width = 800 , height = 350 , font_size = 24 , margin = None , font_family = 'Computer Modern Roman, serif' , score_color = 'rgb(0,109,219)' , enrichment_color = 'rgb(219,109,0)' , cutoff_color = 'rgba... | assert isinstance ( result , mHGResult )
assert isinstance ( show_title , bool )
if title is not None :
assert isinstance ( title , ( str , _oldstr ) )
assert isinstance ( show_inset , bool )
assert isinstance ( plot_fold_enrichment , bool )
assert isinstance ( font_family , ( str , _oldstr ) )
assert isinstance ( ... |
def parse_args ( args ) :
"""Parse command line parameters
Args :
args ( [ str ] ) : Command line parameters as list of strings
Returns :
: obj : ` argparse . Namespace ` : command line parameters namespace""" | parser = argparse . ArgumentParser ( description = "Imports GramVaani data for Deep Speech" )
parser . add_argument ( "--version" , action = "version" , version = "GramVaaniImporter {ver}" . format ( ver = __version__ ) , )
parser . add_argument ( "-v" , "--verbose" , action = "store_const" , required = False , help = ... |
def postinit ( self , expr = None , globals = None , locals = None ) :
"""Do some setup after initialisation .
: param expr : The expression to be executed .
: type expr : NodeNG or None
: param globals : The globals dictionary to execute with .
: type globals : NodeNG or None
: param locals : The locals ... | self . expr = expr
self . globals = globals
self . locals = locals |
def isomap ( geom , n_components = 8 , eigen_solver = 'auto' , random_state = None , path_method = 'auto' , distance_matrix = None , graph_distance_matrix = None , centered_matrix = None , solver_kwds = None ) :
"""Parameters
geom : a Geometry object from megaman . geometry . geometry
n _ components : integer ,... | # Step 1 : use geometry to calculate the distance matrix
if ( ( distance_matrix is None ) and ( centered_matrix is None ) ) :
if geom . adjacency_matrix is None :
distance_matrix = geom . compute_adjacency_matrix ( )
else :
distance_matrix = geom . adjacency_matrix
# Step 2 : use graph _ shortes... |
def add_payload ( self , key , val , append = True ) :
"""Add a key value pair to payload for this request .
. . Note : : For ` ` _ search ` ` you can pass a search argument . ( e . g . _ search ? summary = 1.1.1.1 ) .
Args :
key ( string ) : The payload key
val ( string ) : The payload value
append ( boo... | if append :
self . _params . setdefault ( key , [ ] ) . append ( val )
else :
self . _params [ key ] = val |
def main ( ) :
"""register a function on pypi or gemfury
: return :""" | setup_main ( )
config = ConfigData ( clean = True )
try :
config . register ( )
finally :
config . clean_after_if_needed ( ) |
def apply_exclude ( self , high ) :
'''Read in the _ _ exclude _ _ list and remove all excluded objects from the
high data''' | if '__exclude__' not in high :
return high
ex_sls = set ( )
ex_id = set ( )
exclude = high . pop ( '__exclude__' )
for exc in exclude :
if isinstance ( exc , six . string_types ) : # The exclude statement is a string , assume it is an sls
ex_sls . add ( exc )
if isinstance ( exc , dict ) : # Explici... |
async def variant ( self , elem = None , elem_type = None , params = None , obj = None ) :
"""Loads / dumps variant type
: param elem :
: param elem _ type :
: param params :
: param obj :
: return :""" | elem_type = elem_type if elem_type else elem . __class__
if hasattr ( elem_type , 'kv_serialize' ) :
elem = elem_type ( ) if elem is None else elem
return await elem . kv_serialize ( self , elem = elem , elem_type = elem_type , params = params , obj = obj )
if self . writing :
return await self . dump_varia... |
def preprocess_notebook ( ntbk , cr ) :
"""Process notebook object ` ntbk ` in preparation for conversion to an
rst document . This processing replaces links to online docs with
corresponding sphinx cross - references within the local docs .
Parameter ` cr ` is a CrossReferenceLookup object .""" | # Iterate over cells in notebook
for n in range ( len ( ntbk [ 'cells' ] ) ) : # Only process cells of type ' markdown '
if ntbk [ 'cells' ] [ n ] [ 'cell_type' ] == 'markdown' : # Get text of markdown cell
txt = ntbk [ 'cells' ] [ n ] [ 'source' ]
# Replace links to online docs with sphinx cross - ... |
def next_permutation ( tab ) :
"""find the next permutation of tab in the lexicographical order
: param tab : table with n elements from an ordered set
: modifies : table to next permutation
: returns : False if permutation is already lexicographical maximal
: complexity : O ( n )""" | n = len ( tab )
pivot = None
# find pivot
for i in range ( n - 1 ) :
if tab [ i ] < tab [ i + 1 ] :
pivot = i
if pivot is None : # tab is already the last perm .
return False
for i in range ( pivot + 1 , n ) : # find the element to swap
if tab [ i ] > tab [ pivot ] :
swap = i
tab [ swap ] , ... |
def removeContinuousSet ( self ) :
"""Removes a continuous set from this repo""" | self . _openRepo ( )
dataset = self . _repo . getDatasetByName ( self . _args . datasetName )
continuousSet = dataset . getContinuousSetByName ( self . _args . continuousSetName )
def func ( ) :
self . _updateRepo ( self . _repo . removeContinuousSet , continuousSet )
self . _confirmDelete ( "ContinuousSet" , conti... |
def _notify_remove_at ( self , index , length = 1 ) :
"""Notify about an RemoveChange at a caertain index and length .""" | slice_ = self . _slice_at ( index , length )
self . _notify_remove ( slice_ ) |
def getall ( self , key ) :
"""A list of all the values stored under this key .
Returns an empty list if there are no values under this key .
> > > m = MultiMap ( [ ( ' a ' , 1 ) , ( ' b ' , 2 ) , ( ' b ' , 3 ) , ( ' c ' , 4 ) , ( ' d ' , 5 ) , ( ' c ' , 6 ) ] )
> > > m . getall ( ' a ' )
> > > m . getall (... | key = self . _conform_key ( key )
return [ self . _pairs [ i ] [ 1 ] for i in self . _key_ids [ key ] ] |
def write ( self , outname , dtype = 'default' , format = 'ENVI' , nodata = 'default' , compress_tif = False , overwrite = False ) :
"""write the raster object to a file .
Parameters
outname : str
the file to be written
dtype : str
the data type of the written file ;
data type notations of GDAL ( e . g ... | if os . path . isfile ( outname ) and not overwrite :
raise RuntimeError ( 'target file already exists' )
if format == 'GTiff' and not re . search ( r'\.tif[f]*$' , outname ) :
outname += '.tif'
dtype = Dtype ( self . dtype if dtype == 'default' else dtype ) . gdalint
nodata = self . nodata if nodata == 'defaul... |
def del_nic ( self , nic , sync = True ) :
"""delete nic from this OS instance
: param nic : the nic to be deleted from this OS instance
: param sync : If sync = True ( default ) synchronize with Ariane server . If sync = False ,
add the nic object on list to be removed on next save ( ) .
: return :""" | LOGGER . debug ( "OSInstance.del_nic" )
if not sync :
self . nic_2_rm . append ( nic )
else :
if nic . id is None :
nic . sync ( )
if self . id is not None and nic . id is not None :
params = { 'id' : self . id , 'nicID' : nic . id }
args = { 'http_operation' : 'GET' , 'operation_pat... |
def _capture ( self , args , kwargs ) :
'''Store the input to the captured function''' | self . called = self . called + 1
self . method_args . append ( args )
self . named_method_args . append ( kwargs )
self . never_called = False |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.