signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def AgregarCondicionVenta ( self , codigo , descripcion = None , ** kwargs ) :
"Agrego una o más condicion de venta a la liq ." | cond = { 'codigo' : codigo , 'descripcion' : descripcion }
self . solicitud [ 'liquidacion' ] [ 'condicionVenta' ] . append ( cond )
return True |
def to_project_config ( self , with_packages = False ) :
"""Return a dict representation of the config that could be written to
disk with ` yaml . safe _ dump ` to get this configuration .
: param with _ packages bool : If True , include the serialized packages
file in the root .
: returns dict : The serial... | result = deepcopy ( { 'name' : self . project_name , 'version' : self . version , 'project-root' : self . project_root , 'profile' : self . profile_name , 'source-paths' : self . source_paths , 'macro-paths' : self . macro_paths , 'data-paths' : self . data_paths , 'test-paths' : self . test_paths , 'analysis-paths' : ... |
def detect_clearsky ( measured , clearsky , times , window_length , mean_diff = 75 , max_diff = 75 , lower_line_length = - 5 , upper_line_length = 10 , var_diff = 0.005 , slope_dev = 8 , max_iterations = 20 , return_components = False ) :
"""Detects clear sky times according to the algorithm developed by Reno
and... | # calculate deltas in units of minutes ( matches input window _ length units )
deltas = np . diff ( times . values ) / np . timedelta64 ( 1 , '60s' )
# determine the unique deltas and if we can proceed
unique_deltas = np . unique ( deltas )
if len ( unique_deltas ) == 1 :
sample_interval = unique_deltas [ 0 ]
else ... |
def get_os_filename ( path ) :
"""Return filesystem path for given URL path .""" | if os . name == 'nt' :
path = prepare_urlpath_for_nt ( path )
res = urllib . url2pathname ( fileutil . pathencode ( path ) )
if os . name == 'nt' and res . endswith ( ':' ) and len ( res ) == 2 : # Work around http : / / bugs . python . org / issue11474
res += os . sep
return res |
def copy ( self , key = None ) :
"""Creates another collection with the same items and maxsize with
the given * key * .""" | other = self . __class__ ( maxsize = self . maxsize , redis = self . persistence . redis , key = key )
other . update ( self )
return other |
def values ( self ) :
"""TimeSeries of values .""" | # if accessing and stale - update first
if self . _needupdate or self . now != self . parent . now :
self . update ( self . root . now )
if self . root . stale :
self . root . update ( self . root . now , None )
return self . _values . loc [ : self . now ] |
def CopyFromDateTimeString ( self , time_string ) :
"""Copies time elements from a date and time string .
Args :
time _ string ( str ) : date and time value formatted as :
YYYY - MM - DD hh : mm : ss . # # # # # [ + - ] # # : # #
Where # are numeric digits ranging from 0 to 9 and the seconds
fraction can ... | date_time_values = self . _CopyDateTimeFromString ( time_string )
self . _CopyFromDateTimeValues ( date_time_values ) |
def _deserialize ( self , value , attr , data , partial = None , ** kwargs ) :
"""Same as : meth : ` Field . _ deserialize ` with additional ` ` partial ` ` argument .
: param bool | tuple partial : For nested schemas , the ` ` partial ` `
parameter passed to ` Schema . load ` .
. . versionchanged : : 3.0.0
... | self . _test_collection ( value )
return self . _load ( value , data , partial = partial ) |
def _get_mpr_table ( self , connection , partition ) :
"""Returns name of the sqlite table who stores mpr data .
Args :
connection ( apsw . Connection ) : connection to sqlite database who stores mpr data .
partition ( orm . Partition ) :
Returns :
str :
Raises :
MissingTableError : if partition table... | # TODO : This is the first candidate for optimization . Add field to partition
# with table name and update it while table creation .
# Optimized version .
# return partition . mpr _ table or raise exception
# Not optimized version .
# first check either partition has readonly table .
virtual_table = partition . vid
ta... |
def get_resource_bin_assignment_session ( self , proxy ) :
"""Gets the session for assigning resource to bin mappings .
arg : proxy ( osid . proxy . Proxy ) : a proxy
return : ( osid . resource . ResourceBinAssignmentSession ) - a
` ` ResourceBinAssignmentSession ` `
raise : NullArgument - ` ` proxy ` ` is ... | if not self . supports_resource_bin_assignment ( ) :
raise errors . Unimplemented ( )
# pylint : disable = no - member
return sessions . ResourceBinAssignmentSession ( proxy = proxy , runtime = self . _runtime ) |
def pass_actualremoterelieve_v1 ( self ) :
"""Update the outlet link sequence | dam _ outlets . R | .""" | flu = self . sequences . fluxes . fastaccess
out = self . sequences . outlets . fastaccess
out . r [ 0 ] += flu . actualremoterelieve |
def PopupGetFile ( message , title = None , default_path = '' , default_extension = '' , save_as = False , file_types = ( ( "ALL Files" , "*" ) , ) , no_window = False , size = ( None , None ) , button_color = None , background_color = None , text_color = None , icon = DEFAULT_WINDOW_ICON , font = None , no_titlebar = ... | if no_window :
if Window . QTApplication is None :
Window . QTApplication = QApplication ( sys . argv )
if save_as :
qt_types = convert_tkinter_filetypes_to_qt ( file_types )
filename = QFileDialog . getSaveFileName ( dir = initial_folder , filter = qt_types )
else :
qt_types... |
def alias_repository ( self , repository_id , alias_id ) :
"""Adds an ` ` Id ` ` to a ` ` Repository ` ` for the purpose of creating compatibility .
The primary ` ` Id ` ` of the ` ` Repository ` ` is determined by the
provider . The new ` ` Id ` ` is an alias to the primary ` ` Id ` ` . If
the alias is a poi... | # Implemented from template for
# osid . resource . BinLookupSession . alias _ bin _ template
if self . _catalog_session is not None :
return self . _catalog_session . alias_catalog ( catalog_id = repository_id , alias_id = alias_id )
self . _alias_id ( primary_id = repository_id , equivalent_id = alias_id ) |
def download ( uri , user = None , password = None , saveas = None , ssl_verify = False , get_args = None ) :
'''FIXME : DOCS . . .''' | if saveas is None :
temp = tempfile . NamedTemporaryFile ( prefix = 'requests_' , dir = '/tmp' )
saveas = temp . name
temp . close ( )
if not ( user or password ) : # Fall back to kerberos auth
logr . debug ( "Using Kerberos AUTH" )
auth = HTTPKerberosAuth ( mutual_authentication = OPTIONAL )
else :... |
def generator ( self ) :
"""Returns a generator which yields the items added to the bar during
construction , and updates the progress bar * after * the yielded block
returns .""" | if not self . entered :
raise RuntimeError ( 'You need to use progress bars in a with block.' )
if self . is_hidden :
for rv in self . iter :
yield rv
else :
for rv in self . iter :
self . current_item = rv
yield rv
self . update ( 1 )
self . finish ( )
self . render_... |
def register_plugin ( self ) :
"""Register plugin in Spyder ' s main window""" | self . main . add_dockwidget ( self )
self . findinfiles . result_browser . sig_edit_goto . connect ( self . main . editor . load )
self . findinfiles . find_options . redirect_stdio . connect ( self . main . redirect_internalshell_stdio )
self . main . workingdirectory . refresh_findinfiles . connect ( self . refreshd... |
def absent ( name , poll = 5 , timeout = 60 , profile = None ) :
'''Ensure that the named stack is absent
name
The name of the stack to remove
poll
Poll ( in sec . ) and report events until stack complete
timeout
Stack creation timeout in minutes
profile
Profile to use''' | log . debug ( 'Absent with (%s, %s %s)' , name , poll , profile )
ret = { 'name' : None , 'comment' : '' , 'changes' : { } , 'result' : True }
if not name :
ret [ 'result' ] = False
ret [ 'comment' ] = 'Name ist not valid'
return ret
ret [ 'name' ] = name ,
existing_stack = __salt__ [ 'heat.show_stack' ] ( ... |
def block_perms ( self ) :
"""If the circuit is reducible into permutations within subranges of
the full range of channels , this yields a tuple with the internal
permutations for each such block .
: type : tuple""" | if not self . _block_perms :
self . _block_perms = permutation_to_block_permutations ( self . permutation )
return self . _block_perms |
def removeComponent ( self , component ) :
"""Remove ` ` component ` ` from the glyph .
> > > glyph . removeComponent ( component )
` ` component ` ` may be a : ref : ` BaseComponent ` or an
: ref : ` type - int ` representing a component index .""" | if isinstance ( component , int ) :
index = component
else :
index = self . _getComponentIndex ( component )
index = normalizers . normalizeIndex ( index )
if index >= self . _len__components ( ) :
raise ValueError ( "No component located at index %d." % index )
self . _removeComponent ( index ) |
def affine_coupling ( name , x , mid_channels = 512 , activation = "relu" , reverse = False , dropout = 0.0 ) :
"""Reversible affine coupling layer .
Args :
name : variable scope .
x : 4 - D Tensor .
mid _ channels : number of channels in the coupling layer .
activation : Can be either " relu " or " gatu ... | with tf . variable_scope ( name , reuse = tf . AUTO_REUSE ) :
x_shape = common_layers . shape_list ( x )
x1 , x2 = tf . split ( x , num_or_size_splits = 2 , axis = - 1 )
# scale , shift = NN ( x1)
# If reverse :
# z2 = scale * ( x2 + shift )
# Else :
# z2 = ( x2 / scale ) - shift
z1 = x1... |
def infer ( self , handler ) :
"""infer this column from the table : create and return a new object""" | table = handler . table
new_self = self . copy ( )
new_self . set_table ( table )
new_self . get_attr ( )
new_self . read_metadata ( handler )
return new_self |
def pre_validate ( self , form ) :
'''Calls preprocessors before pre _ validation''' | for preprocessor in self . _preprocessors :
preprocessor ( form , self )
super ( FieldHelper , self ) . pre_validate ( form ) |
def _pys2attributes ( self , line ) :
"""Updates attributes in code _ array""" | splitline = self . _split_tidy ( line )
selection_data = map ( ast . literal_eval , splitline [ : 5 ] )
selection = Selection ( * selection_data )
tab = int ( splitline [ 5 ] )
attrs = { }
for col , ele in enumerate ( splitline [ 6 : ] ) :
if not ( col % 2 ) : # Odd entries are keys
key = ast . literal_eval... |
def get_max_network_adapters ( self , chipset ) :
"""Maximum total number of network adapters associated with every
: py : class : ` IMachine ` instance .
in chipset of type : class : ` ChipsetType `
The chipset type to get the value for .
return max _ network _ adapters of type int
The maximum total numb... | if not isinstance ( chipset , ChipsetType ) :
raise TypeError ( "chipset can only be an instance of type ChipsetType" )
max_network_adapters = self . _call ( "getMaxNetworkAdapters" , in_p = [ chipset ] )
return max_network_adapters |
def any ( self , func = None ) :
"""Determine if at least one element in the object
matches a truth test .""" | if func is None :
func = lambda x , * args : x
self . antmp = False
def testEach ( value , index , * args ) :
if func ( value , index , * args ) is True :
self . antmp = True
return "breaker"
self . _clean . each ( testEach )
return self . _wrap ( self . antmp ) |
def ngfileupload_uploadfactory ( content_length = None , content_type = None , uploaded_file = None ) :
"""Get default put factory .
If Content - Type is ` ` ' multipart / form - data ' ` ` then the stream is aborted .
: param content _ length : The content length . ( Default : ` ` None ` ` )
: param content ... | if not content_type . startswith ( 'multipart/form-data' ) :
abort ( 422 )
return uploaded_file . stream , content_length , None , parse_header_tags ( ) |
def list_subdomains_previous_page ( self ) :
"""When paging through subdomain results , this will return the previous
page , using the same limit . If there are no more results , a
NoMoreResults exception will be raised .""" | uri = self . _paging . get ( "subdomain" , { } ) . get ( "prev_uri" )
if uri is None :
raise exc . NoMoreResults ( "There are no previous pages of subdomains " "to list." )
return self . _list_subdomains ( uri ) |
def ispcr ( args ) :
"""% prog ispcr fastafile
Reformat paired primers into isPcr query format , which is three column
format : name , forward , reverse""" | from jcvi . utils . iter import grouper
p = OptionParser ( ispcr . __doc__ )
p . add_option ( "-r" , dest = "rclip" , default = 1 , type = "int" , help = "pair ID is derived from rstrip N chars [default: %default]" )
opts , args = p . parse_args ( args )
if len ( args ) != 1 :
sys . exit ( not p . print_help ( ) )
... |
def set_secondary_vehicle_position ( self , m ) :
'''show 2nd vehicle on map''' | if m . get_type ( ) != 'GLOBAL_POSITION_INT' :
return
( lat , lon , heading ) = ( m . lat * 1.0e-7 , m . lon * 1.0e-7 , m . hdg * 0.01 )
if abs ( lat ) < 1.0e-3 and abs ( lon ) > 1.0e-3 :
return
# hack for OBC2016
alt = self . ElevationMap . GetElevation ( lat , lon )
agl = m . alt * 0.001 - alt
agl_s = str ( i... |
async def executemany ( self , command : str , args , * , timeout : float = None ) :
"""Execute an SQL * command * for each sequence of arguments in * args * .
Example :
. . code - block : : pycon
> > > await con . executemany ( ' ' '
. . . INSERT INTO mytab ( a ) VALUES ( $ 1 , $ 2 , $ 3 ) ;
. . . ' ' ' ... | self . _check_open ( )
return await self . _executemany ( command , args , timeout ) |
def find_one ( self , * args , ** kwargs ) :
"""Run the pymongo find _ one command against the default database and collection
and paginate the output to the screen .""" | # print ( f " database . collection : ' { self . database . name } . { self . collection . name } ' " )
self . print_doc ( self . collection . find_one ( * args , ** kwargs ) ) |
def height_to_pressure_std ( height ) :
r"""Convert height data to pressures using the U . S . standard atmosphere .
The implementation inverts the formula outlined in [ Hobbs1977 ] _ pg . 60-61.
Parameters
height : ` pint . Quantity `
Atmospheric height
Returns
` pint . Quantity `
The corresponding p... | t0 = 288. * units . kelvin
gamma = 6.5 * units ( 'K/km' )
p0 = 1013.25 * units . mbar
return p0 * ( 1 - ( gamma / t0 ) * height ) ** ( mpconsts . g / ( mpconsts . Rd * gamma ) ) |
def get_fallbackservers ( self , orgid , page = None ) :
"""Get Fallback server""" | opts = { }
if page :
opts [ 'page' ] = page
return self . api_call ( ENDPOINTS [ 'fallbackservers' ] [ 'list' ] , dict ( orgid = orgid ) , ** opts ) |
def get_group ( self , name ) :
"""Get contact group by name
: param name : name of group
: type name : ` ` str ` ` , ` ` unicode ` `
: rtype : ` ` dict ` ` with group data""" | groups = self . get_groups ( )
for group in groups :
if group [ 'contactgroupname' ] == name :
return group
msg = 'No group named: "{name}" found.'
raise FMBaseError ( msg . format ( name = name ) ) |
def RemoveTransaction ( self , tx ) :
"""Remove a transaction from the memory pool if it is found on the blockchain .
Args :
tx ( neo . Core . TX . Transaction ) : instance .
Returns :
bool : True if successfully removed . False otherwise .""" | if BC . Default ( ) is None :
return False
if not BC . Default ( ) . ContainsTransaction ( tx . Hash ) :
return False
if tx . Hash . ToBytes ( ) in self . MemPool :
del self . MemPool [ tx . Hash . ToBytes ( ) ]
return True
return False |
def unique ( series : pd . Series ) -> pd . Series :
"""Test that the data items do not repeat .""" | return ~ series . duplicated ( keep = False ) |
def update ( self , index , iterable , commit = True ) :
"""Updates the index with current data .
: param index : The search _ indexes . Index object
: param iterable : The queryset
: param commit : commit to the backend .""" | parler = False
# setup here because self . existing _ mappings are overridden .
if not self . setup_complete :
try :
self . setup ( )
except elasticsearch . TransportError as e :
if not self . silently_fail :
raise
self . log . error ( "Failed to add documents to Elasticsearc... |
def help ( self , * args ) :
"""Get help for a remote interface method .
Examples
help ( ' ginga ' , ` method ` )
name of the method for which you want help
help ( ' channel ' , ` chname ` , ` method ` )
name of the method in the channel for which you want help
Returns
help : string
a help message""... | if len ( args ) == 0 :
return help_msg
which = args [ 0 ] . lower ( )
if which == 'ginga' :
method = args [ 1 ]
_method = getattr ( self . fv , method )
return _method . __doc__
elif which == 'channel' :
chname = args [ 1 ]
method = args [ 2 ]
chinfo = self . fv . get_channel ( chname )
... |
def exist ( self , table : str , libref : str = "" ) -> bool :
"""Does the SAS data set currently exist
: param table : the name of the SAS Data Set
: param libref : the libref for the Data Set , defaults to WORK , or USER if assigned
: return : Boolean True it the Data Set exists and False if it does not
:... | return self . _io . exist ( table , libref ) |
def gettrace ( self , burn = 0 , thin = 1 , chain = - 1 , slicing = None ) :
"""Return the trace ( last by default ) .
: Parameters :
burn : integer
The number of transient steps to skip .
thin : integer
Keep one in thin .
chain : integer
The index of the chain to fetch . If None , return all chains .... | # XXX : handle chain = = None case properly
if chain is None :
chain = - 1
chain = self . db . chains [ chain ]
arr = self . db . _arrays [ chain , self . name ]
if slicing is not None :
burn , stop , thin = slicing . start , slicing . stop , slicing . step
if slicing is None or stop is None :
stop = arr . ... |
def walk ( self , cli ) :
"""Walk through children .""" | yield self
for i in self . content . walk ( cli ) :
yield i
for f in self . floats :
for i in f . content . walk ( cli ) :
yield i |
def oath ( ctx , password ) :
"""Manage OATH Application .
Examples :
Generate codes for credentials starting with ' yubi ' :
$ ykman oath code yubi
Add a touch credential with the secret key f5up4ub3dw and the name yubico :
$ ykman oath add yubico f5up4ub3dw - - touch
Set a password for the OATH applic... | try :
controller = OathController ( ctx . obj [ 'dev' ] . driver )
ctx . obj [ 'controller' ] = controller
ctx . obj [ 'settings' ] = Settings ( 'oath' )
except APDUError as e :
if e . sw == SW . NOT_FOUND :
ctx . fail ( "The OATH application can't be found on this YubiKey." )
raise
if passw... |
def rgb2short ( r , g , b ) :
"""Converts RGB values to the nearest equivalent xterm - 256 color .""" | # Using list of snap points , convert RGB value to cube indexes
r , g , b = [ len ( tuple ( s for s in snaps if s < x ) ) for x in ( r , g , b ) ]
# Simple colorcube transform
return ( r * 36 ) + ( g * 6 ) + b + 16 |
def coresight_write ( self , reg , data , ap = True ) :
"""Writes an Ap / DP register on a CoreSight DAP .
Note :
` ` coresight _ configure ( ) ` ` must be called prior to calling this method .
Args :
self ( JLink ) : the ` ` JLink ` ` instance
reg ( int ) : index of DP / AP register to write
data ( int... | ap = 1 if ap else 0
res = self . _dll . JLINKARM_CORESIGHT_WriteAPDPReg ( reg , ap , data )
if res < 0 :
raise errors . JLinkException ( res )
return res |
def put ( self , filename , chunkIdx , totalChunks ) :
"""stores a chunk of new file , this is a nop if the file already exists .
: param filename : the filename .
: param chunkIdx : the chunk idx .
: param totalChunks : the no of chunks expected .
: return : the no of bytes written and 200 or 400 if nothin... | logger . info ( 'handling chunk ' + chunkIdx + ' of ' + totalChunks + ' for ' + filename )
import flask
bytesWritten = self . _uploadController . writeChunk ( flask . request . stream , filename , int ( chunkIdx ) )
return str ( bytesWritten ) , 200 if bytesWritten > 0 else 400 |
def _split_into_symbol_words ( sym ) :
"""Split a technical looking word into a set of symbols .
This handles cases where technical words are separated by dots or
arrows , as is the convention in many programming languages .""" | punc = r"[\s\-\*/\+\.,:\;=\)\(\[\]\{\}<>\|\?&\^\$@]"
words = [ w . strip ( ) for w in re . split ( punc , sym ) ]
return words |
def _nodup_filter ( self , min_hash , all_urls , max_sample = 200 ) :
"""This filters results that are considered not duplicates .
But we really need to check that , because lsh . query does not always
return ALL duplicates , esp . when there are a lot of them , so
here we double - check and return only urls ... | if not all_urls :
return 0
urls = random . sample ( all_urls , max_sample ) if len ( all_urls ) > max_sample else all_urls
filtered = [ url for url in urls if min_hash . jaccard ( self . seen_urls [ url ] . min_hash ) < self . jaccard_threshold ]
return int ( len ( filtered ) / len ( urls ) * len ( all_urls ) ) |
def with_args ( self , ** kwargs ) :
"""String substitution for names and docstrings .""" | validators = [ validator . with_args ( ** kwargs ) if hasattr ( validator , 'with_args' ) else validator for validator in self . validators ]
return mutablerecords . CopyRecord ( self , name = util . format_string ( self . name , kwargs ) , docstring = util . format_string ( self . docstring , kwargs ) , validators = v... |
def fetch ( self ) :
"""Fetch a TaskQueueInstance
: returns : Fetched TaskQueueInstance
: rtype : twilio . rest . taskrouter . v1 . workspace . task _ queue . TaskQueueInstance""" | params = values . of ( { } )
payload = self . _version . fetch ( 'GET' , self . _uri , params = params , )
return TaskQueueInstance ( self . _version , payload , workspace_sid = self . _solution [ 'workspace_sid' ] , sid = self . _solution [ 'sid' ] , ) |
def multipart_encode ( params , boundary = None , cb = None ) :
"""Encode ` ` params ` ` as multipart / form - data .
` ` params ` ` should be a sequence of ( name , value ) pairs or MultipartParam
objects , or a mapping of names to values .
Values are either strings parameter values , or file - like objects ... | if boundary is None :
boundary = gen_boundary ( )
else :
boundary = urllib . quote_plus ( boundary )
headers = get_headers ( params , boundary )
params = MultipartParam . from_params ( params )
return MultipartYielder ( params , boundary , cb ) , headers |
def build_permuted_index ( self ) :
"""Build PermutedIndex for all your binary hashings .
PermutedIndex would be used to find the neighbour bucket key
in terms of Hamming distance . Permute _ configs is nested dict
in the following format :
permuted _ config = { " < hash _ name > " :
{ " num _ permutation... | for child_hash in self . child_hashes : # Get config values for child hash
config = child_hash [ 'config' ]
num_permutation = config [ 'num_permutation' ]
beam_size = config [ 'beam_size' ]
num_neighbour = config [ 'num_neighbour' ]
# Get used buckets keys for child hash
bucket_keys = child_hash... |
def pre_filter ( self ) :
"""Return rTorrent condition to speed up data transfer .""" | if self . _name in self . PRE_FILTER_FIELDS :
if not self . _value :
return '"not=${}"' . format ( self . PRE_FILTER_FIELDS [ self . _name ] )
else :
val = self . _value
if self . _exact :
val = val . copy ( ) . pop ( )
return r'"string.contains_i=${},\"{}\""' . forma... |
def get_applicable_overlays ( self , error_bundle ) :
"""Given an error bundle , a list of overlays that are present in the
current package or subpackage are returned .""" | content_paths = self . get_triples ( subject = 'content' )
if not content_paths :
return set ( )
# Create some variables that will store where the applicable content
# instruction path references and where it links to .
chrome_path = ''
content_root_path = '/'
# Look through each of the listed packages and paths .
... |
def _set_options ( ) :
"""Set the options for CleanCommand .
There are a number of reasons that this has to be done in an
external function instead of inline in the class . First of all ,
the setuptools machinery really wants the options to be defined
in a class attribute - otherwise , the help command does... | CleanCommand . user_options = _CleanCommand . user_options [ : ]
CleanCommand . user_options . extend ( [ ( 'dist' , 'd' , 'remove distribution directory' ) , ( 'eggs' , None , 'remove egg and egg-info directories' ) , ( 'environment' , 'E' , 'remove virtual environment directory' ) , ( 'pycache' , 'p' , 'remove __pyca... |
def get_recurring_events ( self , calendar_id , event_id , start_time , end_time , maxResults = None ) :
'''A wrapper for events ( ) . instances . Returns the list of recurring events for the given calendar alias within the specified timeframe .''' | es = [ ]
page_token = None
while True :
events = self . service . events ( ) . instances ( calendarId = self . configured_calendar_ids [ calendar_id ] , eventId = event_id , pageToken = page_token , timeMin = start_time , timeMax = end_time , maxResults = maxResults , showDeleted = False ) . execute ( )
for eve... |
def emit_db_sequence_updates ( self ) :
"""Set database sequence objects to match the source db
Relevant only when generated from SQLAlchemy connection .
Needed to avoid subsequent unique key violations after DB build .""" | if self . source . db_engine and self . source . db_engine . name != 'postgresql' : # not implemented for other RDBMS ; necessity unknown
conn = self . source . db_engine . connect ( )
qry = """SELECT 'SELECT last_value FROM ' || n.nspname || '.' || c.relname || ';'
FROM pg_namespace n
... |
def is_form_get ( attr , attrs ) :
"""Check if this is a GET form action URL .""" | res = False
if attr == "action" :
method = attrs . get_true ( 'method' , u'' ) . lower ( )
res = method != 'post'
return res |
def systemInformationType2ter ( ) :
"""SYSTEM INFORMATION TYPE 2ter Section 9.1.34""" | a = L2PseudoLength ( l2pLength = 0x12 )
b = TpPd ( pd = 0x6 )
c = MessageType ( mesType = 0x3 )
# 0000011
d = NeighbourCellsDescription2 ( )
e = Si2terRestOctets ( )
packet = a / b / c / d / e
return packet |
def build_application_map ( vertices_applications , placements , allocations , core_resource = Cores ) :
"""Build a mapping from application to a list of cores where the
application is used .
This utility function assumes that each vertex is associated with a
specific application .
Parameters
vertices _ a... | application_map = defaultdict ( lambda : defaultdict ( set ) )
for vertex , application in iteritems ( vertices_applications ) :
chip_cores = application_map [ application ] [ placements [ vertex ] ]
core_slice = allocations [ vertex ] . get ( core_resource , slice ( 0 , 0 ) )
chip_cores . update ( range ( ... |
def destroy_label ( self , label , callback = dummy_progress_cb ) :
"""Remove the label ' label ' from all the documents . Takes care of updating
the index .""" | current = 0
total = self . index . get_nb_docs ( )
self . index . start_destroy_label ( label )
while True :
( op , doc ) = self . index . continue_destroy_label ( )
if op == 'end' :
break
callback ( current , total , self . LABEL_STEP_DESTROYING , doc )
current += 1
self . index . end_destroy_l... |
def set ( self , key , value ) :
"""Set a value in the ` Bison ` configuration .
Args :
key ( str ) : The configuration key to set a new value for .
value : The value to set .""" | # the configuration changes , so we invalidate the cached config
self . _full_config = None
self . _override [ key ] = value |
def get_compiler_flags ( self ) :
"""Give the current compiler flags by looking for _ Feature instances
in the globals .""" | flags = 0
for value in self . get_globals ( ) . values ( ) :
if isinstance ( value , __future__ . _Feature ) :
flags |= value . compiler_flag
return flags |
def from_env ( key : str , default : T = None ) -> Union [ str , Optional [ T ] ] :
"""Shortcut for safely reading environment variable .
: param key : Environment var key .
: param default :
Return default value if environment var not found by given key . By
default : ` ` None ` `""" | return os . getenv ( key , default ) |
def thermostat_state ( self , name ) :
"""Changes the thermostat state to the one passed as an argument as name
: param name : The name of the thermostat state to change to .""" | self . _validate_thermostat_state_name ( name )
id_ = next ( ( key for key in STATES . keys ( ) if STATES [ key ] . lower ( ) == name . lower ( ) ) , None )
data = copy . copy ( self . _parameters )
data . update ( { 'state' : 2 , 'temperatureState' : id_ } )
response = self . _get_data ( '/client/auth/schemeState' , d... |
def covars_ ( self ) :
"""Return covars as a full matrix .""" | return fill_covars ( self . _covars_ , self . covariance_type , self . n_components , self . n_features ) |
def redirects ( self ) :
"""list : List of all redirects to this page ; * * i . e . , * * the titles listed here will redirect to this page title
Note :
Not settable""" | if self . _redirects is None :
self . _redirects = list ( )
self . __pull_combined_properties ( )
return self . _redirects |
def logout ( self , refresh_token ) :
"""The logout endpoint logs out the authenticated user .
: param str refresh _ token :""" | return self . _realm . client . post ( self . get_url ( 'end_session_endpoint' ) , data = { 'refresh_token' : refresh_token , 'client_id' : self . _client_id , 'client_secret' : self . _client_secret } ) |
def get_selected ( self ) :
'''返回选中要下载的文件的编号及sha1值 , 从1开始计数 .''' | selected_idx = [ ]
for i , row in enumerate ( self . liststore ) :
if row [ CHECK_COL ] :
selected_idx . append ( i + 1 )
return ( selected_idx , self . file_sha1 ) |
def _dumps ( cnf , ** kwargs ) :
""": param cnf : Configuration data to dump
: param kwargs : optional keyword parameters to be sanitized : : dict
: return : String representation of ' cnf ' object in INI format""" | return os . linesep . join ( l for l in _dumps_itr ( cnf ) ) |
def validate_args ( ** args ) :
"""function to check if input query is not None
and set missing arguments to default value""" | if not args [ 'query' ] :
print ( "\nMissing required query argument." )
sys . exit ( )
for key in DEFAULTS :
if key not in args :
args [ key ] = DEFAULTS [ key ]
return args |
def _get_next_line_indent_delta ( self , newline_token ) :
"""Returns the change in indentation . The return units are in
indentations rather than spaces / tabs .
If the next line ' s indent isn ' t relevant ( e . g . it ' s a comment ) ,
returns None . Since the return value might be 0 , the caller should
... | assert newline_token . type == 'NEWLINE' , 'Can only search for a dent starting from a newline.'
next_line_pos = newline_token . lexpos + len ( newline_token . value )
if next_line_pos == len ( newline_token . lexer . lexdata ) : # Reached end of file
return None
line = newline_token . lexer . lexdata [ next_line_p... |
def unmarshal_json ( obj , cls , allow_extra_keys = True , ctor = None , ) :
"""Unmarshal @ obj into @ cls
Args :
obj : dict , A JSON object
cls : type , The class to unmarshal into
allow _ extra _ keys : bool , False to raise an exception when extra
keys are present , True to ignore
ctor : None - or - ... | return unmarshal_dict ( obj , cls , allow_extra_keys , ctor = ctor , ) |
def _handle_incoming_event ( self ) :
"""Handle an incoming event .
Returns True if further messages should be received , False otherwise
( it should quit , that is ) .
TODO : Move the content of this function into ` _ handle _ one _ message ` .
This class function does not simply handle incoming events .""... | eventstr = self . query_socket . recv ( )
newid = self . id_generator . generate ( )
# Make sure newid is not part of our request vocabulary
assert newid not in ( b"QUERY" , b"PUBLISH" ) , "Generated ID must not be part of req/rep vocabulary."
assert not newid . startswith ( "ERROR" ) , "Generated ID must not be part o... |
def get_inasafe_default_values ( self ) :
"""Return inasafe default from the current wizard state .
: returns : Dictionary of key and value from InaSAFE Default Values .
: rtype : dict""" | inasafe_default_values = { }
parameters = self . parameter_container . get_parameters ( True )
for parameter in parameters :
if parameter . default is not None :
inasafe_default_values [ parameter . guid ] = parameter . default
return inasafe_default_values |
def _create_navigator ( self , response , raise_exc = True ) :
'''Create the appropriate navigator from an api response''' | method = response . request . method
# TODO : refactor once hooks in place
if method in ( POST , PUT , PATCH , DELETE ) and response . status_code in ( http_client . CREATED , http_client . FOUND , http_client . SEE_OTHER , http_client . NO_CONTENT ) and 'Location' in response . headers :
uri = urlparse . urljoin (... |
def classes_and_not_datetimelike ( * klasses ) :
"""evaluate if the tipo is a subclass of the klasses
and not a datetimelike""" | return lambda tipo : ( issubclass ( tipo , klasses ) and not issubclass ( tipo , ( np . datetime64 , np . timedelta64 ) ) ) |
def ordi ( item , inset ) :
"""The function returns the ordinal position of any given item in an
integer set . If the item does not appear in the set , the function
returns - 1.
http : / / naif . jpl . nasa . gov / pub / naif / toolkit _ docs / C / cspice / ordi _ c . html
: param item : An item to locate w... | assert isinstance ( inset , stypes . SpiceCell )
assert inset . is_int ( )
assert isinstance ( item , int )
item = ctypes . c_int ( item )
return libspice . ordi_c ( item , ctypes . byref ( inset ) ) |
def zulu ( ts = None , ms = True ) :
'''Returns the specified epoch time ( or current time if None or not
provided ) as an ISO 8601 string in zulu time ( with millisecond
precision ) , e . g . zulu ( 1362187446.553 ) = > ' 2013-03-02T01:24:06.553Z ' .
If ` ms ` is True ( the default ) , milliseconds will be i... | if ts is None :
ts = time . time ( )
ms = '.%03dZ' % ( ts * 1000 % 1000 , ) if ms else 'Z'
return time . strftime ( '%Y-%m-%dT%H:%M:%S' , time . gmtime ( ts ) ) + ms |
def get_mask ( self , tag = None , field = None ) :
"""Get the mask for all fields which exist in the current bit field .
Parameters
tag : str
Optionally specifies that the mask should only include fields with
the specified tag .
field : str
Optionally specifies that the mask should only include the
s... | if tag is not None and field is not None :
raise TypeError ( "get_mask() takes exactly one keyword argument, " "either 'field' or 'tag' (both given)" )
selected_fields = self . _select_by_field_or_tag ( tag , field )
# Build the mask ( and throw an exception if we encounter a field
# without a fixed size / length .... |
def render_template ( template_name , context ) :
"""Render a jinja template""" | return Environment ( loader = PackageLoader ( 'remarkable' ) ) . get_template ( template_name ) . render ( context ) |
def _handle_start_relation ( self , attrs ) :
"""Handle opening relation element
: param attrs : Attributes of the element
: type attrs : Dict""" | self . _curr = { 'attributes' : dict ( attrs ) , 'members' : [ ] , 'rel_id' : None , 'tags' : { } }
if attrs . get ( 'id' , None ) is not None :
self . _curr [ 'rel_id' ] = int ( attrs [ 'id' ] )
del self . _curr [ 'attributes' ] [ 'id' ] |
def arbanglemap ( self ) :
'''here ' s the center angle of each pixel ( + then - to go from biggest to
smallest angle ) ( e . g . 94.5 deg to 85.5 deg . - - sweeping left to right )''' | # raySpacingDeg = self . arbfov / self . nCutPix
maxAng = self . boresightEl + self . arbfov / 2
minAng = self . boresightEl - self . arbfov / 2
angles = np . linspace ( maxAng , minAng , num = self . ncutpix , endpoint = True )
assert np . isclose ( angles [ 0 ] , maxAng ) & np . isclose ( angles [ - 1 ] , minAng )
re... |
def parse_from_parent ( self , parent , # type : ET . Element
state # type : _ ProcessorState
) : # type : ( . . . ) - > Any
"""Parse the aggregate from the provided parent XML element .""" | parsed_dict = self . _dictionary . parse_from_parent ( parent , state )
return self . _converter . from_dict ( parsed_dict ) |
async def zadd ( self , name , * args , ** kwargs ) :
"""Set any number of score , element - name pairs to the key ` ` name ` ` . Pairs
can be specified in two ways :
As * args , in the form of : score1 , name1 , score2 , name2 , . . .
or as * * kwargs , in the form of : name1 = score1 , name2 = score2 , . . ... | pieces = [ ]
if args :
if len ( args ) % 2 != 0 :
raise RedisError ( "ZADD requires an equal number of " "values and scores" )
pieces . extend ( args )
for pair in iteritems ( kwargs ) :
pieces . append ( pair [ 1 ] )
pieces . append ( pair [ 0 ] )
return await self . execute_command ( 'ZADD' , ... |
def _gluster_output_cleanup ( result ) :
'''Gluster versions prior to 6 have a bug that requires tricking
isatty . This adds " gluster > " to the output . Strip it off and
produce clean xml for ElementTree .''' | ret = ''
for line in result . splitlines ( ) :
if line . startswith ( 'gluster>' ) :
ret += line [ 9 : ] . strip ( )
elif line . startswith ( 'Welcome to gluster prompt' ) :
pass
else :
ret += line . strip ( )
return ret |
def resize ( self , dims ) :
"""Resize our drawing area to encompass a space defined by the
given dimensions .""" | width , height = dims [ : 2 ]
self . dims = ( width , height )
self . logger . debug ( "renderer reconfigured to %dx%d" % ( width , height ) )
# create agg surface the size of the window
self . surface = agg . Draw ( self . rgb_order , self . dims , 'black' ) |
def flatten_grad ( func ) :
r"""Decorator to flatten structured gradients .
Examples
> > > def cost ( w , lambda _ ) :
. . . sq _ norm = w . T . dot ( w )
. . . return lambda _ * w , . 5 * sq _ norm
> > > grad = cost ( np . array ( [ . 5 , . 1 , - . 2 ] ) , . 25)
> > > len ( grad )
> > > grad _ w , gr... | @ wraps ( func )
def new_func ( * args , ** kwargs ) :
return flatten ( func ( * args , ** kwargs ) , returns_shapes = False )
return new_func |
def retry ( self , retries = 3 , backoff_factor = 0.3 , status_forcelist = ( 500 , 502 , 504 ) ) :
"""Add retry to Requests Session
https : / / urllib3 . readthedocs . io / en / latest / reference / urllib3 . util . html # urllib3 . util . retry . Retry""" | retries = Retry ( total = retries , read = retries , connect = retries , backoff_factor = backoff_factor , status_forcelist = status_forcelist , )
# mount all https requests
self . mount ( 'https://' , adapters . HTTPAdapter ( max_retries = retries ) ) |
def delete ( self ) :
"""Deletes the records in the current QuerySet .""" | del_query = self . _clone ( )
# The delete is actually 2 queries - one to find related objects ,
# and one to delete . Make sure that the discovery of related
# objects is performed on the same database as the deletion .
del_query . _clear_ordering ( )
get_es_connection ( self . es_url , self . es_kwargs ) . delete_by_... |
def get_roots ( self ) :
"""Gets the root nodes of this hierarchy .
return : ( osid . id . IdList ) - the root nodes
raise : OperationFailed - unable to complete request
raise : PermissionDenied - authorization failure
* compliance : mandatory - - This method must be implemented . *""" | id_list = [ ]
for r in self . _rls . get_relationships_by_genus_type_for_source ( self . _phantom_root_id , self . _relationship_type ) :
id_list . append ( r . get_destination_id ( ) )
return IdList ( id_list ) |
def get_asset_notification_session ( self , asset_receiver , proxy ) :
"""Gets the notification session for notifications pertaining to
asset changes .
arg : asset _ receiver ( osid . repository . AssetReceiver ) : the
notification callback
arg proxy ( osid . proxy . Proxy ) : a proxy
return : ( osid . re... | if asset_receiver is None :
raise NullArgument ( )
if not self . supports_asset_notification ( ) :
raise Unimplemented ( )
try :
from . import sessions
except ImportError :
raise
# OperationFailed ( )
proxy = self . _convert_proxy ( proxy )
try :
session = sessions . AssetNotificationSession ( a... |
def calculate_path ( self , remote_relative_path , input_type ) :
"""Only for used by Pulsar client , should override for managers to
enforce security and make the directory if needed .""" | directory , allow_nested_files = self . _directory_for_file_type ( input_type )
return self . path_helper . remote_join ( directory , remote_relative_path ) |
def get_organisational_tags_to_task ( self ) :
"""This build a dict for fast retrive tasks id based on organisational tags . The form of the dict is :
{ ' org _ tag _ 1 ' : [ ' task _ id ' , ' task _ id ' , . . . ] ,
' org _ tag _ 2 ' : [ ' task _ id ' , ' task _ id ' , . . . ] ,""" | if self . _organisational_tags_to_task != { } :
return self . _organisational_tags_to_task
for taskid , task in self . get_tasks ( ) . items ( ) :
for tag in task . get_tags ( ) [ 2 ] :
self . _organisational_tags_to_task . setdefault ( tag . get_name ( ) , [ ] ) . append ( taskid )
return self . _organ... |
def exist ( name ) :
'''Return True if the chroot environment is present .''' | dev = os . path . join ( name , 'dev' )
proc = os . path . join ( name , 'proc' )
return all ( os . path . isdir ( i ) for i in ( name , dev , proc ) ) |
def dup ( self , other = None , ** kwds ) :
'''Duplicate attributes of dict or other typedef .''' | if other is None :
d = _dict_typedef . kwds ( )
else :
d = other . kwds ( )
d . update ( kwds )
self . reset ( ** d ) |
def is_tuple ( obj , len_ = None ) :
"""Checks whether given object is a tuple .
: param len _ : Optional expected length of the tuple
: return : ` ` True ` ` if argument is a tuple ( of given length , if any ) ,
` ` False ` ` otherwise""" | if not isinstance ( obj , tuple ) :
return False
if len_ is None :
return True
if not isinstance ( len_ , Integral ) :
raise TypeError ( "length must be a number (got %s instead)" % type ( len_ ) . __name__ )
if len_ < 0 :
raise ValueError ( "length must be positive (got %s instead)" % len_ )
return len... |
def fromexporterror ( cls , bundle , exporterid , rsid , exception , endpoint ) : # type : ( Bundle , Tuple [ str , str ] , Tuple [ Tuple [ str , str ] , int ] , Optional [ Tuple [ Any , Any , Any ] ] , EndpointDescription ) - > RemoteServiceAdminEvent
"""Creates a RemoteServiceAdminEvent object from an export erro... | return RemoteServiceAdminEvent ( RemoteServiceAdminEvent . EXPORT_ERROR , bundle , exporterid , rsid , None , None , exception , endpoint , ) |
def requested ( self , user , include = None ) :
"""Retrieve the requested tickets for this user .
: param include : list of objects to sideload . ` Side - loading API Docs
< https : / / developer . zendesk . com / rest _ api / docs / core / side _ loading > ` _ _ .
: param user : User object or id""" | return self . _query_zendesk ( self . endpoint . requested , 'ticket' , id = user , include = include ) |
def ip_prefixes_sanity_check ( config , bird_configuration ) :
"""Sanity check on IP prefixes .
Arguments :
config ( obg ) : A configparser object which holds our configuration .
bird _ configuration ( dict ) : A dictionary , which holds Bird configuration
per IP protocol version .""" | for ip_version in bird_configuration :
modify_ip_prefixes ( config , bird_configuration [ ip_version ] [ 'config_file' ] , bird_configuration [ ip_version ] [ 'variable_name' ] , bird_configuration [ ip_version ] [ 'dummy_ip_prefix' ] , bird_configuration [ ip_version ] [ 'reconfigure_cmd' ] , bird_configuration [ ... |
def list_contents ( self ) :
"""List the contents of this directory
: return : A LsInfo object that contains directories and files
: rtype : : class : ` ~ . LsInfo ` or : class : ` ~ . ErrorInfo `
Here is an example usage : :
# let dirinfo be a DirectoryInfo object
ldata = dirinfo . list _ contents ( )
... | target = DeviceTarget ( self . device_id )
return self . _fssapi . list_files ( target , self . path ) [ self . device_id ] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.