signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def e ( self , analytic = False , pot = None , ** kwargs ) :
"""NAME :
PURPOSE :
calculate the eccentricity
INPUT :
analytic - compute this analytically
pot - potential to use for analytical calculation
OUTPUT :
eccentricity
HISTORY :
2010-09-15 - Written - Bovy ( NYU )""" | if analytic :
self . _setupaA ( pot = pot , ** kwargs )
return float ( self . _aA . EccZmaxRperiRap ( self ) [ 0 ] )
if not hasattr ( self , 'orbit' ) :
raise AttributeError ( "Integrate the orbit first or use analytic=True for approximate eccentricity" )
if not hasattr ( self , 'rs' ) :
self . rs = nu ... |
def snmp_server_agtconfig_location ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
snmp_server = ET . SubElement ( config , "snmp-server" , xmlns = "urn:brocade.com:mgmt:brocade-snmp" )
agtconfig = ET . SubElement ( snmp_server , "agtconfig" )
location = ET . SubElement ( agtconfig , "location" )
location . text = kwargs . pop ( 'location' )
callback = kwargs . pop ... |
def publish ( self , topic , messages , key = None , timeout = 2 ) :
"""Publish messages to the topic .
: param str topic : Topic to produce messages to .
: param list ( str ) messages : List of message payloads .
: param str key : Message key .
: param float timeout : Maximum time to block in seconds .
:... | if not isinstance ( messages , list ) :
messages = [ messages ]
try :
for m in messages :
m = encodeutils . safe_encode ( m , incoming = 'utf-8' )
self . _producer . produce ( topic , m , key , callback = KafkaProducer . delivery_report )
self . _producer . poll ( 0 )
return self . _... |
def access ( cls , parent , placeholder ) :
"""Resolve the deferred field attribute access .
: param cls : the FieldAccessor class
: param parent : owning structure of the field being accessed
: param placeholder : FieldPlaceholder object which holds our info
: returns : FieldAccessor instance for that fiel... | try :
return parent . lookup_field_by_placeholder ( placeholder )
except KeyError :
field_placeholder , name = placeholder . args
# Find the field whose attribute is being accessed .
field = parent . lookup_field_by_placeholder ( field_placeholder )
# Instantiate the real FieldAccessor that wraps th... |
def get_factors_iterative2 ( n ) :
"""[ summary ]
analog as above
Arguments :
n { [ int ] } - - [ description ]
Returns :
[ list of lists ] - - [ all factors of n ]""" | ans , stack , x = [ ] , [ ] , 2
while True :
if x > n // x :
if not stack :
return ans
ans . append ( stack + [ n ] )
x = stack . pop ( )
n *= x
x += 1
elif n % x == 0 :
stack . append ( x )
n //= x
else :
x += 1 |
def compound_statements ( logical_line ) :
r"""Compound statements ( on the same line ) are generally discouraged .
While sometimes it ' s okay to put an if / for / while with a small body
on the same line , never do this for multi - clause statements .
Also avoid folding such long lines !
Always use a def ... | line = logical_line
last_char = len ( line ) - 1
found = line . find ( ':' )
prev_found = 0
counts = dict ( ( char , 0 ) for char in '{}[]()' )
while - 1 < found < last_char :
update_counts ( line [ prev_found : found ] , counts )
if ( ( counts [ '{' ] <= counts [ '}' ] and # { ' a ' : 1 } ( dict )
counts [... |
def _adjust_prt_flds ( self , kws_xlsx , desc2nts , shade_hdrgos ) :
"""Print user - requested fields or provided fields minus info fields .""" | # Use xlsx prt _ flds from the user , if provided
if "prt_flds" in kws_xlsx :
return kws_xlsx [ "prt_flds" ]
# If the user did not provide specific fields to print in an xlsx file :
dont_print = set ( [ 'hdr_idx' , 'is_hdrgo' , 'is_usrgo' ] )
# Are we printing GO group headers ?
# Build new list of xlsx print field... |
def from_celery ( cls , broker_dict ) :
"""Create a BrokerStats object from the dictionary returned by celery .
Args :
broker _ dict ( dict ) : The dictionary as returned by celery .
Returns :
BrokerStats : A fully initialized BrokerStats object .""" | return BrokerStats ( hostname = broker_dict [ 'hostname' ] , port = broker_dict [ 'port' ] , transport = broker_dict [ 'transport' ] , virtual_host = broker_dict [ 'virtual_host' ] ) |
def set_status ( self , status_code : int , reason : str = None ) -> None :
"""Sets the status code for our response .
: arg int status _ code : Response status code .
: arg str reason : Human - readable reason phrase describing the status
code . If ` ` None ` ` , it will be filled in from
` http . client .... | self . _status_code = status_code
if reason is not None :
self . _reason = escape . native_str ( reason )
else :
self . _reason = httputil . responses . get ( status_code , "Unknown" ) |
async def main ( ) :
"""Main code""" | # Create Client from endpoint string in Duniter format
client = Client ( BMAS_ENDPOINT )
# Get the node summary infos to test the connection
response = await client ( bma . node . summary )
print ( response )
# prompt hidden user entry
salt = getpass . getpass ( "Enter your passphrase (salt): " )
# prompt hidden user e... |
def make_dummy ( instance , relations = { } , datetime_default = dt . strptime ( '1901-01-01' , '%Y-%m-%d' ) , varchar_default = "" , integer_default = 0 , numeric_default = 0.0 , * args , ** kwargs ) :
"""Make an instance to look like an empty dummy .
Every field of the table is set with zeroes / empty strings .... | # init _ data knows how to put an init value depending on data type
init_data = { 'DATETIME' : datetime_default , 'VARCHAR' : varchar_default , 'INTEGER' : integer_default , 'NUMERIC(50, 10)' : numeric_default , 'TEXT' : varchar_default , }
# the type of the instance is the SQLAlchemy Table
table = type ( instance )
fo... |
def paintEvent ( self , event ) :
"""QWidget . paintEvent ( ) implementation""" | painter = QPainter ( self )
painter . fillRect ( event . rect ( ) , self . palette ( ) . color ( QPalette . Window ) )
painter . setPen ( Qt . black )
block = self . _qpart . firstVisibleBlock ( )
blockNumber = block . blockNumber ( )
top = int ( self . _qpart . blockBoundingGeometry ( block ) . translated ( self . _qp... |
def matern_function ( Xi , Xj , * args ) :
r"""Matern covariance function of arbitrary dimension , for use with : py : class : ` ArbitraryKernel ` .
The Matern kernel has the following hyperparameters , always referenced in
the order listed :
0 sigma prefactor
1 nu order of kernel
2 l1 length scale for th... | num_dim = len ( args ) - 2
nu = args [ 1 ]
if isinstance ( Xi , scipy . ndarray ) :
if isinstance ( Xi , scipy . matrix ) :
Xi = scipy . asarray ( Xi , dtype = float )
Xj = scipy . asarray ( Xj , dtype = float )
tau = scipy . asarray ( Xi - Xj , dtype = float )
l_mat = scipy . tile ( args [ ... |
def filer ( filelist , extension = 'fastq' , returndict = False ) :
"""Helper script that creates a set of the stain names created by stripping off parts of the filename .
Hopefully handles different naming conventions ( e . g . 2015 - SEQ - 001 _ S1 _ L001 _ R1_001 . fastq ( . gz ) ,
2015 - SEQ - 001 _ R1_001 ... | # Initialise the variables
fileset = set ( )
filedict = dict ( )
for seqfile in filelist : # Search for the conventional motifs present following strain names
# _ S \ d + _ L001 _ R \ d _ 001 . fastq ( . gz ) is a typical unprocessed Illumina fastq file
if re . search ( "_S\\d+_L001" , seqfile ) :
file_name... |
def add_nio ( self , nio , port_number ) :
"""Adds a NIO as new port on this hub .
: param nio : NIO instance to add
: param port _ number : port to allocate for the NIO""" | if port_number not in [ port [ "port_number" ] for port in self . _ports ] :
raise DynamipsError ( "Port {} doesn't exist" . format ( port_number ) )
if port_number in self . _mappings :
raise DynamipsError ( "Port {} isn't free" . format ( port_number ) )
yield from Bridge . add_nio ( self , nio )
log . info (... |
def sent2examples ( self , sent ) :
"""Convert ngrams into feature vectors .""" | # TODO ( rmyeid ) : use expanders .
words = [ w if w in self . embeddings else TaggerBase . UNK for w in sent ]
ngrams = TaggerBase . ngrams ( words , self . context , self . transfer )
fvs = [ ]
for word , ngram in zip ( sent , ngrams ) :
fv = np . array ( [ self . embeddings . get ( w , self . embeddings . zero_v... |
def _calculateEncodingKey ( comparator ) :
"""Gets the first key of all available encodings where the corresponding
value matches the comparator .
Args :
comparator ( string ) : A view name for an encoding .
Returns :
str : A key for a specific encoding used by python .""" | encodingName = None
for k , v in list ( _encodings . items ( ) ) :
if v == comparator :
encodingName = k
break
return encodingName |
def _resolve ( self , name ) :
"""Resolve the given store
: param name : The store to resolve
: type name : str
: rtype : Repository""" | config = self . _get_config ( name )
if not config :
raise RuntimeError ( 'Cache store [%s] is not defined.' % name )
if config [ 'driver' ] in self . _custom_creators :
repository = self . _call_custom_creator ( config )
else :
repository = getattr ( self , '_create_%s_driver' % config [ 'driver' ] ) ( con... |
def decrease_writes_in_units ( current_provisioning , units , min_provisioned_writes , log_tag ) :
"""Decrease the current _ provisioning with units units
: type current _ provisioning : int
: param current _ provisioning : The current provisioning
: type units : int
: param units : How many units should we... | updated_provisioning = int ( current_provisioning ) - int ( units )
min_provisioned_writes = __get_min_writes ( current_provisioning , min_provisioned_writes , log_tag )
if updated_provisioning < min_provisioned_writes :
logger . info ( '{0} - Reached provisioned writes min limit: {1:d}' . format ( log_tag , int ( ... |
def available_tcp_port ( reactor ) :
"""Returns a Deferred firing an available TCP port on localhost .
It does so by listening on port 0 ; then stopListening and fires the
assigned port number .""" | endpoint = serverFromString ( reactor , 'tcp:0:interface=127.0.0.1' )
port = yield endpoint . listen ( NoOpProtocolFactory ( ) )
address = port . getHost ( )
yield port . stopListening ( )
defer . returnValue ( address . port ) |
def set_menu ( self , ) :
"""Setup the menu that the menu _ tb button uses
: returns : None
: rtype : None
: raises : None""" | self . menu = QtGui . QMenu ( self )
actions = self . reftrack . get_additional_actions ( )
self . actions = [ ]
for a in actions :
if a . icon :
qaction = QtGui . QAction ( a . icon , a . name , self )
else :
qaction = QtGui . QAction ( a . name , self )
qaction . setCheckable ( a . checkab... |
def get_creator ( self , lang = None ) :
"""Get the DC Creator literal value
: param lang : Language to retrieve
: return : Creator string representation
: rtype : Literal""" | return self . metadata . get_single ( key = DC . creator , lang = lang ) |
def offers_to_pwl ( self , offers ) :
"""Updates the piece - wise linear total cost function using the given
offer blocks .
Based on off2case . m from MATPOWER by Ray Zimmerman , developed at PSERC
Cornell . See U { http : / / www . pserc . cornell . edu / matpower / } for more info .""" | assert not self . is_load
# Only apply offers associated with this generator .
g_offers = [ offer for offer in offers if offer . generator == self ]
# Fliter out zero quantity offers .
gt_zero = [ offr for offr in g_offers if round ( offr . quantity , 4 ) > 0.0 ]
# Ignore withheld offers .
valid = [ offer for offer in ... |
def get_stacker_env_file ( path , environment , region ) :
"""Determine Stacker environment file name .""" | for name in gen_stacker_env_files ( environment , region ) :
if os . path . isfile ( os . path . join ( path , name ) ) :
return name
return "%s-%s.env" % ( environment , region ) |
def handle ( self ) :
"""Executes the command .""" | if not self . confirm_to_proceed ( "<question>Are you sure you want to rollback the last migration?:</question> " ) :
return
database = self . option ( "database" )
repository = DatabaseMigrationRepository ( self . resolver , "migrations" )
migrator = Migrator ( repository , self . resolver )
self . _prepare_databa... |
def xpathNewValueTree ( self ) :
"""Create a new xmlXPathObjectPtr of type Value Tree ( XSLT )
and initialize it with the tree root @ val""" | ret = libxml2mod . xmlXPathNewValueTree ( self . _o )
if ret is None :
raise xpathError ( 'xmlXPathNewValueTree() failed' )
return xpathObjectRet ( ret ) |
def remove_null_entries ( input_dict ) :
"""Function to remove entries from a dictionary that have None as their value .
Example usage :
- remove _ null _ entries ( { ' c1 ' : ' Red ' , ' c2 ' : ' Green ' , ' c3 ' : None } ) outputs : { ' c1 ' : ' Red ' , ' c2 ' : ' Green ' }
- remove _ null _ entries ( { ' c... | return { key : val for ( key , val ) in input_dict . items ( ) if val is not None } |
def temporarily_enabled ( self ) :
"""Temporarily enable the cache ( useful for testing )""" | old_setting = self . options . enabled
self . enable ( )
try :
yield
finally :
self . options . enabled = old_setting |
def get_group_by_group_id ( self , group_id ) :
"""return group with given group _ id ( return None if doesn ' t exists )""" | group_id_base64 = base64 . b64encode ( group_id ) . decode ( 'ascii' )
groups = self . m [ "groups" ]
for g in groups :
if ( g [ "group_id" ] == group_id_base64 ) :
return g
return None |
def get_folders ( self , limit = None , * , query = None , order_by = None ) :
"""Returns a list of child folders
: param int limit : max no . of folders to get . Over 999 uses batch .
: param query : applies a OData filter to the request
: type query : Query or str
: param order _ by : orders the result se... | if self . root :
url = self . build_url ( self . _endpoints . get ( 'root_folders' ) )
else :
url = self . build_url ( self . _endpoints . get ( 'child_folders' ) . format ( id = self . folder_id ) )
params = { }
if limit :
params [ '$top' ] = limit
if order_by :
params [ '$orderby' ] = order_by
if quer... |
def bisine_wahwah_wave ( frequency ) :
"""Emit two sine waves with balance oscillating left and right .""" | # This is clearly intended to build on the bisine wave defined above ,
# so we can start by generating that .
waves_a = bisine_wave ( frequency )
# Then , by reversing axis 2 , we swap the stereo channels . By mixing
# this with ` waves _ a ` , we ' ll be able to create the desired effect .
waves_b = tf . reverse ( wav... |
def main ( active , upcoming , hiring , short , goto , platforms , time ) :
"""A CLI for active and upcoming programming challenges from various platforms""" | if not check_platforms ( platforms ) :
raise IncorrectParametersException ( 'Invlaid code for platform. Please check the platform ids' )
try :
if active :
active_challenges = active_contests ( platforms )
if goto :
webbrowser . open ( active_challenges [ goto - 1 ] [ "contest_url" ] ... |
def create ( self , auth , type , desc , defer = False ) :
"""Create something in Exosite .
Args :
auth : < cik >
type : What thing to create .
desc : Information about thing .""" | return self . _call ( 'create' , auth , [ type , desc ] , defer ) |
def set_color_scheme ( self , color_scheme , reset = True ) :
"""Set color scheme of the shell .""" | self . set_bracket_matcher_color_scheme ( color_scheme )
self . style_sheet , dark_color = create_qss_style ( color_scheme )
self . syntax_style = color_scheme
self . _style_sheet_changed ( )
self . _syntax_style_changed ( )
if reset :
self . reset ( clear = True )
if not dark_color :
self . silent_execute ( "%... |
def val ( self , piece , ref_color ) :
"""Finds value of ` ` Piece ` `
: type : piece : Piece
: type : ref _ color : Color
: rtype : int""" | if piece is None :
return 0
if ref_color == piece . color :
const = 1
else :
const = - 1
if isinstance ( piece , Pawn ) :
return self . PAWN_VALUE * const
elif isinstance ( piece , Queen ) :
return self . QUEEN_VALUE * const
elif isinstance ( piece , Bishop ) :
return self . BISHOP_VALUE * const... |
def getStreamURL ( self , ** params ) :
"""Returns a stream url that may be used by external applications such as VLC .
Parameters :
* * params ( dict ) : optional parameters to manipulate the playback when accessing
the stream . A few known parameters include : maxVideoBitrate , videoResolution
offset , co... | if self . TYPE not in ( 'movie' , 'episode' , 'track' ) :
raise Unsupported ( 'Fetching stream URL for %s is unsupported.' % self . TYPE )
mvb = params . get ( 'maxVideoBitrate' )
vr = params . get ( 'videoResolution' , '' )
params = { 'path' : self . key , 'offset' : params . get ( 'offset' , 0 ) , 'copyts' : para... |
def python_version ( i ) :
"""Input : { }
Output : {
version - sys . version
version _ info - sys . version _ info""" | import sys
o = i . get ( 'out' , '' )
v1 = sys . version
v2 = sys . version_info
if o == 'con' :
out ( v1 )
return { 'return' : 0 , 'version' : v1 , 'version_info' : v2 } |
def unescape_json_str ( st ) :
"""Unescape Monero json encoded string
/ monero / external / rapidjson / reader . h
: param st :
: return :""" | c = 0
ln = len ( st )
escape_chmap = { b'b' : b'\b' , b'f' : b'\f' , b'n' : b'\n' , b'r' : b'\r' , b't' : b'\t' , b'\\' : b'\\' , b'"' : b'\"' , b'/' : b'\/' }
ret = [ ]
def at ( i ) :
return st [ i : i + 1 ]
while c < ln :
if at ( c ) == b'\\' :
if at ( c + 1 ) == b'u' :
ret . append ( byte... |
def _unzip_file ( filepath ) :
"""Helper method to unzip a file to a temporary directory
: param string filepath : Absolute path to this file
: return string : Path to the temporary directory where it was unzipped""" | temp_dir = tempfile . mkdtemp ( )
if os . name == 'posix' :
os . chmod ( temp_dir , 0o755 )
LOG . info ( "Decompressing %s" , filepath )
unzip ( filepath , temp_dir )
# The directory that Python returns might have symlinks . The Docker File sharing settings will not resolve
# symlinks . Hence get the real path befo... |
def _update_dPrxy ( self ) :
"""Update ` dPrxy ` , accounting for dependence of ` phi ` on ` beta ` .""" | super ( ExpCM_empirical_phi , self ) . _update_dPrxy ( )
if 'beta' in self . freeparams :
self . dQxy_dbeta = scipy . zeros ( ( N_CODON , N_CODON ) , dtype = 'float' )
for w in range ( N_NT ) :
scipy . copyto ( self . dQxy_dbeta , self . dphi_dbeta [ w ] , where = CODON_NT_MUT [ w ] )
self . dQxy_db... |
def filter_completions ( self , completions ) :
'''Ensures collected completions are Unicode text , de - duplicates them , and excludes those specified by ` ` exclude ` ` .
Returns the filtered completions as an iterable .
This method is exposed for overriding in subclasses ; there is no need to use it directly... | # On Python 2 , we have to make sure all completions are unicode objects before we continue and output them .
# Otherwise , because python disobeys the system locale encoding and uses ascii as the default encoding , it will try
# to implicitly decode string objects using ascii , and fail .
if USING_PYTHON2 :
for i ... |
async def create_signing_key ( self , seed : str = None , metadata : dict = None ) -> KeyInfo :
"""Create a new signing key pair .
Raise WalletState if wallet is closed , ExtantRecord if verification key already exists .
: param seed : optional seed allowing deterministic key creation
: param metadata : optio... | LOGGER . debug ( 'Wallet.create_signing_key >>> seed: [SEED], metadata: %s' , metadata )
if not self . handle :
LOGGER . debug ( 'Wallet.create_signing_key <!< Wallet %s is closed' , self . name )
raise WalletState ( 'Wallet {} is closed' . format ( self . name ) )
try :
verkey = await crypto . create_key (... |
def linsolve ( self , sys , mtx , rhs , autoTranspose = False ) :
"""One - shot solution of system of linear equation . Reuses Numeric object
if possible .
Parameters
sys : constant
one of UMFPACK system description constants , like
UMFPACK _ A , UMFPACK _ At , see umfSys list and UMFPACK docs
mtx : sci... | if sys not in umfSys :
raise ValueError ( 'sys must be in' % umfSys )
if self . _numeric is None :
self . numeric ( mtx )
else :
if self . mtx is not mtx :
self . numeric ( mtx )
sol = self . solve ( sys , mtx , rhs , autoTranspose )
self . free_numeric ( )
return sol |
def cum_fit ( distr , xvals , alpha , thresh ) :
"""Integral of the fitted function above a given value ( reverse CDF )
The fitted function is normalized to 1 above threshold
Parameters
xvals : sequence of floats
Values where the function is to be evaluated
alpha : float
The fitted parameter
thresh : ... | xvals = numpy . array ( xvals )
cum_fit = cum_fndict [ distr ] ( xvals , alpha , thresh )
# set fitted values below threshold to 0
numpy . putmask ( cum_fit , xvals < thresh , 0. )
return cum_fit |
def get ( self , config : dict , access : str = None ) -> Wallet :
"""Instantiate and return VON anchor wallet object on given configuration , respecting wallet manager
default configuration values .
: param config : configuration data for both indy - sdk and VON anchor wallet :
- ' name ' or ' id ' : wallet ... | LOGGER . debug ( 'WalletManager.get >>> config %s, access %s' , config , access )
rv = Wallet ( self . _config2indy ( config ) , self . _config2von ( config , access ) )
LOGGER . debug ( 'WalletManager.get <<< %s' , rv )
return rv |
def stableSlugId ( ) :
"""Returns a closure which can be used to generate stable slugIds .
Stable slugIds can be used in a graph to specify task IDs in multiple
places without regenerating them , e . g . taskId , requires , etc .""" | _cache = { }
def closure ( name ) :
if name not in _cache :
_cache [ name ] = slugId ( )
return _cache [ name ]
return closure |
async def _port_poll ( is_old_bootloader , ports_before_switch = None ) :
"""Checks for the bootloader port""" | new_port = ''
while not new_port :
if is_old_bootloader :
new_port = await _port_on_mode_switch ( ports_before_switch )
else :
ports = await _discover_ports ( )
if ports :
discovered_ports = list ( filter ( lambda x : x . endswith ( 'bootloader' ) , ports ) )
if l... |
def get_branches ( aliases ) :
"""Get unique branch names from an alias dictionary .""" | ignore = [ 'pow' , 'log10' , 'sqrt' , 'max' ]
branches = [ ]
for k , v in aliases . items ( ) :
tokens = re . sub ( '[\(\)\+\*\/\,\=\<\>\&\!\-\|]' , ' ' , v ) . split ( )
for t in tokens :
if bool ( re . search ( r'^\d' , t ) ) or len ( t ) <= 3 :
continue
if bool ( re . search ( r'[... |
def drag ( self ) :
'''Drag the ui object to other point or ui object .
Usage :
d ( text = " Clock " ) . drag . to ( x = 100 , y = 100 ) # drag to point ( x , y )
d ( text = " Clock " ) . drag . to ( text = " Remove " ) # drag to another object''' | def to ( obj , * args , ** kwargs ) :
if len ( args ) >= 2 or "x" in kwargs or "y" in kwargs :
drag_to = lambda x , y , steps = 100 : self . jsonrpc . dragTo ( self . selector , x , y , steps )
else :
drag_to = lambda steps = 100 , ** kwargs : self . jsonrpc . dragTo ( self . selector , Selector... |
def check_dash_and_from ( text ) :
"""Check the text .""" | err = "dates_times.dates"
msg = u"When specifying a date range, write 'from X to Y'."
regex = "[fF]rom \d+[^ \t\n\r\f\va-zA-Z0-9_\.]\d+"
return existence_check ( text , [ regex ] , err , msg ) |
def write_dot ( g ) :
"""Replacement for pygraph . readwrite . dot . write , which is dog slow .
Note :
This isn ' t a general replacement . It will work for the graphs that
Rez generates , but there are no guarantees beyond that .
Args :
g ( ` pygraph . digraph ` ) : Input graph .
Returns :
str : Gra... | lines = [ "digraph g {" ]
def attrs_txt ( items ) :
if items :
txt = ", " . join ( ( '%s="%s"' % ( k , str ( v ) . strip ( '"' ) ) ) for k , v in items )
return '[' + txt + ']'
else :
return ''
for node in g . nodes ( ) :
atxt = attrs_txt ( g . node_attributes ( node ) )
txt = "%... |
def reward ( self , action ) :
"""Reward function for the task .
The dense reward has five components .
Reaching : in [ 0 , 1 ] , to encourage the arm to reach the cube
Grasping : in { 0 , 0.25 } , non - zero if arm is grasping the cube
Lifting : in { 0 , 1 } , non - zero if arm has lifted the cube
Aligni... | r_reach , r_lift , r_stack = self . staged_rewards ( )
if self . reward_shaping :
reward = max ( r_reach , r_lift , r_stack )
else :
reward = 1.0 if r_stack > 0 else 0.0
return reward |
def iscsi_iqn ( ) :
'''Return iSCSI IQN''' | grains = { }
grains [ 'iscsi_iqn' ] = False
if salt . utils . platform . is_linux ( ) :
grains [ 'iscsi_iqn' ] = _linux_iqn ( )
elif salt . utils . platform . is_windows ( ) :
grains [ 'iscsi_iqn' ] = _windows_iqn ( )
elif salt . utils . platform . is_aix ( ) :
grains [ 'iscsi_iqn' ] = _aix_iqn ( )
return g... |
def start_watcher ( self ) :
"""Start the watcher thread that tries to upload usage statistics .""" | if self . _watcher and self . _watcher . is_alive :
self . _watcher_enabled = True
else :
logger . debug ( 'Starting watcher.' )
self . _watcher = threading . Thread ( target = self . _watcher_thread , name = 'usage_tracker' )
self . _watcher . setDaemon ( True )
self . _watcher_enabled = True
s... |
def edit ( self , name , config , events = github . GithubObject . NotSet , add_events = github . GithubObject . NotSet , remove_events = github . GithubObject . NotSet , active = github . GithubObject . NotSet ) :
""": calls : ` PATCH / repos / : owner / : repo / hooks / : id < http : / / developer . github . com ... | assert isinstance ( name , ( str , unicode ) ) , name
assert isinstance ( config , dict ) , config
assert events is github . GithubObject . NotSet or all ( isinstance ( element , ( str , unicode ) ) for element in events ) , events
assert add_events is github . GithubObject . NotSet or all ( isinstance ( element , ( st... |
def update_entity ( self , entity , agent = None , metadata = None ) :
"""Updates the specified entity ' s values with the supplied parameters .""" | body = { }
if agent :
body [ "agent_id" ] = utils . get_id ( agent )
if metadata :
body [ "metadata" ] = metadata
if body :
uri = "/%s/%s" % ( self . uri_base , utils . get_id ( entity ) )
resp , body = self . api . method_put ( uri , body = body ) |
def nashcoef ( obsvalues , # type : Union [ numpy . ndarray , List [ Union [ float , int ] ] ]
simvalues , # type : Union [ numpy . ndarray , List [ Union [ float , int ] ] ]
log = False , # type : bool
expon = 2 # type : Union [ float , int , numpy . ScalarType ]
) : # type : ( . . . ) - > float
"""Calculate Nash ... | if len ( obsvalues ) != len ( simvalues ) :
raise ValueError ( "The size of observed and simulated values must be" " the same for NSE calculation!" )
if not isinstance ( obsvalues , numpy . ndarray ) :
obsvalues = numpy . array ( obsvalues )
if not isinstance ( simvalues , numpy . ndarray ) :
simvalues = nu... |
def _search ( self , category , name , recurse = True ) :
"""Search the scope stack for the name in the specified
category ( types / locals / vars ) .
: category : the category to search in ( locals / types / vars )
: name : name to search for
: returns : None if not found , the result of the found local / ... | idx = len ( self . _scope_stack ) - 1
curr = self . _curr_scope
for scope in reversed ( self . _scope_stack ) :
res = scope [ category ] . get ( name , None )
if res is not None :
return res
if recurse and self . _parent is not None :
return self . _parent . _search ( category , name , recurse )
ret... |
def _pod_inventory ( self ) :
"""Returns the list of all K8sPods found on this K8sNode .
: return : A list of K8sPods .""" | pods = [ ]
namespaces = K8sNamespace ( config = self . config , name = "yo" ) . list ( )
for ns in namespaces :
cfg = self . config
cfg . namespace = ns . name
p = K8sPod ( config = cfg , name = "yo" ) . list ( )
filtered = filter ( lambda x : x . node_name == self . name , p )
pods += filtered
retu... |
def add_asset ( self , asset_type , asset_name ) :
"""Add an asset to the adversary
Args :
asset _ type : ( str ) Either PHONE , HANDLER , or URL
asset _ name : ( str ) the value for the asset
Returns :""" | if not self . can_update ( ) :
self . _tcex . handle_error ( 910 , [ self . type ] )
if asset_type == 'PHONE' :
return self . tc_requests . add_adversary_phone_asset ( self . api_type , self . api_sub_type , self . unique_id , asset_name )
if asset_type == 'HANDLER' :
return self . tc_requests . add_adversa... |
def get_parent_repositories ( self , repository_id ) :
"""Gets the parents of the given repository .
arg : repository _ id ( osid . id . Id ) : the ` ` Id ` ` to query
return : ( osid . repository . RepositoryList ) - the parents of the
repository
raise : NotFound - ` ` repository _ id ` ` not found
raise... | # Implemented from template for
# osid . resource . BinHierarchySession . get _ parent _ bins
if self . _catalog_session is not None :
return self . _catalog_session . get_parent_catalogs ( catalog_id = repository_id )
return RepositoryLookupSession ( self . _proxy , self . _runtime ) . get_repositories_by_ids ( li... |
def kp_pan_zoom_set ( self , viewer , event , data_x , data_y , msg = True ) :
"""Sets the pan position under the cursor .""" | if self . canpan :
reg = 1
with viewer . suppress_redraw :
viewer . panset_xy ( data_x , data_y )
scale_x , scale_y = self . _save . get ( ( viewer , 'scale' , reg ) , ( 1.0 , 1.0 ) )
viewer . scale_to ( scale_x , scale_y )
return True |
def from_onnx ( self , graph ) :
"""Construct symbol from onnx graph .
The inputs from onnx graph is vague , only providing " 1 " , " 2 " . . .
For convenience , we rename the ` real ` input names to " input _ 0 " ,
" input _ 1 " . . . And renaming parameters to " param _ 0 " , " param _ 1 " . . .
Parameter... | # parse network inputs , aka parameters
for init_tensor in graph . initializer :
if not init_tensor . name . strip ( ) :
raise ValueError ( "Tensor's name is required." )
self . _params [ init_tensor . name ] = self . _parse_array ( init_tensor )
# converting GraphProto message
for i in graph . input :
... |
def GroupBy ( self : Iterable , f = None ) :
"""' self ' : [ 1 , 2 , 3 ] ,
' f ' : lambda x : x % 2,
' assert ' : lambda ret : ret [ 0 ] = = [ 2 ] and ret [ 1 ] = = [ 1 , 3]""" | if f and is_to_destruct ( f ) :
f = destruct_func ( f )
return _group_by ( self , f ) |
def from_fits ( cls , filename ) :
"""Loads a MOC from a FITS file .
The specified FITS file must store the MOC ( i . e . the list of HEALPix cells it contains ) in a binary HDU table .
Parameters
filename : str
The path to the FITS file .
Returns
result : ` ~ mocpy . moc . MOC ` or ` ~ mocpy . tmoc . T... | table = Table . read ( filename )
intervals = np . vstack ( ( table [ 'UNIQ' ] , table [ 'UNIQ' ] + 1 ) ) . T
nuniq_interval_set = IntervalSet ( intervals )
interval_set = IntervalSet . from_nuniq_interval_set ( nuniq_interval_set )
return cls ( interval_set ) |
def shard_query_generator ( self , query ) :
'''A generator that queries each shard in sequence .''' | shard_query = query . copy ( )
for shard in self . _stores : # yield all items matching within this shard
cursor = shard . query ( shard_query )
for item in cursor :
yield item
# update query with results of first query
shard_query . offset = max ( shard_query . offset - cursor . skipped , 0 )
... |
def get_engine ( self , app = None , bind = None ) :
"""Returns a specific engine .""" | app = self . get_app ( app )
state = get_state ( app )
with self . _engine_lock :
connector = state . connectors . get ( bind )
if connector is None :
connector = self . make_connector ( app , bind )
state . connectors [ bind ] = connector
return connector . get_engine ( ) |
def real_time_statistics ( self ) :
"""Access the real _ time _ statistics
: returns : twilio . rest . taskrouter . v1 . workspace . task _ queue . task _ queue _ real _ time _ statistics . TaskQueueRealTimeStatisticsList
: rtype : twilio . rest . taskrouter . v1 . workspace . task _ queue . task _ queue _ real... | if self . _real_time_statistics is None :
self . _real_time_statistics = TaskQueueRealTimeStatisticsList ( self . _version , workspace_sid = self . _solution [ 'workspace_sid' ] , task_queue_sid = self . _solution [ 'sid' ] , )
return self . _real_time_statistics |
def set_custom ( self , key , value = None ) :
"""Set a custom value . C { key } might have the form " key = value " when value is C { None } .""" | # Split combined key / value
if value is None :
try :
key , value = key . split ( '=' , 1 )
except ( ValueError , TypeError ) as exc :
raise error . UserError ( "Bad custom field assignment %r, probably missing a '=' (%s)" % ( key , exc ) )
# Check identifier rules
if not key :
raise error .... |
def images_grouped_by_type ( self ) :
""": return : A generator yielding 2 - tuples of ( type , [ creators ] ) where
adjacent creators who share the same role are grouped together .""" | type = - 1
images = [ ]
for wc in self :
if wc . type != type :
if images :
yield ( type , images )
role = wc . role
creators = [ ]
images . append ( wc . image )
if images :
yield ( type , images ) |
def RecurseKey ( recur_item , depth = 15 , key_path = '' ) :
"""Flattens nested dictionaries and lists by yielding it ' s values .
The hierarchy of a plist file is a series of nested dictionaries and lists .
This is a helper function helps plugins navigate the structure without
having to reimplement their own... | if depth < 1 :
logger . debug ( 'Recursion limit hit for key: {0:s}' . format ( key_path ) )
return
if isinstance ( recur_item , ( list , tuple ) ) :
for recur in recur_item :
for key in RecurseKey ( recur , depth = depth , key_path = key_path ) :
yield key
return
if not hasattr ( re... |
def write_model_to_file ( self , mdl , fn ) :
"""Write a YANG model that was extracted from a source identifier
( URL or source . txt file ) to a . yang destination file
: param mdl : YANG model , as a list of lines
: param fn : Name of the YANG model file
: return :""" | # Write the model to file
output = '' . join ( self . post_process_model ( mdl , self . add_line_refs ) )
if fn :
fqfn = self . dst_dir + '/' + fn
if os . path . isfile ( fqfn ) :
self . error ( "File '%s' exists" % fqfn )
return
with open ( fqfn , 'w' ) as of :
of . write ( output )... |
def process_request ( self , request ) :
"""Reads url name , args , kwargs from GET parameters , reverses the url and resolves view function
Returns the result of resolved view function , called with provided args and kwargs
Since the view function is called directly , it isn ' t ran through middlewares , so th... | if request . path == self . ANGULAR_REVERSE :
url_name = request . GET . get ( 'djng_url_name' )
url_args = request . GET . getlist ( 'djng_url_args' , [ ] )
url_kwargs = { }
# Remove falsy values ( empty strings )
url_args = filter ( lambda x : x , url_args )
# Read kwargs
for param in requ... |
def upstart ( state , host , name , running = True , restarted = False , reloaded = False , command = None , enabled = None , ) :
'''Manage the state of upstart managed services .
+ name : name of the service to manage
+ running : whether the service should be running
+ restarted : whether the service should ... | yield _handle_service_control ( name , host . fact . upstart_status , 'initctl {1} {0}' , running , restarted , reloaded , command , )
# Upstart jobs are setup w / runlevels etc in their config files , so here we just check
# there ' s no override file .
if enabled is True :
yield files . file ( state , host , '/et... |
def _write_cache_to_file ( self ) :
"""Write the contents of the cache to a file on disk .""" | with ( open ( self . _cache_file_name , 'w' ) ) as fp :
fp . write ( simplejson . dumps ( self . _cache ) ) |
def _update_advanced_peer_ack_point ( self ) :
"""Try to advance " Advanced . Peer . Ack . Point " according to RFC 3758.""" | if uint32_gt ( self . _last_sacked_tsn , self . _advanced_peer_ack_tsn ) :
self . _advanced_peer_ack_tsn = self . _last_sacked_tsn
done = 0
streams = { }
while self . _sent_queue and self . _sent_queue [ 0 ] . _abandoned :
chunk = self . _sent_queue . popleft ( )
self . _advanced_peer_ack_tsn = chunk . tsn
... |
async def update_notifications ( self , on_match_open : bool = None , on_tournament_end : bool = None ) :
"""update participants notifications for this tournament
| methcoro |
Args :
on _ match _ open : Email registered Challonge participants when matches open up for them
on _ tournament _ end : Email regis... | params = { }
if on_match_open is not None :
params [ 'notify_users_when_matches_open' ] = on_match_open
if on_tournament_end is not None :
params [ 'notify_users_when_the_tournament_ends' ] = on_tournament_end
assert_or_raise ( len ( params ) > 0 , ValueError , 'At least one of the notifications must be given' ... |
def space ( self , newlines = 1 ) :
"""Creates a vertical space of newlines
Args :
newlines ( int ) : number of empty lines
Returns :
self for chaining""" | space = Space ( )
for line in range ( newlines ) :
space . add_line ( '\n' )
self . _container . structure . insert ( self . _idx , space )
self . _idx += 1
return self |
def get_package_format_names ( predicate = None ) :
"""Get names for available package formats .""" | return [ k for k , v in six . iteritems ( get_package_formats ( ) ) if not predicate or predicate ( k , v ) ] |
def format_sql ( self ) :
"""Builds the sql in a format that is easy for humans to read and debug
: return : The formatted sql for this query
: rtype : str""" | # TODO : finish adding the other parts of the sql generation
sql = ''
# build SELECT
select_segment = self . build_select_fields ( )
select_segment = select_segment . replace ( 'SELECT ' , '' , 1 )
fields = [ field . strip ( ) for field in select_segment . split ( ',' ) ]
sql += 'SELECT\n\t{0}\n' . format ( ',\n\t' . j... |
def buy_close_order_quantity ( self ) :
"""[ int ] 买方向挂单量""" | return sum ( order . unfilled_quantity for order in self . open_orders if order . side == SIDE . BUY and order . position_effect in [ POSITION_EFFECT . CLOSE , POSITION_EFFECT . CLOSE_TODAY ] ) |
def get_input_score_end_range_metadata ( self ) :
"""Gets the metadata for the input score start range .
return : ( osid . Metadata ) - metadata for the input score start
range
* compliance : mandatory - - This method must be implemented . *""" | # Implemented from template for osid . resource . ResourceForm . get _ group _ metadata _ template
metadata = dict ( self . _mdata [ 'input_score_end_range' ] )
metadata . update ( { 'existing_decimal_values' : self . _my_map [ 'inputScoreEndRange' ] } )
return Metadata ( ** metadata ) |
def to_deeper_graph ( graph ) :
'''deeper graph''' | weighted_layer_ids = graph . deep_layer_ids ( )
if len ( weighted_layer_ids ) >= Constant . MAX_LAYERS :
return None
deeper_layer_ids = sample ( weighted_layer_ids , 1 )
for layer_id in deeper_layer_ids :
layer = graph . layer_list [ layer_id ]
new_layer = create_new_layer ( layer , graph . n_dim )
grap... |
def command ( name = None , cls = None , ** attrs ) :
"""Commands are the basic building block of command line interfaces in
Click . A basic command handles command line parsing and might dispatch
more parsing to commands nested below it .
: param name : the name of the command to use unless a group overrides... | return click . command ( name = name , cls = cls or Command , ** attrs ) |
def draw_quadmesh ( data , obj ) :
"""Returns the PGFPlots code for an graphics environment holding a
rendering of the object .""" | content = [ ]
# Generate file name for current object
filename , rel_filepath = files . new_filename ( data , "img" , ".png" )
# Get the dpi for rendering and store the original dpi of the figure
dpi = data [ "dpi" ]
fig_dpi = obj . figure . get_dpi ( )
obj . figure . set_dpi ( dpi )
# Render the object and save as png... |
def group_dashboard ( request , group_slug ) :
"""Dashboard for managing a TenantGroup .""" | groups = get_user_groups ( request . user )
group = get_object_or_404 ( groups , slug = group_slug )
tenants = get_user_tenants ( request . user , group )
can_edit_group = request . user . has_perm ( 'multitenancy.change_tenantgroup' , group )
count = len ( tenants )
if count == 1 : # Redirect to the detail page for th... |
def extract_words ( lines ) :
"""Extract from the given iterable of lines the list of words .
: param lines : an iterable of lines ;
: return : a generator of words of lines .""" | for line in lines :
for word in re . findall ( r"\w+" , line ) :
yield word |
def get_user_by_name ( uname , ** kwargs ) :
"""Get a user by username""" | try :
user_i = db . DBSession . query ( User ) . filter ( User . username == uname ) . one ( )
return user_i
except NoResultFound :
return None |
def vn_release ( call = None , kwargs = None ) :
'''Releases a virtual network lease that was previously on hold .
. . versionadded : : 2016.3.0
vn _ id
The ID of the virtual network from which to release the lease . Can be
used instead of ` ` vn _ name ` ` .
vn _ name
The name of the virtual network fr... | if call != 'function' :
raise SaltCloudSystemExit ( 'The vn_reserve function must be called with -f or --function.' )
if kwargs is None :
kwargs = { }
vn_id = kwargs . get ( 'vn_id' , None )
vn_name = kwargs . get ( 'vn_name' , None )
path = kwargs . get ( 'path' , None )
data = kwargs . get ( 'data' , None )
i... |
def _print ( self , msg , color = None , arrow = False , indent = None ) :
"""Print the msg with the color provided .""" | if color :
msg = colored ( msg , color )
if arrow :
msg = colored ( '===> ' , 'blue' ) + msg
if indent :
msg = ( ' ' * indent ) + msg
print ( msg )
return msg |
def setup_arrow_buttons ( self ) :
"""Setup the up and down arrow buttons that are placed at the top and
bottom of the scrollarea .""" | # Get the height of the up / down arrow of the default vertical
# scrollbar :
vsb = self . scrollarea . verticalScrollBar ( )
style = vsb . style ( )
opt = QStyleOptionSlider ( )
vsb . initStyleOption ( opt )
vsb_up_arrow = style . subControlRect ( QStyle . CC_ScrollBar , opt , QStyle . SC_ScrollBarAddLine , self )
# S... |
def copy ( self , keys , source , sample_only_filter = None , sample_size = None , done_copy = None ) :
""": param keys : THE KEYS TO LOAD FROM source
: param source : THE SOURCE ( USUALLY S3 BUCKET )
: param sample _ only _ filter : SOME FILTER , IN CASE YOU DO NOT WANT TO SEND EVERYTHING
: param sample _ si... | num_keys = 0
queue = None
pending = [ ]
# FOR WHEN WE DO NOT HAVE QUEUE YET
for key in keys :
timer = Timer ( "Process {{key}}" , param = { "key" : key } , silent = not DEBUG )
try :
with timer :
for rownum , line in enumerate ( source . read_lines ( strip_extension ( key ) ) ) :
... |
def weighted_choice ( self , probabilities , key ) :
"""Makes a weighted choice between several options .
Probabilities is a list of 2 - tuples , ( probability , option ) . The
probabilties don ' t need to add up to anything , they are automatically
scaled .""" | total = sum ( x [ 0 ] for x in probabilities )
choice = total * self . _random ( key )
for probability , option in probabilities :
choice -= probability
if choice <= 0 :
return option |
def get_mean_and_stddevs ( self , sites , rup , dists , imt , stddev_types ) :
"""See : meth : ` superclass method
< . base . GroundShakingIntensityModel . get _ mean _ and _ stddevs > `
for spec of input and result values .
: raises ValueError :
if imt is instance of : class : ` openquake . hazardlib . imt... | assert all ( stddev_type in self . DEFINED_FOR_STANDARD_DEVIATION_TYPES for stddev_type in stddev_types )
if imt not in self . IMTS_TABLES :
raise ValueError ( 'IMT %s not supported in FrankelEtAl1996NSHMP. ' % repr ( imt ) + 'FrankelEtAl1996NSHMP does not allow interpolation for ' + 'unsupported periods.' )
mean =... |
def facet ( table , key ) :
"""Return a dictionary mapping field values to tables . E . g . : :
> > > import petl as etl
> > > table1 = [ [ ' foo ' , ' bar ' , ' baz ' ] ,
. . . [ ' a ' , 4 , 9.3 ] ,
. . . [ ' a ' , 2 , 88.2 ] ,
. . . [ ' b ' , 1 , 23.3 ] ,
. . . [ ' c ' , 8 , 42.0 ] ,
. . . [ ' d ' ,... | fct = dict ( )
for v in set ( values ( table , key ) ) :
fct [ v ] = selecteq ( table , key , v )
return fct |
def parse_memory_value ( s ) :
"""Parse a string that contains a number of bytes , optionally with a unit like MB .
@ return the number of bytes encoded by the string""" | number , unit = split_number_and_unit ( s )
if not unit or unit == 'B' :
return number
elif unit == 'kB' :
return number * _BYTE_FACTOR
elif unit == 'MB' :
return number * _BYTE_FACTOR * _BYTE_FACTOR
elif unit == 'GB' :
return number * _BYTE_FACTOR * _BYTE_FACTOR * _BYTE_FACTOR
elif unit == 'TB' :
r... |
def switchTo ( self , app ) :
"""Use the given L { ITerminalServerFactory } to create a new
L { ITerminalProtocol } and connect it to C { self . terminal } ( such that it
cannot actually disconnect , but can do most anything else ) . Control of
the terminal is delegated to it until it gives up that control by... | viewer = _AuthenticatedShellViewer ( list ( getAccountNames ( self . _store ) ) )
self . _protocol = app . buildTerminalProtocol ( viewer )
self . _protocol . makeConnection ( _ReturnToMenuWrapper ( self , self . terminal ) ) |
def get_organization_guid ( self ) :
"""Returns the GUID for the organization currently targeted .""" | if 'PREDIX_ORGANIZATION_GUID' in os . environ :
return os . environ [ 'PREDIX_ORGANIZATION_GUID' ]
else :
info = self . _get_organization_info ( )
for key in ( 'Guid' , 'GUID' ) :
if key in info . keys ( ) :
return info [ key ]
raise ValueError ( 'Unable to determine cf organization ... |
def from_sec ( class_ , sec ) :
"""Create a key from an sec bytestream ( which is an encoding of a public pair ) .""" | public_pair = sec_to_public_pair ( sec , class_ . _generator )
return class_ ( public_pair = public_pair , is_compressed = is_sec_compressed ( sec ) ) |
def analysis_summary_report ( feature , parent ) :
"""Retrieve an HTML table report of current selected analysis .""" | _ = feature , parent
# NOQA
project_context_scope = QgsExpressionContextUtils . projectScope ( QgsProject . instance ( ) )
key = provenance_layer_analysis_impacted [ 'provenance_key' ]
if not project_context_scope . hasVariable ( key ) :
return None
analysis_dir = dirname ( project_context_scope . variable ( key ) ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.