signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def coverage_score ( gold , pred , ignore_in_gold = [ ] , ignore_in_pred = [ ] ) :
"""Calculate ( global ) coverage .
Args :
gold : A 1d array - like of gold labels
pred : A 1d array - like of predicted labels ( assuming abstain = 0)
ignore _ in _ gold : A list of labels for which elements having that gold ... | gold , pred = _preprocess ( gold , pred , ignore_in_gold , ignore_in_pred )
return np . sum ( pred != 0 ) / len ( pred ) |
def search ( self , ** kwargs ) :
"""Method to search environments based on extends search .
: param search : Dict containing QuerySets to find environments .
: param include : Array containing fields to include on response .
: param exclude : Array containing fields to exclude on response .
: param fields ... | return super ( ApiEnvironment , self ) . get ( self . prepare_url ( 'api/v3/environment/' , kwargs ) ) |
def _ExtractSymbols ( self , descriptors ) :
"""Pulls out all the symbols from descriptor protos .
Args :
descriptors : The messages to extract descriptors from .
Yields :
A two element tuple of the type name and descriptor object .""" | for desc in descriptors :
yield ( _PrefixWithDot ( desc . full_name ) , desc )
for symbol in self . _ExtractSymbols ( desc . nested_types ) :
yield symbol
for enum in desc . enum_types :
yield ( _PrefixWithDot ( enum . full_name ) , enum ) |
def iq_query ( self , message : str ) :
"""Send data query to IQFeed API .""" | end_msg = '!ENDMSG!'
recv_buffer = 4096
# Send the historical data request message and buffer the data
self . _send_cmd ( message )
chunk = ""
data = ""
while True :
chunk = self . _sock . recv ( recv_buffer ) . decode ( 'latin-1' )
data += chunk
if chunk . startswith ( 'E,' ) : # error condition
if... |
def delete ( rule : str , cls_method_name_or_view_fn : Optional [ Union [ str , Callable ] ] = None , * , defaults : Optional [ Defaults ] = _missing , endpoint : Optional [ str ] = _missing , is_member : Optional [ bool ] = _missing , only_if : Optional [ Union [ bool , Callable [ [ FlaskUnchained ] , bool ] ] ] = _mi... | rule_options . pop ( 'methods' , None )
yield Route ( rule , cls_method_name_or_view_fn , defaults = defaults , endpoint = endpoint , is_member = is_member , methods = [ 'DELETE' ] , only_if = only_if , ** rule_options ) |
def visit_BinOp ( self , node : ast . BinOp ) -> Any :
"""Recursively visit the left and right operand , respectively , and apply the operation on the results .""" | # pylint : disable = too - many - branches
left = self . visit ( node = node . left )
right = self . visit ( node = node . right )
if isinstance ( node . op , ast . Add ) :
result = left + right
elif isinstance ( node . op , ast . Sub ) :
result = left - right
elif isinstance ( node . op , ast . Mult ) :
re... |
def open ( filename , frame = 'unspecified' ) :
"""Creates a PointCloudImage from a file .
Parameters
filename : : obj : ` str `
The file to load the data from . Must be one of . png , . jpg ,
. npy , or . npz .
frame : : obj : ` str `
A string representing the frame of reference in which the new image ... | data = Image . load_data ( filename )
return PointCloudImage ( data , frame ) |
def update_history ( self , directory ) :
"""Update browse history""" | try :
directory = osp . abspath ( to_text_string ( directory ) )
if directory in self . history :
self . histindex = self . history . index ( directory )
except Exception :
user_directory = get_home_dir ( )
self . chdir ( directory = user_directory , browsing_history = True ) |
def check_successful_tx ( web3 : Web3 , txid : str , timeout = 180 ) -> Tuple [ dict , dict ] :
"""See if transaction went through ( Solidity code did not throw ) .
: return : Transaction receipt and transaction info""" | receipt = wait_for_transaction_receipt ( web3 = web3 , txid = txid , timeout = timeout )
txinfo = web3 . eth . getTransaction ( txid )
if 'status' not in receipt :
raise KeyError ( 'A transaction receipt does not contain the "status" field. ' 'Does your chain have Byzantium rules enabled?' , )
if receipt [ 'status'... |
def get_new_actions ( self ) :
"""Wrapper function for do _ get _ new _ actions
For stats purpose
: return : None
TODO : Use a decorator for timing this function""" | try :
_t0 = time . time ( )
self . do_get_new_actions ( )
statsmgr . timer ( 'actions.got.time' , time . time ( ) - _t0 )
except RuntimeError :
logger . error ( "Exception like issue #1007" ) |
def get_queryset ( self ) :
'''We want to still be able to modify archived users , but they
shouldn ' t show up on list views .
We have an archived query param , where ' true ' shows archived , ' false '
omits them , and ' both ' shows both .''' | if self . action == 'list' :
active = get_true_false_both ( self . request . query_params , 'active' , 'true' )
if active == 'true' :
return self . queryset . filter ( is_active = True )
if active == 'false' :
return self . queryset . filter ( is_active = False )
return self . queryset |
def PrintIndented ( self , file , ident , code ) :
"""Takes an array , add indentation to each entry and prints it .""" | for entry in code :
print >> file , '%s%s' % ( ident , entry ) |
def execute_catch ( c , sql , vars = None ) :
"""Run a query , but ignore any errors . For error recovery paths where the error handler should not raise another .""" | try :
c . execute ( sql , vars )
except Exception as err :
cmd = sql . split ( ' ' , 1 ) [ 0 ]
log . error ( "Error executing %s: %s" , cmd , err ) |
def request_uniq ( func ) :
"""return unique dict for each uwsgi request .
note : won ' t work on non - uwsgi cases""" | def _wrapped ( * args , ** kwargs ) :
data = _get_request_unique_cache ( )
return func ( data , * args , ** kwargs )
return _wrapped |
def Recurrent ( step_model ) :
"""Apply a stepwise model over a sequence , maintaining state . For RNNs""" | ops = step_model . ops
def recurrent_fwd ( seqs , drop = 0.0 ) :
lengths = [ len ( X ) for X in seqs ]
X , size_at_t , unpad = ops . square_sequences ( seqs )
Y = ops . allocate ( ( X . shape [ 0 ] , X . shape [ 1 ] , step_model . nO ) )
cell_drop = ops . get_dropout_mask ( ( len ( seqs ) , step_model .... |
def render_twitter ( text , ** kwargs ) :
"""Strict template block for rendering twitter embeds .""" | author = render_author ( ** kwargs [ 'author' ] )
metadata = render_metadata ( ** kwargs [ 'metadata' ] )
image = render_image ( ** kwargs [ 'image' ] )
html = """
<div class="attachment attachment-twitter">
{author}
<p class="twitter-content">{text}</p>
{metadata}
... |
def conv2d_trans ( ni : int , nf : int , ks : int = 2 , stride : int = 2 , padding : int = 0 , bias = False ) -> nn . ConvTranspose2d :
"Create ` nn . ConvTranspose2d ` layer ." | return nn . ConvTranspose2d ( ni , nf , kernel_size = ks , stride = stride , padding = padding , bias = bias ) |
def clean_ufo ( path ) :
"""Make sure old UFO data is removed , as it may contain deleted glyphs .""" | if path . endswith ( ".ufo" ) and os . path . exists ( path ) :
shutil . rmtree ( path ) |
def plot_joint_sfs ( s , ax = None , imshow_kwargs = None ) :
"""Plot a joint site frequency spectrum .
Parameters
s : array _ like , int , shape ( n _ chromosomes _ pop1 , n _ chromosomes _ pop2)
Joint site frequency spectrum .
ax : axes , optional
Axes on which to draw . If not provided , a new figure w... | import matplotlib . pyplot as plt
from matplotlib . colors import LogNorm
# check inputs
s = asarray_ndim ( s , 2 )
# setup axes
if ax is None :
w = plt . rcParams [ 'figure.figsize' ] [ 0 ]
fig , ax = plt . subplots ( figsize = ( w , w ) )
# set plotting defaults
if imshow_kwargs is None :
imshow_kwargs = ... |
def predict ( self , input ) :
"""Submits an input batch to the model . Returns a MpsFloatArray
representing the model predictions . Calling asnumpy ( ) on this value will
wait for the batch to finish and yield the predictions as a numpy array .""" | assert self . _mode == MpsGraphMode . Inference
assert input . shape == self . _ishape
input_array = MpsFloatArray ( input )
result_handle = _ctypes . c_void_p ( )
status_code = self . _LIB . TCMPSPredictGraph ( self . handle , input_array . handle , _ctypes . byref ( result_handle ) )
assert status_code == 0 , "Error ... |
def last ( self ) :
"""Returns the last object matched or None if there is no
matching object .
> > > iterator = Host . objects . iterator ( )
> > > c = iterator . filter ( ' kali ' )
> > > if c . exists ( ) :
> > > print ( c . last ( ) )
Host ( name = kali - foo )
: return : element or None""" | if len ( self ) :
self . _params . update ( limit = 1 )
if 'filter' not in self . _params :
return list ( self ) [ - 1 ]
else : # Filter may not return results
result = list ( self )
if result :
return result [ - 1 ] |
def get_action_meanings ( self ) :
"""Return a list of actions meanings .""" | actions = sorted ( self . _action_meanings . keys ( ) )
return [ self . _action_meanings [ action ] for action in actions ] |
def tracking_number ( self , service : str = 'usps' ) -> str :
"""Generate random tracking number .
Supported services : USPS , FedEx and UPS .
: param str service : Post service .
: return : Tracking number .""" | service = service . lower ( )
if service not in ( 'usps' , 'fedex' , 'ups' ) :
raise ValueError ( 'Unsupported post service' )
services = { 'usps' : ( '#### #### #### #### ####' , '@@ ### ### ### US' , ) , 'fedex' : ( '#### #### ####' , '#### #### #### ###' , ) , 'ups' : ( '1Z@####@##########' , ) , }
mask = self .... |
def set_mappings ( self , mappings ) :
"""Applies VC mappings
: param mappings : mappings ( dict )""" | for source , destination in mappings . items ( ) :
if not isinstance ( source , str ) or not isinstance ( destination , str ) :
raise DynamipsError ( "Invalid Frame-Relay mappings" )
source_port , source_dlci = map ( int , source . split ( ':' ) )
destination_port , destination_dlci = map ( int , de... |
def sync_folder_to_container ( self , folder_path , container , delete = False , include_hidden = False , ignore = None , ignore_timestamps = False , object_prefix = "" , verbose = False ) :
"""Compares the contents of the specified folder , and checks to make sure
that the corresponding object is present in the ... | cont = self . get_container ( container )
self . _local_files = [ ]
# Load a list of all the remote objects so we don ' t have to keep
# hitting the service
if verbose :
log = logging . getLogger ( "pyrax" )
log . info ( "Loading remote object list (prefix=%s)" , object_prefix )
data = cont . get_objects ( pref... |
def geometrize_shapes ( shapes : DataFrame , * , use_utm : bool = False ) -> DataFrame :
"""Given a GTFS shapes DataFrame , convert it to a GeoPandas
GeoDataFrame and return the result .
The result has a ` ` ' geometry ' ` ` column of WGS84 LineStrings
instead of the columns ` ` ' shape _ pt _ sequence ' ` ` ... | import geopandas as gpd
f = shapes . copy ( ) . sort_values ( [ "shape_id" , "shape_pt_sequence" ] )
def my_agg ( group ) :
d = { }
d [ "geometry" ] = sg . LineString ( group [ [ "shape_pt_lon" , "shape_pt_lat" ] ] . values )
return pd . Series ( d )
g = f . groupby ( "shape_id" ) . apply ( my_agg ) . reset... |
def option_changed ( self , option , value ) :
"""Handle when the value of an option has changed""" | setattr ( self , to_text_string ( option ) , value )
self . shellwidget . set_namespace_view_settings ( )
if self . setup_in_progress is False :
self . sig_option_changed . emit ( option , value ) |
def parse_lookup_expression ( element ) :
"""This syntax parses lookups that are defined with their own element""" | lookup_grammar = r"""
lookup = _ "(" range? _ ( "(" _ number _ "," _ number _ ")" _ ","? _ )+ ")"
number = ("+"/"-")? ~r"\d+\.?\d*(e[+-]\d+)?"
_ = ~r"[\s\\]*" # whitespace character
range = _ "[" ~r"[^\]]*" "]" _ ","
"""
parser = parsimonious . Grammar ( lookup_grammar )
tree = parser . parse ( elemen... |
def _can_access_request ( self ) :
"""Can access current request object if all are true
- The serializer is the root .
- A request context was passed in .
- The request method is GET .""" | if self . parent :
return False
if not hasattr ( self , "context" ) or not self . context . get ( "request" , None ) :
return False
return self . context [ "request" ] . method == "GET" |
def dft ( blk , freqs , normalize = True ) :
"""Complex non - optimized Discrete Fourier Transform
Finds the DFT for values in a given frequency list , in order , over the data
block seen as periodic .
Parameters
blk :
An iterable with well - defined length . Don ' t use this function with Stream
object... | dft_data = ( sum ( xn * cexp ( - 1j * n * f ) for n , xn in enumerate ( blk ) ) for f in freqs )
if normalize :
lblk = len ( blk )
return [ v / lblk for v in dft_data ]
return list ( dft_data ) |
def fix_e722 ( self , result ) :
"""fix bare except""" | ( line_index , _ , target ) = get_index_offset_contents ( result , self . source )
if BARE_EXCEPT_REGEX . search ( target ) :
self . source [ line_index ] = '{0}{1}' . format ( target [ : result [ 'column' ] - 1 ] , "except Exception:" ) |
def fit ( self , X , chunks ) :
"""Learn the RCA model .
Parameters
data : ( n x d ) data matrix
Each row corresponds to a single instance
chunks : ( n , ) array of ints
When ` ` chunks [ i ] = = - 1 ` ` , point i doesn ' t belong to any chunklet .
When ` ` chunks [ i ] = = j ` ` , point i belongs to ch... | X = self . _prepare_inputs ( X , ensure_min_samples = 2 )
# PCA projection to remove noise and redundant information .
if self . pca_comps is not None :
pca = decomposition . PCA ( n_components = self . pca_comps )
X_t = pca . fit_transform ( X )
M_pca = pca . components_
else :
X_t = X - X . mean ( axi... |
def zoom ( image , factor , dimension , hdr = False , order = 3 ) :
"""Zooms the provided image by the supplied factor in the supplied dimension .
The factor is an integer determining how many slices should be put between each
existing pair .
If an image header ( hdr ) is supplied , its voxel spacing gets upd... | # check if supplied dimension is valid
if dimension >= image . ndim :
raise argparse . ArgumentError ( 'The supplied zoom-dimension {} exceeds the image dimensionality of 0 to {}.' . format ( dimension , image . ndim - 1 ) )
# get logger
logger = Logger . getInstance ( )
logger . debug ( 'Old shape = {}.' . format ... |
def subvol_create ( self , path ) :
"""Create a btrfs subvolume in the specified path
: param path : path to create""" | args = { 'path' : path }
self . _subvol_chk . check ( args )
self . _client . sync ( 'btrfs.subvol_create' , args ) |
def _get_auth_from_console ( self , realm ) :
"""Prompt for the user and password .""" | self . user , self . password = self . AUTH_MEMOIZE_INPUT . get ( realm , ( self . user , None ) )
if not self . auth_valid ( ) :
if not self . user :
login = getpass . getuser ( )
self . user = self . _raw_input ( 'Username for "{}" [{}]: ' . format ( realm , login ) ) or login
self . password ... |
def requote_uri ( uri ) :
"""Requote uri if it contains non - ascii chars , spaces etc .""" | # To reduce tabulator import time
import requests . utils
if six . PY2 :
def url_encode_non_ascii ( bytes ) :
pattern = '[\x80-\xFF]'
replace = lambda c : ( '%%%02x' % ord ( c . group ( 0 ) ) ) . upper ( )
return re . sub ( pattern , replace , bytes )
parts = urlparse ( uri )
uri = u... |
def _populate_lp ( self , dataset , ** kwargs ) :
"""Populate columns necessary for an LP dataset
This should not be called directly , but rather via : meth : ` Body . populate _ observable `
or : meth : ` System . populate _ observables `""" | logger . debug ( "{}._populate_lp(dataset={})" . format ( self . component , dataset ) )
profile_rest = kwargs . get ( 'profile_rest' , self . lp_profile_rest . get ( dataset ) )
rv_cols = self . _populate_rv ( dataset , ** kwargs )
cols = rv_cols
# rvs = ( rv _ cols [ ' rvs ' ] * u . solRad / u . d ) . to ( u . m / u ... |
def scene_remove ( frames ) :
"""parse a scene . rm message""" | # " scene . rm " < scene _ id >
reader = MessageReader ( frames )
results = reader . string ( "command" ) . uint32 ( "scene_id" ) . assert_end ( ) . get ( )
if results . command != "scene.rm" :
raise MessageParserError ( "Command is not 'scene.rm'" )
return ( results . scene_id , ) |
def _send_command_raw ( self , command , opt = '' ) :
"""Description :
The TV doesn ' t handle long running connections very well ,
so we open a new connection every time .
There might be a better way to do this ,
but it ' s pretty quick and resilient .
Returns :
If a value is being requested ( opt2 is ... | # According to the documentation :
# http : / / files . sharpusa . com / Downloads / ForHome /
# HomeEntertainment / LCDTVs / Manuals / tel _ man _ LC40_46_52_60LE830U . pdf
# Page 58 - Communication conditions for IP
# The connection could be lost ( but not only after 3 minutes ) ,
# so we need to the remote commands ... |
def decode_hparams ( overrides = "" ) :
"""Hparams for decoding .""" | hparams = decoding . decode_hparams ( )
# Number of interpolations between [ 0.0 , 1.0 ] .
hparams . add_hparam ( "num_interp" , 11 )
# Which level ( s ) to interpolate .
hparams . add_hparam ( "level_interp" , [ 0 , 1 , 2 ] )
# " all " or " ranked " , interpolate all channels or a " ranked " .
hparams . add_hparam ( "... |
def get ( self , resource_id = None ) :
"""Return an HTTP response object resulting from an HTTP GET call .
If * resource _ id * is provided , return just the single resource .
Otherwise , return the full collection .
: param resource _ id : The value of the resource ' s primary key""" | if request . path . endswith ( 'meta' ) :
return self . _meta ( )
if resource_id is None :
error_message = is_valid_method ( self . __model__ )
if error_message :
raise BadRequestException ( error_message )
if 'export' in request . args :
return self . _export ( self . _all_resources ( )... |
def _prompt ( self , prompt = None ) :
"""Reads a line written by the user
: param prompt : An optional prompt message
: return : The read line , after a conversion to str""" | if prompt : # Print the prompt
self . write ( prompt )
self . output . flush ( )
# Read the line
return to_str ( self . input . readline ( ) ) |
def filter_slaves ( selfie , slaves ) :
"""Remove slaves that are in an ODOWN or SDOWN state
also remove slaves that do not have ' ok ' master - link - status""" | return [ ( s [ 'ip' ] , s [ 'port' ] ) for s in slaves if not s [ 'is_odown' ] and not s [ 'is_sdown' ] and s [ 'master-link-status' ] == 'ok' ] |
def ServicesGet ( self , sensor_id ) :
"""Retrieve services connected to a sensor in CommonSense .
If ServicesGet is successful , the result can be obtained by a call to getResponse ( ) and should be a json string .
@ sensor _ id ( int ) - Sensor id of sensor to retrieve services from .
@ return ( bool ) - Bo... | if self . __SenseApiCall__ ( '/sensors/{0}/services.json' . format ( sensor_id ) , 'GET' ) :
return True
else :
self . __error__ = "api call unsuccessful"
return False |
def get_text_style ( text ) :
"""Return the text style dict for a text instance""" | style = { }
style [ 'alpha' ] = text . get_alpha ( )
if style [ 'alpha' ] is None :
style [ 'alpha' ] = 1
style [ 'fontsize' ] = text . get_size ( )
style [ 'color' ] = color_to_hex ( text . get_color ( ) )
style [ 'halign' ] = text . get_horizontalalignment ( )
# left , center , right
style [ 'valign' ] = text . g... |
def add_key ( service , key ) :
"""Add a key to a keyring .
Creates the keyring if it doesn ' t already exist .
Logs and returns if the key is already in the keyring .""" | keyring = _keyring_path ( service )
if os . path . exists ( keyring ) :
with open ( keyring , 'r' ) as ring :
if key in ring . read ( ) :
log ( 'Ceph keyring exists at %s and has not changed.' % keyring , level = DEBUG )
return
log ( 'Updating existing keyring %s.' % keyring ... |
def stats_timing ( stats_key , stats_logger ) :
"""Provide a transactional scope around a series of operations .""" | start_ts = now_as_float ( )
try :
yield start_ts
except Exception as e :
raise e
finally :
stats_logger . timing ( stats_key , now_as_float ( ) - start_ts ) |
def add_note ( self , note ) :
"""Add a note to the usernotes wiki page .
Arguments :
note : the note to be added ( Note )
Returns the update message for the usernotes wiki
Raises :
ValueError when the warning type of the note can not be found in the
stored list of warnings .""" | notes = self . cached_json
if not note . moderator :
note . moderator = self . r . user . me ( ) . name
# Get index of moderator in mod list from usernotes
# Add moderator to list if not already there
try :
mod_index = notes [ 'constants' ] [ 'users' ] . index ( note . moderator )
except ValueError :
notes ... |
def setup_logging ( debug , logfile = None ) :
'''Setup logging format and log level .''' | if debug :
level = logging . DEBUG
else :
level = logging . INFO
if logfile is not None :
logging . basicConfig ( format = "%(asctime)s %(levelname)8s %(message)s" , datefmt = "%H:%M:%S %Y/%m/%d" , level = level , filename = logfile )
else :
logging . basicConfig ( format = "%(asctime)s %(levelname)8s %... |
def get_subset_riverid_index_list ( self , river_id_list ) :
"""Gets the subset riverid _ list from the netcdf file
Optional returns include the list of valid river ids in the dataset
as well as a list of missing rive rids
Parameters
river _ id _ list : list or : obj : ` numpy . array `
Array of river ID ... | netcdf_river_indices_list = [ ]
valid_river_ids = [ ]
missing_river_ids = [ ]
for river_id in river_id_list : # get where streamids are in netcdf file
try :
netcdf_river_indices_list . append ( self . get_river_index ( river_id ) )
valid_river_ids . append ( river_id )
except IndexError :
... |
def kill_cursor ( self , cursor ) :
"""Kills the text selected by the give cursor .""" | text = cursor . selectedText ( )
if text :
cursor . removeSelectedText ( )
self . kill ( text ) |
def return_single_real_id_base ( dbpath , set_object , object_id ) :
"""Generic function which returns a real _ id string of an object specified by the object _ id
Parameters
dbpath : string , path to SQLite database file
set _ object : object ( either TestSet or TrainSet ) which is stored in the database
o... | engine = create_engine ( 'sqlite:////' + dbpath )
session_cl = sessionmaker ( bind = engine )
session = session_cl ( )
tmp_object = session . query ( set_object ) . get ( object_id )
session . close ( )
return tmp_object . real_id |
def _flush_graph_val ( self ) :
"""Send all new and changed graph values to the database .""" | if not self . _graphvals2set :
return
delafter = { }
for graph , key , branch , turn , tick , value in self . _graphvals2set :
if ( graph , key , branch ) in delafter :
delafter [ graph , key , branch ] = min ( ( ( turn , tick ) , delafter [ graph , key , branch ] ) )
else :
delafter [ graph... |
def can_proceed ( self ) :
"""Checks whether app can proceed
: return : True iff app is not locked and times since last update < app
update interval""" | now = datetime . datetime . now ( )
delta = datetime . timedelta ( days = self . update_interval )
return now >= self . last_update + delta |
def list_shares ( self , prefix = None , marker = None , num_results = None , include_metadata = False , timeout = None ) :
'''Returns a generator to list the shares under the specified account .
The generator will lazily follow the continuation tokens returned by
the service and stop when all shares have been ... | include = 'metadata' if include_metadata else None
operation_context = _OperationContext ( location_lock = True )
kwargs = { 'prefix' : prefix , 'marker' : marker , 'max_results' : num_results , 'include' : include , 'timeout' : timeout , '_context' : operation_context }
resp = self . _list_shares ( ** kwargs )
return ... |
def create_system ( self , new_machine_id = False ) :
"""Create the machine via the API""" | client_hostname = determine_hostname ( )
machine_id = generate_machine_id ( new_machine_id )
branch_info = self . branch_info
if not branch_info :
return False
remote_branch = branch_info [ 'remote_branch' ]
remote_leaf = branch_info [ 'remote_leaf' ]
data = { 'machine_id' : machine_id , 'remote_branch' : remote_br... |
def put ( self , page , payload , parms = None ) :
'''Puts an XML object on the server - used to update Redmine items . Returns nothing useful .''' | if self . readonlytest :
print 'Redmine read only test: Pretending to update: ' + page
else :
return self . open ( page , parms , payload , HTTPrequest = self . PUT_Request ) |
def load_presets ( self , presets_path = None ) :
"""Load presets from disk .
Read JSON formatted preset data from the specified path ,
or the default location at ` ` / var / lib / sos / presets ` ` .
: param presets _ path : a directory containing JSON presets .""" | presets_path = presets_path or self . presets_path
if not os . path . exists ( presets_path ) :
return
for preset_path in os . listdir ( presets_path ) :
preset_path = os . path . join ( presets_path , preset_path )
try :
preset_data = json . load ( open ( preset_path ) )
except ValueError :
... |
def isbns ( self , key , value ) :
"""Populate the ` ` isbns ` ` key .""" | def _get_medium ( value ) :
def _normalize ( medium ) :
schema = load_schema ( 'hep' )
valid_media = schema [ 'properties' ] [ 'isbns' ] [ 'items' ] [ 'properties' ] [ 'medium' ] [ 'enum' ]
medium = medium . lower ( ) . replace ( '-' , '' ) . replace ( ' ' , '' )
if medium in valid_m... |
def new ( type_dict , type_factory , * type_parameters ) :
"""Create a fully reified type from a type schema .""" | type_tuple = ( type_factory , ) + type_parameters
if type_tuple not in type_dict :
factory = TypeFactory . get_factory ( type_factory )
reified_type = factory . create ( type_dict , * type_parameters )
type_dict [ type_tuple ] = reified_type
return type_dict [ type_tuple ] |
def check_param ( param , param_name , dtype , constraint = None , iterable = True , max_depth = 2 ) :
"""checks the dtype of a parameter ,
and whether it satisfies a numerical contraint
Parameters
param : object
param _ name : str , name of the parameter
dtype : str , desired dtype of the parameter
con... | msg = [ ]
msg . append ( param_name + " must be " + dtype )
if iterable :
msg . append ( " or nested iterable of depth " + str ( max_depth ) + " containing " + dtype + "s" )
msg . append ( ", but found " + param_name + " = {}" . format ( repr ( param ) ) )
if constraint is not None :
msg = ( " " + constraint ) ... |
def ensure_xpointer_compatibility ( node_id ) :
"""makes a given node ID xpointer compatible .
xpointer identifiers must not contain ' : ' , so we ' ll
replace it by ' _ ' .
Parameters
node _ id : str or unicode or int
a node or edge ID
Returns
xpointer _ id : str or unicode or int
int IDs are retur... | assert isinstance ( node_id , ( int , str , unicode ) ) , "node ID must be an int, str or unicode, not" . format ( type ( node_id ) )
if isinstance ( node_id , ( str , unicode ) ) :
return FORBIDDEN_XPOINTER_RE . sub ( '_' , node_id )
else :
return node_id |
def create_gce_image ( zone , project , instance_name , name , description ) :
"""Shuts down the instance and creates and image from the disk .
Assumes that the disk name is the same as the instance _ name ( this is the
default behavior for boot disks on GCE ) .""" | disk_name = instance_name
try :
down_gce ( instance_name = instance_name , project = project , zone = zone )
except HttpError as e :
if e . resp . status == 404 :
log_yellow ( "the instance {} is already down" . format ( instance_name ) )
else :
raise e
body = { "rawDisk" : { } , "name" : na... |
def reload ( self , client = None ) :
"""Reload properties from Cloud Storage .
If : attr : ` user _ project ` is set , bills the API request to that project .
: type client : : class : ` ~ google . cloud . storage . client . Client ` or
` ` NoneType ` `
: param client : the client to use . If not passed , ... | client = self . _require_client ( client )
query_params = self . _query_params
# Pass only ' ? projection = noAcl ' here because ' acl ' and related
# are handled via custom endpoints .
query_params [ "projection" ] = "noAcl"
api_response = client . _connection . api_request ( method = "GET" , path = self . path , quer... |
def create ( self , rate , amount , order_type , pair ) :
'''create new order function
: param rate : float
: param amount : float
: param order _ type : str ; set ' buy ' or ' sell '
: param pair : str ; set ' btc _ jpy ' ''' | nonce = nounce ( )
payload = { 'rate' : rate , 'amount' : amount , 'order_type' : order_type , 'pair' : pair }
url = 'https://coincheck.com/api/exchange/orders'
body = 'rate={rate}&amount={amount}&order_type={order_type}&pair={pair}' . format ( ** payload )
message = nonce + url + body
signature = hmac . new ( self . s... |
def _assign_uid ( self , sid ) :
"""Purpose : Assign a uid to the current object based on the sid passed""" | self . _uid = ru . generate_id ( 'task.%(item_counter)04d' , ru . ID_CUSTOM , namespace = sid ) |
def get_repository_config ( namespace , config , snapshot_id ) :
"""Get a method configuration from the methods repository .
Args :
namespace ( str ) : Methods namespace
config ( str ) : config name
snapshot _ id ( int ) : snapshot _ id of the method
Swagger :
https : / / api . firecloud . org / # ! / M... | uri = "configurations/{0}/{1}/{2}" . format ( namespace , config , snapshot_id )
return __get ( uri ) |
def paths ( self ) :
"""Get list of paths to look in for configuration data""" | filename = '.mbed_cloud_config.json'
return [ # Global config in / etc for * nix users
"/etc/%s" % filename , # Config file in home directory
os . path . join ( os . path . expanduser ( "~" ) , filename ) , # Config file in current directory
os . path . join ( os . getcwd ( ) , filename ) , # Config file specified usin... |
def properties_changed ( self , properties , changed_properties , invalidated_properties ) :
value = changed_properties . get ( 'Value' )
"""Called when a Characteristic property has changed .""" | if value is not None :
self . service . device . characteristic_value_updated ( characteristic = self , value = bytes ( value ) ) |
def _compute ( self , arrays , dates , assets , mask ) :
"""Compute our stored expression string with numexpr .""" | out = full ( mask . shape , self . missing_value , dtype = self . dtype )
# This writes directly into our output buffer .
numexpr . evaluate ( self . _expr , local_dict = { "x_%d" % idx : array for idx , array in enumerate ( arrays ) } , global_dict = { 'inf' : inf } , out = out , )
return out |
def by_filter ( cls , session , opts , ** kwargs ) :
"""Get packages from given filters .
: param session : SQLAlchemy session
: type session : : class : ` sqlalchemy . Session `
: param opts : filtering options
: type opts : ` dict
: return : package instances
: rtype : generator of : class : ` pyshop ... | where = [ ]
if opts . get ( 'local_only' ) :
where . append ( cls . local == True )
if opts . get ( 'names' ) :
where . append ( cls . name . in_ ( opts [ 'names' ] ) )
if opts . get ( 'classifiers' ) :
ids = [ c . id for c in opts . get ( 'classifiers' ) ]
cls_pkg = classifier__package
qry = sessio... |
def get_catalogue ( self , locale ) :
"""Reloads messages catalogue if requested after more than one second
since last reload""" | if locale is None :
locale = self . locale
if locale not in self . catalogues or datetime . now ( ) - self . last_reload > timedelta ( seconds = 1 ) :
self . _load_catalogue ( locale )
self . last_reload = datetime . now ( )
return self . catalogues [ locale ] |
def data ( self , data ) :
""": type : numppy . ndarray""" | self . _assert_shape ( data , self . _x_indexes , self . _y_indexes )
data [ data == - np . inf ] = 0.0
data [ data == np . inf ] = 0.0
self . _data = data
self . _min_value = np . nanmin ( self . data )
self . _max_value = np . nanmax ( self . data )
self . _data_x_indexes = list ( range ( data . shape [ 0 ] ) )
self ... |
def reply_inform ( self , connection , inform , orig_req ) :
"""Send an inform as part of the reply to an earlier request .
Parameters
connection : ClientConnection object
The client to send the inform to .
inform : Message object
The inform message to send .
orig _ req : Message object
The request me... | if isinstance ( connection , ClientRequestConnection ) :
self . _logger . warn ( 'Deprecation warning: do not use self.reply_inform() ' 'within a reply handler context -- ' 'use req.inform(*inform_arguments)\n' 'Traceback:\n %s' , "" . join ( traceback . format_stack ( ) ) )
# Get the underlying ClientConnectio... |
def delete ( self , path ) :
"""Wrap the hvac delete call , using the right token for
cubbyhole interactions .""" | path = sanitize_mount ( path )
val = None
if path . startswith ( 'cubbyhole' ) :
self . token = self . initial_token
val = super ( Client , self ) . delete ( path )
self . token = self . operational_token
else :
super ( Client , self ) . delete ( path )
return val |
def make_bcbiornaseq_object ( data ) :
"""load the initial bcb . rda object using bcbioRNASeq""" | if "bcbiornaseq" not in dd . get_tools_on ( data ) :
return data
upload_dir = tz . get_in ( ( "upload" , "dir" ) , data )
report_dir = os . path . join ( upload_dir , "bcbioRNASeq" )
safe_makedir ( report_dir )
organism = dd . get_bcbiornaseq ( data ) . get ( "organism" , None )
groups = dd . get_bcbiornaseq ( data... |
def run ( self , task ) :
'''Runs a task and re - schedule it''' | self . _remove_dead_greenlet ( task . name )
if isinstance ( task . timer , types . GeneratorType ) : # Starts the task immediately
greenlet_ = gevent . spawn ( task . action , * task . args , ** task . kwargs )
self . active [ task . name ] . append ( greenlet_ )
try : # total _ seconds is available in Pyt... |
def spawn_callback ( self , callback : Callable , * args : Any , ** kwargs : Any ) -> None :
"""Calls the given callback on the next IOLoop iteration .
As of Tornado 6.0 , this method is equivalent to ` add _ callback ` .
. . versionadded : : 4.0""" | self . add_callback ( callback , * args , ** kwargs ) |
def main ( arguments = None ) : # suppress ( unused - function )
"""Entry point for the linter .""" | result = _parse_arguments ( arguments )
linter_funcs = _ordered ( linter_functions_from_filters , result . whitelist , result . blacklist )
global_options = vars ( result )
tool_options = tool_options_from_global ( global_options , len ( result . files ) )
any_would_run = _any_would_run ( _run_lint_on_file_exceptions ,... |
def task_menu ( course , task , template_helper ) :
"""Displays the link to the scoreboards on the task page , if the plugin is activated for this course and the task is used in scoreboards""" | scoreboards = course . get_descriptor ( ) . get ( 'scoreboard' , [ ] )
try :
tolink = [ ]
for sid , scoreboard in enumerate ( scoreboards ) :
if task . get_id ( ) in scoreboard [ "content" ] :
tolink . append ( ( sid , scoreboard [ "name" ] ) )
if tolink :
return str ( template_h... |
def force_start ( self , infohash_list , value = True ) :
"""Force start selected torrents .
: param infohash _ list : Single or list ( ) of infohashes .
: param value : Force start value ( bool )""" | data = self . _process_infohash_list ( infohash_list )
data . update ( { 'value' : json . dumps ( value ) } )
return self . _post ( 'command/setForceStart' , data = data ) |
def get_all_unresolved ( self ) :
"""Returns a set of all unresolved imports .""" | assert self . final , 'Call build() before using the graph.'
out = set ( )
for v in self . broken_deps . values ( ) :
out |= v
return out |
def _build_master ( cls ) :
"""Prepare the master working set .""" | ws = cls ( )
try :
from __main__ import __requires__
except ImportError : # The main program does not list any requirements
return ws
# ensure the requirements are met
try :
ws . require ( __requires__ )
except VersionConflict :
return cls . _build_from_requirements ( __requires__ )
return ws |
def verify ( self , public_pair , val , sig ) :
""": param : public _ pair : a : class : ` Point < pycoin . ecdsa . Point . Point > ` on the curve
: param : val : an integer value
: param : sig : a pair of integers ` ` ( r , s ) ` ` representing an ecdsa signature
: returns : True if and only if the signature... | order = self . _order
r , s = sig
if r < 1 or r >= order or s < 1 or s >= order :
return False
s_inverse = self . inverse ( s )
u1 = val * s_inverse
u2 = r * s_inverse
point = u1 * self + u2 * self . Point ( * public_pair )
v = point [ 0 ] % order
return v == r |
def convert ( self , inp ) :
"""Converts a string representation of some quantity of units into a
quantities object .
Args :
inp ( str ) : A textual representation of some quantity of units ,
e . g . , " fifty kilograms " .
Returns :
A quantities object representing the described quantity and its
unit... | inp = self . _preprocess ( inp )
n = NumberService ( ) . longestNumber ( inp )
units = self . extractUnits ( inp )
# Convert to quantity object , attempt conversion
quantity = pq . Quantity ( float ( n ) , units [ 0 ] )
quantity . units = units [ 1 ]
return quantity |
def sign ( self , payload ) :
"""Sign payload using the supplied authenticator""" | if self . authenticator :
return self . authenticator . signed ( payload )
return payload |
def alter_change_column ( self , table , column , field ) :
"""Support change columns .""" | return self . _update_column ( table , column , lambda a , b : b ) |
def imagetransformer_base_10l_8h_big_uncond_dr03_dan_64_2d ( ) :
"""big 1d model for unconditional generation on imagenet .""" | hparams = image_transformer2d_base ( )
hparams . unconditional = True
hparams . hidden_size = 512
hparams . batch_size = 1
hparams . img_len = 64
hparams . num_heads = 8
hparams . filter_size = 2048
hparams . batch_size = 1
hparams . max_length = 3075
hparams . max_length = 14000
hparams . layer_preprocess_sequence = "... |
def get_tensor_num_entries ( self , tensor_name , partial_layout = None , mesh_dimension_to_size = None ) :
"""The number of entries in a tensor .
If partial _ layout is specified , then mesh _ dimension _ to _ size must also be . In
this case , the number of entries on a single device is returned .
Args :
... | shape = self . get_tensor_shape ( tensor_name )
# We don ' t have to worry about divisiblity issues because Mesh TensorFlow
# only allows evenly divisible assignments .
num_entries = 1
for dim in shape . dims :
num_entries = num_entries * dim . value
if not partial_layout :
return num_entries
for mtf_dimension_... |
def get_feature_variable_boolean ( self , feature_key , variable_key , user_id , attributes = None ) :
"""Returns value for a certain boolean variable attached to a feature flag .
Args :
feature _ key : Key of the feature whose variable ' s value is being accessed .
variable _ key : Key of the variable whose ... | variable_type = entities . Variable . Type . BOOLEAN
return self . _get_feature_variable_for_type ( feature_key , variable_key , variable_type , user_id , attributes ) |
def get_db_references ( cls , entry ) :
"""get list of ` models . DbReference ` from XML node entry
: param entry : XML node entry
: return : list of : class : ` pyuniprot . manager . models . DbReference `""" | db_refs = [ ]
for db_ref in entry . iterfind ( "./dbReference" ) :
db_ref_dict = { 'identifier' : db_ref . attrib [ 'id' ] , 'type_' : db_ref . attrib [ 'type' ] }
db_refs . append ( models . DbReference ( ** db_ref_dict ) )
return db_refs |
def _check_hetcaller ( item ) :
"""Ensure upstream SV callers requires to heterogeneity analysis are available .""" | svs = _get_as_list ( item , "svcaller" )
hets = _get_as_list ( item , "hetcaller" )
if hets or any ( [ x in svs for x in [ "titancna" , "purecn" ] ] ) :
if not any ( [ x in svs for x in [ "cnvkit" , "gatk-cnv" ] ] ) :
raise ValueError ( "Heterogeneity caller used but need CNV calls. Add `gatk4-cnv` " "or `c... |
def analyze ( self , count ) :
"""Analyze count data from : meth : ` PDFHistogram . count ` .
Turns an array of counts ( see : meth : ` PDFHistogram . count ` ) into a
histogram of probabilities , and estimates the mean , standard
deviation , and other statistical characteristics of the corresponding
probab... | if numpy . ndim ( count ) != 1 :
raise ValueError ( 'count must have dimension 1' )
if len ( count ) == len ( self . midpoints ) + 2 :
norm = numpy . sum ( count )
data = numpy . asarray ( count [ 1 : - 1 ] ) / norm
elif len ( count ) != len ( self . midpoints ) :
raise ValueError ( 'wrong data length: ... |
def save_macros ( self , filepath , macros ) :
"""Saves macros to file
Parameters
filepath : String
\t Path to macro file
macros : String
\t Macro code""" | io_error_text = _ ( "Error writing to file {filepath}." )
io_error_text = io_error_text . format ( filepath = filepath )
# Make sure that old macro file does not get lost on abort save
tmpfile = filepath + "~"
try :
wx . BeginBusyCursor ( )
self . main_window . grid . Disable ( )
with open ( tmpfile , "w" )... |
def zoom_to_ligand ( self ) :
"""Zoom in too ligand and its interactions .""" | cmd . center ( self . ligname )
cmd . orient ( self . ligname )
cmd . turn ( 'x' , 110 )
# If the ligand is aligned with the longest axis , aromatic rings are hidden
if 'AllBSRes' in cmd . get_names ( "selections" ) :
cmd . zoom ( '%s or AllBSRes' % self . ligname , 3 )
else :
if self . object_exists ( self . l... |
def hasScoreBetterThan ( self , score ) :
"""Is there an HSP with a score better than a given value ?
@ return : A C { bool } , C { True } if there is at least one HSP in the
alignments for this title with a score better than C { score } .""" | # Note : Do not assume that HSPs in an alignment are sorted in
# decreasing order ( as they are in BLAST output ) . If we could
# assume that , we could just check the first HSP in each alignment .
for hsp in self . hsps ( ) :
if hsp . betterThan ( score ) :
return True
return False |
def start_stop_video ( self ) :
"""Start and stop the video , and change the button .""" | if self . parent . info . dataset is None :
self . parent . statusBar ( ) . showMessage ( 'No Dataset Loaded' )
return
# & is added automatically by PyQt , it seems
if 'Start' in self . idx_button . text ( ) . replace ( '&' , '' ) :
try :
self . update_video ( )
except IndexError as er :
... |
def smallest_pair_diff ( pairs_list ) :
"""This function find the smallest difference in the pairs of the given list of tuples .
Examples :
smallest _ pair _ diff ( [ ( 3 , 5 ) , ( 1 , 7 ) , ( 10 , 3 ) , ( 1 , 2 ) ] ) - > 1
smallest _ pair _ diff ( [ ( 4 , 6 ) , ( 12 , 8 ) , ( 11 , 4 ) , ( 2 , 13 ) ] ) - > 2 ... | diff_list = [ abs ( a - b ) for a , b in pairs_list ]
min_diff = min ( diff_list )
return min_diff |
def sobol ( N , dim , scrambled = 1 ) :
"""Sobol sequence .
Parameters
N : int
length of sequence
dim : int
dimension
scrambled : int
which scrambling method to use :
+ 0 : no scrambling
+ 1 : Owen ' s scrambling
+ 2 : Faure - Tezuka
+ 3 : Owen + Faure - Tezuka
Returns
( N , dim ) numpy ar... | while ( True ) :
seed = np . random . randint ( 2 ** 32 )
out = lowdiscrepancy . sobol ( N , dim , scrambled , seed , 1 , 0 )
if ( scrambled == 0 ) or ( ( out < 1. ) . all ( ) and ( out > 0. ) . all ( ) ) : # no need to test if scrambled = = 0
return out |
def write_data ( self , buf ) :
"""Send data to the device .
If the write fails for any reason , an : obj : ` IOError ` exception
is raised .
: param buf : the data to send .
: type buf : list ( int )
: return : success status .
: rtype : bool""" | if sys . version_info [ 0 ] < 3 :
str_buf = '' . join ( map ( chr , buf ) )
else :
str_buf = bytes ( buf )
result = self . dev . controlWrite ( libusb1 . LIBUSB_ENDPOINT_OUT | libusb1 . LIBUSB_TYPE_CLASS | libusb1 . LIBUSB_RECIPIENT_INTERFACE , libusb1 . LIBUSB_REQUEST_SET_CONFIGURATION , 0x200 , 0 , str_buf , ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.