signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def _add_reference ( self , obj , ident = 0 ) :
"""Adds a read reference to the marshaler storage
: param obj : Reference to add
: param ident : Log indentation level""" | log_debug ( "## New reference handle 0x{0:X}: {1} -> {2}" . format ( len ( self . references ) + self . BASE_REFERENCE_IDX , type ( obj ) . __name__ , repr ( obj ) , ) , ident , )
self . references . append ( obj ) |
def get_activity_lookup_session ( self , proxy ) :
"""Gets the ` ` OsidSession ` ` associated with the activity lookup service .
arg : proxy ( osid . proxy . Proxy ) : a proxy
return : ( osid . learning . ActivityLookupSession ) - an
` ` ActivityLookupSession ` `
raise : NullArgument - ` ` proxy ` ` is ` ` ... | if not self . supports_activity_lookup ( ) :
raise errors . Unimplemented ( )
# pylint : disable = no - member
return sessions . ActivityLookupSession ( proxy = proxy , runtime = self . _runtime ) |
def _evaluate ( self , * args , ** kwargs ) :
"""NAME :
_ _ call _ _ ( _ evaluate )
PURPOSE :
evaluate the actions ( jr , lz , jz )
INPUT :
Either :
a ) R , vR , vT , z , vz [ , phi ] :
1 ) floats : phase - space value for single object ( phi is optional ) ( each can be a Quantity )
2 ) numpy . ndar... | delta = kwargs . pop ( 'delta' , self . _delta )
order = kwargs . get ( 'order' , self . _order )
if ( ( self . _c and not ( 'c' in kwargs and not kwargs [ 'c' ] ) ) or ( ext_loaded and ( ( 'c' in kwargs and kwargs [ 'c' ] ) ) ) ) and _check_c ( self . _pot ) :
if len ( args ) == 5 : # R , vR . vT , z , vz
... |
def _pick_level ( cls , btc_amount ) :
"""Choose between small , medium , large , . . . depending on the
amount specified .""" | for size , level in cls . TICKER_LEVEL :
if btc_amount < size :
return level
return cls . TICKER_LEVEL [ - 1 ] [ 1 ] |
def mktk03 ( terms , seed , G2 , G3 ) :
"""generates a list of gauss coefficients drawn from the TK03 distribution""" | # random . seed ( n )
p = 0
n = seed
gh = [ ]
g10 , sfact , afact = - 18e3 , 3.8 , 2.4
g20 = G2 * g10
g30 = G3 * g10
alpha = g10 / afact
s1 = s_l ( 1 , alpha )
s10 = sfact * s1
gnew = random . normal ( g10 , s10 )
if p == 1 :
print ( 1 , 0 , gnew , 0 )
gh . append ( gnew )
gh . append ( random . normal ( 0 , s1 ) )... |
def wait ( self , timeout = None ) :
"""An implementation of the wait method which doesn ' t involve
polling but instead utilizes a " real " synchronization
scheme .""" | import threading
if self . _state != self . PENDING :
return
e = threading . Event ( )
self . addCallback ( lambda v : e . set ( ) )
self . addErrback ( lambda r : e . set ( ) )
e . wait ( timeout ) |
def _run_python ( work_bam_a , work_bam_b , out_dir , aligner , prefix , items ) :
"""Run python version of disambiguation""" | Args = collections . namedtuple ( "Args" , "A B output_dir intermediate_dir " "no_sort prefix aligner" )
args = Args ( work_bam_a , work_bam_b , out_dir , out_dir , True , "" , aligner )
disambiguate_main ( args ) |
def loadScopeGroupbyName ( self , name , service_group_id , callback = None , errback = None ) :
"""Load an existing Scope Group by name and service group id into a high level Scope Group object
: param str name : Name of an existing Scope Group
: param int service _ group _ id : id of the service group the Sco... | import ns1 . ipam
scope_group = ns1 . ipam . Scopegroup ( self . config , name = name , service_group_id = service_group_id )
return scope_group . load ( callback = callback , errback = errback ) |
def _params_extend ( params , _ignore_name = False , ** kwargs ) :
'''Extends the params dictionary by values from keyword arguments .
. . versionadded : : 2016.3.0
: param params : Dictionary with parameters for zabbix API .
: param _ ignore _ name : Salt State module is passing first line as ' name ' parame... | # extend params value by optional zabbix API parameters
for key in kwargs :
if not key . startswith ( '_' ) :
params . setdefault ( key , kwargs [ key ] )
# ignore name parameter passed from Salt state module , use firstname or visible _ name instead
if _ignore_name :
params . pop ( 'name' , None )
... |
def alocar ( self , nome , id_tipo_rede , id_ambiente , descricao , id_ambiente_vip = None , vrf = None ) :
"""Inserts a new VLAN .
: param nome : Name of Vlan . String with a maximum of 50 characters .
: param id _ tipo _ rede : Identifier of the Network Type . Integer value and greater than zero .
: param i... | vlan_map = dict ( )
vlan_map [ 'nome' ] = nome
vlan_map [ 'id_tipo_rede' ] = id_tipo_rede
vlan_map [ 'id_ambiente' ] = id_ambiente
vlan_map [ 'descricao' ] = descricao
vlan_map [ 'id_ambiente_vip' ] = id_ambiente_vip
vlan_map [ 'vrf' ] = vrf
code , xml = self . submit ( { 'vlan' : vlan_map } , 'POST' , 'vlan/' )
return... |
def update ( self , title , key ) :
"""Update this key .
: param str title : ( required ) , title of the key
: param str key : ( required ) , text of the key file
: returns : bool""" | json = None
if title and key :
data = { 'title' : title , 'key' : key }
json = self . _json ( self . _patch ( self . _api , data = dumps ( data ) ) , 200 )
if json :
self . _update_ ( json )
return True
return False |
def Vdiff ( D1 , D2 ) :
"""finds the vector difference between two directions D1 , D2""" | A = dir2cart ( [ D1 [ 0 ] , D1 [ 1 ] , 1. ] )
B = dir2cart ( [ D2 [ 0 ] , D2 [ 1 ] , 1. ] )
C = [ ]
for i in range ( 3 ) :
C . append ( A [ i ] - B [ i ] )
return cart2dir ( C ) |
def copy ( self ) :
"""Deeply copies everything in the query object except the connection object is shared""" | connection = self . connection
del self . connection
copied_query = deepcopy ( self )
copied_query . connection = connection
self . connection = connection
return copied_query |
def to_pb ( self ) :
"""Converts the column family to a protobuf .
: rtype : : class : ` . table _ v2 _ pb2 . ColumnFamily `
: returns : The converted current object .""" | if self . gc_rule is None :
return table_v2_pb2 . ColumnFamily ( )
else :
return table_v2_pb2 . ColumnFamily ( gc_rule = self . gc_rule . to_pb ( ) ) |
def get_possible_importers ( file_uris , current_doc = None ) :
"""Return all the importer objects that can handle the specified files .
Possible imports may vary depending on the currently active document""" | importers = [ ]
for importer in IMPORTERS :
if importer . can_import ( file_uris , current_doc ) :
importers . append ( importer )
return importers |
def run_with_reloader ( main_func , extra_files = None , interval = 1 ) :
"""Run the given function in an independent python interpreter .""" | import signal
signal . signal ( signal . SIGTERM , lambda * args : sys . exit ( 0 ) )
if os . environ . get ( 'WERKZEUG_RUN_MAIN' ) == 'true' :
thread . start_new_thread ( main_func , ( ) )
try :
reloader_loop ( extra_files , interval )
except KeyboardInterrupt :
return
try :
sys . exit ... |
def to_latlon ( array , domain , axis = 'lon' ) :
"""Broadcasts a 1D axis dependent array across another axis .
: param array input _ array : the 1D array used for broadcasting
: param domain : the domain associated with that
array
: param axis : the axis that the input array will
be broadcasted across
... | # if array is latitude dependent ( has the same shape as lat )
axis , array , depth = np . meshgrid ( domain . axes [ axis ] . points , array , domain . axes [ 'depth' ] . points )
if axis == 'lat' : # if array is longitude dependent ( has the same shape as lon )
np . swapaxes ( array , 1 , 0 )
return Field ( array... |
def _map_agent_mod ( self , agent , mod_condition ) :
"""Map a single modification condition on an agent .
Parameters
agent : : py : class : ` indra . statements . Agent `
Agent to check for invalid modification sites .
mod _ condition : : py : class : ` indra . statements . ModCondition `
Modification to... | # Get the UniProt ID of the agent , if not found , return
up_id = _get_uniprot_id ( agent )
if not up_id :
logger . debug ( "No uniprot ID for %s" % agent . name )
return None
# If no site information for this residue , skip
if mod_condition . position is None or mod_condition . residue is None :
return Non... |
def duplicate_items ( * collections ) :
"""Search for duplicate items in all collections .
Examples
> > > duplicate _ items ( [ 1 , 2 ] , [ 3 ] )
set ( )
> > > duplicate _ items ( { 1 : ' a ' , 2 : ' a ' } )
set ( )
> > > duplicate _ items ( [ ' a ' , ' b ' , ' a ' ] )
> > > duplicate _ items ( [ 1 , ... | duplicates = set ( )
seen = set ( )
for item in flatten ( collections ) :
if item in seen :
duplicates . add ( item )
else :
seen . add ( item )
return duplicates |
def ParseDestList ( self , parser_mediator , olecf_item ) :
"""Parses the DestList OLECF item .
Args :
parser _ mediator ( ParserMediator ) : mediates interactions between parsers
and other components , such as storage and dfvfs .
olecf _ item ( pyolecf . item ) : OLECF item .
Raises :
UnableToParseFile... | header_map = self . _GetDataTypeMap ( 'dest_list_header' )
try :
header , entry_offset = self . _ReadStructureFromFileObject ( olecf_item , 0 , header_map )
except ( ValueError , errors . ParseError ) as exception :
raise errors . UnableToParseFile ( 'Unable to parse DestList header with error: {0!s}' . format ... |
def start ( self ) :
"""Confirm that we may access the target cluster .""" | version = yield self . request ( "get" , "/version" )
if version != 2 :
raise GanetiApiError ( "Can't work with Ganeti RAPI version %d" % version )
log . msg ( "Accessing Ganeti RAPI, version %d" % version , system = "Gentleman" )
self . version = version
try :
features = yield self . request ( "get" , "/2/feat... |
def display ( self , ret , indent , prefix , out ) :
'''Recursively iterate down through data structures to determine output''' | if isinstance ( ret , six . string_types ) :
lines = ret . split ( '\n' )
for line in lines :
out += '{0}{1}{2}{3}{4}\n' . format ( self . colors [ 'RED' ] , ' ' * indent , prefix , line , self . colors [ 'ENDC' ] )
elif isinstance ( ret , dict ) :
for key in sorted ( ret ) :
val = ret [ key... |
def set_review_solution ( self , during_attempt = None , after_attempt = None , before_deadline = None , after_deadline = None ) :
"""stub""" | solution = self . my_osid_object_form . _my_map [ 'reviewOptions' ] [ 'solution' ]
if during_attempt is not None :
solution [ 'duringAttempt' ] = bool ( during_attempt )
if after_attempt is not None :
solution [ 'afterAttempt' ] = bool ( after_attempt )
if before_deadline is not None :
solution [ 'beforeDea... |
def cipher_block ( self , state ) :
"""Perform AES block cipher on input""" | # PKCS7 Padding
state = state + [ 16 - len ( state ) ] * ( 16 - len ( state ) )
# Fails test if it changes the input with + =
self . _add_round_key ( state , 0 )
for i in range ( 1 , self . _Nr ) :
self . _sub_bytes ( state )
self . _shift_rows ( state )
self . _mix_columns ( state , False )
self . _add... |
def _gegetate_args ( self , options ) :
"""Generator of args parts based on options specification .""" | for optkey , optval in self . _normalize_options ( options ) :
yield optkey
if isinstance ( optval , ( list , tuple ) ) :
assert len ( optval ) == 2 and optval [ 0 ] and optval [ 1 ] , 'Option value can only be either a string or a (tuple, list) of 2 items'
yield optval [ 0 ]
yield optva... |
def update ( self , ** kwargs ) :
"""Fetch all changes for this remote , including new branches which will
be forced in ( in case your local remote branch is not part the new remote branches
ancestry anymore ) .
: param kwargs :
Additional arguments passed to git - remote update
: return : self""" | scmd = 'update'
kwargs [ 'insert_kwargs_after' ] = scmd
self . repo . git . remote ( scmd , self . name , ** kwargs )
return self |
def _cursor_down ( self , count = 1 ) :
"""Moves cursor down count lines in same column . Cursor stops at bottom
margin .""" | self . y = min ( self . size [ 0 ] - 1 , self . y + count ) |
def save ( self , data , * args , ** kwargs ) :
"""inserts data ( dict or list of dicts )
expected kwargs :
collection _ name : by default uses MONGODB _ DEFAULT _ COLLECTION
w : by default set to 0 to disable write acknowledgement
assumes that data has been verified / validated""" | try :
collection_name = kwargs . get ( 'collection_name' , MONGODB_DEFAULT_COLLECTION )
w = kwargs . get ( 'w' , 0 )
if not self . collection :
self . set_collection ( collection_name )
self . collection . insert ( data , w )
except ( ConnectionFailure , AutoReconnect , InvalidURI ) , e : # fail... |
def _base_signup_form_class ( ) :
"""Currently , we inherit from the custom form , if any . This is all
not very elegant , though it serves a purpose :
- There are two signup forms : one for local accounts , and one for
social accounts
- Both share a common base ( BaseSignupForm )
- Given the above , how ... | if not app_settings . SIGNUP_FORM_CLASS :
return _DummyCustomSignupForm
try :
fc_module , fc_classname = app_settings . SIGNUP_FORM_CLASS . rsplit ( '.' , 1 )
except ValueError :
raise exceptions . ImproperlyConfigured ( '%s does not point to a form' ' class' % app_settings . SIGNUP_FORM_CLASS )
try :
m... |
def publish ( self , topic , options = None , args = None , kwargs = None ) :
"""Publishes a messages to the server""" | topic = self . get_full_uri ( topic )
if options is None :
options = { 'acknowledge' : True }
if options . get ( 'acknowledge' ) :
request = PUBLISH ( options = options or { } , topic = topic , args = args or [ ] , kwargs = kwargs or { } )
result = self . send_and_await_response ( request )
return resul... |
def assign ( self , role ) :
'''Assign : class : ` Role ` ` ` role ` ` to this : class : ` Subject ` . If this
: class : ` Subject ` is the : attr : ` Role . owner ` , this method does nothing .''' | if role . owner_id != self . id :
return self . roles . add ( role ) |
def wrap ( self , text ) :
'''Wraps the text object to width , breaking at whitespaces . Runs of
whitespace characters are preserved , provided they do not fall at a
line boundary . The implementation is based on that of textwrap from the
standard library , but we can cope with StringWithFormatting objects . ... | result = [ ]
chunks = self . _chunk ( text )
while chunks :
self . _lstrip ( chunks )
current_line = [ ]
current_line_length = 0
current_chunk_length = 0
while chunks :
current_chunk_length = len ( chunks [ 0 ] )
if current_line_length + current_chunk_length <= self . width :
... |
def key_from_keybase ( username , fingerprint = None ) :
"""Look up a public key from a username""" | url = keybase_lookup_url ( username )
resp = requests . get ( url )
if resp . status_code == 200 :
j_resp = json . loads ( polite_string ( resp . content ) )
if 'them' in j_resp and len ( j_resp [ 'them' ] ) == 1 :
kb_obj = j_resp [ 'them' ] [ 0 ]
if fingerprint :
return fingerprint_... |
def notification_selected_sm_changed ( self , model , prop_name , info ) :
"""If a new state machine is selected , make sure expansion state is stored and tree updated""" | selected_state_machine_id = self . model . selected_state_machine_id
if selected_state_machine_id is None :
return
self . update ( ) |
def quantile_for_single_value ( self , ** kwargs ) :
"""Returns quantile of each column or row .
Returns :
A new QueryCompiler object containing the quantile of each column or row .""" | if self . _is_transposed :
kwargs [ "axis" ] = kwargs . get ( "axis" , 0 ) ^ 1
return self . transpose ( ) . quantile_for_single_value ( ** kwargs )
axis = kwargs . get ( "axis" , 0 )
q = kwargs . get ( "q" , 0.5 )
assert type ( q ) is float
def quantile_builder ( df , ** kwargs ) :
try :
return pan... |
def columns_classes ( self ) :
'''returns columns count''' | md = 12 / self . objects_per_row
sm = None
if self . objects_per_row > 2 :
sm = 12 / ( self . objects_per_row / 2 )
return md , ( sm or md ) , 12 |
def get_fld2val ( self , name , vals ) :
"""Describe summary statistics for a list of numbers .""" | if vals :
return self . _init_fld2val_stats ( name , vals )
return self . _init_fld2val_null ( name ) |
def merge_versioned ( releases , schema = None , merge_rules = None ) :
"""Merges a list of releases into a versionedRelease .""" | if not merge_rules :
merge_rules = get_merge_rules ( schema )
merged = OrderedDict ( )
for release in sorted ( releases , key = lambda release : release [ 'date' ] ) :
release = release . copy ( )
# Don ' t version the OCID .
ocid = release . pop ( 'ocid' )
merged [ ( 'ocid' , ) ] = ocid
release... |
def appraise_source_model ( self ) :
"""Identify parameters defined in NRML source model file , so that
shapefile contains only source model specific fields .""" | for src in self . sources : # source params
src_taglist = get_taglist ( src )
if "areaSource" in src . tag :
self . has_area_source = True
npd_node = src . nodes [ src_taglist . index ( "nodalPlaneDist" ) ]
npd_size = len ( npd_node )
hdd_node = src . nodes [ src_taglist . index ... |
def deletelogicalnetwork ( check_processor = default_logicalnetwork_delete_check , reorder_dict = default_iterate_dict ) :
""": param check _ processor : check _ processor ( logicalnetwork , logicalnetworkmap ,
physicalnetwork , physicalnetworkmap ,
walk , write , \ * , parameters )""" | def walker ( walk , write , timestamp , parameters_dict ) :
for key , parameters in reorder_dict ( parameters_dict ) :
try :
value = walk ( key )
except KeyError :
pass
else :
try :
logmap = walk ( LogicalNetworkMap . _network . leftkey ( k... |
def MobileDevice ( self , data = None , subset = None ) :
"""{ dynamic _ docstring }""" | return self . factory . get_object ( jssobjects . MobileDevice , data , subset ) |
def children_after_parents ( self , piper1 , piper2 ) :
"""Custom compare function . Returns ` ` 1 ` ` if the first ` ` Piper ` ` instance
is upstream of the second ` ` Piper ` ` instance , ` ` - 1 ` ` if the first
` ` Piper ` ` is downstream of the second ` ` Piper ` ` and ` ` 0 ` ` if the two
` ` Pipers ` `... | if piper1 in self [ piper2 ] . deep_nodes ( ) :
return 1
elif piper2 in self [ piper1 ] . deep_nodes ( ) :
return - 1
else :
return 0 |
def _can_construct_from_str ( strict_mode : bool , from_type : Type , to_type : Type ) -> bool :
"""Returns true if the provided types are valid for constructor _ with _ str _ arg conversion
Explicitly declare that we are not able to convert primitive types ( they already have their own converters )
: param str... | return to_type not in { int , float , bool } |
def extract ( pattern , string , * , assert_equal = False , one = False , condense = False , default = None , default_if_multiple = True , default_if_none = True ) :
"""Used to extract a given regex pattern from a string , given several options""" | if isinstance ( pattern , str ) :
output = get_content ( pattern , string )
else : # Must be a linear container
output = [ ]
for p in pattern :
output += get_content ( p , string )
output = process_output ( output , one = one , condense = condense , default = default , default_if_multiple = default_... |
def _gssapi_login ( self ) :
"""Authenticate to the / ssllogin endpoint with GSSAPI authentication .
: returns : deferred that when fired returns a dict from sslLogin""" | method = treq_kerberos . post
auth = treq_kerberos . TreqKerberosAuth ( force_preemptive = True )
return self . _request_login ( method , auth = auth ) |
def get_registry ( entry , runtime ) :
"""Returns a record registry given an entry and runtime""" | try :
records_location_param_id = Id ( 'parameter:recordsRegistry@mongo' )
registry = runtime . get_configuration ( ) . get_value_by_parameter ( records_location_param_id ) . get_string_value ( )
return import_module ( registry ) . __dict__ . get ( entry , { } )
except ( ImportError , AttributeError , KeyEr... |
def _read_config_file ( cf , _globals = globals ( ) , _locals = locals ( ) , interactive = True ) : # noqa : E501
"""Read a config file : execute a python file while loading scapy , that may contain # noqa : E501
some pre - configured values .
If _ globals or _ locals are specified , they will be updated with t... | log_loading . debug ( "Loading config file [%s]" , cf )
try :
exec ( compile ( open ( cf ) . read ( ) , cf , 'exec' ) , _globals , _locals )
except IOError as e :
if interactive :
raise
log_loading . warning ( "Cannot read config file [%s] [%s]" , cf , e )
except Exception :
if interactive :
... |
def image ( self , raw_url , title = '' , alt = '' ) :
'''extract the images''' | max_images = self . _config . get ( 'count' )
if max_images is not None and len ( self . _out . images ) >= max_images : # We already have enough images , so bail out
return ' '
image_specs = raw_url
if title :
image_specs += ' "{}"' . format ( title )
alt , container_args = image . parse_alt_text ( alt )
spec_... |
def visit ( spht , node ) :
"""Append opening tags to document body list .
: param sphinx . writers . html . SmartyPantsHTMLTranslator spht : Object to modify .
: param sphinxcontrib . imgur . nodes . ImgurImageNode node : This class ' instance .""" | if node . options [ 'target' ] :
html_attrs_ah = dict ( CLASS = 'reference external image-reference' , href = node . options [ 'target' ] )
spht . body . append ( spht . starttag ( node , 'a' , '' , ** html_attrs_ah ) )
html_attrs_img = dict ( src = node . src , alt = node . options [ 'alt' ] )
if node . option... |
def update ( records , column , values ) :
"""Update the column of records
: param records : a list of dictionaries
: param column : a string
: param values : an iterable or a function
: returns : new records with the columns updated
> > > movies = [
. . . { ' title ' : ' The Holy Grail ' , ' year ' : 1... | new_records = deepcopy ( records )
if values . __class__ . __name__ == 'function' :
for row in new_records :
row [ column ] = values ( row [ column ] )
elif isiterable ( values ) :
for i , row in enumerate ( new_records ) :
row [ column ] = values [ i ]
else :
msg = "You must provide a funct... |
def fake_lens_path_set ( lens_path , value , obj ) :
"""Simulates R . set with a lens _ path since we don ' t have lens functions
: param lens _ path : Array of string paths
: param value : The value to set at the lens path
: param obj : Object containing the given path
: return : The value at the path or N... | segment = head ( lens_path )
obj_copy = copy . copy ( obj )
def set_array_index ( i , v , l ) : # Fill the array with None up to the given index and set the index to v
try :
l [ i ] = v
except IndexError :
for _ in range ( i - len ( l ) + 1 ) :
l . append ( None )
l [ i ] = v... |
def delete_doc ( self , doc_id , revision ) :
'''Imitates sending DELETE request to CouchDB server''' | d = defer . Deferred ( )
self . increase_stat ( 'delete_doc' )
try :
doc = self . _get_doc ( doc_id )
if doc [ '_rev' ] != revision :
raise ConflictError ( "Document update conflict." )
if doc . get ( '_deleted' , None ) :
raise NotFoundError ( '%s deleted' % doc_id )
doc [ '_deleted' ] ... |
def patch_namespaced_role_binding ( self , name , namespace , body , ** kwargs ) : # noqa : E501
"""patch _ namespaced _ role _ binding # noqa : E501
partially update the specified RoleBinding # 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_role_binding_with_http_info ( name , namespace , body , ** kwargs )
# noqa : E501
else :
( data ) = self . patch_namespaced_role_binding_with_http_info ( name , namespace , body , ** kwargs )
# no... |
def _handle_unsubscribed ( self , * args , chanId = None , ** kwargs ) :
"""Handles responses to unsubscribe ( ) commands - removes a channel id from
the client .
: param chanId : int , represent channel id as assigned by server""" | log . debug ( "_handle_unsubscribed: %s - %s" , chanId , kwargs )
try :
self . channels . pop ( chanId )
except KeyError :
raise NotRegisteredError ( )
try :
self . _heartbeats . pop ( chanId )
except KeyError :
pass
try :
self . _late_heartbeats . pop ( chanId )
except KeyError :
pass |
def _curve ( x1 , y1 , x2 , y2 , hunit = HUNIT , vunit = VUNIT ) :
"""Return a PyX curved path from ( x1 , y1 ) to ( x2 , y2 ) ,
such that the slope at either end is zero .""" | ax1 , ax2 , axm = x1 * hunit , x2 * hunit , ( x1 + x2 ) * hunit / 2
ay1 , ay2 = y1 * vunit , y2 * vunit
return pyx . path . curve ( ax1 , ay1 , axm , ay1 , axm , ay2 , ax2 , ay2 ) |
def isochrone_to_aa ( w , potential ) :
"""Transform the input cartesian position and velocity to action - angle
coordinates in the Isochrone potential . See Section 3.5.2 in
Binney & Tremaine ( 2008 ) , and be aware of the errata entry for
Eq . 3.225.
This transformation is analytic and can be used as a " ... | if not isinstance ( potential , PotentialBase ) :
potential = IsochronePotential ( ** potential )
usys = potential . units
GM = ( G * potential . parameters [ 'm' ] ) . decompose ( usys ) . value
b = potential . parameters [ 'b' ] . decompose ( usys ) . value
E = w . energy ( Hamiltonian ( potential ) ) . decompose... |
def random_walk ( self , path_length , alpha = 0 , rand = random . Random ( ) , start = None ) :
"""Returns a truncated random walk .
path _ length : Length of the random walk .
alpha : probability of restarts .
start : the start node of the random walk .""" | G = self
if start :
path = [ start ]
else : # Sampling is uniform w . r . t V , and not w . r . t E
path = [ rand . choice ( list ( G . keys ( ) ) ) ]
while len ( path ) < path_length :
cur = path [ - 1 ]
if len ( G [ cur ] ) > 0 :
if rand . random ( ) >= alpha :
path . append ( rand... |
def remove_listener ( self , uid ) :
"""Remove listener with given uid .""" | self . listeners [ : ] = ( listener for listener in self . listeners if listener [ 'uid' ] != uid ) |
def gotoItem ( self , path ) :
"""Goes to a particular path within the XDK .
: param path | < str >""" | if not path :
return
sections = nativestring ( path ) . split ( '/' )
check = projex . text . underscore ( sections [ 0 ] )
for i in range ( self . uiContentsTREE . topLevelItemCount ( ) ) :
item = self . uiContentsTREE . topLevelItem ( i )
if check in ( projex . text . underscore ( item . text ( 0 ) ) , it... |
def _close ( self ) :
"""Close the TCP connection .""" | self . client . stop ( )
self . open = False
self . waiting = False |
def handle ( self , connection_id , message_content ) :
"""A connection must use one of the supported authorization types
to prove their identity . If a requester deviates
from the procedure in any way , the requester will be rejected and the
connection will be closed . The same is true if the requester sends... | message = ConnectionRequest ( )
message . ParseFromString ( message_content )
LOGGER . debug ( "got connect message from %s. sending ack" , connection_id )
# Need to use join here to get the string " 0.0.0.0 " . Otherwise ,
# bandit thinks we are binding to all interfaces and returns a
# Medium security risk .
interfac... |
def return_on_initial_capital ( capital , period_pl , leverage = None ) :
"""Return the daily return series based on the capital""" | if capital <= 0 :
raise ValueError ( 'cost must be a positive number not %s' % capital )
leverage = leverage or 1.
eod = capital + ( leverage * period_pl . cumsum ( ) )
ltd_rets = ( eod / capital ) - 1.
dly_rets = ltd_rets
dly_rets . iloc [ 1 : ] = ( 1. + ltd_rets ) . pct_change ( ) . iloc [ 1 : ]
return dly_rets |
def random_leaf ( self ) :
"Returns a random variable with the associated weight" | for i in range ( self . _number_tries_feasible_ind ) :
var = np . random . randint ( self . nvar )
v = self . _random_leaf ( var )
if v is None :
continue
return v
raise RuntimeError ( "Could not find a suitable random leaf" ) |
def formatTime ( self , record , datefmt = None ) :
"""Format time , including milliseconds .""" | formatted = super ( PalletFormatter , self ) . formatTime ( record , datefmt = datefmt )
return formatted + '.%03dZ' % record . msecs |
def get_cpu_info ( self ) -> str :
'''Show device CPU information .''' | output , _ = self . _execute ( '-s' , self . device_sn , 'shell' , 'cat' , '/proc/cpuinfo' )
return output |
def clear_time_value ( self ) :
"""stub""" | if ( self . get_time_value_metadata ( ) . is_read_only ( ) or self . get_time_value_metadata ( ) . is_required ( ) ) :
raise NoAccess ( )
self . my_osid_object_form . _my_map [ 'timeValue' ] = dict ( self . get_time_value_metadata ( ) . get_default_duration_values ( ) [ 0 ] ) |
def join ( self , other ) :
"""Join two headings into a new one .
It assumes that self and other are headings that share no common dependent attributes .""" | return Heading ( [ self . attributes [ name ] . todict ( ) for name in self . primary_key ] + [ other . attributes [ name ] . todict ( ) for name in other . primary_key if name not in self . primary_key ] + [ self . attributes [ name ] . todict ( ) for name in self . dependent_attributes if name not in other . primary_... |
def get_raw_data ( self ) :
"""Get raw HID report based on internal report item settings ,
creates new c _ ubytes storage""" | if self . __report_kind != HidP_Output and self . __report_kind != HidP_Feature :
raise HIDError ( "Only for output or feature reports" )
self . __prepare_raw_data ( )
# return read - only object for internal storage
return helpers . ReadOnlyList ( self . __raw_data ) |
def default_font_toggled ( self , settings , key , user_data ) :
"""If the gconf var use _ default _ font be changed , this method
will be called and will change the font style to the gnome
default or to the chosen font in style / font / style in all
terminals open .""" | font_name = None
if settings . get_boolean ( key ) :
gio_settings = Gio . Settings ( 'org.gnome.desktop.interface' )
font_name = gio_settings . get_string ( 'monospace-font-name' )
else :
font_name = self . settings . styleFont . get_string ( 'style' )
if not font_name :
log . error ( "Error: unable to ... |
def typewrite ( message , interval = 0.0 , pause = None , _pause = True ) :
"""Performs a keyboard key press down , followed by a release , for each of
the characters in message .
The message argument can also be list of strings , in which case any valid
keyboard name can be used .
Since this performs a seq... | interval = float ( interval )
_failSafeCheck ( )
for c in message :
if len ( c ) > 1 :
c = c . lower ( )
press ( c , _pause = False )
time . sleep ( interval )
_failSafeCheck ( )
_autoPause ( pause , _pause ) |
def sils ( T , f , c , d , h ) :
"""sils - - LP lotsizing for the single item lot sizing problem
Parameters :
- T : number of periods
- P : set of products
- f [ t ] : set - up costs ( on period t )
- c [ t ] : variable costs
- d [ t ] : demand values
- h [ t ] : holding costs
Returns a model , read... | model = Model ( "single item lotsizing" )
Ts = range ( 1 , T + 1 )
M = sum ( d [ t ] for t in Ts )
y , x , I = { } , { } , { }
for t in Ts :
y [ t ] = model . addVar ( vtype = "I" , ub = 1 , name = "y(%s)" % t )
x [ t ] = model . addVar ( vtype = "C" , ub = M , name = "x(%s)" % t )
I [ t ] = model . addVar ... |
def retrieve_page ( self , method , path , post_params = { } , headers = { } , status = 200 , username = None , password = None , * args , ** kwargs ) :
"""Makes the actual request . This will also go through and generate the
needed steps to make the request , i . e . basic auth .
` ` method ` ` :
Any support... | # Copy headers so that making changes here won ' t affect the original
headers = headers . copy ( )
# Update basic auth information
basicauth = self . _prepare_basicauth ( username , password )
if basicauth :
headers . update ( [ basicauth ] )
# If this is a POST or PUT , we can put the data into the body as
# form... |
def verify ( path ) :
"""Verify folder file format
The folder file format is only valid when
there is only one file format present .""" | valid = True
fifo = SeriesFolder . _search_files ( path )
# dataset size
if len ( fifo ) == 0 :
valid = False
# number of different file formats
fifmts = [ ff [ 1 ] for ff in fifo ]
if len ( set ( fifmts ) ) != 1 :
valid = False
return valid |
def usearch_sort_by_abundance ( fasta_filepath , output_filepath = None , sizein = True , sizeout = True , minsize = 0 , log_name = "abundance_sort.log" , usersort = False , HALT_EXEC = False , save_intermediate_files = False , remove_usearch_logs = False , working_dir = None ) :
"""Sorts fasta file by abundance
... | if not output_filepath :
_ , output_filepath = mkstemp ( prefix = 'usearch_abundance_sorted' , suffix = '.fasta' )
log_filepath = join ( working_dir , "minsize_" + str ( minsize ) + "_" + log_name )
params = { }
app = Usearch ( params , WorkingDir = working_dir , HALT_EXEC = HALT_EXEC )
if usersort :
app . Para... |
def dispatch ( self , * args , ** kwargs ) :
"""This decorator sets this view to have restricted permissions .""" | return super ( StrainDelete , self ) . dispatch ( * args , ** kwargs ) |
def check_input ( self , token ) :
"""Performs checks on the input token . Raises an exception if unsupported .
: param token : the token to check
: type token : Token""" | if token is None :
raise Exception ( self . full_name + ": No token provided!" )
if isinstance ( token . payload , str ) :
return
raise Exception ( self . full_name + ": Unhandled class: " + classes . get_classname ( token . payload ) ) |
async def set_mode ( self , target , * modes ) :
"""Set mode on target .
Users should only rely on the mode actually being changed when receiving an on _ { channel , user } _ mode _ change callback .""" | if self . is_channel ( target ) and not self . in_channel ( target ) :
raise NotInChannel ( target )
await self . rawmsg ( 'MODE' , target , * modes ) |
def perform_command ( self ) :
"""Perform command and return the appropriate exit code .
: rtype : int""" | self . log ( u"This function should be overloaded in derived classes" )
self . log ( [ u"Invoked with %s" , self . actual_arguments ] )
return self . NO_ERROR_EXIT_CODE |
def serve_coil_assets ( path ) :
"""Serve Coil assets .
This is meant to be used ONLY by the internal dev server .
Please configure your web server to handle requests to this URL : :
/ coil _ assets / = > coil / data / coil _ assets""" | res = pkg_resources . resource_filename ( 'coil' , os . path . join ( 'data' , 'coil_assets' ) )
return send_from_directory ( res , path ) |
def plot_sn_discovery_ratio_map ( log , snSurveyDiscoveryTimes , redshifts , peakAppMagList , snCampaignLengthList , extraSurveyConstraints , pathToOutputPlotFolder ) :
"""* Plot the SN discoveries and non - discoveries in a polar plot as function of redshift *
* * Key Arguments : * *
- ` ` log ` ` - - logger
... | # # # # # # > IMPORTS # # # # #
# # STANDARD LIB # #
import sys
# # THIRD PARTY # #
import matplotlib . pyplot as plt
import numpy as np
# # LOCAL APPLICATION # #
import dryxPython . plotting as dp
filters = [ 'g' , 'r' , 'i' , 'z' ]
faintMagLimit = extraSurveyConstraints [ 'Faint-Limit of Peak Magnitude' ]
# # # # # #... |
def _calcOrbits ( self ) :
"""Prepares data structure for breaking data into orbits . Not intended
for end user .""" | # if the breaks between orbit have not been defined , define them
# also , store the data so that grabbing different orbits does not
# require reloads of whole dataset
if len ( self . _orbit_breaks ) == 0 : # determine orbit breaks
self . _detBreaks ( )
# store a copy of data
self . _fullDayData = self . sa... |
def send_audio ( self , chat_id , audio , duration = None , performer = None , title = None , reply_to_message_id = None , reply_markup = None ) :
"""Use this method to send audio files , if you want Telegram clients to display them in the music player .
Your audio must be in the . mp3 format . On success , the s... | self . logger . info ( 'sending audio payload %s' , audio )
payload = dict ( chat_id = chat_id , duration = duration , performer = performer , title = title , reply_to_message_id = reply_to_message_id , reply_markup = reply_markup )
files = dict ( audio = open ( audio , 'rb' ) )
return Message . from_api ( self , ** se... |
def get_post_data ( self ) :
'''Get all the arguments from post request . Only get the first argument by default .''' | post_data = { }
for key in self . request . arguments :
post_data [ key ] = self . get_arguments ( key ) [ 0 ]
return post_data |
def is_none ( self ) :
"""Ensures : attr : ` subject ` is ` ` None ` ` .""" | self . _run ( unittest_case . assertIsNone , ( self . _subject , ) )
return ChainInspector ( self . _subject ) |
def get_share_dirname ( url ) :
'''从url中提取出当前的目录''' | dirname_match = re . search ( '(dir|path)=([^&]+)' , encoder . decode_uri_component ( url ) )
if dirname_match :
return dirname_match . group ( 2 )
else :
return None |
def analyze ( self , scratch , ** kwargs ) :
"""Run and return the results from the DuplicateScripts plugin .
Only takes into account scripts with more than 3 blocks .""" | scripts_set = set ( )
for script in self . iter_scripts ( scratch ) :
if script [ 0 ] . type . text == 'define %s' :
continue
# Ignore user defined scripts
blocks_list = [ ]
for name , _ , _ in self . iter_blocks ( script . blocks ) :
blocks_list . append ( name )
blocks_tuple = ... |
def find_range_in_section_list ( start , end , section_list ) :
"""Returns all sections belonging to the given range .
The given list is assumed to contain start points of consecutive
sections , except for the final point , assumed to be the end point of the
last section . For example , the list [ 5 , 8 , 30 ... | ind = find_range_ix_in_section_list ( start , end , section_list )
return section_list [ ind [ 0 ] : ind [ 1 ] ] |
def import_ ( zone , path ) :
'''Import the configuration to memory from stable storage .
zone : string
name of zone
path : string
path of file to export to
CLI Example :
. . code - block : : bash
salt ' * ' zonecfg . import epyon / zones / epyon . cfg''' | ret = { 'status' : True }
# create from file
_dump_cfg ( path )
res = __salt__ [ 'cmd.run_all' ] ( 'zonecfg -z {zone} -f {path}' . format ( zone = zone , path = path , ) )
ret [ 'status' ] = res [ 'retcode' ] == 0
ret [ 'message' ] = res [ 'stdout' ] if ret [ 'status' ] else res [ 'stderr' ]
if ret [ 'message' ] == '' ... |
def open ( cls , name = None , mode = "r" , fileobj = None , bufsize = RECORDSIZE , ** kwargs ) :
"""Open a tar archive for reading , writing or appending . Return
an appropriate TarFile class .
mode :
' r ' or ' r : * ' open for reading with transparent compression
' r : ' open for reading exclusively unco... | if not name and not fileobj :
raise ValueError ( "nothing to open" )
if mode in ( "r" , "r:*" ) : # Find out which * open ( ) is appropriate for opening the file .
for comptype in cls . OPEN_METH :
func = getattr ( cls , cls . OPEN_METH [ comptype ] )
if fileobj is not None :
saved_p... |
def updateDefinition ( self , json_dict ) :
"""The updateDefinition operation supports updating a definition
property in a hosted feature service . The result of this
operation is a response indicating success or failure with error
code and description .
Input :
json _ dict - part to add to host service .... | definition = None
if json_dict is not None :
if isinstance ( json_dict , collections . OrderedDict ) == True :
definition = json_dict
else :
definition = collections . OrderedDict ( )
if 'hasStaticData' in json_dict :
definition [ 'hasStaticData' ] = json_dict [ 'hasStaticDat... |
def crypto_validator ( func ) :
"""This a decorator to be used for any method relying on the cryptography library . # noqa : E501
Its behaviour depends on the ' crypto _ valid ' attribute of the global ' conf ' .""" | def func_in ( * args , ** kwargs ) :
if not conf . crypto_valid :
raise ImportError ( "Cannot execute crypto-related method! " "Please install python-cryptography v1.7 or later." )
# noqa : E501
return func ( * args , ** kwargs )
return func_in |
def set_pragmas ( self , pragmas ) :
"""Set pragmas for the current database connection .
Parameters
pragmas : dict
Dictionary of pragmas ; see constants . default _ pragmas for a template
and http : / / www . sqlite . org / pragma . html for a full list .""" | self . pragmas = pragmas
c = self . conn . cursor ( )
c . executescript ( ';\n' . join ( [ 'PRAGMA %s=%s' % i for i in self . pragmas . items ( ) ] ) )
self . conn . commit ( ) |
def astra_projection_geometry ( geometry ) :
"""Create an ASTRA projection geometry from an ODL geometry object .
As of ASTRA version 1.7 , the length values are not required any more to be
rescaled for 3D geometries and non - unit ( but isotropic ) voxel sizes .
Parameters
geometry : ` Geometry `
ODL pro... | if not isinstance ( geometry , Geometry ) :
raise TypeError ( '`geometry` {!r} is not a `Geometry` instance' '' . format ( geometry ) )
if 'astra' in geometry . implementation_cache : # Shortcut , reuse already computed value .
return geometry . implementation_cache [ 'astra' ]
if not geometry . det_partition .... |
def compat_serializer_attr ( serializer , obj ) :
"""Required only for DRF 3.1 , which does not make dynamically added attribute available in obj in serializer .
This is a quick solution but works without breajing anything .""" | if DRFVLIST [ 0 ] == 3 and DRFVLIST [ 1 ] == 1 :
for i in serializer . instance :
if i . id == obj . id :
return i
else :
return obj |
def get_bip32_address ( self , ecdh = False ) :
"""Compute BIP32 derivation address according to SLIP - 0013/0017.""" | index = struct . pack ( '<L' , self . identity_dict . get ( 'index' , 0 ) )
addr = index + self . to_bytes ( )
log . debug ( 'bip32 address string: %r' , addr )
digest = hashlib . sha256 ( addr ) . digest ( )
s = io . BytesIO ( bytearray ( digest ) )
hardened = 0x80000000
addr_0 = 17 if bool ( ecdh ) else 13
address_n ... |
def get_hist ( rfile , histname , get_overflow = False ) :
"""Read a 1D Histogram .""" | import root_numpy as rnp
rfile = open_rfile ( rfile )
hist = rfile [ histname ]
xlims = np . array ( list ( hist . xedges ( ) ) )
bin_values = rnp . hist2array ( hist , include_overflow = get_overflow )
rfile . close ( )
return bin_values , xlims |
def plotPointing ( self , maptype = None , colour = 'b' , mod3 = 'r' , showOuts = True , ** kwargs ) :
"""Plot the FOV""" | if maptype is None :
maptype = self . defaultMap
radec = self . currentRaDec
for ch in radec [ : , 2 ] [ : : 4 ] :
idx = np . where ( radec [ : , 2 ] . astype ( np . int ) == ch ) [ 0 ]
idx = np . append ( idx , idx [ 0 ] )
# % points to draw a box
c = colour
if ch in self . brokenChannels :
... |
def get_correctness_for_response ( self , response ) :
"""get measure of correctness available for a particular response""" | for answer in self . my_osid_object . get_answers ( ) :
if self . _is_match ( response , answer ) :
try :
return answer . get_score ( )
except AttributeError :
return 100
for answer in self . my_osid_object . get_wrong_answers ( ) :
if self . _is_match ( response , answer... |
async def open_clients_async ( self ) :
"""Responsible for establishing connection to event hub client
throws EventHubsException , IOException , InterruptedException , ExecutionException .""" | await self . partition_context . get_initial_offset_async ( )
# Create event hub client and receive handler and set options
self . eh_client = EventHubClientAsync ( self . host . eh_config . client_address , debug = self . host . eph_options . debug_trace , http_proxy = self . host . eph_options . http_proxy )
self . p... |
def colon_subscripts ( u ) :
"""Array colon subscripts foo ( 1:10 ) and colon expressions 1:10 look
too similar to each other . Now is the time to find out who is who .""" | if u . __class__ in ( node . arrayref , node . cellarrayref ) :
for w in u . args :
if w . __class__ is node . expr and w . op == ":" :
w . _replace ( op = "::" ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.