signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def eye ( N , M = 0 , k = 0 , ctx = None , dtype = None , ** kwargs ) :
"""Return a 2 - D array with ones on the diagonal and zeros elsewhere .
Parameters
N : int
Number of rows in the output .
M : int , optional
Number of columns in the output . If 0 , defaults to N .
k : int , optional
Index of the ... | # pylint : disable = unused - argument
if ctx is None :
ctx = current_context ( )
dtype = mx_real_t if dtype is None else dtype
# pylint : disable = no - member , protected - access
return _internal . _eye ( N = N , M = M , k = k , ctx = ctx , dtype = dtype , ** kwargs ) |
def start ( ) :
r"""Starts ec .""" | processPendingModules ( )
if not state . main_module_name in ModuleMembers : # don ' t start the core when main is not Ec - ed
return
MainModule = sys . modules [ state . main_module_name ]
if not MainModule . __ec_member__ . Members : # there was some error while loading script ( s )
return
global BaseGroup
Ba... |
def reset ( self , route = None ) :
'''Reset all routes ( force plugins to be re - applied ) and clear all
caches . If an ID or route object is given , only that specific route
is affected .''' | if route is None :
routes = self . routes
elif isinstance ( route , Route ) :
routes = [ route ]
else :
routes = [ self . routes [ route ] ]
for route in routes :
route . reset ( )
if DEBUG :
for route in routes :
route . prepare ( )
self . trigger_hook ( 'app_reset' ) |
def square_root_mod_prime ( a , p ) :
"""Modular square root of a , mod p , p prime .""" | # Based on the Handbook of Applied Cryptography , algorithms 3.34 to 3.39.
# This module has been tested for all values in [ 0 , p - 1 ] for
# every prime p from 3 to 1229.
assert 0 <= a < p
assert 1 < p
if a == 0 :
return 0
if p == 2 :
return a
jac = jacobi ( a , p )
if jac == - 1 :
raise SquareRootError (... |
def rewrite_properties ( self , properties ) :
"""Set the properties and write to disk .""" | with self . __library_storage_lock :
self . __library_storage = properties
self . __write_properties ( None ) |
def statuses_show ( self , id , trim_user = None , include_my_retweet = None , include_entities = None ) :
"""Returns a single Tweet , specified by the id parameter .
https : / / dev . twitter . com / docs / api / 1.1 / get / statuses / show / % 3Aid
: param str id :
( * required * ) The numerical ID of the d... | params = { 'id' : id }
set_bool_param ( params , 'trim_user' , trim_user )
set_bool_param ( params , 'include_my_retweet' , include_my_retweet )
set_bool_param ( params , 'include_entities' , include_entities )
return self . _get_api ( 'statuses/show.json' , params ) |
def gha ( julian_day , f ) :
"""returns greenwich hour angle""" | rad = old_div ( np . pi , 180. )
d = julian_day - 2451545.0 + f
L = 280.460 + 0.9856474 * d
g = 357.528 + 0.9856003 * d
L = L % 360.
g = g % 360.
# ecliptic longitude
lamb = L + 1.915 * np . sin ( g * rad ) + .02 * np . sin ( 2 * g * rad )
# obliquity of ecliptic
epsilon = 23.439 - 0.0000004 * d
# right ascension ( in ... |
def visual ( title , X , activation ) :
'''create a grid of images and save it as a final image
title : grid image name
X : array of images''' | assert len ( X . shape ) == 4
X = X . transpose ( ( 0 , 2 , 3 , 1 ) )
if activation == 'sigmoid' :
X = np . clip ( ( X ) * ( 255.0 ) , 0 , 255 ) . astype ( np . uint8 )
elif activation == 'tanh' :
X = np . clip ( ( X + 1.0 ) * ( 255.0 / 2.0 ) , 0 , 255 ) . astype ( np . uint8 )
n = np . ceil ( np . sqrt ( X . s... |
def listDatasetArray ( self , ** kwargs ) :
"""API to list datasets in DBS .
: param dataset : list of datasets [ dataset1 , dataset2 , . . , dataset n ] ( Required if dataset _ id is not presented ) , Max length 1000.
: type dataset : list
: param dataset _ id : list of dataset _ ids that are the primary key... | validParameters = [ 'dataset' , 'dataset_access_type' , 'detail' , 'dataset_id' ]
requiredParameters = { 'multiple' : [ 'dataset' , 'dataset_id' ] }
checkInputParameter ( method = "listDatasetArray" , parameters = kwargs . keys ( ) , validParameters = validParameters , requiredParameters = requiredParameters )
# set de... |
def generate_identifier ( result ) :
"""Returns a fixed length identifier based on a hash of a combined set of
playbook / task values which are as close as we can guess to unique for each
task .""" | # Determine the playbook file path to use for the ID
if result . task . playbook and result . task . playbook . path :
playbook_file = result . task . playbook . path
else :
playbook_file = ''
play_path = u'%s.%s' % ( playbook_file , result . task . play . name )
# Determine the task file path to use for the ID... |
def _add_saved_device_info ( self , ** kwarg ) :
"""Register device info from the saved data file .""" | addr = kwarg . get ( 'address' )
_LOGGER . debug ( 'Found saved device with address %s' , addr )
self . _saved_devices [ addr ] = kwarg |
def shorten ( string , maxlen ) :
"""shortens string if longer than maxlen , appending ellipsis""" | if 1 < maxlen < len ( string ) :
string = string [ : maxlen - 1 ] + u'…'
return string [ : maxlen ] |
def _edit_main ( self , request ) :
"""Adds the link to the new unit testing results on the repo ' s main wiki page .""" | self . prefix = "{}_Pull_Request_{}" . format ( request . repo . name , request . pull . number )
if not self . testmode :
page = site . pages [ self . basepage ]
text = page . text ( )
else :
text = "This is a fake wiki page.\n\n<!--@CI:Placeholder-->"
self . newpage = self . prefix
link = "Pull Request #{... |
def is_package ( name ) :
"""Check if string maps to a package installed via pip .
name ( unicode ) : Name of package .
RETURNS ( bool ) : True if installed package , False if not .""" | name = name . lower ( )
# compare package name against lowercase name
packages = pkg_resources . working_set . by_key . keys ( )
for package in packages :
if package . lower ( ) . replace ( '-' , '_' ) == name :
return True
return False |
def filter_rows ( self , filters , rows ) :
'''returns rows as filtered by filters''' | ret = [ ]
for row in rows :
if not self . row_is_filtered ( row , filters ) :
ret . append ( row )
return ret |
def gen_matches ( self , word ) :
"""Generate a sequence of possible completions for ` ` word ` ` .
: param word : the word to complete""" | if word . startswith ( "$" ) :
for match in self . gen_variable_completions ( word , os . environ ) :
yield match
else :
head , tail = os . path . split ( word )
filenames = os . listdir ( head or '.' )
completions = self . gen_filename_completions ( tail , filenames )
for match in completio... |
def _get_paths ( options ) :
"""Retrieves paths needed to run sphinx .
Returns a Bundle with the required values filled in .""" | opts = options
docroot = path ( opts . get ( 'docroot' , 'docs' ) )
if not docroot . exists ( ) :
raise BuildFailure ( "Sphinx documentation root (%s) does not exist." % docroot )
builddir = docroot / opts . get ( "builddir" , ".build" )
srcdir = docroot / opts . get ( "sourcedir" , "" )
if not srcdir . exists ( ) ... |
def from_yuv ( y , u , v , alpha = 1.0 , wref = _DEFAULT_WREF ) :
"""Create a new instance based on the specifed YUV values .
Parameters :
The Y component value [ 0 . . . 1]
The U component value [ - 0.436 . . . 0.436]
The V component value [ - 0.615 . . . 0.615]
: alpha :
The color transparency [ 0 . .... | return Color ( yuv_to_rgb ( y , u , v ) , 'rgb' , alpha , wref ) |
def set_contents_from_string ( self , s , headers = None , replace = True , cb = None , num_cb = 10 , policy = None , md5 = None ) :
"""Store an object in S3 using the name of the Key object as the
key in S3 and the string ' s ' as the contents .
See set _ contents _ from _ file method for details about the
p... | if isinstance ( s , unicode ) :
s = s . encode ( "utf-8" )
fp = StringIO . StringIO ( s )
r = self . set_contents_from_file ( fp , headers , replace , cb , num_cb , policy , md5 )
fp . close ( )
return r |
def intervalantijoin ( left , right , lstart = 'start' , lstop = 'stop' , rstart = 'start' , rstop = 'stop' , lkey = None , rkey = None , include_stop = False , missing = None ) :
"""Return rows from the ` left ` table with no overlapping rows from the ` right `
table .
Note start coordinates are included and s... | assert ( lkey is None ) == ( rkey is None ) , 'facet key field must be provided for both or neither table'
return IntervalAntiJoinView ( left , right , lstart = lstart , lstop = lstop , rstart = rstart , rstop = rstop , lkey = lkey , rkey = rkey , include_stop = include_stop , missing = missing ) |
def ActionEnum ( ctx ) :
"""Action Enumeration .""" | return Enum ( ctx , interact = 0 , stop = 1 , ai_interact = 2 , move = 3 , add_attribute = 5 , give_attribute = 6 , ai_move = 10 , resign = 11 , spec = 15 , waypoint = 16 , stance = 18 , guard = 19 , follow = 20 , patrol = 21 , formation = 23 , save = 27 , ai_waypoint = 31 , chapter = 32 , ai_command = 53 , ai_queue = ... |
def download_sheet ( self , file_path , sheet_id , cell_range ) :
"""Download the cell range from the sheet and store it as CSV in the
` file _ path ` file .""" | result = self . service . spreadsheets ( ) . values ( ) . get ( spreadsheetId = sheet_id , range = cell_range , ) . execute ( )
values = result . get ( 'values' , [ ] )
with open ( file_path , newline = '' , encoding = 'utf-8' , mode = 'w' ) as f :
writer = csv . writer ( f , lineterminator = '\n' )
for row in ... |
def _compute_rtfilter_map ( self ) :
"""Returns neighbor ' s RT filter ( permit / allow filter based on RT ) .
Walks RT filter tree and computes current RT filters for each peer that
have advertised RT NLRIs .
Returns :
dict of peer , and ` set ` of rts that a particular neighbor is
interested in .""" | rtfilter_map = { }
def get_neigh_filter ( neigh ) :
neigh_filter = rtfilter_map . get ( neigh )
# Lazy creation of neighbor RT filter
if neigh_filter is None :
neigh_filter = set ( )
rtfilter_map [ neigh ] = neigh_filter
return neigh_filter
# Check if we have to use all paths or just bes... |
def ApplicationReceiving ( self , app , streams ) :
"""Called when the list of streams with data ready to be read changes .""" | # we should only proceed if we are in TCP mode
if stype != socket . SOCK_STREAM :
return
# handle all streams
for stream in streams : # read object from the stream
obj = StreamRead ( stream )
if obj :
if obj [ 0 ] == cmdData : # data were received , reroute it to the tunnel based on the tunnel ID
... |
def power_law ( target , X , A1 = '' , A2 = '' , A3 = '' ) :
r"""Calculates the rate , as well as slope and intercept of the following
function at the given value of * X * :
. . math : :
r = A _ { 1 } x ^ { A _ { 2 } } + A _ { 3}
Parameters
A1 - > A3 : string
The dictionary keys on the target object con... | A = _parse_args ( target = target , key = A1 , default = 1.0 )
B = _parse_args ( target = target , key = A2 , default = 1.0 )
C = _parse_args ( target = target , key = A3 , default = 0.0 )
X = target [ X ]
r = A * X ** B + C
S1 = A * B * X ** ( B - 1 )
S2 = A * X ** B * ( 1 - B ) + C
values = { 'S1' : S1 , 'S2' : S2 , ... |
def contextMenuEvent ( self , event ) :
"""Slot automatically called by Qt on right click on the WebView .
: param event : the event that caused the context menu to be called .""" | context_menu = QMenu ( self )
# add select all
action_select_all = self . page ( ) . action ( QtWebKitWidgets . QWebPage . SelectAll )
action_select_all . setEnabled ( not self . page_to_text ( ) == '' )
context_menu . addAction ( action_select_all )
# add copy
action_copy = self . page ( ) . action ( QtWebKitWidgets .... |
def download ( name , course , github = 'SheffieldML/notebook/master/lab_classes/' ) :
"""Download a lab class from the relevant course
: param course : the course short name to download the class from .
: type course : string
: param reference : reference to the course for downloading the class .
: type re... | github_stub = 'https://raw.githubusercontent.com/'
if not name . endswith ( '.ipynb' ) :
name += '.ipynb'
from pods . util import download_url
download_url ( os . path . join ( github_stub , github , course , name ) , store_directory = course ) |
def is_empty ( self ) :
"""Test interval emptiness .
: return : True if interval is empty , False otherwise .""" | return ( self . _lower > self . _upper or ( self . _lower == self . _upper and ( self . _left == OPEN or self . _right == OPEN ) ) ) |
def plugin ( cls , name ) :
"""Retrieves the plugin based on the inputted name .
: param name | < str >
: return < Plugin >""" | cls . loadPlugins ( )
plugs = getattr ( cls , '_%s__plugins' % cls . __name__ , { } )
return plugs . get ( nstr ( name ) ) |
def stop ( self , accountID , ** kwargs ) :
"""Shortcut to create a Stop Order in an Account
Args :
accountID : The ID of the Account
kwargs : The arguments to create a StopOrderRequest
Returns :
v20 . response . Response containing the results from submitting
the request""" | return self . create ( accountID , order = StopOrderRequest ( ** kwargs ) ) |
def take_off ( self , height = None , velocity = VELOCITY ) :
"""Takes off , that is starts the motors , goes straigt up and hovers .
Do not call this function if you use the with keyword . Take off is
done automatically when the context is created .
: param height : the height ( meters ) to hover at . None u... | if self . _is_flying :
raise Exception ( 'Already flying' )
if not self . _cf . is_connected ( ) :
raise Exception ( 'Crazyflie is not connected' )
self . _is_flying = True
self . _reset_position_estimator ( )
self . _thread = _SetPointThread ( self . _cf )
self . _thread . start ( )
if height is None :
hei... |
def read_parameters ( self ) :
"""Read a parameters . out file
Returns
dict
A dictionary containing all the configuration used by MAGICC""" | param_fname = join ( self . out_dir , "PARAMETERS.OUT" )
if not exists ( param_fname ) :
raise FileNotFoundError ( "No PARAMETERS.OUT found" )
with open ( param_fname ) as nml_file :
parameters = dict ( f90nml . read ( nml_file ) )
for group in [ "nml_years" , "nml_allcfgs" , "nml_outputcfgs" ] :
pa... |
def initialize_hmac ( self ) : # type : ( EncryptionMetadata ) - > hmac . HMAC
"""Initialize an hmac from a signing key if it exists
: param EncryptionMetadata self : this
: rtype : hmac . HMAC or None
: return : hmac""" | if self . _signkey is not None :
return hmac . new ( self . _signkey , digestmod = hashlib . sha256 )
else :
return None |
def run_cm ( cm , time_scale ) :
"""Iterate a connectivity matrix the specified number of steps .
Args :
cm ( np . ndarray ) : A connectivity matrix .
time _ scale ( int ) : The number of steps to run .
Returns :
np . ndarray : The connectivity matrix at the new timescale .""" | cm = np . linalg . matrix_power ( cm , time_scale )
# Round non - unitary values back to 1
cm [ cm > 1 ] = 1
return cm |
def full_subgraph ( self , vertices ) :
"""Return the subgraph of this graph whose vertices
are the given ones and whose edges are all the edges
of the original graph between those vertices .""" | subgraph_vertices = { v for v in vertices }
subgraph_edges = { edge for v in subgraph_vertices for edge in self . _out_edges [ v ] if self . _heads [ edge ] in subgraph_vertices }
subgraph_heads = { edge : self . _heads [ edge ] for edge in subgraph_edges }
subgraph_tails = { edge : self . _tails [ edge ] for edge in s... |
def is_eyeish ( board , c ) :
'Check if c is an eye , for the purpose of restricting MC rollouts .' | # pass is fine .
if c is None :
return
color = is_koish ( board , c )
if color is None :
return None
diagonal_faults = 0
diagonals = DIAGONALS [ c ]
if len ( diagonals ) < 4 :
diagonal_faults += 1
for d in diagonals :
if not board [ d ] in ( color , EMPTY ) :
diagonal_faults += 1
if diagonal_fau... |
def place ( vertices_resources , nets , machine , constraints , chip_order = None ) :
"""Places vertices in breadth - first order onto chips in the machine .
This is a thin wrapper around the : py : func : ` sequential
< rig . place _ and _ route . place . sequential . place > ` placement algorithm which
uses... | return sequential_place ( vertices_resources , nets , machine , constraints , breadth_first_vertex_order ( vertices_resources , nets ) , chip_order ) |
def get_word_file ( self , mmax_base_file ) :
"""parses an MMAX base file ( ` ` * . mmax ` ` ) and returns the path
to the corresponding ` ` _ words . xml ` ` file ( which contains
the tokens of the document ) .""" | return os . path . join ( self . mmax_project . paths [ 'project_path' ] , self . mmax_project . paths [ 'basedata' ] , etree . parse ( mmax_base_file ) . find ( '//words' ) . text ) |
def rotation_matrix ( self ) :
"""Get the 3x3 rotation matrix equivalent of the quaternion rotation .
Returns :
A 3x3 orthogonal rotation matrix as a 3x3 Numpy array
Note :
This feature only makes sense when referring to a unit quaternion . Calling this method will implicitly normalise the Quaternion object... | self . _normalise ( )
product_matrix = np . dot ( self . _q_matrix ( ) , self . _q_bar_matrix ( ) . conj ( ) . transpose ( ) )
return product_matrix [ 1 : ] [ : , 1 : ] |
def add_option ( self , K = None , price = None , St = None , kind = "call" , pos = "long" ) :
"""Add an option to the object ' s ` options ` container .""" | kinds = { "call" : Call , "Call" : Call , "c" : Call , "C" : Call , "put" : Put , "Put" : Put , "p" : Put , "P" : Put , }
St = self . St if St is None else St
option = kinds [ kind ] ( St = St , K = K , price = price , pos = pos )
self . options . append ( option ) |
def get_size_in_bytes ( self , handle ) :
"""Return the size in bytes .""" | fpath = self . _fpath_from_handle ( handle )
return os . stat ( fpath ) . st_size |
def _module_name ( filename ) :
"""Try to find a module name for a file path
by stripping off a prefix found in sys . modules .""" | absfile = os . path . abspath ( filename )
match = filename
for base in [ '' ] + sys . path :
base = os . path . abspath ( base )
if absfile . startswith ( base ) :
match = absfile [ len ( base ) : ]
break
return SUFFIX_RE . sub ( '' , match ) . lstrip ( '/' ) . replace ( '/' , '.' ) |
def plotConvergenceByDistantConnectionChance ( results , featureRange , columnRange , longDistanceConnectionsRange , numTrials ) :
"""Plots the convergence graph : iterations vs number of columns .
Each curve shows the convergence for a given number of unique features .""" | # Accumulate all the results per column in a convergence array .
# Convergence [ f , c , t ] = how long it took it to converge with f unique
# features , c columns and topology t .
convergence = numpy . zeros ( ( len ( featureRange ) , len ( longDistanceConnectionsRange ) , len ( columnRange ) ) )
for r in results :
... |
def prune ( tdocs ) :
"""Prune terms which are totally subsumed by a phrase
This could be better if it just removes the individual keywords
that occur in a phrase for each time that phrase occurs .""" | all_terms = set ( [ t for toks in tdocs for t in toks ] )
terms = set ( )
phrases = set ( )
for t in all_terms :
if gram_size ( t ) > 1 :
phrases . add ( t )
else :
terms . add ( t )
# Identify candidates for redundant terms ( 1 - gram terms found in a phrase )
redundant = set ( )
for t in terms... |
def get_files ( self , file_paths ) :
"""returns a list of files faster by using threads""" | results = [ ]
def get_file_thunk ( path , interface ) :
result = error = None
try :
result = interface . get_file ( path )
except Exception as err :
error = err
# important to print immediately because
# errors are collected at the end
print ( err )
content , enco... |
def replacePatterns ( self , vector , layer = None ) :
"""Replaces patterned inputs or targets with activation vectors .""" | if not self . patterned :
return vector
if type ( vector ) == str :
return self . replacePatterns ( self . lookupPattern ( vector , layer ) , layer )
elif type ( vector ) != list :
return vector
# should be a vector if we made it here
vec = [ ]
for v in vector :
if type ( v ) == str :
retval = s... |
def match_dim_specs ( specs1 , specs2 ) :
"""Matches dimension specs used to link axes .
Axis dimension specs consists of a list of tuples corresponding
to each dimension , each tuple spec has the form ( name , label , unit ) .
The name and label must match exactly while the unit only has to
match if both s... | if ( specs1 is None or specs2 is None ) or ( len ( specs1 ) != len ( specs2 ) ) :
return False
for spec1 , spec2 in zip ( specs1 , specs2 ) :
for s1 , s2 in zip ( spec1 , spec2 ) :
if s1 is None or s2 is None :
continue
if s1 != s2 :
return False
return True |
def _generate_state ( self , trans ) :
"""Creates a new POP state ( type - 2 ) with the same transitions .
The POPed symbol is the unique number of the state .
Args :
trans ( dict ) : Transition dictionary
Returns :
Int : The state identifier""" | state = PDAState ( )
state . id = self . nextstate ( )
state . type = 2
state . sym = state . id
state . trans = trans . copy ( )
self . toadd . append ( state )
return state . id |
def percentile ( values , percent ) :
"""PERCENTILE WITH INTERPOLATION
RETURN VALUE AT , OR ABOVE , percentile OF THE VALUES
snagged from http : / / code . activestate . com / recipes / 511478 - finding - the - percentile - of - the - values /""" | N = sorted ( values )
if not N :
return None
k = ( len ( N ) - 1 ) * percent
f = int ( math . floor ( k ) )
c = int ( math . ceil ( k ) )
if f == c :
return N [ int ( k ) ]
d0 = N [ f ] * ( c - k )
d1 = N [ c ] * ( k - f )
return d0 + d1 |
def path ( self , args , kw ) :
"""Builds the URL path fragment for this route .""" | params = self . _pop_params ( args , kw )
if args or kw :
raise InvalidArgumentError ( "Extra parameters (%s, %s) when building path for %s" % ( args , kw , self . template ) )
return self . build_url ( ** params ) |
def format_file_node ( import_graph , node , indent ) :
"""Prettyprint nodes based on their provenance .""" | f = import_graph . provenance [ node ]
if isinstance ( f , resolve . Direct ) :
out = '+ ' + f . short_path
elif isinstance ( f , resolve . Local ) :
out = ' ' + f . short_path
elif isinstance ( f , resolve . System ) :
out = ':: ' + f . short_path
elif isinstance ( f , resolve . Builtin ) :
out = '(%s... |
def _sanity_check_no_nested_folds ( ir_blocks ) :
"""Assert that there are no nested Fold contexts , and that every Fold has a matching Unfold .""" | fold_seen = False
for block in ir_blocks :
if isinstance ( block , Fold ) :
if fold_seen :
raise AssertionError ( u'Found a nested Fold contexts: {}' . format ( ir_blocks ) )
else :
fold_seen = True
elif isinstance ( block , Unfold ) :
if not fold_seen :
... |
def displayname ( self ) :
"""Return the display name for the entity referenced by this cursor .
The display name contains extra information that helps identify the
cursor , such as the parameters of a function or template or the
arguments of a class template specialization .""" | if not hasattr ( self , '_displayname' ) :
self . _displayname = conf . lib . clang_getCursorDisplayName ( self )
return self . _displayname |
def refine ( args ) :
"""% prog refine bedfile1 bedfile2 refinedbed
Refine bed file using a second bed file . The final bed is keeping all the
intervals in bedfile1 , but refined by bedfile2 whenever they have
intersection .""" | p = OptionParser ( refine . __doc__ )
opts , args = p . parse_args ( args )
if len ( args ) != 3 :
sys . exit ( not p . print_help ( ) )
abedfile , bbedfile , refinedbed = args
fw = open ( refinedbed , "w" )
intersected = refined = 0
for a , b in intersectBed_wao ( abedfile , bbedfile ) :
if b is None :
... |
def read_data ( self , timeout = 10.0 ) :
"""Read blocks of raw PCM data from the file .""" | # Read from stdout in a separate thread and consume data from
# the queue .
start_time = time . time ( )
while True : # Wait for data to be available or a timeout .
data = None
try :
data = self . stdout_reader . queue . get ( timeout = timeout )
if data :
yield data
else : #... |
def create_ckan_ini ( self ) :
"""Use make - config to generate an initial development . ini file""" | self . run_command ( command = '/scripts/run_as_user.sh /usr/lib/ckan/bin/paster make-config' ' ckan /project/development.ini' , rw_project = True , ro = { scripts . get_script_path ( 'run_as_user.sh' ) : '/scripts/run_as_user.sh' } , ) |
def tolerate ( substitute = None , exceptions = None , switch = DEFAULT_TOLERATE_SWITCH ) :
"""A function decorator which makes a function fail silently
To disable fail silently in a decorated function , specify
` ` fail _ silently = False ` ` .
To disable fail silenlty in decorated functions globally , speci... | def decorator ( fn ) :
@ wraps ( fn )
def inner ( * args , ** kwargs ) :
if getattr ( tolerate , 'disabled' , False ) : # the function has disabled so call normally .
return fn ( * args , ** kwargs )
if switch is not None :
status , args , kwargs = switch ( * args , ** kw... |
def clean_retinotopy_potential ( hemi , retinotopy = Ellipsis , mask = Ellipsis , weight = Ellipsis , surface = 'midgray' , min_weight = Ellipsis , min_eccentricity = 0.75 , visual_area = None , map_visual_areas = Ellipsis , visual_area_field_signs = Ellipsis , measurement_uncertainty = 0.3 , measurement_knob = 1 , mag... | from neuropythy . util import curry
import neuropythy . optimize as op
# first , get the mesh and the retinotopy data
mesh = geo . to_mesh ( ( hemi , surface ) )
rdat = ( retinotopy_data ( mesh ) if retinotopy is Ellipsis else retinotopy if pimms . is_map ( retinotopy ) else retinotopy_data ( mesh , retinotopy ) )
lbls... |
def do_macro_arg ( parser , token ) :
"""Function taking a parsed template tag
to a MacroArgNode .""" | # macro _ arg takes no arguments , so we don ' t
# need to split the token / do validation .
nodelist = parser . parse ( ( 'endmacro_arg' , ) )
parser . delete_first_token ( )
# simply save the contents to a MacroArgNode .
return MacroArgNode ( nodelist ) |
def hybrid_forward ( self , F , inputs , mask = None ) : # pylint : disable = arguments - differ
r"""Forward computation for char _ encoder
Parameters
inputs : NDArray
The input tensor is of shape ` ( seq _ len , batch _ size , embedding _ size ) ` TNC .
mask : NDArray
The mask applied to the input of sha... | if mask is not None :
inputs = F . broadcast_mul ( inputs , mask . expand_dims ( - 1 ) )
inputs = F . transpose ( inputs , axes = ( 1 , 2 , 0 ) )
output = self . _convs ( inputs )
if self . _highways :
output = self . _highways ( output )
if self . _projection :
output = self . _projection ( output )
return... |
def _read_register ( self , reg ) :
"""Read 16 bit register value .""" | self . buf [ 0 ] = reg
with self . i2c_device as i2c :
i2c . write ( self . buf , end = 1 , stop = False )
i2c . readinto ( self . buf , end = 2 )
return self . buf [ 0 ] << 8 | self . buf [ 1 ] |
def _shift_wavelengths ( model1 , model2 ) :
"""One of the models is either ` ` RedshiftScaleFactor ` ` or ` ` Scale ` ` .
Possible combos : :
RedshiftScaleFactor | Model
Scale | Model
Model | Scale""" | if isinstance ( model1 , _models . RedshiftScaleFactor ) :
val = _get_sampleset ( model2 )
if val is None :
w = val
else :
w = model1 . inverse ( val )
elif isinstance ( model1 , _models . Scale ) :
w = _get_sampleset ( model2 )
else :
w = _get_sampleset ( model1 )
return w |
def get_default_config ( self ) :
"""Returns the default collector settings""" | config = super ( MemoryCgroupCollector , self ) . get_default_config ( )
config . update ( { 'path' : 'memory_cgroup' , 'memory_path' : '/sys/fs/cgroup/memory/' , 'skip' : [ ] , } )
return config |
def start ( self , attach = False ) :
"""Start a container . If the container is running it will return itself .
returns a running Container .""" | if self . state ( ) [ 'running' ] :
logger . info ( 'is already running.' , extra = { 'formatter' : 'container' , 'container' : self . name } )
return True
else :
try :
logger . info ( 'is being started.' , extra = { 'formatter' : 'container' , 'container' : self . name } )
# returns None on... |
def prompt_pass ( name , default = None ) :
"""Grabs hidden ( password ) input from command line .
: param name : prompt text
: param default : default value if no input provided .""" | prompt = name + ( default and ' [%s]' % default or '' )
prompt += name . endswith ( '?' ) and ' ' or ': '
while True :
rv = getpass . getpass ( prompt )
if rv :
return rv
if default is not None :
return default |
def _dcm_to_q ( self , dcm ) :
"""Create q from dcm
Reference :
- Shoemake , Quaternions ,
http : / / www . cs . ucr . edu / ~ vbz / resources / quatut . pdf
: param dcm : 3x3 dcm array
returns : quaternion array""" | assert ( dcm . shape == ( 3 , 3 ) )
q = np . zeros ( 4 )
tr = np . trace ( dcm )
if tr > 0 :
s = np . sqrt ( tr + 1.0 )
q [ 0 ] = s * 0.5
s = 0.5 / s
q [ 1 ] = ( dcm [ 2 ] [ 1 ] - dcm [ 1 ] [ 2 ] ) * s
q [ 2 ] = ( dcm [ 0 ] [ 2 ] - dcm [ 2 ] [ 0 ] ) * s
q [ 3 ] = ( dcm [ 1 ] [ 0 ] - dcm [ 0 ] [ ... |
def _check_ubridge_version ( self , env = None ) :
"""Checks if the ubridge executable version""" | try :
output = yield from subprocess_check_output ( self . _path , "-v" , cwd = self . _working_dir , env = env )
match = re . search ( "ubridge version ([0-9a-z\.]+)" , output )
if match :
self . _version = match . group ( 1 )
if sys . platform . startswith ( "win" ) or sys . platform . sta... |
def infer_si_prefix ( f ) :
"""Infers the SI prefix of a value * f * and returns the string label and decimal magnitude in a
2 - tuple . Example :
. . code - block : : python
infer _ si _ prefix ( 1 ) # - > ( " " , 0)
infer _ si _ prefix ( 25 ) # - > ( " " , 0)
infer _ si _ prefix ( 4320 ) # - > ( " k " ,... | if f == 0 :
return "" , 0
else :
mag = 3 * int ( math . log10 ( abs ( float ( f ) ) ) // 3 )
return si_refixes [ mag ] , mag |
def server ( value = None ) :
"""Get the hostname of the server or set the server using hostname or aliases .
Supported aliases : ' localhost ' , ' staging ' , ' labs ' .
Also set via environment variable GRAPHISTRY _ HOSTNAME .""" | if value is None :
return PyGraphistry . _config [ 'hostname' ]
# setter
shortcuts = { 'dev' : 'localhost:3000' , 'staging' : 'staging.graphistry.com' , 'labs' : 'labs.graphistry.com' }
if value in shortcuts :
resolved = shortcuts [ value ]
PyGraphistry . _config [ 'hostname' ] = resolved
util . warn ( ... |
def __unroll ( self , rolled ) :
"""Converts parameter matrices into an array .""" | return np . array ( np . concatenate ( [ matrix . flatten ( ) for matrix in rolled ] , axis = 1 ) ) . reshape ( - 1 ) |
def dataset_splits ( self ) :
"""Splits of data to produce and number the output shards for each .""" | return [ { "split" : problem . DatasetSplit . TRAIN , "shards" : self . num_train_shards , } , { "split" : problem . DatasetSplit . EVAL , "shards" : self . num_eval_shards , } , { "split" : problem . DatasetSplit . TEST , "shards" : self . num_test_shards , } ] |
def uniquetwig ( self , ps = None ) :
"""see also : meth : ` twig `
Determine the shortest ( more - or - less ) twig which will point
to this single Parameter in a given parent : class : ` ParameterSet `
: parameter ps : : class : ` ParameterSet ` in which the returned
uniquetwig will point to this Paramete... | if ps is None :
ps = self . _bundle
if ps is None :
return self . twig
return ps . _uniquetwig ( self . twig ) |
def satisfiesShapeNot ( cntxt : Context , n : Node , se : ShExJ . ShapeNot , _ : DebugContext ) -> bool :
"""Se is a ShapeNot and for the shape expression se2 at shapeExpr , notSatisfies ( n , se2 , G , m )""" | return not satisfies ( cntxt , n , se . shapeExpr ) |
def process_response ( self , request , response ) :
"""Sets the cache , if needed .""" | # never cache headers + ETag
add_never_cache_headers ( response )
if not hasattr ( request , '_cache_update_cache' ) or not request . _cache_update_cache : # We don ' t need to update the cache , just return .
return response
if request . method != 'GET' : # This is a stronger requirement than above . It is needed
... |
def confd_state_internal_cdb_client_type ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
confd_state = ET . SubElement ( config , "confd-state" , xmlns = "http://tail-f.com/yang/confd-monitoring" )
internal = ET . SubElement ( confd_state , "internal" )
cdb = ET . SubElement ( internal , "cdb" )
client = ET . SubElement ( cdb , "client" )
type = ET . SubElement ( client ,... |
def get_selected_subassistant_path ( self , ** kwargs ) :
"""Recursively searches self . _ tree - has format of ( Assistant : [ list _ of _ subassistants ] ) -
for specific path from first to last selected subassistants .
Args :
kwargs : arguments containing names of the given assistants in form of
subassis... | path = [ self ]
previous_subas_list = None
currently_searching = self . get_subassistant_tree ( ) [ 1 ]
# len ( path ) - 1 always points to next subassistant _ N , so we can use it to control iteration
while settings . SUBASSISTANT_N_STRING . format ( len ( path ) - 1 ) in kwargs and kwargs [ settings . SUBASSISTANT_N_... |
def analyzer ( self , * args , ** kwargs ) :
"""Explicitly add an analyzer to an index . Note that all custom analyzers
defined in mappings will also be created . This is useful for search analyzers .
Example : :
from elasticsearch _ dsl import analyzer , tokenizer
my _ analyzer = analyzer ( ' my _ analyzer... | analyzer = analysis . analyzer ( * args , ** kwargs )
d = analyzer . get_analysis_definition ( )
# empty custom analyzer , probably already defined out of our control
if not d :
return
# merge the definition
merge ( self . _analysis , d , True ) |
def __create_handler_settings ( config ) :
""": type config : dict""" | server_config = config [ 'conf' ] [ 'server' ]
plugins_conf = config [ 'conf' ] [ 'plugins_enabled' ]
api_handler_settings = { 'auth_required' : server_config . get ( 'auth_required' , True ) , 'upstream_timeout' : server_config . get ( 'upstream_timeout' , None ) , 'registry' : PluginBuilder . build_plugins ( plugins_... |
def get_ns_commands ( self , cmd_name ) :
"""Retrieves the possible name spaces and commands associated to the given
command name .
: param cmd _ name : The given command name
: return : A list of 2 - tuples ( name space , command )
: raise ValueError : Unknown command name""" | namespace , command = _split_ns_command ( cmd_name )
if not namespace : # Name space not given , look for the commands
spaces = self . __find_command_ns ( command )
if not spaces : # Unknown command
raise ValueError ( "Unknown command {0}" . format ( command ) )
else : # Return a sorted list of tupl... |
def terminate ( library , session , degree , job_id ) :
"""Requests a VISA session to terminate normal execution of an operation .
Corresponds to viTerminate function of the VISA library .
: param library : the visa library wrapped by ctypes .
: param session : Unique logical identifier to a session .
: par... | return library . viTerminate ( session , degree , job_id ) |
def migrate_config ( self , current_config , config_to_migrate , always_update , update_defaults ) :
"""Migrate config value in current _ config , updating config _ to _ migrate .
Given the current _ config object , it will attempt to find a value
based on all the names given . If no name could be found , then ... | value = self . _search_config_for_possible_names ( current_config )
self . _update_config ( config_to_migrate , value , always_update , update_defaults ) |
def create_linked_data_element ( self , url , kind , id = None , # pylint : disable = W0622
relation = None , title = None ) :
"""Returns a new linked data element for the given url and kind .
: param str url : URL to assign to the linked data element .
: param str kind : kind of the resource that is linked . O... | mp = self . __mp_reg . find_or_create_mapping ( Link )
return mp . data_element_class . create ( url , kind , id = id , relation = relation , title = title ) |
def get_percentage_bond_dist_changes ( self , max_radius = 3.0 ) :
"""Returns the percentage bond distance changes for each site up to a
maximum radius for nearest neighbors .
Args :
max _ radius ( float ) : Maximum radius to search for nearest
neighbors . This radius is applied to the initial structure ,
... | data = collections . defaultdict ( dict )
for inds in itertools . combinations ( list ( range ( len ( self . initial ) ) ) , 2 ) :
( i , j ) = sorted ( inds )
initial_dist = self . initial [ i ] . distance ( self . initial [ j ] )
if initial_dist < max_radius :
final_dist = self . final [ i ] . dist... |
def start_server ( self , protocol = 'TCP' , port = 5001 , mss = None , window = None ) :
"""iperf - s - D - - mss mss""" | cmd = [ 'iperf' , '-s' , '-p' , str ( port ) ]
if not cmp ( protocol , 'UDP' ) :
cmd . append ( '-u' )
if mss :
cmd . extend ( [ '-M' , str ( mss ) ] )
if window :
cmd . extend ( [ '-w' , str ( window ) ] )
pid = utils . create_deamon ( cmd )
data = dict ( )
data [ 'pid' ] = pid
return data |
def start ( name ) : # type : ( str ) - > None
"""Start working on a new feature by branching off develop .
This will create a new branch off develop called feature / < name > .
Args :
name ( str ) :
The name of the new feature .""" | branch = git . current_branch ( refresh = True )
task_branch = 'task/' + common . to_branch_name ( name )
if branch . type not in ( 'feature' , 'hotfix' ) :
log . err ( "Task branches can only branch off <33>feature<32> or " "<33>hotfix<32> branches" )
sys . exit ( 1 )
common . git_checkout ( task_branch , crea... |
def _find_consonant_cluster ( self , letters : List [ str ] ) -> List [ int ] :
"""Find clusters of consonants that do not contain a vowel .
: param letters :
: return :""" | for idx , letter_group in enumerate ( letters ) :
if self . _contains_consonants ( letter_group ) and not self . _contains_vowels ( letter_group ) :
return [ idx ]
return [ ] |
def get_ip ( self , use_cached = True ) :
"""Get the last known IP of this device""" | device_json = self . get_device_json ( use_cached )
return device_json . get ( "dpLastKnownIp" ) |
def _is_pid_running_on_unix ( pid ) :
"""Check if PID is running for Unix systems .""" | try :
os . kill ( pid , 0 )
except OSError as err : # if error is ESRCH , it means the process doesn ' t exist
return not err . errno == os . errno . ESRCH
return True |
def saveWeights ( self , filename , mode = 'pickle' , counter = None ) :
"""Saves weights to file in pickle , plain , or tlearn mode .""" | # modes : pickle / conx , plain , tlearn
if "?" in filename : # replace ? pattern in filename with epoch number
import re
char = "?"
match = re . search ( re . escape ( char ) + "+" , filename )
if match :
num = self . epoch
if counter != None :
num = counter
elif sel... |
def fetch ( self , keyDict ) :
"""Like update ( ) , but for retrieving values .""" | for key in keyDict . keys ( ) :
keyDict [ key ] = self . tbl [ key ] |
def as_coeff_unit ( self ) :
"""Factor the coefficient multiplying a unit
For units that are multiplied by a constant dimensionless
coefficient , returns a tuple containing the coefficient and
a new unit object for the unmultiplied unit .
Example
> > > import unyt as u
> > > unit = ( u . m * * 2 / u . c... | coeff , mul = self . expr . as_coeff_Mul ( )
coeff = float ( coeff )
ret = Unit ( mul , self . base_value / coeff , self . base_offset , self . dimensions , self . registry , )
return coeff , ret |
def command_queue_worker ( self , command_queue ) :
"""Process commands in command queues .""" | while True :
try : # set timeout to ensure self . stopping is checked periodically
command , data = command_queue . get ( timeout = 3 )
try :
self . process_command ( command , data )
except Exception as e :
_logger . exception ( e )
self . worker_exceptio... |
def reset ( self ) :
"""Clears the ` cells ` and leaderboards , and sets all corners to ` 0,0 ` .""" | self . cells . clear ( )
self . leaderboard_names . clear ( )
self . leaderboard_groups . clear ( )
self . top_left . set ( 0 , 0 )
self . bottom_right . set ( 0 , 0 ) |
def count ( self ) :
"""return the count of the criteria""" | # count queries shouldn ' t care about sorting
fields_sort = self . fields_sort
self . fields_sort = self . fields_sort_class ( )
self . default_val = 0
ret = self . _query ( 'count' )
# restore previous values now that count is done
self . fields_sort = fields_sort
return ret |
def get_statements ( self ) :
"""Returns a list of SQL statements as strings , stripped""" | statements = [ ]
for statement in self . _parsed :
if statement :
sql = str ( statement ) . strip ( ' \n;\t' )
if sql :
statements . append ( sql )
return statements |
def delete ( self ) :
"""Deletes this item from its bucket .
Raises :
Exception if there was an error deleting the item .""" | if self . exists ( ) :
try :
self . _api . objects_delete ( self . _bucket , self . _key )
except Exception as e :
raise e |
def calc_choice_sequence_probs ( prob_array , choice_vec , rows_to_mixers , return_type = None ) :
"""Parameters
prob _ array : 2D ndarray .
All elements should be ints , floats , or longs . All elements should be
between zero and one ( exclusive ) . Each element should represent the
probability of the corr... | if return_type not in [ None , 'all' ] :
raise ValueError ( "return_type must be None or 'all'." )
log_chosen_prob_array = choice_vec [ : , None ] * np . log ( prob_array )
# Create a 2D array with shape ( num _ mixing _ units , num _ random _ draws )
# Each element will be the log of the probability of the sequenc... |
def unpack_varint ( self , max_bytes ) :
"""Decode variable integer using algorithm similar to that described
in MQTT Version 3.1.1 line 297.
Parameters
max _ bytes : int or None
If a varint cannot be constructed using ` max _ bytes ` or fewer
from f then raises a ` DecodeError ` . If None then there is n... | num_bytes_consumed , value = decode_varint ( self . __f , max_bytes )
self . __num_bytes_consumed += num_bytes_consumed
return num_bytes_consumed , value |
def get_stream_or_content_from_request ( request ) :
"""Ensure the proper content is uploaded .
Stream might be already consumed by authentication process .
Hence flask . request . stream might not be readable and return improper value .
This methods checks if the stream has already been consumed and if so
... | if request . stream . tell ( ) :
logger . info ( 'Request stream already consumed. ' 'Storing file content using in-memory data.' )
return request . data
else :
logger . info ( 'Storing file content using request stream.' )
return request . stream |
def from_config ( cls , config ) :
"""Create a new Connector instance from a Config object .""" | auth_key = None
password_file = config [ "authentication.passwordFile" ]
if password_file is not None :
try :
auth_key = open ( config [ "authentication.passwordFile" ] ) . read ( )
auth_key = re . sub ( r"\s" , "" , auth_key )
except IOError :
LOG . error ( "Could not load password file... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.