signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def get_token ( self ) :
"""sets client token from Cerberus""" | auth_resp = self . get_auth ( )
if auth_resp [ 'status' ] == 'mfa_req' :
token_resp = self . get_mfa ( auth_resp )
else :
token_resp = auth_resp
token = token_resp [ 'data' ] [ 'client_token' ] [ 'client_token' ]
return token |
def __boost ( self , grad , hess ) :
"""Boost Booster for one iteration with customized gradient statistics .
Note
For multi - class task , the score is group by class _ id first , then group by row _ id .
If you want to get i - th row score in j - th class , the access way is score [ j * num _ data + i ]
a... | grad = list_to_1d_numpy ( grad , name = 'gradient' )
hess = list_to_1d_numpy ( hess , name = 'hessian' )
assert grad . flags . c_contiguous
assert hess . flags . c_contiguous
if len ( grad ) != len ( hess ) :
raise ValueError ( "Lengths of gradient({}) and hessian({}) don't match" . format ( len ( grad ) , len ( he... |
def union ( self , sr , geometries ) :
"""The union operation is performed on a geometry service resource . This
operation constructs the set - theoretic union of the geometries in the
input array . All inputs must be of the same type .
Inputs :
geometries - array of geometries to be unioned ( structured as... | url = self . _url + "/union"
params = { "f" : "json" , "sr" : sr , "geometries" : self . __geometryListToGeomTemplate ( geometries = geometries ) }
return self . _get ( url = url , param_dict = params , securityHandler = self . _securityHandler , proxy_url = self . _proxy_url , proxy_port = self . _proxy_port ) |
def fit ( self , Xs , ys = None , Xt = None , yt = None ) :
"""Build a coupling matrix from source and target sets of samples
( Xs , ys ) and ( Xt , yt )
Parameters
Xs : array - like , shape ( n _ source _ samples , n _ features )
The training input samples .
ys : array - like , shape ( n _ source _ sampl... | # check the necessary inputs parameters are here
if check_params ( Xs = Xs , Xt = Xt , ys = ys ) :
super ( SinkhornL1l2Transport , self ) . fit ( Xs , ys , Xt , yt )
returned_ = sinkhorn_l1l2_gl ( a = self . mu_s , labels_a = ys , b = self . mu_t , M = self . cost_ , reg = self . reg_e , eta = self . reg_cl , n... |
def project_create_notif ( self , tenant_id , tenant_name ) :
"""Tenant Create notification .""" | if not self . fw_init :
return
self . os_helper . create_router ( '_' . join ( [ fw_constants . TENANT_EDGE_RTR , tenant_name ] ) , tenant_id , [ ] ) |
def convert ( self , money , to_currency , date = None ) :
"""Convert the given ` ` money ` ` to ` ` to _ currency ` ` using exchange rate on ` ` date ` `
If ` ` date ` ` is omitted then the date given by ` ` money . date ` ` will be used .""" | if str ( money . currency ) == str ( to_currency ) :
return copy . copy ( money )
return Money ( amount = money . amount * self . rate ( money . currency , to_currency , date or datetime . date . today ( ) ) , currency = to_currency , ) |
def enable ( self , ids ) :
"""Enable Pool Members Running Script
: param ids : List of ids
: return : None on success
: raise PoolMemberDoesNotExistException
: raise InvalidIdPoolMemberException
: raise ScriptEnablePoolException
: raise NetworkAPIException""" | data = dict ( )
data [ "ids" ] = ids
uri = "api/pools/enable/"
return self . post ( uri , data ) |
def NewFile ( self , filename , encoding , options ) :
"""parse an XML file from the filesystem or the network . The
parsing flags @ options are a combination of
xmlParserOption . This reuses the existing @ reader
xmlTextReader .""" | ret = libxml2mod . xmlReaderNewFile ( self . _o , filename , encoding , options )
return ret |
def demo_login ( self , auth = None , url = None ) :
"""Authenticate with a " Share Your Class " URL using a demo user .
You may provide either the entire ` ` url ` ` or simply the ` ` auth ` `
parameter .
: param url : Example - " https : / / piazza . com / demo _ login ? nid = hbj11a1gcvl1s6 & auth = 06c111... | self . _rpc_api = PiazzaRPC ( )
self . _rpc_api . demo_login ( auth = auth , url = url ) |
def abbreviate ( s , maxlength = 25 ) :
"""Color - aware abbreviator""" | assert maxlength >= 4
skip = False
abbrv = None
i = 0
for j , c in enumerate ( s ) :
if c == '\033' :
skip = True
elif skip :
if c == 'm' :
skip = False
else :
i += 1
if i == maxlength - 1 :
abbrv = s [ : j ] + '\033[0m...'
elif i > maxlength :
bre... |
def _extract_hunt_results ( self , output_file_path ) :
"""Open a hunt output archive and extract files .
Args :
output _ file _ path : The path where the hunt archive is downloaded to .
Returns :
list : tuples containing :
str : The name of the client from where the files were downloaded .
str : The di... | # Extract items from archive by host for processing
collection_paths = [ ]
client_ids = set ( )
client_id_to_fqdn = { }
hunt_dir = None
try :
with zipfile . ZipFile ( output_file_path ) as archive :
items = archive . infolist ( )
for f in items :
if not hunt_dir :
hunt_di... |
def get_info ( self ) :
"""Return surface reconstruction as well as primary and
secondary adsorption site labels""" | reconstructed = self . is_reconstructed ( )
site , site_type = self . get_site ( )
return reconstructed , site , site_type |
def ingest_containers ( self , containers = None ) :
"""Transform the YAML into a dict with normalized keys""" | containers = containers or self . stream or { }
output_containers = [ ]
for container_name , definition in containers . items ( ) :
container = definition . copy ( )
container [ 'name' ] = container_name
output_containers . append ( container )
return output_containers |
def usermacro_updateglobal ( globalmacroid , value , ** kwargs ) :
'''Update existing global usermacro .
: param globalmacroid : id of the host usermacro
: param value : new value of the host usermacro
: param _ connection _ user : Optional - zabbix user ( can also be set in opts or pillar , see module ' s do... | conn_args = _login ( ** kwargs )
ret = { }
try :
if conn_args :
params = { }
method = 'usermacro.updateglobal'
params [ 'globalmacroid' ] = globalmacroid
params [ 'value' ] = value
params = _params_extend ( params , _ignore_name = True , ** kwargs )
ret = _query ( met... |
def factorgraph_viz ( d ) :
"""Map the dictionary into factorgraph - viz format . See https : / / github . com / mbforbes / factorgraph - viz
: param d : The dictionary
: return : The formatted dictionary""" | m = defaultdict ( list )
for node in d [ 'nodes' ] :
m [ 'nodes' ] . append ( dict ( id = node [ 'id' ] , type = 'rv' ) )
for factor in d [ 'factors' ] :
m [ 'nodes' ] . append ( dict ( id = factor [ 'id' ] , type = 'fac' ) )
for source in factor [ 'sources' ] :
m [ 'links' ] . append ( dict ( sourc... |
def _wrap ( obj , wrapper = None , methods_to_add = ( ) , name = None , skip = ( ) , wrap_return_values = False , wrap_filenames = ( ) , filename = None , wrapped_name_func = None , wrapped = None ) :
"""Wrap module , class , function or another variable recursively
: param Any obj : Object to wrap recursively
... | # noinspection PyUnresolvedReferences
class ModuleProxy ( types . ModuleType , Proxy ) : # noinspection PyShadowingNames
def __init__ ( self , name , doc = None ) :
super ( ) . __init__ ( name = name , doc = doc )
try : # Subclassing from obj to pass isinstance ( some _ object , obj ) checks . If defining t... |
def merge_csv ( filenames : List [ str ] , outfile : TextIO = sys . stdout , input_dialect : str = 'excel' , output_dialect : str = 'excel' , debug : bool = False , headers : bool = True ) -> None :
"""Amalgamate multiple CSV / TSV / similar files into one .
Args :
filenames : list of filenames to process
out... | writer = csv . writer ( outfile , dialect = output_dialect )
written_header = False
header_items = [ ]
# type : List [ str ]
for filename in filenames :
log . info ( "Processing file " + repr ( filename ) )
with open ( filename , 'r' ) as f :
reader = csv . reader ( f , dialect = input_dialect )
... |
def _bright_star_match ( self , matchedObjects , catalogueName , magnitudeLimitFilter , lowerMagnitudeLimit ) :
"""* perform a bright star match on the crossmatch results if required by the catalogue search *
* * Key Arguments : * *
- ` ` matchedObjects ` ` - - the list of matched sources from the catalogue cro... | self . log . debug ( 'starting the ``_bright_star_match`` method' )
import decimal
decimal . getcontext ( ) . prec = 10
# MATCH BRIGHT STAR ASSOCIATIONS
brightStarMatches = [ ]
for row in matchedObjects :
mag = decimal . Decimal ( row [ magnitudeLimitFilter ] )
if mag and mag < lowerMagnitudeLimit :
sep... |
def include_config ( include , orig_path , verbose , exit_on_config_errors = False ) :
'''Parses extra configuration file ( s ) specified in an include list in the
main config file .''' | # Protect against empty option
if not include :
return { }
if orig_path is None : # When the passed path is None , we just want the configuration
# defaults , not actually loading the whole configuration .
return { }
if isinstance ( include , six . string_types ) :
include = [ include ]
configuration = { }
... |
def tag ( self , alt = '' , use_size = None , ** attrs ) :
"""Return a standard XHTML ` ` < img . . . / > ` ` tag for this field .
: param alt : The ` ` alt = " " ` ` text for the tag . Defaults to ` ` ' ' ` ` .
: param use _ size : Whether to get the size of the thumbnail image for use
in the tag attributes ... | if use_size is None :
if getattr ( self , '_dimensions_cache' , None ) :
use_size = True
else :
try :
self . storage . path ( self . name )
use_size = True
except NotImplementedError :
use_size = False
attrs [ 'alt' ] = alt
attrs [ 'src' ] = self . url... |
def isready ( self ) :
"""Used to synchronize the python engine object with the back - end engine . Sends ' isready ' and waits for ' readyok . '""" | self . put ( 'isready' )
while True :
text = self . stdout . readline ( ) . strip ( )
if text == 'readyok' :
return text |
def times ( p , mint , maxt = None ) :
'''Repeat a parser between ` mint ` and ` maxt ` times . DO AS MUCH MATCH AS IT CAN .
Return a list of values .''' | maxt = maxt if maxt else mint
@ Parser
def times_parser ( text , index ) :
cnt , values , res = 0 , Value . success ( index , [ ] ) , None
while cnt < maxt :
res = p ( text , index )
if res . status :
values = values . aggregate ( Value . success ( res . index , [ res . value ] ) )
... |
def _grid_sample ( x : TensorImage , coords : FlowField , mode : str = 'bilinear' , padding_mode : str = 'reflection' , remove_out : bool = True ) -> TensorImage :
"Resample pixels in ` coords ` from ` x ` by ` mode ` , with ` padding _ mode ` in ( ' reflection ' , ' border ' , ' zeros ' ) ." | coords = coords . flow . permute ( 0 , 3 , 1 , 2 ) . contiguous ( ) . permute ( 0 , 2 , 3 , 1 )
# optimize layout for grid _ sample
if mode == 'bilinear' : # hack to get smoother downwards resampling
mn , mx = coords . min ( ) , coords . max ( )
# max amount we ' re affine zooming by ( > 1 means zooming in )
... |
def _cast_expected_to_returned_type ( expected , returned ) :
'''Determine the type of variable returned
Cast the expected to the type of variable returned''' | ret_type = type ( returned )
new_expected = expected
if expected == "False" and ret_type == bool :
expected = False
try :
new_expected = ret_type ( expected )
except ValueError :
log . info ( "Unable to cast expected into type of returned" )
log . info ( "returned = %s" , returned )
log . info ( "ty... |
def new ( namespace , name , protected = False , attributes = dict ( ) , api_url = fapi . PROD_API_ROOT ) :
"""Create a new FireCloud workspace .
Returns :
Workspace : A new FireCloud workspace
Raises :
FireCloudServerError : API call failed .""" | r = fapi . create_workspace ( namespace , name , protected , attributes , api_url )
fapi . _check_response_code ( r , 201 )
return Workspace ( namespace , name , api_url ) |
def capsule ( height = 1.0 , radius = 1.0 , count = [ 32 , 32 ] ) :
"""Create a mesh of a capsule , or a cylinder with hemispheric ends .
Parameters
height : float
Center to center distance of two spheres
radius : float
Radius of the cylinder and hemispheres
count : ( 2 , ) int
Number of sections on l... | height = float ( height )
radius = float ( radius )
count = np . array ( count , dtype = np . int )
count += np . mod ( count , 2 )
# create a theta where there is a double band around the equator
# so that we can offset the top and bottom of a sphere to
# get a nicely meshed capsule
theta = np . linspace ( 0 , np . pi... |
def bids_to_pwl ( self , bids ) :
"""Updates the piece - wise linear total cost function using the given
bid blocks .
Based on off2case . m from MATPOWER by Ray Zimmerman , developed at PSERC
Cornell . See U { http : / / www . pserc . cornell . edu / matpower / } for more info .""" | assert self . is_load
# Apply only those bids associated with this dispatchable load .
vl_bids = [ bid for bid in bids if bid . vLoad == self ]
# Filter out zero quantity bids .
gt_zero = [ bid for bid in vl_bids if round ( bid . quantity , 4 ) > 0.0 ]
# Ignore withheld offers .
valid_bids = [ bid for bid in gt_zero if... |
def get_document_frequency ( self , term ) :
"""Returns the number of documents the specified term appears in .""" | if term not in self . _terms :
raise IndexError ( TERM_DOES_NOT_EXIST )
else :
return len ( self . _terms [ term ] ) |
def _writeImage ( dataArray = None , inputHeader = None ) :
"""Writes out the result of the combination step .
The header of the first ' outsingle ' file in the
association parlist is used as the header of the
new image .
Parameters
dataArray : arr
Array of data to be written to a fits . PrimaryHDU obje... | prihdu = fits . PrimaryHDU ( data = dataArray , header = inputHeader )
pf = fits . HDUList ( )
pf . append ( prihdu )
return pf |
def triangle_address ( fx , pt ) :
'''triangle _ address ( FX , P ) yields an address coordinate ( t , r ) for the point P in the triangle
defined by the ( 3 x d ) - sized coordinate matrix FX , in which each row of the matrix is the
d - dimensional vector representing the respective triangle vertx for triangle... | fx = np . asarray ( fx )
pt = np . asarray ( pt )
# The triangle vectors . . .
ab = fx [ 1 ] - fx [ 0 ]
ac = fx [ 2 ] - fx [ 0 ]
bc = fx [ 2 ] - fx [ 1 ]
ap = np . asarray ( [ pt_i - a_i for ( pt_i , a_i ) in zip ( pt , fx [ 0 ] ) ] )
# get the unnormalized distance . . .
r = np . sqrt ( ( ap ** 2 ) . sum ( 0 ) )
# now... |
def hexcolor ( color ) :
"returns hex color given a tuple , wx . Color , or X11 named color" | # first , if this is a hex color already , return !
# Python 3 : needs rewrite for str / unicode change
if isinstance ( color , six . string_types ) :
if color [ 0 ] == '#' and len ( color ) == 7 :
return color . lower ( )
# now , get color to an rgb tuple
rgb = ( 0 , 0 , 0 )
if isinstance ( color , tuple )... |
def raw_corpus_rougel ( hypotheses : Iterable [ str ] , references : Iterable [ str ] ) -> float :
"""Simple wrapper around ROUGE - L implementation .
: param hypotheses : Hypotheses stream .
: param references : Reference stream .
: return : ROUGE - L score as float between 0 and 1.""" | return rouge . rouge_l ( hypotheses , references ) |
def facter_info ( ) :
"""Returns data from facter .""" | with suppress ( FileNotFoundError ) : # facter may not be installed
proc = subprocess . Popen ( [ 'facter' , '--yaml' ] , stdout = subprocess . PIPE , stderr = subprocess . PIPE )
stdout , stderr = proc . communicate ( )
if not proc . returncode :
data = serializer . load ( stdout )
return {... |
def from_settings ( cls , settings ) :
"""Read Mongodb Source configuration from the provided settings""" | if not 'mongodb' in settings or not 'collection' in settings or settings [ 'mongodb' ] == '' or settings [ 'collection' ] == '' :
raise Exception ( "Erroneous mongodb settings, " "needs a collection and mongodb setting" , settings )
cx_uri = urlparse . urlsplit ( settings [ "mongodb" ] )
db_name = cx_uri . path
if ... |
def diff ( self , other = Index , paths = None , create_patch = False , ** kwargs ) :
"""Creates diffs between two items being trees , trees and index or an
index and the working tree . It will detect renames automatically .
: param other :
Is the item to compare us with .
If None , we will be compared to t... | args = [ ]
args . append ( "--abbrev=40" )
# we need full shas
args . append ( "--full-index" )
# get full index paths , not only filenames
args . append ( "-M" )
# check for renames , in both formats
if create_patch :
args . append ( "-p" )
else :
args . append ( "--raw" )
# in any way , assure we don ' t see ... |
def complex_median ( complex_list ) :
"""Get the median value of a list of complex numbers .
Parameters
complex _ list : list
List of complex numbers to calculate the median .
Returns
a + 1 . j * b : complex number
The median of the real and imaginary parts .""" | median_real = numpy . median ( [ complex_number . real for complex_number in complex_list ] )
median_imag = numpy . median ( [ complex_number . imag for complex_number in complex_list ] )
return median_real + 1.j * median_imag |
def main ( ) :
"""Simulates HHL with matrix input , and outputs Pauli observables of the
resulting qubit state | x > .
Expected observables are calculated from the expected solution | x > .""" | # Eigendecomposition :
# (4.537 , [ - 0.971555 , - 0.0578339 + 0.229643j ] )
# (0.349 , [ - 0.236813 , 0.237270-0.942137j ] )
# | b > = ( 0.64510-0.47848j , 0.35490-0.47848j )
# | x > = ( - 0.0662724-0.214548j , 0.784392-0.578192j )
A = np . array ( [ [ 4.30213466 - 6.01593490e-08j , 0.23531802 + 9.34386156e-01j ] , [ ... |
def compamp_to_ac ( compamp , window = np . hanning ) : # convert single or multi - subband compamps into autocorrelation waterfall
'''Adapted from Gerry Harp at SETI .''' | header = compamp . header ( )
cdata = compamp . complex_data ( )
# Apply Windowing and Padding
cdata = np . multiply ( cdata , window ( cdata . shape [ 2 ] ) )
# window for smoothing sharp time series start / end in freq . dom .
cdata_normal = cdata - cdata . mean ( axis = 2 ) [ : , : , np . newaxis ]
# zero mean , doe... |
def match ( subject : Expression , pattern : Pattern ) -> Iterator [ Substitution ] :
r"""Tries to match the given * pattern * to the given * subject * .
Yields each match in form of a substitution .
Parameters :
subject :
An subject to match .
pattern :
The pattern to match .
Yields :
All possible ... | if not is_constant ( subject ) :
raise ValueError ( "The subject for matching must be constant." )
global_constraints = [ c for c in pattern . constraints if not c . variables ]
local_constraints = set ( c for c in pattern . constraints if c . variables )
for subst in _match ( [ subject ] , pattern . expression , S... |
def _api_args ( self ) :
"""Glances API RESTful implementation .
Return the JSON representation of the Glances command line arguments
HTTP / 200 if OK
HTTP / 404 if others error""" | response . content_type = 'application/json; charset=utf-8'
try : # Get the JSON value of the args ' dict
# Use vars to convert namespace to dict
# Source : https : / / docs . python . org / % s / library / functions . html # vars
args_json = json . dumps ( vars ( self . args ) )
except Exception as e :
abort (... |
def _setup ( self ) :
"""Generates _ reverse _ map from _ map""" | ValueMap . _setup ( self )
cls = self . __class__
if cls . _map is not None :
cls . _size = max ( self . _map . keys ( ) ) + 1 |
def ketbra ( i , j , Ne ) :
"""This function returns the outer product : math : ` | i > < j | ` where : math : ` | i > ` and : math : ` | j > ` are elements of the canonical basis of an Ne - dimensional Hilbert space ( in matrix form ) .
> > > ketbra ( 2 , 3 , 3)
Matrix ( [
[0 , 0 , 0 ] ,
[0 , 0 , 1 ] ,
[... | return ket ( i , Ne ) * bra ( j , Ne ) |
def import_pyfiles ( path ) :
"""Import all * . py files in specified directory .""" | n = 0
for pyfile in glob . glob ( os . path . join ( path , '*.py' ) ) :
m = import_file ( pyfile )
IMPORTED_BUILD_SOURCES . append ( m )
n += 1
return n |
def isVisible ( self ) :
"""Returns whether or not this layer is visible . If the inheritVisibility
value is set to True , then this will look up its parent hierarchy to ensure it is visible .
: return < bool >""" | if self . _visible and self . _inheritVisibility and self . _parent :
return self . _parent . isVisible ( )
return self . _visible |
def __RetrieveContent ( host , port , adapter , version , path , keyFile , certFile , thumbprint , sslContext , connectionPoolTimeout = CONNECTION_POOL_IDLE_TIMEOUT_SEC ) :
"""Retrieve service instance for connection .
@ param host : Which host to connect to .
@ type host : string
@ param port : Port
@ type... | # XXX remove the adapter and service arguments once dependent code is fixed
if adapter != "SOAP" :
raise ValueError ( adapter )
# Create the SOAP stub adapter
stub = SoapStubAdapter ( host , port , version = version , path = path , certKeyFile = keyFile , certFile = certFile , thumbprint = thumbprint , sslContext =... |
def xor ( * variables ) :
'''XOR definition for multiple variables''' | sum_ = False
for value in variables :
sum_ = sum_ ^ bool ( value )
return sum_ |
def indent ( indent_str = None ) :
"""An example indentation ruleset .""" | def indentation_rule ( ) :
inst = Indentator ( indent_str )
return { 'layout_handlers' : { Indent : inst . layout_handler_indent , Dedent : inst . layout_handler_dedent , Newline : inst . layout_handler_newline , OptionalNewline : inst . layout_handler_newline_optional , OpenBlock : layout_handler_openbrace , C... |
def create ( input_width , input_height , input_channels = 1 , output_dim = 512 ) :
"""Vel factory function""" | def instantiate ( ** _ ) :
return NatureCnn ( input_width = input_width , input_height = input_height , input_channels = input_channels , output_dim = output_dim )
return ModelFactory . generic ( instantiate ) |
def set ( self , instance , value , ** kw ) :
"""Set Analyses to an AR
: param instance : Analysis Request
: param value : Single AS UID or a list of dictionaries containing AS UIDs
: param kw : Additional keyword parameters passed to the field""" | if not isinstance ( value , ( list , tuple ) ) :
value = [ value ]
uids = [ ]
for item in value :
uid = None
if isinstance ( item , dict ) :
uid = item . get ( "uid" )
if api . is_uid ( value ) :
uid = item
if uid is None :
logger . warn ( "Could extract UID of value" )
... |
def set ( self , name , value , ex = None , px = None , nx = False , xx = False ) :
"""Set the value at key ` ` name ` ` to ` ` value ` `
` ` ex ` ` sets an expire flag on key ` ` name ` ` for ` ` ex ` ` seconds .
` ` px ` ` sets an expire flag on key ` ` name ` ` for ` ` px ` ` milliseconds .
` ` nx ` ` if s... | with self . pipe as pipe :
value = self . valueparse . encode ( value )
return pipe . set ( self . redis_key ( name ) , value , ex = ex , px = px , nx = nx , xx = xx ) |
def _load_cmap_list ( self ) :
"""Searches the colormaps directory for all files , populates the list .""" | # store the current name
name = self . get_name ( )
# clear the list
self . _combobox_cmaps . blockSignals ( True )
self . _combobox_cmaps . clear ( )
# list the existing contents
paths = _settings . ListDir ( 'colormaps' )
# loop over the paths and add the names to the list
for path in paths :
self . _combobox_cma... |
def extract_images_generic ( pike , root , log , options ) :
"""Extract any > = 2bpp image we think we can improve""" | jpegs = [ ]
pngs = [ ]
for _ , xref , ext in extract_images ( pike , root , log , options , extract_image_generic ) :
log . debug ( 'xref = %s ext = %s' , xref , ext )
if ext == '.png' :
pngs . append ( xref )
elif ext == '.jpg' :
jpegs . append ( xref )
log . debug ( "Optimizable images: JP... |
def index_to_slices ( index ) :
"""take a numpy array of integers ( index ) and return a nested list of slices such that the slices describe the start , stop points for each integer in the index .
e . g .
> > > index = np . asarray ( [ 0,0,0,1,1,1,2,2,2 ] )
returns
> > > [ [ slice ( 0,3 , None ) ] , [ slice... | if len ( index ) == 0 :
return [ ]
# contruct the return structure
ind = np . asarray ( index , dtype = np . int )
ret = [ [ ] for i in range ( ind . max ( ) + 1 ) ]
# find the switchpoints
ind_ = np . hstack ( ( ind , ind [ 0 ] + ind [ - 1 ] + 1 ) )
switchpoints = np . nonzero ( ind_ - np . roll ( ind_ , + 1 ) ) [... |
def keyColor ( self , key ) :
"""Returns a color for the inputed key ( used in pie charts ) .
: param key | < str >
: return < QColor >""" | self . _keyColors . setdefault ( nativestring ( key ) , self . color ( ) )
return self . _keyColors [ nativestring ( key ) ] |
def get_func_kwargs ( func , recursive = True ) :
"""func = ibeis . run _ experiment
SeeAlso :
argparse _ funckw
recursive _ parse _ kwargs
parse _ kwarg _ keys
parse _ func _ kwarg _ keys
get _ func _ kwargs""" | import utool as ut
argspec = ut . get_func_argspec ( func )
if argspec . defaults is None :
header_kw = { }
else :
header_kw = dict ( zip ( argspec . args [ : : - 1 ] , argspec . defaults [ : : - 1 ] ) )
if argspec . keywords is not None :
header_kw . update ( dict ( ut . recursive_parse_kwargs ( func ) ) )... |
def retrieve_tags_from_component ( user , c_id ) :
"""Retrieve all tags attached to a component .""" | JCT = models . JOIN_COMPONENTS_TAGS
query = ( sql . select ( [ models . TAGS ] ) . select_from ( JCT . join ( models . TAGS ) ) . where ( JCT . c . component_id == c_id ) )
rows = flask . g . db_conn . execute ( query )
return flask . jsonify ( { 'tags' : rows , '_meta' : { 'count' : rows . rowcount } } ) |
def filter ( cls , parent = None , ** filters ) :
"""Gets all resources of the given type and parent ( if provided ) which match the given filters .
This will trigger an api GET request .
: param parent ResourceBase : the parent of the resource - used for nesting the request url , optional
: param * * filters... | data = cls . _process_filter_request ( parent , ** filters )
return cls . _load_resources ( data ) |
def FindByName ( cls , name ) :
"""Find a specific installed auth provider by name .""" | reg = ComponentRegistry ( )
for _ , entry in reg . load_extensions ( 'iotile.auth_provider' , name_filter = name ) :
return entry |
def local_ip ( ) :
"""Get the local network IP of this machine""" | try :
ip = socket . gethostbyname ( socket . gethostname ( ) )
except IOError :
ip = socket . gethostbyname ( 'localhost' )
if ip . startswith ( '127.' ) :
ip = get_local_ip_by_interfaces ( )
if ip is None :
ip = get_local_ip_by_socket ( )
return ip |
def write ( self , args ) : # pylint : disable = no - self - use
"""writes the progres""" | ShellProgressView . done = False
message = args . get ( 'message' , '' )
percent = args . get ( 'percent' , None )
if percent :
ShellProgressView . progress_bar = _format_value ( message , percent )
if int ( percent ) == 1 :
ShellProgressView . progress_bar = None
ShellProgressView . progress = message |
def unbind ( self , func , etype ) :
'''Remove @ func from the execution list for events with ` . type ` of @ etype
or meta - events with ` . utype ` of @ etype . If @ func is not in said list ,
a ValueError will be raised .''' | i = self . event_funcs [ etype ] . index ( func )
del self . event_funcs [ etype ] [ i ] |
def current_iid ( self ) :
"""Currently active item ' s iid
: rtype : str""" | current = self . current
if current is None or current not in self . _canvas_markers :
return None
return self . _canvas_markers [ current ] |
def density_2d ( self , x , y , rho0 , Ra , Rs , center_x = 0 , center_y = 0 ) :
"""projected density
: param x :
: param y :
: param rho0:
: param Ra :
: param Rs :
: param center _ x :
: param center _ y :
: return :""" | Ra , Rs = self . _sort_ra_rs ( Ra , Rs )
x_ = x - center_x
y_ = y - center_y
r = np . sqrt ( x_ ** 2 + y_ ** 2 )
sigma0 = self . rho2sigma ( rho0 , Ra , Rs )
sigma = sigma0 * Ra * Rs / ( Rs - Ra ) * ( 1 / np . sqrt ( Ra ** 2 + r ** 2 ) - 1 / np . sqrt ( Rs ** 2 + r ** 2 ) )
return sigma |
def _configure_from_mapping ( self , item , whitelist_keys = False , whitelist = None ) :
"""Configure from a mapping , or dict , like object .
Args :
item ( dict ) :
A dict - like object that we can pluck values from .
Keyword Args :
whitelist _ keys ( bool ) :
Should we whitelist the keys before addin... | if whitelist is None :
whitelist = self . config . keys ( )
if whitelist_keys :
item = { k : v for k , v in item . items ( ) if k in whitelist }
self . config . from_mapping ( item )
return self |
def proj_l1 ( x , radius = 1 , out = None ) :
r"""Projection onto l1 - ball .
Projection onto : :
` ` { x \ in X | | | x | | _ 1 \ leq r } ` `
with ` ` r ` ` being the radius .
Parameters
space : ` LinearSpace `
Space / domain ` ` X ` ` .
radius : positive float , optional
Radius ` ` r ` ` of the ba... | if out is None :
out = x . space . element ( )
u = x . ufuncs . absolute ( )
v = x . ufuncs . sign ( )
proj_simplex ( u , radius , out )
out *= v
return out |
def build_message ( self ) :
'''Build a message .
: raises InvalidPayloadError :''' | if self . _text is None :
raise InvalidPayloadError ( 'text is required' )
message = { 'text' : self . _text , 'markdown' : self . _markdown }
if self . _channel != Incoming . DEFAULT_CHANNEL :
message [ 'channel' ] = self . _channel
if self . _attachments :
message [ 'attachments' ] = [ ]
for attachmen... |
def purge_module ( self , module_name ) :
"""A module has been removed e . g . a module that had an error .
We need to find any containers and remove the module from them .""" | containers = self . config [ "py3_config" ] [ ".module_groups" ]
containers_to_update = set ( )
if module_name in containers :
containers_to_update . update ( set ( containers [ module_name ] ) )
for container in containers_to_update :
try :
self . modules [ container ] . module_class . items . remove (... |
def write_bytecode ( self , f ) :
"""Dump the bytecode into the file or file like object passed .""" | if self . code is None :
raise TypeError ( 'can\'t write empty bucket' )
f . write ( bc_magic )
pickle . dump ( self . checksum , f , 2 )
if isinstance ( f , file ) :
marshal . dump ( self . code , f )
else :
f . write ( marshal . dumps ( self . code ) ) |
def get_request_id ( self , renew = False ) :
""": Brief : This method is used in every place to get the already generated request ID or
generate new request ID and sent off""" | if not AppRequest . __request_id or renew :
self . set_request_id ( uuid . uuid1 ( ) )
return AppRequest . __request_id |
def dbmax20years ( self , value = None ) :
"""Corresponds to IDD Field ` dbmax20years `
20 - year return period values for maximum extreme dry - bulb temperature
Args :
value ( float ) : value for IDD Field ` dbmax20years `
Unit : C
if ` value ` is None it will not be checked against the
specification a... | if value is not None :
try :
value = float ( value )
except ValueError :
raise ValueError ( 'value {} need to be of type float ' 'for field `dbmax20years`' . format ( value ) )
self . _dbmax20years = value |
def get_asset_repository_assignment_session ( self ) :
"""Gets the session for assigning asset to repository mappings .
return : ( osid . repository . AssetRepositoryAssignmentSession ) - an
` ` AssetRepositoryAsignmentSession ` `
raise : OperationFailed - unable to complete request
raise : Unimplemented - ... | if not self . supports_asset_repository_assignment ( ) :
raise errors . Unimplemented ( )
# pylint : disable = no - member
return sessions . AssetRepositoryAssignmentSession ( runtime = self . _runtime ) |
def image_task ( self ) :
"""Returns a json - schema document that represents an task entity .""" | uri = "/%s/task" % self . uri_base
resp , resp_body = self . api . method_get ( uri )
return resp_body |
def get ( self , targetId ) :
"""Yields the analysed wav data .
: param targetId :
: return :""" | result = self . _targetController . analyse ( targetId )
if result :
if len ( result ) == 2 :
if result [ 1 ] == 404 :
return result
else :
return { 'name' : targetId , 'data' : self . _jsonify ( result ) } , 200
else :
return None , 404
else :
return None , 5... |
def BuildDefaultValue ( self , value_cls ) :
"""Renders default value of a given class .
Args :
value _ cls : Default value of this class will be rendered . This class has to
be ( or to be a subclass of ) a self . value _ class ( i . e . a class that this
renderer is capable of rendering ) .
Returns :
A... | try :
return value_cls ( )
except Exception as e : # pylint : disable = broad - except
logging . exception ( e )
raise DefaultValueError ( "Can't create default for value %s: %s" % ( value_cls . __name__ , e ) ) |
def reindex_rethrottle ( self , task_id = None , params = None ) :
"""Change the value of ` ` requests _ per _ second ` ` of a running ` ` reindex ` ` task .
` < https : / / www . elastic . co / guide / en / elasticsearch / reference / current / docs - reindex . html > ` _
: arg task _ id : The task id to rethr... | return self . transport . perform_request ( "POST" , _make_path ( "_reindex" , task_id , "_rethrottle" ) , params = params ) |
def output_ip ( gandi , ip , datacenters , vms , ifaces , output_keys , justify = 11 ) :
"""Helper to output an ip information .""" | output_generic ( gandi , ip , output_keys , justify )
if 'type' in output_keys :
iface = ifaces . get ( ip [ 'iface_id' ] )
type_ = 'private' if iface . get ( 'vlan' ) else 'public'
output_line ( gandi , 'type' , type_ , justify )
if type_ == 'private' :
output_line ( gandi , 'vlan' , iface [ 'v... |
def get_match_history ( self , account_id = None , ** kwargs ) :
"""Returns a dictionary containing a list of the most recent Dota matches
: param account _ id : ( int , optional )
: param hero _ id : ( int , optional )
: param game _ mode : ( int , optional ) see ` ` ref / modes . json ` `
: param skill : ... | if 'account_id' not in kwargs :
kwargs [ 'account_id' ] = account_id
url = self . __build_url ( urls . GET_MATCH_HISTORY , ** kwargs )
req = self . executor ( url )
if self . logger :
self . logger . info ( 'URL: {0}' . format ( url ) )
if not self . __check_http_err ( req . status_code ) :
return response ... |
def close ( self ) :
"""Close the connection this context wraps .""" | self . logger = None
for exc in _EXCEPTIONS :
setattr ( self , exc , None )
try :
self . mdr . close ( )
finally :
self . mdr = None |
def contribute_to_class ( model_class , name = 'slots' , descriptor = None ) :
"""Function that adds a description to a model Class .
: param model _ class : The model class the descriptor is to be added
to .
: param name : The attribute name the descriptor will be assigned to .
: param descriptor : The des... | rel_obj = descriptor or PlaceholderDescriptor ( )
rel_obj . contribute_to_class ( model_class , name )
setattr ( model_class , name , rel_obj )
return True |
def project_surface ( surface , angle = DEFAULT_ANGLE ) :
"""Returns the height of the surface when projected at the given angle .
Args :
surface ( surface ) : the surface to project
angle ( float ) : the angle at which to project the surface
Returns :
surface : A projected surface .""" | z_coef = np . sin ( np . radians ( angle ) )
y_coef = np . cos ( np . radians ( angle ) )
surface_height , surface_width = surface . shape
slope = np . tile ( np . linspace ( 0. , 1. , surface_height ) , [ surface_width , 1 ] ) . T
return slope * y_coef + surface * z_coef |
def resample_boundaries ( polygon , resolution , clip = None ) :
"""Return a version of a polygon with boundaries resampled
to a specified resolution .
Parameters
polygon : shapely . geometry . Polygon object
resolution : float , desired distance between points on boundary
clip : ( 2 , ) int , upper and l... | def resample_boundary ( boundary ) : # add a polygon . exterior or polygon . interior to
# the deque after resampling based on our resolution
count = boundary . length / resolution
count = int ( np . clip ( count , * clip ) )
return resample_path ( boundary . coords , count = count )
if clip is None :
c... |
async def receive_updates ( self , request : Request ) :
"""Handle updates from Telegram""" | body = await request . read ( )
try :
content = ujson . loads ( body )
except ValueError :
return json_response ( { 'error' : True , 'message' : 'Cannot decode body' , } , status = 400 )
logger . debug ( 'Received from Telegram: %s' , content )
message = TelegramMessage ( content , self )
responder = TelegramRe... |
def author ( self ) :
"""Return the full path of the theme used by this page .""" | r = self . site . site_config [ 'default_author' ]
if 'author' in self . _config :
r = self . _config [ 'author' ]
return r |
def _reciprocal_condition_number ( lu_mat , one_norm ) :
r"""Compute reciprocal condition number of a matrix .
Args :
lu _ mat ( numpy . ndarray ) : A 2D array of a matrix : math : ` A ` that has been
LU - factored , with the non - diagonal part of : math : ` L ` stored in the
strictly lower triangle and : ... | if _scipy_lapack is None :
raise OSError ( "This function requires SciPy for calling into LAPACK." )
# pylint : disable = no - member
rcond , info = _scipy_lapack . dgecon ( lu_mat , one_norm )
# pylint : enable = no - member
if info != 0 :
raise RuntimeError ( "The reciprocal 1-norm condition number could not ... |
def instagram_config ( self , id , secret , scope = None , ** _ ) :
"""Get config dictionary for instagram oauth""" | scope = scope if scope else 'basic'
token_params = dict ( scope = scope )
config = dict ( # request _ token _ url = None ,
access_token_url = '/oauth/access_token/' , authorize_url = '/oauth/authorize/' , base_url = 'https://api.instagram.com/' , consumer_key = id , consumer_secret = secret , request_token_params = tok... |
def BuscarCertConSaldoDisponible ( self , cuit_depositante = None , cod_grano = 2 , campania = 1314 , coe = None , fecha_emision_des = None , fecha_emision_has = None , ) :
"""Devuelve los certificados de depósito en los que un productor tiene
saldo disponible para Liquidar / Retirar / Transferir""" | ret = self . client . cgBuscarCertConSaldoDisponible ( auth = { 'token' : self . Token , 'sign' : self . Sign , 'cuit' : self . Cuit , } , cuitDepositante = cuit_depositante or self . Cuit , codGrano = cod_grano , campania = campania , coe = coe , fechaEmisionDes = fecha_emision_des , fechaEmisionHas = fecha_emision_ha... |
def is_valid ( data ) :
"""Checks if the input data is a Swagger document
: param dict data : Data to be validated
: return : True , if data is a Swagger""" | return bool ( data ) and isinstance ( data , dict ) and bool ( data . get ( "swagger" ) ) and isinstance ( data . get ( 'paths' ) , dict ) |
def _meanprecision ( D , tol = 1e-7 , maxiter = None ) :
'''Mean and precision alternating method for MLE of Dirichlet
distribution''' | N , K = D . shape
logp = log ( D ) . mean ( axis = 0 )
a0 = _init_a ( D )
s0 = a0 . sum ( )
if s0 < 0 :
a0 = a0 / s0
s0 = 1
elif s0 == 0 :
a0 = ones ( a . shape ) / len ( a )
s0 = 1
m0 = a0 / s0
# Start updating
if maxiter is None :
maxiter = MAXINT
for i in xrange ( maxiter ) :
a1 = _fit_s ( D ... |
def load ( self ) :
"""Load the data file , do some basic type conversions""" | df = pd . read_csv ( self . input_file , encoding = 'utf8' )
df [ 'wiki_id' ] = df [ 'artist' ] . str . split ( '/' ) . str [ - 1 ]
# some years of birth are given as timestamps with prefix ' t ' , convert to string
timestamps = df [ 'dob' ] . str . startswith ( 't' )
df . loc [ timestamps , 'dob' ] = df . loc [ timest... |
def make_blocks ( ec_infos , codewords ) :
"""Returns the data and error blocks .
: param ec _ infos : Iterable of ECC information
: param codewords : Iterable of ( integer ) code words .""" | data_blocks , error_blocks = [ ] , [ ]
offset = 0
for ec_info in ec_infos :
for i in range ( ec_info . num_blocks ) :
block = codewords [ offset : offset + ec_info . num_data ]
data_blocks . append ( block )
error_blocks . append ( make_error_block ( ec_info , block ) )
offset += ec_... |
def lgauss ( x , mu , sigma = 1.0 , logpdf = False ) :
"""Log10 normal distribution . . .
x : Parameter of interest for scanning the pdf
mu : Peak of the lognormal distribution ( mean of the underlying
normal distribution is log10 ( mu )
sigma : Standard deviation of the underlying normal distribution""" | x = np . array ( x , ndmin = 1 )
lmu = np . log10 ( mu )
s2 = sigma * sigma
lx = np . zeros ( x . shape )
v = np . zeros ( x . shape )
lx [ x > 0 ] = np . log10 ( x [ x > 0 ] )
v = 1. / np . sqrt ( 2 * s2 * np . pi ) * np . exp ( - ( lx - lmu ) ** 2 / ( 2 * s2 ) )
if not logpdf :
v /= ( x * np . log ( 10. ) )
v [ x... |
def lhlo ( self ) :
"""Send LMTP LHLO greeting , and process the server response .
A regular LMTP greeting is sent , and if accepted by the server , the
capabilities it returns are parsed .
DLMTP authentication starts here by announcing the dlmtp _ ident in
the LHLO as our hostname . When the ident is accep... | if self . dlmtp_ident is not None :
host = self . dlmtp_ident
else :
host = socket . getfqdn ( )
self . _send ( 'LHLO ' + host + '\r\n' )
finished = False
while not finished :
resp = self . _read ( )
if not resp . startswith ( '250' ) :
raise DspamClientError ( 'Unexpected server response at LHL... |
def duplicate ( self , request , * args , ** kwargs ) :
"""Duplicate ( make copy of ) ` ` Collection ` ` models .""" | if not request . user . is_authenticated :
raise exceptions . NotFound
ids = self . get_ids ( request . data )
queryset = get_objects_for_user ( request . user , 'view_collection' , Collection . objects . filter ( id__in = ids ) )
actual_ids = queryset . values_list ( 'id' , flat = True )
missing_ids = list ( set (... |
def send ( self , path , value , metric_type ) :
"""Send a metric to Statsd .
: param list path : The metric path to record
: param mixed value : The value to record
: param str metric _ type : The metric type""" | msg = self . _msg_format . format ( path = self . _build_path ( path , metric_type ) , value = value , metric_type = metric_type )
LOGGER . debug ( 'Sending %s to %s:%s' , msg . encode ( 'ascii' ) , self . _host , self . _port )
try :
if self . _tcp :
if self . _sock . closed ( ) :
return
... |
def get_weights ( self ) :
'''Computes the PLD weights vector : py : obj : ` w ` .
. . warning : : Deprecated and not thoroughly tested .''' | log . info ( "Computing PLD weights..." )
# Loop over all chunks
weights = [ None for i in range ( len ( self . breakpoints ) ) ]
for b , brkpt in enumerate ( self . breakpoints ) : # Masks for current chunk
m = self . get_masked_chunk ( b )
c = self . get_chunk ( b )
# This block of the masked covariance m... |
def bounds ( self , pixelbuffer = 0 ) :
"""Return Tile boundaries .
- pixelbuffer : tile buffer in pixels""" | left = self . _left
bottom = self . _bottom
right = self . _right
top = self . _top
if pixelbuffer :
offset = self . pixel_x_size * float ( pixelbuffer )
left -= offset
bottom -= offset
right += offset
top += offset
# on global grids clip at northern and southern TilePyramid bound
if self . tp . gri... |
def log ( message , severity = "INFO" , print_debug = True ) :
"""Logs , prints , or raises a message .
Arguments :
message - - message to report
severity - - string of one of these values :
CRITICAL | ERROR | WARNING | INFO | DEBUG""" | print_me = [ 'WARNING' , 'INFO' , 'DEBUG' ]
if severity in print_me :
if severity == 'DEBUG' :
if print_debug :
print ( "{0}: {1}" . format ( severity , message ) )
else :
print ( "{0}: {1}" . format ( severity , message ) )
else :
raise Exception ( "{0}: {1}" . format ( severity... |
def mkdir ( dirname , overwrite = False ) :
"""Wraps around os . mkdir ( ) , but checks for existence first .""" | if op . isdir ( dirname ) :
if overwrite :
shutil . rmtree ( dirname )
os . mkdir ( dirname )
logging . debug ( "Overwrite folder `{0}`." . format ( dirname ) )
else :
return False
# Nothing is changed
else :
try :
os . mkdir ( dirname )
except :
o... |
def print_message ( self , message , verbosity_needed = 1 ) :
"""Prints the message , if verbosity is high enough .""" | if self . args . verbosity >= verbosity_needed :
print ( message ) |
def is_fp_closed ( obj ) :
"""Checks whether a given file - like object is closed .
: param obj :
The file - like object to check .""" | try : # Check ` isclosed ( ) ` first , in case Python3 doesn ' t set ` closed ` .
# GH Issue # 928
return obj . isclosed ( )
except AttributeError :
pass
try : # Check via the official file - like - object way .
return obj . closed
except AttributeError :
pass
try : # Check if the object is a container ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.