signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def use ( self , obj , parent_form = None ) :
"""Note : if title is None , will be replaced with obj . filename""" | if not isinstance ( obj , self . input_classes ) :
raise RuntimeError ( '{0!s} cannot handle a {1!s}' . format ( self . __class__ . __name__ , obj . __class__ . __name__ ) )
self . parent_form = parent_form
if self . title is None :
self . title = 'file: ' + obj . filename
self . _do_use ( obj ) |
def _all ( confs = None , ** kwargs ) :
"""True iif all input confs are True .
: param confs : confs to check .
: type confs : list or dict or str
: param kwargs : additional task kwargs .
: return : True if all conditions are checked . False otherwise .
: rtype : bool""" | result = False
if confs is not None : # ensure confs is a list
if isinstance ( confs , string_types ) or isinstance ( confs , dict ) :
confs = [ confs ]
# if at least one conf exists , result is True by default
result = True
for conf in confs :
result = run ( conf , ** kwargs )
#... |
def get_targets ( self , predicate = None ) :
"""Returns the candidate targets this task should act on .
This method is a convenience for processing optional transitivity . Tasks may bypass it
and make their own decisions on which targets to act on .
NOTE : This method was introduced in 2018 , so at the time ... | initial_targets = ( self . context . targets ( predicate ) if self . act_transitively else list ( filter ( predicate , self . context . target_roots ) ) )
if not self . target_filtering_enabled :
return initial_targets
else :
return self . _filter_targets ( initial_targets ) |
def get_extra_info ( self , name , default = None ) :
"""Called by the client protocol to return optional transport
information . Information requests not recognized by the
` ` FramerProtocol ` ` are passed on to the underlying transport .
The values of ` ` name ` ` recognized directly by
` ` FramerProtocol... | # Handle data we know about
if name in self . _handlers :
return self . _handlers [ name ] ( self )
# Call get _ extra _ info ( ) on the transport
return self . _transport . get_extra_info ( name , default = default ) |
def from_oauth_file ( cls , filepath = None ) :
"""Get an object bound to the Twitter API using your own credentials .
The ` twitter ` library ships with a ` twitter ` command that uses PIN
OAuth . Generate your own OAuth credentials by running ` twitter ` from
the shell , which will open a browser window to ... | if filepath is None : # Use default OAuth filepath from ` twitter ` command - line program .
home = os . environ . get ( 'HOME' , os . environ . get ( 'USERPROFILE' , '' ) )
filepath = os . path . join ( home , '.twitter_oauth' )
oauth_token , oauth_token_secret = read_token_file ( filepath )
twitter = cls ( au... |
def get_fileb64_image_prediction ( self , model_id , filename , token = None , url = API_GET_PREDICTION_IMAGE_URL ) :
"""Gets a prediction from a supplied image on your machine , by encoding the image data as b64
and posting to the API .
: param model _ id : string , once you train a model you ' ll be given a m... | auth = 'Bearer ' + self . check_for_token ( token )
h = { 'Authorization' : auth , 'Cache-Control' : 'no-cache' }
the_url = url
with open ( filename , "rb" ) as image_file :
encoded_string = base64 . b64encode ( image_file . read ( ) )
m = MultipartEncoder ( fields = { 'sampleBase64Content' : encoded_string , 'mode... |
def _check_for_definition ( iface , cls , tag , defines ) :
"""Check for a valid definition of a value .
Args :
iface ( Iface ) : An Iface specification .
cls ( type ) : Some type to check for a definition .
tag ( str ) : The name of the tag attribute used to mark the abstract
methods .
defines ( callab... | attributes = ( attr for attr in iface . __abstractmethods__ if hasattr ( getattr ( iface , attr ) , tag ) )
for attribute in attributes :
for node in cls . __mro__ :
if hasattr ( node , attribute ) and defines ( getattr ( node , attribute ) ) :
return True
try :
attribute
return False
ex... |
def rpc_get_subdomains_owned_by_address ( self , address , ** con_info ) :
"""Get the list of subdomains owned by an address .
Return { ' status ' : True , ' subdomains ' : . . . } on success
Return { ' error ' : . . . } on error""" | if not check_address ( address ) :
return { 'error' : 'Invalid address' , 'http_status' : 400 }
res = get_subdomains_owned_by_address ( address )
return self . success_response ( { 'subdomains' : res } ) |
def getCredentialValues ( self , new = False ) :
"""Return the values in credentials . * .""" | credentials_base = "credentials."
return tuple ( [ self . getValue ( credentials_base + p ) for p in [ "username" , "password" , "private_key" ] ] ) |
def update_configuration ( self ) :
"""Asynchronously applies or re - applies the SAS Logical Interconnect configuration to all managed interconnects
of a SAS Logical Interconnect .
Returns :
dict : SAS Logical Interconnect .""" | uri = "{}/configuration" . format ( self . data [ "uri" ] )
result = self . _helper . update ( { } , uri )
self . refresh ( )
return result |
def differentiate ( self , n = 1 ) :
"""n - th derivative , default 1.""" | ak = self . coefficients ( )
a_ , b_ = self . domain ( )
for _ in range ( n ) :
ak = self . differentiator ( ak )
return self . from_coeff ( ( 2. / ( b_ - a_ ) ) ** n * ak , domain = self . domain ( ) ) |
def prior_model_name_prior_tuples_dict ( self ) :
"""Returns
class _ priors _ dict : { String : [ Prior ] }
A dictionary mapping _ matrix the names of priors to lists of associated priors""" | return { name : list ( prior_model . prior_tuples ) for name , prior_model in self . prior_model_tuples } |
def editors ( self , value ) :
"""Update editors .
DEPRECATED : use ` ` policy [ " roles / editors " ] = value ` ` instead .""" | warnings . warn ( _ASSIGNMENT_DEPRECATED_MSG . format ( "editors" , EDITOR_ROLE ) , DeprecationWarning , )
self [ EDITOR_ROLE ] = value |
def pseudo_dir ( source_path , cache_path = None , delete = Ellipsis , credentials = None , meta_data = None ) :
'''pseudo _ dir ( source _ path ) yields a pseudo - directory object that represents files in the given
source path .
Pseudo - dir objects act as an interface for loading data from abstract sources .... | return PseudoDir ( source_path , cache_path = cache_path , delete = delete , credentials = credentials , meta_data = meta_data ) |
def scatter ( self , * args , ** kwargs ) :
"""Add a scatter plot .""" | cls = _make_class ( ScatterVisual , _default_marker = kwargs . pop ( 'marker' , None ) , )
return self . _add_item ( cls , * args , ** kwargs ) |
def dict_given_run_array ( samples , thread_min_max ) :
"""Converts an array of information about samples back into a nested sampling
run dictionary ( see data _ processing module docstring for more details ) .
N . B . the output dict only contains the following keys : ' logl ' ,
' thread _ label ' , ' nlive ... | ns_run = { 'logl' : samples [ : , 0 ] , 'thread_labels' : samples [ : , 1 ] , 'thread_min_max' : thread_min_max , 'theta' : samples [ : , 3 : ] }
if np . all ( ~ np . isnan ( ns_run [ 'thread_labels' ] ) ) :
ns_run [ 'thread_labels' ] = ns_run [ 'thread_labels' ] . astype ( int )
assert np . array_equal ( sampl... |
def next ( self , now = None , increments = _increments , delta = True , default_utc = WARN_CHANGE ) :
'''How long to wait in seconds before this crontab entry can next be
executed .''' | if default_utc is WARN_CHANGE and ( isinstance ( now , _number_types ) or ( now and not now . tzinfo ) or now is None ) :
warnings . warn ( WARNING_CHANGE_MESSAGE , FutureWarning , 2 )
default_utc = False
now = now or ( datetime . utcnow ( ) if default_utc and default_utc is not WARN_CHANGE else datetime . now ... |
def find_files ( folder ) :
"""Discover stereo photos and return them as a pairwise sorted list .""" | files = [ i for i in os . listdir ( folder ) if i . startswith ( "left" ) ]
files . sort ( )
for i in range ( len ( files ) ) :
insert_string = "right{}" . format ( files [ i * 2 ] [ 4 : ] )
files . insert ( i * 2 + 1 , insert_string )
files = [ os . path . join ( folder , filename ) for filename in files ]
ret... |
def _hardware_count ( self ) :
"""Amount of hardware resources .
: return : integer""" | return self . _counts . get ( "hardware" ) + self . _counts . get ( "serial" ) + self . _counts . get ( "mbed" ) |
def train ( ) :
"""Training process""" | start_pipeline_time = time . time ( )
# Training / Testing
best_valid_acc = 0
stop_early = 0
for epoch in range ( args . epochs ) : # Epoch training stats
start_epoch_time = time . time ( )
epoch_L = 0.0
epoch_sent_num = 0
epoch_wc = 0
# Log interval training stats
start_log_interval_time = time... |
def finish ( self ) :
"""Finalize the MAR file .
The MAR header , index and signatures need to be updated once we ' ve
finished adding all the files .""" | # Update the last _ offset in the mar header
self . write_header ( )
# Write out the index of contents
self . write_index ( )
if not self . use_old_format : # Refresh the signature
sigs = self . calculate_signatures ( )
self . write_signatures ( sigs ) |
def __driver_completer ( self , toks , text , state ) :
"""Driver level completer .
Arguments :
toks : A list of tokens , tokenized from the original input line .
text : A string , the text to be replaced if a completion candidate is
chosen .
state : An integer , the index of the candidate out of the list... | if state != 0 :
return self . __completion_candidates [ state ]
# Update the cache when this method is first called , i . e . , state = = 0.
# If the line is empty or the user is still inputing the first token ,
# complete with available commands .
if not toks or ( len ( toks ) == 1 and text == toks [ 0 ] ) :
t... |
def pre_save ( self , instance , add ) :
"""Ensure slug uniqunes before save .""" | slug = self . value_from_object ( instance )
# We don ' t want to change slug defined by user .
predefined_slug = bool ( slug )
if not slug and self . populate_from :
slug = self . _get_populate_from_value ( instance )
if slug :
slug = slugify ( slug )
if not slug :
slug = None
if not self . blank :
... |
def _process_input_wcs_single ( fname , wcskey , updatewcs ) :
"""See docs for _ process _ input _ wcs .
This is separated to be spawned in parallel .""" | if wcskey in [ '' , ' ' , 'INDEF' , None ] :
if updatewcs :
uw . updatewcs ( fname , checkfiles = False )
else :
numext = fileutil . countExtn ( fname )
extlist = [ ]
for extn in range ( 1 , numext + 1 ) :
extlist . append ( ( 'SCI' , extn ) )
if wcskey in string . ascii_uppercase :
... |
def _list_nodes ( call = None ) :
'''List the nodes , ask all ' vagrant ' minions , return dict of grains .''' | local = salt . client . LocalClient ( )
ret = local . cmd ( 'salt-cloud:driver:vagrant' , 'grains.items' , '' , tgt_type = 'grain' )
return ret |
def get_page ( self , url ) :
"""Get the HTML for an URL , possibly from an in - memory cache .
XXX TODO Note : this cache is never actually cleared . It ' s assumed that
the data won ' t get stale over the lifetime of a locator instance ( not
necessarily true for the default _ locator ) .""" | # http : / / peak . telecommunity . com / DevCenter / EasyInstall # package - index - api
scheme , netloc , path , _ , _ , _ = urlparse ( url )
if scheme == 'file' and os . path . isdir ( url2pathname ( path ) ) :
url = urljoin ( ensure_slash ( url ) , 'index.html' )
if url in self . _page_cache :
result = self... |
def history ( namespace_module ) :
"""Hash all versions on Artifactory .""" | for path in get_namespace_history ( namespace_module ) :
h = get_bel_resource_hash ( path . as_posix ( ) )
click . echo ( '{}\t{}' . format ( path , h ) ) |
def conv2d ( self , filter_size , output_channels , stride = 1 , padding = 'SAME' , activation_fn = tf . nn . relu , b_value = 0.0 , s_value = 1.0 , bn = True , stoch = False ) :
""": param filter _ size : int . assumes square filter
: param output _ channels : int
: param stride : int
: param padding : ' VAL... | self . count [ 'conv' ] += 1
self . _layer_count += 1
scope = 'conv_' + str ( self . count [ 'conv' ] )
if stoch is True :
clean = False
else :
clean = True
with tf . variable_scope ( scope ) :
input_channels = self . input . get_shape ( ) [ 3 ]
output_shape = [ filter_size , filter_size , input_channel... |
def between ( self , minimum : int = 1 , maximum : int = 1000 ) -> int :
"""Generate a random number between minimum and maximum .
: param minimum : Minimum of range .
: param maximum : Maximum of range .
: return : Number .""" | return self . random . randint ( minimum , maximum ) |
def get_course ( self , courseid ) :
""": param courseid : the course id of the course
: raise InvalidNameException , CourseNotFoundException , CourseUnreadableException
: return : an object representing the course , of the type given in the constructor""" | if not id_checker ( courseid ) :
raise InvalidNameException ( "Course with invalid name: " + courseid )
if self . _cache_update_needed ( courseid ) :
self . _update_cache ( courseid )
return self . _cache [ courseid ] [ 0 ] |
def get_id_token_hint ( self , request_args = None , ** kwargs ) :
"""Add id _ token _ hint to request
: param request _ args :
: param kwargs :
: return :""" | request_args = self . multiple_extend_request_args ( request_args , kwargs [ 'state' ] , [ 'id_token' ] , [ 'auth_response' , 'token_response' , 'refresh_token_response' ] , orig = True )
try :
request_args [ 'id_token_hint' ] = request_args [ 'id_token' ]
except KeyError :
pass
else :
del request_args [ 'i... |
def acp_users_delete ( ) :
"""Delete or undelete an user account .""" | if not current_user . is_admin :
return error ( "Not authorized to edit users." , 401 )
if not db :
return error ( 'The ACP is not available in single-user mode.' , 500 )
form = UserDeleteForm ( )
if not form . validate ( ) :
return error ( "Bad Request" , 400 )
user = get_user ( int ( request . form [ 'uid... |
def fprint ( fmt , * args , ** kwargs ) :
"""Parse and print a colored and perhaps formatted string .
The remaining keyword arguments are the same as for Python ' s built - in print
function . Colors are returning to their defaults before the function
returns .""" | if not fmt :
return
hascolor = False
target = kwargs . get ( "target" , sys . stdout )
# Format the string before feeding it to the parser
fmt = fmt . format ( * args , ** kwargs )
for txt , markups in _color_format_parser . parse ( fmt ) :
if markups != ( None , None ) :
_color_manager . set_color ( * ... |
def get_resource_name ( context , expand_polymorphic_types = False ) :
"""Return the name of a resource .""" | from rest_framework_json_api . serializers import PolymorphicModelSerializer
view = context . get ( 'view' )
# Sanity check to make sure we have a view .
if not view :
return None
# Check to see if there is a status code and return early
# with the resource _ name value of ` errors ` .
try :
code = str ( view .... |
def _get_build_flags ( cls , build_flags_from_option , is_flagged , target ) :
"""Merge build flags with global < target < command - line order
Build flags can be defined as globals ( in ` pants . ini ` ) , as arguments to a Target , and
via the command - line .""" | # If self . get _ options ( ) . build _ flags returns a quoted string , remove the outer quotes ,
# which happens for flags passed from the command - line .
if ( build_flags_from_option . startswith ( '\'' ) and build_flags_from_option . endswith ( '\'' ) ) or ( build_flags_from_option . startswith ( '"' ) and build_fl... |
def extract_geo ( self ) :
'''Extract geo - related information from exif''' | altitude = self . extract_altitude ( )
dop = self . extract_dop ( )
lon , lat = self . extract_lon_lat ( )
d = { }
if lon is not None and lat is not None :
d [ 'latitude' ] = lat
d [ 'longitude' ] = lon
if altitude is not None :
d [ 'altitude' ] = altitude
if dop is not None :
d [ 'dop' ] = dop
return d |
def figure_populate ( outputpath , csv , xlabels , ylabels , analysistype , description , fail = False ) :
"""Create the report image from the summary report created in self . dataframesetup
: param outputpath : Path in which the outputs are to be created
: param csv : Name of the report file from which data ar... | # Create a data frame from the summary report
df = pd . read_csv ( os . path . join ( outputpath , csv ) , delimiter = ',' , index_col = 0 )
# Set the palette appropriately - ' template ' uses only grey
if description == 'template' :
cmap = [ '#a0a0a0' ]
# ' fail ' uses red ( fail ) , grey ( not detected ) , and gr... |
def bootstrap_indexes_moving_block ( data , n_samples = 10000 , block_length = 3 , wrap = False ) :
"""Generate moving - block bootstrap samples .
Given data points ` data ` , where axis 0 is considered to delineate points ,
return a generator for sets of bootstrap indexes . This can be used as a
list of boot... | n_obs = data . shape [ 0 ]
n_blocks = int ( ceil ( n_obs / block_length ) )
nexts = np . repeat ( np . arange ( 0 , block_length ) [ None , : ] , n_blocks , axis = 0 )
if wrap :
last_block = n_obs
else :
last_block = n_obs - block_length
for _ in xrange ( n_samples ) :
blocks = np . random . randint ( 0 , l... |
def contribute_to_class ( self , cls , name , ** kwargs ) :
"""Internal Django method to associate the field with the Model ; it assigns the descriptor .""" | super ( PlaceholderField , self ) . contribute_to_class ( cls , name , ** kwargs )
# overwrites what instance . < colname > returns ; give direct access to the placeholder
setattr ( cls , name , PlaceholderFieldDescriptor ( self . slot ) )
# Make placeholder fields easy to find
# Can ' t assign this to cls . _ meta bec... |
def add_status_message ( self , message , level = "info" ) :
"""Set a portal status message""" | return self . context . plone_utils . addPortalMessage ( message , level ) |
def pos_tags ( self ) :
"""Returns an list of tuples of the form ( word , POS tag ) .
Example :
[ ( ' At ' , ' IN ' ) , ( ' eight ' , ' CD ' ) , ( " o ' clock " , ' JJ ' ) , ( ' on ' , ' IN ' ) ,
( ' Thursday ' , ' NNP ' ) , ( ' morning ' , ' NN ' ) ]
: rtype : list of tuples""" | return [ ( Word ( word , pos_tag = t ) , unicode ( t ) ) for word , t in self . pos_tagger . tag ( self . raw ) # new keyword PatternTagger ( include _ punc = False )
# if not PUNCTUATION _ REGEX . match ( unicode ( t ) )
] |
def wifi_status ( self ) :
"""Get the wifi status .""" | return self . _info_json . get ( CONST . STATUS , { } ) . get ( CONST . WIFI_LINK ) |
def add_field ( self , name , ftype , docfield = None ) :
"""Add a field to the document ( and to the underlying schema )
: param name : name of the new field
: type name : str
: param ftype : type of the new field
: type ftype : subclass of : class : ` . GenericType `""" | self . schema . add_field ( name , ftype )
self [ name ] = docfield or DocField . FromType ( ftype ) |
def authenticate ( url , account , key , by = 'name' , expires = 0 , timestamp = None , timeout = None , request_type = "xml" , admin_auth = False , use_password = False , raise_on_error = False ) :
"""Authenticate to the Zimbra server
: param url : URL of Zimbra SOAP service
: param account : The account to be... | if timestamp is None :
timestamp = int ( time . time ( ) ) * 1000
pak = ""
if not admin_auth :
pak = preauth . create_preauth ( account , key , by , expires , timestamp )
if request_type == 'xml' :
auth_request = RequestXml ( )
else :
auth_request = RequestJson ( )
request_data = { 'account' : { 'by' : ... |
def init_scalable ( X , n_clusters , random_state = None , max_iter = None , oversampling_factor = 2 ) :
"""K - Means initialization using k - means | |
This is algorithm 2 in Scalable K - Means + + ( 2012 ) .""" | logger . info ( "Initializing with k-means||" )
# Step 1 : Initialize Centers
idx = 0
centers = da . compute ( X [ idx , np . newaxis ] ) [ 0 ]
c_idx = { idx }
# Step 2 : Initialize cost
cost , = compute ( evaluate_cost ( X , centers ) )
if cost == 0 :
n_iter = 0
else :
n_iter = int ( np . round ( np . log ( co... |
def encode ( self , key ) :
"""Encodes a user key into a particular format . The result of this method
will be used by swauth for storing user credentials .
If salt is not manually set in conf file , a random salt will be
generated and used .
: param key : User ' s secret key
: returns : A string represen... | salt = self . salt or os . urandom ( 32 ) . encode ( 'base64' ) . rstrip ( )
return self . encode_w_salt ( salt , key ) |
def get_device_names_to_objects ( devices ) :
'''Map a list of devices to their hostnames .
: param devices : list - - list of ManagementRoot objects
: returns : dict - - mapping of hostnames to ManagementRoot objects''' | name_to_object = { }
for device in devices :
device_name = get_device_info ( device ) . name
name_to_object [ device_name ] = device
return name_to_object |
def replace ( parent , idx , value , check_value = _NO_VAL ) :
"""Replace a value in a dict .""" | if isinstance ( parent , dict ) :
if idx not in parent :
raise JSONPatchError ( "Item does not exist" )
elif isinstance ( parent , list ) :
idx = int ( idx )
if idx < 0 or idx >= len ( parent ) :
raise JSONPatchError ( "List index out of range" )
if check_value is not _NO_VAL :
if parent... |
def match_planted ( fk_candidate_observations , match_filename , bright_limit = BRIGHT_LIMIT , object_planted = OBJECT_PLANTED , minimum_bright_detections = MINIMUM_BRIGHT_DETECTIONS , bright_fraction = MINIMUM_BRIGHT_FRACTION ) :
"""Using the fk _ candidate _ observations as input get the Object . planted file fro... | found_pos = [ ]
detections = fk_candidate_observations . get_sources ( )
for detection in detections :
reading = detection . get_reading ( 0 )
# create a list of positions , to be used later by match _ lists
found_pos . append ( [ reading . x , reading . y ] )
# Now get the Object . planted file , either fr... |
def get_input ( self , key , force = False ) :
"""Get the value of < key > if it already exists , or prompt for it if not""" | if key not in self . _inputs :
raise InputException ( "Key {0} is not a valid input!" . format ( key ) )
if self . _inputs [ key ] . prompt :
prompt = self . _inputs [ key ] . prompt
elif self . _inputs [ key ] . is_bool ( ) :
prompt = "{0}?" . format ( key )
else :
prompt = "please enter your {0}" . fo... |
def _webfinger ( provider , request , ** kwargs ) :
"""Handle webfinger requests .""" | params = urlparse . parse_qs ( request )
if params [ "rel" ] [ 0 ] == OIC_ISSUER :
wf = WebFinger ( )
return Response ( wf . response ( params [ "resource" ] [ 0 ] , provider . baseurl ) , headers = [ ( "Content-Type" , "application/jrd+json" ) ] )
else :
return BadRequest ( "Incorrect webfinger." ) |
def make_remote_image_result ( annotations = None , labels = None ) :
"""Instantiate BuildResult for image not built locally .""" | return BuildResult ( image_id = BuildResult . REMOTE_IMAGE , annotations = annotations , labels = labels ) |
def get_data_specifier ( string ) :
"""Return a tuple ( table , col ) for some [ incr tsdb ( ) ] data specifier .
For example : :
item - > ( ' item ' , None )
item : i - input - > ( ' item ' , [ ' i - input ' ] )
item : i - input @ i - wf - > ( ' item ' , [ ' i - input ' , ' i - wf ' ] )
: i - input - > (... | match = data_specifier_re . match ( string )
if match is None :
return ( None , None )
table = match . group ( 'table' )
if table is not None :
table = table . strip ( )
cols = _split_cols ( match . group ( 'cols' ) )
return ( table , cols ) |
def _addDatasetAction ( self , dataset ) :
"""Adds an action for the inputed dataset to the toolbar
: param dataset | < XChartDataset >""" | # create the toolbar action
action = QAction ( dataset . name ( ) , self )
action . setIcon ( XColorIcon ( dataset . color ( ) ) )
action . setCheckable ( True )
action . setChecked ( True )
action . setData ( wrapVariant ( dataset ) )
action . toggled . connect ( self . toggleDataset )
self . uiDatasetTBAR . addAction... |
def respond ( request , code ) :
"""Responds to the request with the given response code .
If ` ` next ` ` is in the form , it will redirect instead .""" | redirect = request . GET . get ( 'next' , request . POST . get ( 'next' ) )
if redirect :
return HttpResponseRedirect ( redirect )
return type ( 'Response%d' % code , ( HttpResponse , ) , { 'status_code' : code } ) ( ) |
def Get3DData ( self , datapath , qt_app = None , dataplus_format = True , gui = False , start = 0 , stop = None , step = 1 , convert_to_gray = True , series_number = None , use_economic_dtype = True , dicom_expected = None , ** kwargs ) :
"""Returns 3D data and its metadata .
# NOTE ( : param qt _ app : ) If it ... | self . orig_datapath = datapath
datapath = os . path . expanduser ( datapath )
if series_number is not None and type ( series_number ) != int :
series_number = int ( series_number )
if not os . path . exists ( datapath ) :
logger . error ( "Path '" + datapath + "' does not exist" )
return
if qt_app is None ... |
def get_mean_DEV ( sum_ptrm_checks , sum_abs_ptrm_checks , n_pTRM , delta_x_prime ) :
"""input : sum _ ptrm _ checks , sum _ abs _ ptrm _ checks , n _ pTRM , delta _ x _ prime
output : Mean deviation of a pTRM check""" | if not n_pTRM :
return float ( 'nan' ) , float ( 'nan' )
mean_DEV = ( ( old_div ( 1. , n_pTRM ) ) * ( old_div ( sum_ptrm_checks , delta_x_prime ) ) ) * 100
mean_DEV_prime = ( ( old_div ( 1. , n_pTRM ) ) * ( old_div ( sum_abs_ptrm_checks , delta_x_prime ) ) ) * 100
return mean_DEV , mean_DEV_prime |
def _check_smart_storage_message ( self ) :
"""Check for smart storage message .
: returns : result , raid _ message""" | ssc_mesg = self . smart_storage_config_message
result = True
raid_message = ""
for element in ssc_mesg :
if "Success" not in element [ 'MessageId' ] :
result = False
raid_message = element [ 'MessageId' ]
return result , raid_message |
def _failed ( self , msg ) :
"""Log a validation failure .
: param string msg : the error message""" | self . log ( msg )
self . result . passed = False
self . result . add_error ( msg )
self . log ( u"Failed" ) |
def for_name ( modpath , classname ) :
'''Returns a class of " classname " from module " modname " .''' | module = __import__ ( modpath , fromlist = [ classname ] )
classobj = getattr ( module , classname )
return classobj ( ) |
def pretty_dict_str ( d , indent = 2 ) :
"""shows JSON indented representation of d""" | b = StringIO ( )
write_pretty_dict_str ( b , d , indent = indent )
return b . getvalue ( ) |
def purge_stream ( self , stream_id , remove_definition = False , sandbox = None ) :
"""Purge the stream
: param stream _ id : The stream identifier
: param remove _ definition : Whether to remove the stream definition as well
: param sandbox : The sandbox for this stream
: return : None
: raises : NotImp... | # TODO : Add time interval to this
if sandbox is not None :
raise NotImplementedError
if stream_id not in self . streams :
raise StreamNotFoundError ( "Stream with id '{}' not found" . format ( stream_id ) )
stream = self . streams [ stream_id ]
query = stream_id . as_raw ( )
with switch_db ( StreamInstanceMode... |
def get_keys ( logger = None , host_pkey_directories = None , allow_agent = False ) :
"""Load public keys from any available SSH agent or local
. ssh directory .
Arguments :
logger ( Optional [ logging . Logger ] )
host _ pkey _ directories ( Optional [ list [ str ] ] ) :
List of local directories where h... | keys = SSHTunnelForwarder . get_agent_keys ( logger = logger ) if allow_agent else [ ]
if host_pkey_directories is not None :
paramiko_key_types = { 'rsa' : paramiko . RSAKey , 'dsa' : paramiko . DSSKey , 'ecdsa' : paramiko . ECDSAKey , 'ed25519' : paramiko . Ed25519Key }
for directory in host_pkey_directories ... |
def export_epoch_file ( stimfunction , filename , tr_duration , temporal_resolution = 100.0 ) :
"""Output an epoch file , necessary for some inputs into brainiak
This takes in the time course of stimulus events and outputs the epoch
file used in Brainiak . The epoch file is a way to structure the timing
infor... | # Cycle through the participants , different entries in the list
epoch_file = [ 0 ] * len ( stimfunction )
for ppt_counter in range ( len ( stimfunction ) ) : # What is the time course for the participant ( binarized )
stimfunction_ppt = np . abs ( stimfunction [ ppt_counter ] ) > 0
# Down sample the stim funct... |
def fsplit ( pred , objs ) :
"""Split a list into two classes according to the predicate .""" | t = [ ]
f = [ ]
for obj in objs :
if pred ( obj ) :
t . append ( obj )
else :
f . append ( obj )
return ( t , f ) |
def generate_challenge ( self ) : # local import to avoid circular import
from two_factor . utils import totp_digits
"""Sends the current TOTP token to ` self . number ` using ` self . method ` .""" | no_digits = totp_digits ( )
token = str ( totp ( self . bin_key , digits = no_digits ) ) . zfill ( no_digits )
if self . method == 'call' :
make_call ( device = self , token = token )
else :
send_sms ( device = self , token = token ) |
def write_schema_to_file ( cls , schema , file_pointer = stdout , folder = MISSING , context = DEFAULT_DICT ) :
"""Given a Marshmallow schema , create a JSON Schema for it .
Args :
schema ( marshmallow . Schema | str ) : The Marshmallow schema , or the
Python path to one , to create the JSON schema for .
Ke... | schema = cls . _get_schema ( schema )
json_schema = cls . generate_json_schema ( schema , context = context )
if folder :
schema_filename = getattr ( schema . Meta , 'json_schema_filename' , '.' . join ( [ schema . __class__ . __name__ , 'json' ] ) )
json_path = os . path . join ( folder , schema_filename )
... |
def _get_commands_by_name ( self , blueprint , name ) :
"""Get all of the commands with a given name .""" | return list ( filter ( lambda value : value . name == name , blueprint . get_commands ( ) ) ) |
def repr_size ( n_bytes ) :
"""> > > repr _ size ( 1000)
'1000 Bytes '
> > > repr _ size ( 8257332324597)
'7.5 TiB '""" | if n_bytes < 1024 :
return '{0} Bytes' . format ( n_bytes )
i = - 1
while n_bytes > 1023 :
n_bytes /= 1024.0
i += 1
return '{0} {1}iB' . format ( round ( n_bytes , 1 ) , si_prefixes [ i ] ) |
def load_object ( target , namespace = None ) :
"""This helper function loads an object identified by a dotted - notation string .
For example :
# Load class Foo from example . objects
load _ object ( ' example . objects : Foo ' )
If a plugin namespace is provided simple name references are allowed . For ex... | if namespace and ':' not in target :
allowable = dict ( ( i . name , i ) for i in pkg_resources . iter_entry_points ( namespace ) )
if target not in allowable :
raise ValueError ( 'Unknown plugin "' + target + '"; found: ' + ', ' . join ( allowable ) )
return allowable [ target ] . load ( )
parts , ... |
def _upload_file_bytes ( self , conn , http_conn , fp , file_length , total_bytes_uploaded , cb , num_cb ) :
"""Makes one attempt to upload file bytes , using an existing resumable
upload connection .
Returns etag from server upon success .
Raises ResumableUploadException if any problems occur .""" | buf = fp . read ( self . BUFFER_SIZE )
if cb :
if num_cb > 2 :
cb_count = file_length / self . BUFFER_SIZE / ( num_cb - 2 )
elif num_cb < 0 :
cb_count = - 1
else :
cb_count = 0
i = 0
cb ( total_bytes_uploaded , file_length )
# Build resumable upload headers for the transfer .... |
def flatMap ( self , f , preservesPartitioning = False ) :
"""Return a new RDD by first applying a function to all elements of this
RDD , and then flattening the results .
> > > rdd = sc . parallelize ( [ 2 , 3 , 4 ] )
> > > sorted ( rdd . flatMap ( lambda x : range ( 1 , x ) ) . collect ( ) )
[1 , 1 , 1 , ... | def func ( s , iterator ) :
return chain . from_iterable ( map ( fail_on_stopiteration ( f ) , iterator ) )
return self . mapPartitionsWithIndex ( func , preservesPartitioning ) |
def get_url ( url : str , params : dict = { } , timeout : float = 5.0 , cache : bool = True ) :
"""Wrapper for requests . get ( url )
Args :
url : url to retrieve
params : query string parameters
timeout : allow this much time for the request and time it out if over
cache : Cache for up to a day unless th... | try :
if not cache :
with requests_cache . disabled ( ) :
r = requests . get ( url , params = params , timeout = timeout )
else :
r = requests . get ( url , params = params , timeout = timeout )
log . debug ( f"Response headers {r.headers} From cache {r.from_cache}" )
return... |
def _norm_index ( dim , index , start , stop ) :
"""Return an index normalized to an farray start index .""" | length = stop - start
if - length <= index < 0 :
normindex = index + length
elif start <= index < stop :
normindex = index - start
else :
fstr = "expected dim {} index in range [{}, {})"
raise IndexError ( fstr . format ( dim , start , stop ) )
return normindex |
def outline ( self , inner , outer ) :
"""Compute region outline by differencing two dilations .
Parameters
inner : int
Size of inner outline boundary ( in pixels )
outer : int
Size of outer outline boundary ( in pixels )""" | return self . dilate ( outer ) . exclude ( self . dilate ( inner ) ) |
def n_relative_paths ( self , n ) :
"""return relative paths of n levels , including basename .
eg : File ( ' a / b / c / d ' ) . n _ parent _ paths ( 3 ) = = ' b / c / d '""" | rv = os . path . join ( self . n_parent_paths ( n - 1 ) , self . basename )
return rv . replace ( '\\' , '/' ) |
async def _send_packet ( self , pkt ) :
"""Queue a packet to be sent to the server .""" | if self . state != 'connected' :
return
await self . queue . put ( pkt )
self . logger . info ( 'Sending packet %s data %s' , packet . packet_names [ pkt . packet_type ] , pkt . data if not isinstance ( pkt . data , bytes ) else '<binary>' ) |
def form_invalid ( self , form ) :
"""Handles an invalid form .""" | messages . error ( self . request , form . errors [ NON_FIELD_ERRORS ] )
return redirect ( reverse ( 'forum_conversation:topic' , kwargs = { 'forum_slug' : self . object . topic . forum . slug , 'forum_pk' : self . object . topic . forum . pk , 'slug' : self . object . topic . slug , 'pk' : self . object . topic . pk }... |
def getFileDialogTitle ( msg , title ) :
"""Create nicely - formatted string based on arguments msg and title
: param msg : the msg to be displayed
: param title : the window title
: return : None""" | if msg and title :
return "%s - %s" % ( title , msg )
if msg and not title :
return str ( msg )
if title and not msg :
return str ( title )
return None |
def do_file_download ( client , args ) :
"""Download file""" | # Sanity check
if not os . path . isdir ( args . dest_path ) and not args . dest_path . endswith ( '/' ) :
print ( "file-download: " "target '{}' is not a directory" . format ( args . dest_path ) )
if not os . path . exists ( args . dest_path ) :
print ( "\tHint: add trailing / to create one" )
retu... |
def _add_node ( self , agent ) :
"""Add an Agent as a node to the graph .""" | if agent is None :
return
node_label = _get_node_label ( agent )
if isinstance ( agent , Agent ) and agent . bound_conditions :
bound_agents = [ bc . agent for bc in agent . bound_conditions if bc . is_bound ]
if bound_agents :
bound_names = [ _get_node_label ( a ) for a in bound_agents ]
no... |
def find_if ( pred , iterable , default = None ) :
"""Returns a reference to the first element in the ` ` iterable ` ` range for
which ` ` pred ` ` returns ` ` True ` ` . If no such element is found , the
function returns ` ` default ` ` .
> > > find _ if ( lambda x : x = = 3 , [ 1 , 2 , 3 , 4 ] )
: param p... | return next ( ( i for i in iterable if pred ( i ) ) , default ) |
def i2osp ( x , x_len ) :
'''Converts the integer x to its big - endian representation of length
x _ len .''' | if x > 256 ** x_len :
raise exceptions . IntegerTooLarge
h = hex ( x ) [ 2 : ]
if h [ - 1 ] == 'L' :
h = h [ : - 1 ]
if len ( h ) & 1 == 1 :
h = '0%s' % h
x = binascii . unhexlify ( h )
return b'\x00' * int ( x_len - len ( x ) ) + x |
def addCellScalars ( self , scalars , name ) :
"""Add cell scalars to the actor ' s polydata assigning it a name .""" | poly = self . polydata ( False )
if isinstance ( scalars , str ) :
scalars = vtk_to_numpy ( poly . GetPointData ( ) . GetArray ( scalars ) )
if len ( scalars ) != poly . GetNumberOfCells ( ) :
colors . printc ( "~times Number of scalars != nr. of cells" , c = 1 )
exit ( )
arr = numpy_to_vtk ( np . ascontigu... |
def projection ( x , A , b ) :
"""Returns the vector xhat closest to x in 2 - norm , satisfying A . xhat = b .
: param x : vector
: param A , b : matrix and array characterizing the constraints on x ( A . x = b )
: return x _ hat : optimum angle vector , minimizing cost .
: return cost : least square error ... | A_pseudoinv = pseudo_inverse ( A )
tmp_ = A . dot ( x )
tmp_ -= b
x_hat = A_pseudoinv . dot ( tmp_ )
np . subtract ( x , x_hat , out = x_hat )
cost = mse ( x_hat , x )
A . dot ( x_hat , out = tmp_ )
constraints_error = mse ( tmp_ , b )
return x_hat , cost , constraints_error |
def parse_emails ( emails ) :
"""A function that returns a list of valid email addresses .
This function will also convert a single email address into
a list of email addresses .
None value is also converted into an empty list .""" | if isinstance ( emails , string_types ) :
emails = [ emails ]
elif emails is None :
emails = [ ]
for email in emails :
try :
validate_email_with_name ( email )
except ValidationError :
raise ValidationError ( '%s is not a valid email address' % email )
return emails |
def _hash_internal ( method , salt , password ) :
"""Internal password hash helper . Supports plaintext without salt ,
unsalted and salted passwords . In case salted passwords are used
hmac is used .""" | if method == 'plain' :
return password , method
if isinstance ( password , text_type ) :
password = password . encode ( 'utf-8' )
if method . startswith ( 'pbkdf2:' ) :
args = method [ 7 : ] . split ( ':' )
if len ( args ) not in ( 1 , 2 ) :
raise ValueError ( 'Invalid number of arguments for PB... |
def return_dat ( self , chan , begsam , endsam ) :
"""Return the data as 2D numpy . ndarray .
Parameters
chan : list of int
index ( indices ) of the channels to read
begsam : int
index of the first sample ( inclusively )
endsam : int
index of the last sample ( exclusively )
Returns
numpy . ndarray... | # n _ sam = self . hdr [ 4]
interval = endsam - begsam
dat = empty ( ( len ( chan ) , interval ) )
# beg _ block = floor ( ( begsam / n _ sam ) * n _ block )
# end _ block = floor ( ( endsam / n _ sam ) * n _ block )
for i , chan in enumerate ( chan ) :
k = 0
with open ( self . chan_files [ chan ] , 'rt' ) as f... |
def _addupdate_hdxobject ( self , hdxobjects , id_field , new_hdxobject ) : # type : ( List [ HDXObjectUpperBound ] , str , HDXObjectUpperBound ) - > HDXObjectUpperBound
"""Helper function to add a new HDX object to a supplied list of HDX objects or update existing metadata if the object
already exists in the lis... | for hdxobject in hdxobjects :
if hdxobject [ id_field ] == new_hdxobject [ id_field ] :
merge_two_dictionaries ( hdxobject , new_hdxobject )
return hdxobject
hdxobjects . append ( new_hdxobject )
return new_hdxobject |
def load_file ( self , filename ) :
"""load file which contains yaml configuration entries . and merge it by
current instance
: param files : files to load and merge into existing configuration
instance
: type files : list""" | if not path . exists ( filename ) :
raise FileNotFoundError ( filename )
loaded_yaml = load_yaml ( filename , self . context )
if loaded_yaml :
self . merge ( loaded_yaml ) |
def rndstr ( size = 16 ) :
"""Returns a string of random ascii characters or digits
: param size : The length of the string
: return : string""" | _basech = string . ascii_letters + string . digits
return "" . join ( [ rnd . choice ( _basech ) for _ in range ( size ) ] ) |
def to_cell_table ( self , merged = True ) :
"""Returns a list of lists of Cells with the cooked value and note for each cell .""" | new_rows = [ ]
for row_index , row in enumerate ( self . rows ( CellMode . cooked ) ) :
new_row = [ ]
for col_index , cell_value in enumerate ( row ) :
new_row . append ( Cell ( cell_value , self . get_note ( ( col_index , row_index ) ) ) )
new_rows . append ( new_row )
if merged :
for cell_low ... |
def register ( self , app : 'Quart' , first_registration : bool , * , url_prefix : Optional [ str ] = None , ) -> None :
"""Register this blueprint on the app given .""" | state = self . make_setup_state ( app , first_registration , url_prefix = url_prefix )
if self . has_static_folder :
state . add_url_rule ( self . static_url_path + '/<path:filename>' , view_func = self . send_static_file , endpoint = 'static' , )
for func in self . deferred_functions :
func ( state ) |
def qteDisconnectHook ( self , hookName : str , slot : ( types . FunctionType , types . MethodType ) ) :
"""Disconnect ` ` slot ` ` from ` ` hookName ` ` .
If ` ` hookName ` ` does not exist , or ` ` slot ` ` is not connected
to ` ` hookName ` ` then return * * False * * , otherwise disassociate
` ` slot ` ` ... | # Shorthand .
reg = self . _qteRegistryHooks
# Return immediately if no hook with that name exists .
if hookName not in reg :
msg = 'There is no hook called <b>{}</b>.'
self . qteLogger . info ( msg . format ( hookName ) )
return False
# Return immediately if the ` ` slot ` ` is not connected to the hook .
... |
def connection_lost ( self , reason ) :
"""Stops all timers and notifies peer that connection is lost .""" | if self . _peer :
state = self . _peer . state . bgp_state
if self . _is_bound or state == BGP_FSM_OPEN_SENT :
self . _peer . connection_lost ( reason )
self . _peer = None
if reason :
LOG . info ( reason )
else :
LOG . info ( 'Connection to peer closed for unknown reasons.' ) |
def check_siblings ( graph , outputs ) :
"""Check that all outputs have their siblings listed .""" | siblings = set ( )
for node in outputs :
siblings |= graph . siblings ( node )
siblings = { node . path for node in siblings }
missing = siblings - { node . path for node in outputs }
if missing :
msg = ( 'Include the files above in the command ' 'or use the --with-siblings option.' )
raise click . ClickExc... |
def normalize_unicode ( text ) :
"""Normalize any unicode characters to ascii equivalent
https : / / docs . python . org / 2 / library / unicodedata . html # unicodedata . normalize""" | if isinstance ( text , six . text_type ) :
return unicodedata . normalize ( 'NFKD' , text ) . encode ( 'ascii' , 'ignore' ) . decode ( 'utf8' )
else :
return text |
def addSection ( self , data , name = ".pype32\x00" , flags = 0x60000000 ) :
"""Adds a new section to the existing L { PE } instance .
@ type data : str
@ param data : The data to be added in the new section .
@ type name : str
@ param name : ( Optional ) The name for the new section .
@ type flags : int ... | fa = self . ntHeaders . optionalHeader . fileAlignment . value
sa = self . ntHeaders . optionalHeader . sectionAlignment . value
padding = "\xcc" * ( fa - len ( data ) )
sh = SectionHeader ( )
if len ( self . sectionHeaders ) : # get the va , vz , ra and rz of the last section in the array of section headers
vaLast... |
def get_file_by_id ( self , file_id ) :
"""Get folder details for a file id .
: param file _ id : str : uuid of the file
: return : File""" | return self . _create_item_response ( self . data_service . get_file ( file_id ) , File ) |
def checkpoint ( key = 0 , unpickler = pickle . load , pickler = pickle . dump , work_dir = gettempdir ( ) , refresh = False ) :
"""A utility decorator to save intermediate results of a function . It is the
caller ' s responsibility to specify a key naming scheme such that the output of
each function call with ... | def decorator ( func ) :
def wrapped ( * args , ** kwargs ) : # If first arg is a string , use it directly .
if isinstance ( key , str ) :
save_file = os . path . join ( work_dir , key )
elif isinstance ( key , Template ) :
save_file = os . path . join ( work_dir , key . subs... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.