signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def build ( self , builder ) :
"""Build XML by appending to builder
. . note : : Questions can contain translations""" | builder . start ( "Question" , { } )
for translation in self . translations :
translation . build ( builder )
builder . end ( "Question" ) |
def handle_data ( self , data ) :
'''handle _ data - Internal for parsing''' | if data :
inTag = self . _inTag
if len ( inTag ) > 0 :
if inTag [ - 1 ] . tagName not in PRESERVE_CONTENTS_TAGS :
data = data . replace ( '\t' , ' ' ) . strip ( '\r\n' )
if data . startswith ( ' ' ) :
data = ' ' + data . lstrip ( )
if data . endswith (... |
def get_login_information ( self , code = None ) :
"""Return Clef user info after exchanging code for OAuth token .""" | # do the handshake to get token
access_token = self . _get_access_token ( code )
# make request with token to get user details
return self . _get_user_info ( access_token ) |
def _training_stats ( self ) :
"""Return a dictionary of statistics collected during creation of the
model . These statistics are also available with the ` ` get ` ` method and
are described in more detail in that method ' s documentation .
Returns
out : dict
Dictionary of statistics compiled during creat... | fields = self . _list_fields ( )
stat_fields = [ 'training_time' , 'training_iterations' ]
if 'validation_perplexity' in fields :
stat_fields . append ( 'validation_perplexity' )
ret = { k : self . _get ( k ) for k in stat_fields }
return ret |
def get ( self , field = None , index = None , lpar = 0 , prompt = 1 , native = 0 , mode = "h" ) :
"""Return value of this parameter as a string ( or in native format
if native is non - zero . )""" | if field :
return self . _getField ( field , native = native , prompt = prompt )
# may prompt for value if prompt flag is set
# XXX should change _ optionalPrompt so we prompt for each element of
# XXX the array separately ? I think array parameters are
# XXX not useful as non - hidden params .
if prompt :
self... |
def parse_date ( string , force_datetime = False ) :
"""Takes a Xero formatted date , e . g . / Date ( 1426849200000 + 1300 ) /""" | matches = DATE . match ( string )
if not matches :
return None
values = dict ( [ ( k , v if v [ 0 ] in '+-' else int ( v ) ) for k , v in matches . groupdict ( ) . items ( ) if v and int ( v ) ] )
if 'timestamp' in values :
value = datetime . datetime . utcfromtimestamp ( 0 ) + datetime . timedelta ( hours = in... |
def get_references ( basis_name , elements = None , version = None , fmt = None , data_dir = None ) :
'''Get the references / citations for a basis set
Parameters
basis _ name : str
Name of the basis set . This is not case sensitive .
elements : list
List of element numbers that you want the basis set for... | data_dir = fix_data_dir ( data_dir )
basis_dict = get_basis ( basis_name , elements = elements , version = version , data_dir = data_dir )
all_ref_data = get_reference_data ( data_dir )
ref_data = references . compact_references ( basis_dict , all_ref_data )
if fmt is None :
return ref_data
return refconverters . c... |
def _pad_data ( self , index_len ) :
"""Pad the data in Series with [ None ] to ensure that data is the same length as index
: param index _ len : length of index to extend data to
: return : nothing""" | self . _data . extend ( [ None ] * ( index_len - len ( self . _data ) ) ) |
def get_secret ( self , secure_data_path , key , version = None ) :
"""( Deprecated ) Return the secret based on the secure data path and key
This method is deprecated because it misleads users into thinking they ' re only getting one value from Cerberus
when in reality they ' re getting all values , from which... | warnings . warn ( "get_secret is deprecated, use get_secrets_data instead" , DeprecationWarning )
secret_resp_json = self . _get_secrets ( secure_data_path , version )
if key in secret_resp_json [ 'data' ] :
return secret_resp_json [ 'data' ] [ key ]
else :
raise CerberusClientException ( "Key '%s' not found" %... |
def zincr ( self , name , key , amount = 1 ) :
"""Increase the score of ` ` key ` ` in zset ` ` name ` ` by ` ` amount ` ` . If no key
exists , the value will be initialized as ` ` amount ` `
Like * * Redis . ZINCR * *
: param string name : the zset name
: param string key : the key name
: param int amoun... | amount = get_integer ( 'amount' , amount )
return self . execute_command ( 'zincr' , name , key , amount ) |
def on_train_end ( self , ** kwargs : Any ) -> None :
"Store the notebook and stop run" | self . client . log_artifact ( run_id = self . run , local_path = self . nb_path )
self . client . set_terminated ( run_id = self . run ) |
def _checkConflictingNames ( interfaces ) :
"""Raise an exception if any of the names present in the given interfaces
conflict with each other .
@ param interfaces : a list of Zope Interface objects .
@ return : None
@ raise ConflictingNames : if any of the attributes of the provided
interfaces are the sa... | names = { }
for interface in interfaces :
for name in interface :
if name in names :
otherInterface = names [ name ]
parent = _commonParent ( interface , otherInterface )
if parent is None or name not in parent :
raise ConflictingNames ( "%s conflicts with... |
def _translate_symbols ( string ) :
"""Given a description of a Greek letter or other special character ,
return the appropriate unicode letter .""" | res = [ ]
string = str ( string )
for s in re . split ( r'(\W+)' , string , flags = re . UNICODE ) :
tex_str = _GREEK_DICTIONARY . get ( s )
if tex_str :
res . append ( tex_str )
elif s . lower ( ) in _GREEK_DICTIONARY :
res . append ( _GREEK_DICTIONARY [ s ] )
else :
res . appen... |
def get_coding ( text , force_chardet = False ) :
"""Function to get the coding of a text .
@ param text text to inspect ( string )
@ return coding string""" | if not force_chardet :
for line in text . splitlines ( ) [ : 2 ] :
try :
result = CODING_RE . search ( to_text_string ( line ) )
except UnicodeDecodeError : # This could fail because to _ text _ string assume the text
# is utf8 - like and we don ' t know the encoding to give
... |
def _convert_todo ( p_todo ) :
"""Converts a Todo instance to a dictionary .""" | creation_date = p_todo . creation_date ( )
completion_date = p_todo . completion_date ( )
result = { 'source' : p_todo . source ( ) , 'text' : p_todo . text ( ) , 'priority' : p_todo . priority ( ) , 'completed' : p_todo . is_completed ( ) , 'tags' : p_todo . tags ( ) , 'projects' : list ( p_todo . projects ( ) ) , 'co... |
def write_to_file ( path_file , callback ) :
"""Reads the content of the given file , puts the content into the callback and writes the result back to the file .
: param path _ file : the path to the file
: type path _ file : str
: param callback : the callback function
: type callback : function""" | try :
with open ( path_file , 'r+' , encoding = 'utf-8' ) as f :
content = callback ( f . read ( ) )
f . seek ( 0 )
f . write ( content )
f . truncate ( )
except Exception as e :
raise Exception ( 'unable to minify file %(file)s, exception was %(exception)r' % { 'file' : path_fil... |
def _get ( self , k , obj = None ) :
'Return Option object for k in context of obj . Cache result until any set ( ) .' | opt = self . _cache . get ( ( k , obj ) , None )
if opt is None :
opt = self . _opts . _get ( k , obj )
self . _cache [ ( k , obj or vd . sheet ) ] = opt
return opt |
def get_categories ( self ) :
"""Return a list of categories that a safe deposit box can belong to""" | sdb_resp = get_with_retry ( self . cerberus_url + '/v1/category' , headers = self . HEADERS )
throw_if_bad_response ( sdb_resp )
return sdb_resp . json ( ) |
def add_device ( self , device , container ) :
"""Add a device to a group . Wraps JSSObject . add _ object _ to _ path .
Args :
device : A JSSObject to add ( as list data ) , to this object .
location : Element or a string path argument to find ( )""" | # There is a size tag which the JSS manages for us , so we can
# ignore it .
if self . findtext ( "is_smart" ) == "false" :
self . add_object_to_path ( device , container )
else : # Technically this isn ' t true . It will strangely accept
# them , and they even show up as members of the group !
raise ValueError... |
def _spoken_representation_L2 ( lst_lst_char ) :
"""> > > lst = [ [ ' M ' , ' O ' , ' R ' , ' S ' , ' E ' ] , [ ' C ' , ' O ' , ' D ' , ' E ' ] ]
> > > _ spoken _ representation _ L2 ( lst )
' - - - - - . - . . . . . ( space ) - . - . - - - - . . . '""" | s = ''
inter_char = ' '
inter_word = ' (space) '
for i , word in enumerate ( lst_lst_char ) :
if i >= 1 :
s += inter_word
for j , c in enumerate ( word ) :
if j != 0 :
s += inter_char
s += mtalk . encoding . morsetab [ c ]
return s |
def get_transports ( ) :
"""get all known transports from Ariane Server
: return :""" | LOGGER . debug ( "TransportService.get_transports" )
params = SessionService . complete_transactional_req ( None )
if params is None :
if MappingService . driver_type != DriverFactory . DRIVER_REST :
params = { 'OPERATION' : 'getTransports' }
args = { 'properties' : params }
else :
args ... |
def _parse_pages ( self , unicode = False ) :
"""Auxiliary function to parse and format page range of a document .""" | if self . pageRange :
pages = 'pp. {}' . format ( self . pageRange )
elif self . startingPage :
pages = 'pp. {}-{}' . format ( self . startingPage , self . endingPage )
else :
pages = '(no pages found)'
if unicode :
pages = u'{}' . format ( pages )
return pages |
def contains_glob ( path , glob_expr ) :
'''. . deprecated : : 0.17.0
Use : func : ` search ` instead .
Return ` ` True ` ` if the given glob matches a string in the named file
CLI Example :
. . code - block : : bash
salt ' * ' file . contains _ glob / etc / foobar ' * cheese * ' ''' | path = os . path . expanduser ( path )
if not os . path . exists ( path ) :
return False
try :
with salt . utils . filebuffer . BufferedReader ( path ) as breader :
for chunk in breader :
if fnmatch . fnmatch ( chunk , glob_expr ) :
return True
return False
except ( I... |
def __in_choice_context ( self ) :
"""Whether we are currently processing a choice parameter group .
This includes processing a parameter defined directly or indirectly
within such a group .
May only be called during parameter processing or the result will be
calculated based on the context left behind by t... | for x in self . __stack :
if x . __class__ is ChoiceFrame :
return True
return False |
def vsclg ( s , v1 , ndim ) :
"""Multiply a scalar and a double precision vector of arbitrary dimension .
http : / / naif . jpl . nasa . gov / pub / naif / toolkit _ docs / C / cspice / vsclg _ c . html
: param s : Scalar to multiply a vector
: type s : float
: param v1 : Vector to be multiplied
: type v1... | s = ctypes . c_double ( s )
v1 = stypes . toDoubleVector ( v1 )
vout = stypes . emptyDoubleVector ( ndim )
ndim = ctypes . c_int ( ndim )
libspice . vsclg_c ( s , v1 , ndim , vout )
return stypes . cVectorToPython ( vout ) |
def relaxation_operators ( p ) :
"""Return the amplitude damping Kraus operators""" | k0 = np . array ( [ [ 1.0 , 0.0 ] , [ 0.0 , np . sqrt ( 1 - p ) ] ] )
k1 = np . array ( [ [ 0.0 , np . sqrt ( p ) ] , [ 0.0 , 0.0 ] ] )
return k0 , k1 |
def generate_X_grid ( self , term , n = 100 , meshgrid = False ) :
"""create a nice grid of X data
array is sorted by feature and uniformly spaced ,
so the marginal and joint distributions are likely wrong
if term is > = 0 , we generate n samples per feature ,
which results in n ^ deg samples ,
where deg ... | if not self . _is_fitted :
raise AttributeError ( 'GAM has not been fitted. Call fit first.' )
# cant do Intercept
if self . terms [ term ] . isintercept :
raise ValueError ( 'cannot create grid for intercept term' )
# process each subterm in a TensorTerm
if self . terms [ term ] . istensor :
Xs = [ ]
f... |
def copyNodeList ( self , node ) :
"""Do a recursive copy of the node list .""" | if node is None :
node__o = None
else :
node__o = node . _o
ret = libxml2mod . xmlDocCopyNodeList ( self . _o , node__o )
if ret is None :
raise treeError ( 'xmlDocCopyNodeList() failed' )
__tmp = xmlNode ( _obj = ret )
return __tmp |
def price_in_btc ( self , minimum : float = 0 , maximum : float = 2 ) -> str :
"""Generate random price in BTC .
: param minimum : Minimum value of price .
: param maximum : Maximum value of price .
: return : Price in BTC .""" | return '{} BTC' . format ( self . random . uniform ( minimum , maximum , precision = 7 , ) , ) |
def adjust_attributes_on_object ( self , collection , name , things , values , how ) :
"""adjust labels or annotations on object
labels have to match RE : ( ( [ A - Za - z0-9 ] [ - A - Za - z0-9 _ . ] * ) ? [ A - Za - z0-9 ] ) ? and
have at most 63 chars
: param collection : str , object collection e . g . ' ... | url = self . _build_url ( "%s/%s" % ( collection , name ) )
response = self . _get ( url )
logger . debug ( "before modification: %s" , response . content )
build_json = response . json ( )
how ( build_json [ 'metadata' ] , things , values )
response = self . _put ( url , data = json . dumps ( build_json ) , use_json =... |
def per_from_id_except ( s , flavors = chat_flavors + inline_flavors ) :
""": param s :
a list or set of from id
: param flavors :
` ` all ` ` or a list of flavors
: return :
a seeder function that returns the from id only if the from id is * not * in ` ` s ` `
and message flavor is in ` ` flavors ` ` .... | return _wrap_none ( lambda msg : msg [ 'from' ] [ 'id' ] if ( flavors == 'all' or flavor ( msg ) in flavors ) and msg [ 'from' ] [ 'id' ] not in s else None ) |
def Input_synthesizePinchGesture ( self , x , y , scaleFactor , ** kwargs ) :
"""Function path : Input . synthesizePinchGesture
Domain : Input
Method name : synthesizePinchGesture
WARNING : This function is marked ' Experimental ' !
Parameters :
Required arguments :
' x ' ( type : number ) - > X coordin... | assert isinstance ( x , ( float , int ) ) , "Argument 'x' must be of type '['float', 'int']'. Received type: '%s'" % type ( x )
assert isinstance ( y , ( float , int ) ) , "Argument 'y' must be of type '['float', 'int']'. Received type: '%s'" % type ( y )
assert isinstance ( scaleFactor , ( float , int ) ) , "Argument ... |
def call ( function , * args , ** kwargs ) :
"""Call a function or constructor with given args and kwargs after removing args and kwargs that doesn ' t match
function or constructor signature
: param function : Function or constructor to call
: type function : callable
: param args :
: type args :
: par... | func = constructor_args if inspect . isclass ( function ) else function_args
call_args , call_kwargs = func ( function , * args , ** kwargs )
return function ( * call_args , ** call_kwargs ) |
def get_required_config ( cls ) :
"""Roll up configuration options for this class and parent classes .
This handles subclasses overriding options in parent classes .
: returns : final ` ` ConfigOptions ` ` representing all configuration for
this class""" | options = ConfigOptions ( )
for cls in reversed ( cls . __mro__ ) :
try :
options . update ( cls . required_config )
except AttributeError :
pass
return options |
def _backward_sampling_ON ( self , M , idx ) :
"""O ( N ) version of backward sampling .
not meant to be called directly , see backward _ sampling""" | nattempts = 0
for t in reversed ( range ( self . T - 1 ) ) :
where_rejected = np . arange ( M )
who_rejected = self . X [ t + 1 ] [ idx [ t + 1 , : ] ]
nrejected = M
gen = rs . MultinomialQueue ( self . wgt [ t ] . W , M = M )
while nrejected > 0 :
nattempts += nrejected
nprop = gen ... |
def plot_feature_correlation_heatmap ( df , features , font_size = 9 , figsize = ( 15 , 15 ) , save_filename = None ) :
"""Plot a correlation heatmap between every feature pair .
Args :
df : Pandas dataframe containing the target column ( named ' target ' ) .
features : The list of features to include in the ... | features = features [ : ]
features += [ 'target' ]
mcorr = df [ features ] . corr ( )
mask = np . zeros_like ( mcorr , dtype = np . bool )
mask [ np . triu_indices_from ( mask ) ] = True
cmap = sns . diverging_palette ( 220 , 10 , as_cmap = True )
fig = plt . figure ( figsize = figsize )
heatmap = sns . heatmap ( mcorr... |
def packages ( state , host , packages = None , present = True , pkg_path = None ) :
'''Install / remove / update pkg _ * packages .
+ packages : list of packages to ensure
+ present : whether the packages should be installed
+ pkg _ path : the PKG _ PATH environment variable to set
pkg _ path :
By defaul... | if present is True : # Autogenerate package path
if not pkg_path :
host_os = host . fact . os or ''
pkg_path = 'http://ftp.{http}.org/pub/{os}/{version}/packages/{arch}/' . format ( http = host_os . lower ( ) , os = host_os , version = host . fact . os_version , arch = host . fact . arch , )
yield e... |
def _ratio_enum ( anchor , ratios ) :
"""Enumerate a set of anchors for each aspect ratio wrt an anchor .""" | w , h , x_ctr , y_ctr = AnchorGenerator . _whctrs ( anchor )
size = w * h
size_ratios = size / ratios
ws = np . round ( np . sqrt ( size_ratios ) )
hs = np . round ( ws * ratios )
anchors = AnchorGenerator . _mkanchors ( ws , hs , x_ctr , y_ctr )
return anchors |
def _align ( terms ) :
"""Align a set of terms""" | try : # flatten the parse tree ( a nested list , really )
terms = list ( com . flatten ( terms ) )
except TypeError : # can ' t iterate so it must just be a constant or single variable
if isinstance ( terms . value , pd . core . generic . NDFrame ) :
typ = type ( terms . value )
return typ , _zi... |
def sort ( self , field , direction = "asc" ) :
"""Adds sort criteria .""" | if not isinstance ( field , basestring ) :
raise ValueError ( "Field should be a string" )
if direction not in [ "asc" , "desc" ] :
raise ValueError ( "Sort direction should be `asc` or `desc`" )
self . sorts . append ( { field : direction } ) |
def event_return ( events ) :
'''Send the events to a mattermost room .
: param events : List of events
: return : Boolean if messages were sent successfully .''' | _options = _get_options ( )
api_url = _options . get ( 'api_url' )
channel = _options . get ( 'channel' )
username = _options . get ( 'username' )
hook = _options . get ( 'hook' )
is_ok = True
for event in events :
log . debug ( 'Event: %s' , event )
log . debug ( 'Event data: %s' , event [ 'data' ] )
messa... |
def three_dim_props ( event ) :
"""Get information for a pick event on a 3D artist .
Parameters
event : PickEvent
The pick event to process
Returns
A dict with keys :
` x ` : The estimated x - value of the click on the artist
` y ` : The estimated y - value of the click on the artist
` z ` : The est... | ax = event . artist . axes
if ax . M is None :
return { }
xd , yd = event . mouseevent . xdata , event . mouseevent . ydata
p = ( xd , yd )
edges = ax . tunit_edges ( )
ldists = [ ( mplot3d . proj3d . line2d_seg_dist ( p0 , p1 , p ) , i ) for i , ( p0 , p1 ) in enumerate ( edges ) ]
ldists . sort ( )
# nearest edge... |
def _pull_out_perm_rhs ( rest , rhs , out_port , in_port ) :
"""Similar to : func : ` _ pull _ out _ perm _ lhs ` but on the RHS of a series
product self - feedback .""" | in_im , rhs_red = rhs . _factor_rhs ( in_port )
return ( Feedback . create ( SeriesProduct . create ( * rest ) , out_port = out_port , in_port = in_im ) << rhs_red ) |
def rs_find_errata_locator ( e_pos , generator = 2 ) :
'''Compute the erasures / errors / errata locator polynomial from the erasures / errors / errata positions ( the positions must be relative to the x coefficient , eg : " hello worldxxxxx " is tampered to " h _ ll _ worldxxxxx " with xxxxx being the ecc of lengt... | # See : http : / / ocw . usu . edu / Electrical _ and _ Computer _ Engineering / Error _ Control _ Coding / lecture7 . pdf and Blahut , Richard E . " Transform techniques for error control codes . " IBM Journal of Research and development 23.3 ( 1979 ) : 299-315 . http : / / citeseerx . ist . psu . edu / viewdoc / down... |
def sort ( self , key = None , reverse = False ) :
"""Sort the items of this collection according to the optional callable
* key * . If * reverse * is set then the sort order is reversed .
. . note : :
This sort requires all items to be retrieved from Redis and stored
in memory .""" | def sort_trans ( pipe ) :
values = list ( self . __iter__ ( pipe ) )
values . sort ( key = key , reverse = reverse )
pipe . multi ( )
pipe . delete ( self . key )
pipe . rpush ( self . key , * ( self . _pickle ( v ) for v in values ) )
if self . writeback :
self . cache = { }
return self... |
def dq_name ( queue_name ) :
"""Returns the delayed queue name for a given queue . If the given
queue name already belongs to a delayed queue , then it is returned
unchanged .""" | if queue_name . endswith ( ".DQ" ) :
return queue_name
if queue_name . endswith ( ".XQ" ) :
queue_name = queue_name [ : - 3 ]
return queue_name + ".DQ" |
def pyephem_earthsun_distance ( time ) :
"""Calculates the distance from the earth to the sun using pyephem .
Parameters
time : pd . DatetimeIndex
Returns
pd . Series . Earth - sun distance in AU .""" | import ephem
sun = ephem . Sun ( )
earthsun = [ ]
for thetime in time :
sun . compute ( ephem . Date ( thetime ) )
earthsun . append ( sun . earth_distance )
return pd . Series ( earthsun , index = time ) |
def tobytes ( s , encoding = 'ascii' ) :
"""Convert string s to the ' bytes ' type , in all Pythons , even
back before Python 2.6 . What ' str ' means varies by PY3K or not .
In Pythons before 3.0 , this is technically the same as the str type
in terms of the character data in memory .""" | # NOTE : after we abandon 2.5 , we might simply instead use " bytes ( s ) "
# NOTE : after we abandon all 2 . * , del this and prepend byte strings with ' b '
if PY3K :
if isinstance ( s , bytes ) :
return s
else :
return s . encode ( encoding )
else : # for py2.6 on ( before 3.0 ) , bytes is sa... |
def load_child_sections_for_section ( context , section , count = None ) :
'''Returns all child sections
If the ` locale _ code ` in the context is not the main language , it will
return the translations of the live articles .''' | page = section . get_main_language_page ( )
locale = context . get ( 'locale_code' )
qs = SectionPage . objects . child_of ( page ) . filter ( language__is_main_language = True )
if not locale :
return qs [ : count ]
return get_pages ( context , qs , locale ) |
def h5_file_exists ( fname , size_guess = None , rtol = 0.1 , atol = 1. , dsets = { } ) :
"""Returns ` ` True ` ` if an HDF5 file exists , has the expected file size , and
contains ( at least ) the given datasets , with the correct shapes .
Args :
fname ( str ) : Filename to check .
size _ guess ( Optional ... | # Check if the file exists
if not os . path . isfile ( fname ) : # print ( ' File does not exist . ' )
return False
# Check file size , withe the given tolerances
if size_guess is not None :
size = os . path . getsize ( fname )
tol = atol + rtol * size_guess
if abs ( size - size_guess ) > tol : # print ... |
def generate_samples ( net : BayesNet , sample_from : Iterable [ Vertex ] , sampling_algorithm : PosteriorSamplingAlgorithm = None , drop : int = 0 , down_sample_interval : int = 1 , live_plot : bool = False , refresh_every : int = 100 , ax : Any = None ) -> sample_generator_types :
""": param net : Bayesian Networ... | sample_from = list ( sample_from )
id_to_label = __check_if_vertices_are_labelled ( sample_from )
if sampling_algorithm is None :
sampling_algorithm = MetropolisHastingsSampler ( proposal_distribution = "prior" , latents = sample_from )
vertices_unwrapped : JavaList = k . to_java_object_list ( sample_from )
probabi... |
def _set_constance_value ( key , value ) :
"""Parses and sets a Constance value from a string
: param key :
: param value :
: return :""" | form = ConstanceForm ( initial = get_values ( ) )
field = form . fields [ key ]
clean_value = field . clean ( field . to_python ( value ) )
setattr ( config , key , clean_value ) |
async def find_backwards ( self , stream_name , predicate , predicate_label = 'predicate' ) :
"""Return first event matching predicate , or None if none exists .
Note : ' backwards ' , both here and in Event Store , means ' towards the
event emitted furthest in the past ' .""" | logger = self . _logger . getChild ( predicate_label )
logger . info ( 'Fetching first matching event' )
uri = self . _head_uri
try :
page = await self . _fetcher . fetch ( uri )
except HttpNotFoundError as e :
raise StreamNotFoundError ( ) from e
while True :
evt = next ( page . iter_events_matching ( pred... |
def _add_sentence ( self , sentence , ignore_traces = True ) :
"""add a sentence from the input document to the document graph .
Parameters
sentence : nltk . tree . Tree
a sentence represented by a Tree instance""" | self . sentences . append ( self . _node_id )
# add edge from document root to sentence root
self . add_edge ( self . root , self . _node_id , edge_type = dg . EdgeTypes . dominance_relation )
self . _parse_sentencetree ( sentence , ignore_traces = ignore_traces )
self . _node_id += 1 |
def _distribution_info ( self ) :
"""Creates the distribution name and the expected extension for the
CSPICE package and returns it .
: return ( distribution , extension ) tuple where distribution is the best
guess from the strings available within the platform _ urls list
of strings , and extension is eith... | print ( 'Gathering information...' )
system = platform . system ( )
# Cygwin system is CYGWIN - NT - xxx .
system = 'cygwin' if 'CYGWIN' in system else system
processor = platform . processor ( )
machine = '64bit' if sys . maxsize > 2 ** 32 else '32bit'
print ( 'SYSTEM: ' , system )
print ( 'PROCESSOR:' , processor )... |
def __init ( self , folder = 'root' ) :
"""loads the property data into the class""" | params = { "f" : "json" }
if folder == "root" :
url = self . root
else :
url = self . location
json_dict = self . _get ( url = url , param_dict = params , securityHandler = self . _securityHandler , proxy_port = self . _proxy_port , proxy_url = self . _proxy_url )
self . _json_dict = json_dict
self . _json = js... |
def just_find_proxy ( pacfile , url , host = None ) :
"""This function is a wrapper around init , parse _ pac , find _ proxy
and cleanup . This is the function to call if you want to find
proxy just for one url .""" | if not os . path . isfile ( pacfile ) :
raise IOError ( 'Pac file does not exist: {}' . format ( pacfile ) )
init ( )
parse_pac ( pacfile )
proxy = find_proxy ( url , host )
cleanup ( )
return proxy |
def log_file_list_handler ( self , ** kwargs ) : # noqa : E501
"""log _ file _ list _ handler # noqa : E501
This method makes a synchronous HTTP request by default . To make an
asynchronous HTTP request , please pass async _ req = True
> > > thread = api . log _ file _ list _ handler ( async _ req = True )
... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'async_req' ) :
return self . log_file_list_handler_with_http_info ( ** kwargs )
# noqa : E501
else :
( data ) = self . log_file_list_handler_with_http_info ( ** kwargs )
# noqa : E501
return data |
def read ( path , encoding = "utf-8" ) :
"""Auto - decoding string reader .
Usage : :
> > > from angora . dataIO import textfile
or
> > > from angora . dataIO import *
> > > textfile . read ( " test . txt " )""" | with open ( path , "rb" ) as f :
content = f . read ( )
try :
text = content . decode ( encoding )
except :
res = chardet . detect ( content )
text = content . decode ( res [ "encoding" ] )
return text |
def pythonize ( self , val ) :
"""If value is a single list element just return the element
does nothing otherwise
: param val : value to convert
: type val :
: return : converted value
: rtype :""" | if isinstance ( val , list ) and len ( set ( val ) ) == 1 : # If we have a list with a unique value just use it
return val [ 0 ]
# Well , can ' t choose to remove something .
return val |
def to_file ( self , outputfile = DEFAULT_OUTPUTFILE ) :
"""Write the report to a file .
By default a name is generated .
Parameters :
outputfile : str
The name or the path of the file to generale including the extension ( . html ) .""" | if outputfile != NO_OUTPUTFILE :
if outputfile == DEFAULT_OUTPUTFILE :
outputfile = 'profile_' + str ( hash ( self ) ) + ".html"
# TODO : should be done in the template
with codecs . open ( outputfile , 'w+b' , encoding = 'utf8' ) as self . file :
self . file . write ( templates . template (... |
def load_obo_file ( self , obo_file , optional_attrs , load_obsolete , prt ) :
"""Read obo file . Store results .""" | reader = OBOReader ( obo_file , optional_attrs )
# Save alt _ ids and their corresponding main GO ID . Add to GODag after populating GO Terms
alt2rec = { }
for rec in reader : # Save record if :
# 1 ) Argument load _ obsolete is True OR
# 2 ) Argument load _ obsolete is False and the GO term is " live " ( not obsolete ... |
def implicit_step ( self ) :
"""Integrate one step using trapezoidal method . Sets convergence and niter flags .
Returns
None""" | config = self . config
system = self . system
dae = self . system . dae
# constant short names
In = spdiag ( [ 1 ] * dae . n )
h = self . h
while self . err > config . tol and self . niter < config . maxit :
if self . t - self . t_jac >= 5 :
dae . rebuild = True
self . t_jac = self . t
elif self... |
def exclude_paths ( args ) :
"""Returns the absolute paths for excluded path .""" | results = [ ]
if args . exclude :
for excl_path in args . exclude :
results . append ( os . path . abspath ( os . path . join ( args . root , excl_path ) ) )
return results |
def _set_mtu ( self , v , load = False ) :
"""Setter method for mtu , mapped from YANG variable / pw _ profile / mtu ( container )
If this variable is read - only ( config : false ) in the
source YANG file , then _ set _ mtu is considered as a private
method . Backends looking to populate this variable should... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = mtu . mtu , is_container = 'container' , presence = False , yang_name = "mtu" , rest_name = "mtu" , parent = self , path_helper = self . _path_helper , extmethods = self . _extmethods , register_paths = True , extensions = { ... |
def apply ( modifications , state ) :
"""applies modifications to given state
Parameters
modifications : list of tuples
created by this class . list method .
state : dict
state dictionary""" | count = 0
for a in modifications :
if _debug :
assert a [ 0 ] in ( 'set' , 'mv' , 'map' , 'rm' )
logger . debug ( "processing rule: %s" , str ( a ) )
if len ( a ) == 3 :
operation , name , value = a
if operation == 'set' :
state [ name ] = value
count += 1... |
def weighted_tanimoto ( a , b , weights ) :
"""Same as the Tanimoto coefficient , but wit weights for each dimension .""" | weighted = lambda s : map ( lambda ( x , y ) : float ( x ) * float ( y ) , zip ( s , weights ) )
return tanimoto_coefficient ( weighted ( a ) , weighted ( b ) ) |
def generate_branches ( scales = None , angles = None , shift_angle = 0 ) :
"""Generates branches with alternative system .
Args :
scales ( tuple / array ) : Indicating how the branch / es length / es develop / s from age to age .
angles ( tuple / array ) : Holding the branch and shift angle in radians .
sh... | branches = [ ]
for pos , scale in enumerate ( scales ) :
angle = - sum ( angles ) / 2 + sum ( angles [ : pos ] ) + shift_angle
branches . append ( [ scale , angle ] )
return branches |
def rasterPlot ( spikeTrain , model ) :
"""Plots raster and saves figure in working directory
@ param spikeTrain ( array ) matrix of spike trains
@ param model ( string ) string specifying the name of the origin of the spike trains
for the purpose of concatenating it to the filename ( either TM or Poisson )""... | nTrials = np . shape ( spikeTrain ) [ 0 ]
spikes = [ ]
for i in range ( nTrials ) :
spikes . append ( spikeTrain [ i ] . nonzero ( ) [ 0 ] . tolist ( ) )
plt . figure ( )
ax = raster ( spikes )
plt . xlabel ( 'Time' )
plt . ylabel ( 'Neuron' )
# plt . show ( )
plt . savefig ( "raster" + str ( model ) )
plt . close ... |
def branch_indirect ( self , addr ) :
"""Indirect branch to target * addr * .""" | br = instructions . IndirectBranch ( self . block , "indirectbr" , addr )
self . _set_terminator ( br )
return br |
def _sigmainf ( N , h , m , dW , Km0 , Pm0 ) :
"""Asymptotic covariance matrix \ Sigma _ \ infty Wiktorsson2001 eqn ( 4.5)""" | M = m * ( m - 1 ) // 2
Im = broadcast_to ( np . eye ( m ) , ( N , m , m ) )
IM = broadcast_to ( np . eye ( M ) , ( N , M , M ) )
Ims0 = np . eye ( m ** 2 )
factor1 = broadcast_to ( ( 2.0 / h ) * np . dot ( Km0 , Ims0 - Pm0 ) , ( N , M , m ** 2 ) )
factor2 = _kp2 ( Im , _dot ( dW , _t ( dW ) ) )
factor3 = broadcast_to (... |
def _initialize_buffers ( self , view_size ) :
"""Create the buffers to cache tile drawing
: param view _ size : ( int , int ) : size of the draw area
: return : None""" | import math
from pygame import Rect
tw , th = self . data . tile_size
mw , mh = self . data . map_size
buffer_tile_width = int ( math . ceil ( view_size [ 0 ] / tw ) + 2 ) * 2
buffer_tile_height = int ( math . ceil ( view_size [ 1 ] / th ) + 2 ) * 2
buffer_pixel_size = buffer_tile_width * tw , buffer_tile_height * th
s... |
def object_as_dict ( obj ) :
"""Turn an SQLAlchemy model into a dict of field names and values .
Based on https : / / stackoverflow . com / a / 37350445/1579058""" | return { c . key : getattr ( obj , c . key ) for c in inspect ( obj ) . mapper . column_attrs } |
def export ( id , local = False , scrub_pii = False ) :
"""Export data from an experiment .""" | print ( "Preparing to export the data..." )
if local :
db_uri = db . db_url
else :
db_uri = HerokuApp ( id ) . db_uri
# Create the data package if it doesn ' t already exist .
subdata_path = os . path . join ( "data" , id , "data" )
try :
os . makedirs ( subdata_path )
except OSError as e :
if e . errno... |
def ids2strids ( ids : Iterable [ int ] ) -> str :
"""Returns a string representation of a sequence of integers .
: param ids : Sequence of integers .
: return : String sequence""" | return C . TOKEN_SEPARATOR . join ( map ( str , ids ) ) |
def delete_mountpoints ( self , paths = None , folder_ids = None ) :
""": param folder _ ids : list of ids
: param path : list of folder ' s paths""" | self . delete_folders ( paths = paths , folder_ids = folder_ids , f_type = 'link' ) |
def register_endpoints ( self ) :
"""Creates a list of all the endpoints this backend module needs to listen to . In this case
it ' s the authentication response from the underlying OP that is redirected from the OP to
the proxy .
: rtype : Sequence [ ( str , Callable [ [ satosa . context . Context ] , satosa... | url_map = [ ]
redirect_path = urlparse ( self . config [ "client" ] [ "client_metadata" ] [ "redirect_uris" ] [ 0 ] ) . path
if not redirect_path :
raise SATOSAError ( "Missing path in redirect uri" )
url_map . append ( ( "^%s$" % redirect_path . lstrip ( "/" ) , self . response_endpoint ) )
return url_map |
def raw ( self ) :
"""Red , green , and blue components of the detected color , as a tuple .
Officially in the range 0-1020 but the values returned will never be
that high . We do not yet know why the values returned are low , but
pointing the color sensor at a well lit sheet of white paper will return
valu... | self . _ensure_mode ( self . MODE_RGB_RAW )
return self . value ( 0 ) , self . value ( 1 ) , self . value ( 2 ) |
def truncate ( v : str , * , max_len : int = 80 ) -> str :
"""Truncate a value and add a unicode ellipsis ( three dots ) to the end if it was too long""" | if isinstance ( v , str ) and len ( v ) > ( max_len - 2 ) : # -3 so quote + string + . . . + quote has correct length
return repr ( v [ : ( max_len - 3 ) ] + '…' )
v = repr ( v )
if len ( v ) > max_len :
v = v [ : max_len - 1 ] + '…'
return v |
def output ( self , _filename ) :
"""_ filename is not used
Args :
_ filename ( string )""" | for contract in self . contracts :
txt = "\nContract %s\n" % contract . name
table = PrettyTable ( [ "Function" , "State variables written" , "Conditions on msg.sender" ] )
for function in contract . functions :
state_variables_written = [ v . name for v in function . all_state_variables_written ( )... |
def split ( self , s ) :
"""Split the string on ( . ) while preserving any ( . ) inside the
' { } ' alternalte syntax for full ns qualification .
@ param s : A plain or qualifed name .
@ type s : str
@ return : A list of the name ' s parts .
@ rtype : [ str , . . ]""" | parts = [ ]
b = 0
while 1 :
m = self . splitp . match ( s , b )
if m is None :
break
b , e = m . span ( )
parts . append ( s [ b : e ] )
b = e + 1
return parts |
def GetFormattedField ( self , event , field_name ) :
"""Formats the specified field .
Args :
event ( EventObject ) : event .
field _ name ( str ) : name of the field .
Returns :
str : value of the field .""" | callback_name = self . _FIELD_FORMAT_CALLBACKS . get ( field_name , None )
callback_function = None
if callback_name :
callback_function = getattr ( self , callback_name , None )
if callback_function :
output_value = callback_function ( event )
else :
output_value = getattr ( event , field_name , '-' )
if o... |
def get_environment ( default = DEVELOPMENT , detectors = None , detectors_opts = None , use_envfiles = True ) :
"""Returns current environment type object .
: param str | Environment | None default : Default environment type or alias .
: param list [ Detector ] detectors : List of environment detectors to be u... | detectors_opts = detectors_opts or { }
if detectors is None :
detectors = DETECTORS . keys ( )
env = None
for detector in detectors :
opts = detectors_opts . get ( detector , { } )
detector = get_detector ( detector )
detector = detector ( ** opts )
env_name = detector . probe ( )
if env_name :
... |
def getUserCaPath ( self , name ) :
'''Gets the path to the CA certificate that issued a given user keypair .
Args :
name ( str ) : The name of the user keypair .
Examples :
Get the path to the CA cert which issue the cert for " myuser " :
mypath = cdir . getUserCaPath ( ' myuser ' )
Returns :
str : T... | cert = self . getUserCert ( name )
if cert is None :
return None
return self . _getCaPath ( cert ) |
def ip_route_show ( session , destination , device , ** kwargs ) :
"""Returns a selected route record matching the given filtering rules .
The arguments are similar to " ip route showdump " command of iproute2.
: param session : Session instance connecting to database .
: param destination : Destination prefi... | intf = interface . ip_link_show ( session , ifname = device )
if not intf :
LOG . debug ( 'Interface "%s" does not exist' , device )
return None
return session . query ( Route ) . filter_by ( destination = destination , ifindex = intf . ifindex , ** kwargs ) . first ( ) |
def create_customer ( name , email , phone ) :
"""Create a customer with the name .
Then attach the email and phone as contact methods""" | Party = client . model ( 'party.party' )
ContactMechanism = client . model ( 'party.contact_mechanism' )
party , = Party . create ( [ { 'name' : name } ] )
# Bulk create the email and phone
ContactMechanism . create ( [ { 'type' : 'email' , 'value' : email , 'party' : party } , { 'type' : 'phone' , 'value' : phone , 'p... |
def get_package_id ( self , name ) :
"""Retrieve the smart package id given is English name
@ param ( str ) name : the Aruba Smart package size name , ie : " small " , " medium " , " large " , " extra large " .
@ return : The package id that depends on the Data center and the size choosen .""" | json_scheme = self . gen_def_json_scheme ( 'GetPreConfiguredPackages' , dict ( HypervisorType = 4 ) )
json_obj = self . call_method_post ( method = 'GetPreConfiguredPackages ' , json_scheme = json_scheme )
for package in json_obj [ 'Value' ] :
packageId = package [ 'PackageID' ]
for description in package [ 'De... |
def setup ( cmd_args , suppress_output = False ) :
"""Call a setup . py command or list of commands
> > > result = setup ( ' - - name ' , suppress _ output = True )
> > > result . exitval
> > > result = setup ( ' notreal ' )
> > > result . exitval""" | if not funcy . is_list ( cmd_args ) and not funcy . is_tuple ( cmd_args ) :
cmd_args = shlex . split ( cmd_args )
cmd_args = [ sys . executable , 'setup.py' ] + [ x for x in cmd_args ]
return call ( cmd_args , suppress_output = suppress_output ) |
def export_hmaps_csv ( key , dest , sitemesh , array , comment ) :
"""Export the hazard maps of the given realization into CSV .
: param key : output _ type and export _ type
: param dest : name of the exported file
: param sitemesh : site collection
: param array : a composite array of dtype hmap _ dt
: ... | curves = util . compose_arrays ( sitemesh , array )
writers . write_csv ( dest , curves , comment = comment )
return [ dest ] |
def on_go ( self , target ) :
"""RUN target WHEN SIGNALED""" | if not target :
Log . error ( "expecting target" )
with self . lock :
if not self . _go :
DEBUG and self . _name and Log . note ( "Adding target to signal {{name|quote}}" , name = self . name )
if not self . job_queue :
self . job_queue = [ target ]
else :
self . ... |
def month ( self ) :
"""Get the overall Unsplash stats for the past 30 days .
: return [ Stat ] : The Unsplash Stat .""" | url = "/stats/month"
result = self . _get ( url )
return StatModel . parse ( result ) |
def to_type ( self , tokens ) :
"""Convert [ Token , . . . ] to [ Class ( . . . ) , ] useful for base classes .
For example , code like class Foo : public Bar < x , y > { . . . } ;
the " Bar < x , y > " portion gets converted to an AST .
Returns :
[ Class ( . . . ) , . . . ]""" | result = [ ]
name_tokens = [ ]
reference = pointer = array = False
inside_array = False
empty_array = True
templated_tokens = [ ]
def add_type ( ) :
if not name_tokens :
return
# Partition tokens into name and modifier tokens .
names = [ ]
modifiers = [ ]
for t in name_tokens :
if ke... |
def expansion_max_H ( self ) :
"""" Return the maximum distance between expansions for the largest
allowable H / S ratio .
: returns : Maximum expansion distance
: rtype : float * meter
Examples
exp _ dist _ max ( 20 * u . L / u . s , 40 * u . cm , 37000 , 25 * u . degC , 2 * u . m )
0.375 meter""" | return ( ( ( self . BAFFLE_K / ( 2 * pc . viscosity_kinematic ( self . temp ) * ( self . vel_grad_avg ** 2 ) ) ) * ( self . Q * self . RATIO_MAX_HS / self . channel_W ) ** 3 ) ** ( 1 / 4 ) ) . to ( u . m ) |
def makeCoreValuesSubqueryCondition ( engine , column , values : List [ Union [ int , str ] ] ) :
"""Make Core Values Subquery
: param engine : The database engine , used to determine the dialect
: param column : The column , eg TableItem . _ _ table _ _ . c . colName
: param values : A list of string or int ... | if isPostGreSQLDialect ( engine ) :
return column . in_ ( values )
if not isMssqlDialect ( engine ) :
raise NotImplementedError ( )
sql = _createMssqlSqlText ( values )
return column . in_ ( sql ) |
def has_import_permission ( self , request ) :
"""Returns whether a request has import permission .""" | IMPORT_PERMISSION_CODE = getattr ( settings , 'IMPORT_EXPORT_IMPORT_PERMISSION_CODE' , None )
if IMPORT_PERMISSION_CODE is None :
return True
opts = self . opts
codename = get_permission_codename ( IMPORT_PERMISSION_CODE , opts )
return request . user . has_perm ( "%s.%s" % ( opts . app_label , codename ) ) |
def translate ( usercodes , rgb_mode = False ) :
"""Translate one or more hex , term , or rgb value into the others .
Yields strings with the results for each code translated .""" | for code in usercodes :
code = code . strip ( ) . lower ( )
if code . isalpha ( ) and ( code in codes [ 'fore' ] ) : # Basic color name .
yield translate_basic ( code )
else :
if ',' in code :
try :
r , g , b = ( int ( c . strip ( ) ) for c in code . split ( ',' )... |
def bwrite ( stream , obj ) :
"""Encode a given object to a file or stream .""" | handle = None
if not hasattr ( stream , "write" ) :
stream = handle = open ( stream , "wb" )
try :
stream . write ( bencode ( obj ) )
finally :
if handle :
handle . close ( ) |
def _proxy_connect ( name , method_name , kwargs , econtext ) :
"""Implements the target portion of Router . _ proxy _ connect ( ) by upgrading the
local context to a parent if it was not already , then calling back into
Router . _ connect ( ) using the arguments passed to the parent ' s
Router . connect ( ) ... | upgrade_router ( econtext )
try :
context = econtext . router . _connect ( klass = stream_by_method_name ( method_name ) , name = name , ** kwargs )
except mitogen . core . StreamError :
return { u'id' : None , u'name' : None , u'msg' : 'error occurred on host %s: %s' % ( socket . gethostname ( ) , sys . exc_in... |
def grouper_list ( l , n ) :
"""Evenly divide list into fixed - length piece , no filled value if chunk
size smaller than fixed - length .
Example : :
> > > list ( grouper ( range ( 10 ) , n = 3)
[ [ 0 , 1 , 2 ] , [ 3 , 4 , 5 ] , [ 6 , 7 , 8 ] , [ 9 ] ]
* * 中文文档 * *
将一个列表按照尺寸n , 依次打包输出 , 有多少输出多少 , 并不强制填... | chunk = list ( )
counter = 0
for item in l :
counter += 1
chunk . append ( item )
if counter == n :
yield chunk
chunk = list ( )
counter = 0
if len ( chunk ) > 0 :
yield chunk |
def create_container ( config , image , command = None , hostname = None , user = None , detach = True , entrypoint = None , stdin_open = False , tty = False , mem_limit = 0 , cpu_shares = None , ports = None , environment = None , dns = None , volumes = None , volumes_from = None , name = None , * args , ** kwargs ) :... | err = "Unknown"
client = _get_client ( config )
try :
img_infos = _get_image_infos ( config , image )
mountpoints = { }
binds = { }
# create empty mountpoints for them to be
# editable
# either we have a list of guest or host : guest
if isinstance ( volumes , list ) :
for mountpoint ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.