signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def decode_list_oov ( self , ids , source_oov_id_to_token ) :
"""decode ids back to tokens , considering OOVs temporary IDs .
Args :
ids : vocab ids . Could possibly include source temporary OOV ID starting
from vocab _ size .
source _ oov _ id _ to _ token : a list of source OOV tokens , with the order the... | seq = reversed ( ids ) if self . _reverse else ids
tokens = [ ]
for cur_id in seq :
if cur_id in self . _id_to_token :
tokens . append ( self . _id_to_token [ cur_id ] )
else :
tokens . append ( source_oov_id_to_token [ cur_id - self . vocab_size ] )
return tokens |
def session_callback ( self , signal ) :
"""Signalling from stream session .
Data - new data available for processing .
Playing - Connection is healthy .
Retry - if there is no connection to device .""" | if signal == SIGNAL_DATA :
self . event . new_event ( self . data )
elif signal == SIGNAL_FAILED :
self . retry ( )
if signal in [ SIGNAL_PLAYING , SIGNAL_FAILED ] and self . connection_status_callback :
self . connection_status_callback ( signal ) |
def collect_transitive_dependencies ( collected : Set [ str ] , dep_graph : DepGraph , from_name : str ) -> None :
"""Collect transitive dependencies .
From a dependency graph , collects a list of transitive dependencies by recursing
through a dependency graph .""" | immediate_deps = dep_graph [ from_name ]
for to_name in immediate_deps :
if to_name not in collected :
collected . add ( to_name )
collect_transitive_dependencies ( collected , dep_graph , to_name ) |
def _validate_row_label ( label , column_type_map ) :
"""Validate a row label column .
Parameters
label : str
Name of the row label column .
column _ type _ map : dict [ str , type ]
Dictionary mapping the name of each column in an SFrame to the type of
the values in the column .""" | if not isinstance ( label , str ) :
raise TypeError ( "The row label column name must be a string." )
if not label in column_type_map . keys ( ) :
raise ToolkitError ( "Row label column not found in the dataset." )
if not column_type_map [ label ] in ( str , int ) :
raise TypeError ( "Row labels must be int... |
def deserialize ( cls , target_class , obj ) :
""": type target _ class : object _ . ShareDetail | type
: type obj : dict
: rtype : object _ . ShareDetail""" | share_detail = target_class . __new__ ( target_class )
share_detail . __dict__ = { cls . _ATTRIBUTE_PAYMENT : converter . deserialize ( object_ . ShareDetailPayment , cls . _get_field_or_none ( cls . _FIELD_DRAFT_PAYMENT , obj ) ) , cls . _ATTRIBUTE_READ_ONLY : converter . deserialize ( object_ . ShareDetailReadOnly , ... |
def zero_crossing_before ( self , n ) :
"""Find nearest zero crossing in waveform before frame ` ` n ` `""" | n_in_samples = int ( n * self . samplerate )
search_start = n_in_samples - self . samplerate
if search_start < 0 :
search_start = 0
frame = zero_crossing_last ( self . range_as_mono ( search_start , n_in_samples ) ) + search_start
return frame / float ( self . samplerate ) |
def add_errors ( self , property_name , errors ) :
"""Add one or several errors to properties .
: param property _ name : str , property name
: param errors : list or Error , error object ( s )
: return : shiftschema . result . Result""" | if type ( errors ) is not list :
errors = [ errors ]
for error in errors :
if not isinstance ( error , Error ) :
err = 'Error must be of type {}'
raise x . InvalidErrorType ( err . format ( Error ) )
if property_name in self . errors :
self . errors [ property_name ] . extend ( errors )
else... |
def get_position ( ) :
"""Returns the mouse ' s location as a tuple of ( x , y ) .""" | e = Quartz . CGEventCreate ( None )
point = Quartz . CGEventGetLocation ( e )
return ( point . x , point . y ) |
def semantic_distance ( go_id1 , go_id2 , godag , branch_dist = None ) :
'''Finds the semantic distance ( minimum number of connecting branches )
between two GO terms .''' | return min_branch_length ( go_id1 , go_id2 , godag , branch_dist ) |
def calculate_within_class_scatter_matrix ( X , y ) :
"""Calculates the Within - Class Scatter matrix
Parameters :
X : array - like , shape ( m , n ) - the samples
y : array - like , shape ( m , ) - the class labels
Returns :
within _ class _ scatter _ matrix : array - like , shape ( n , n )""" | mean_vectors = calculate_mean_vectors ( X , y )
n_features = X . shape [ 1 ]
Sw = np . zeros ( ( n_features , n_features ) )
for cl , m in zip ( np . unique ( y ) , mean_vectors ) :
Si = np . zeros ( ( n_features , n_features ) )
m = m . reshape ( n_features , 1 )
for x in X [ y == cl , : ] :
v = x ... |
def generate_next_population ( individuals , toolbox ) :
"""Perform truncated selection with elitism .
: param individuals :
: param toolbox :
: return :""" | individuals = [ toolbox . clone ( ind ) for ind in individuals ]
individuals . sort ( key = lambda x : x . error )
offspring = [ ]
pop_size = len ( individuals )
num_top = math . floor ( pop_size / 2 )
parents = individuals [ 0 : num_top + 1 ]
for _ in range ( pop_size - 1 ) :
off = toolbox . clone ( random . choic... |
def connect_engine ( self ) :
"""Establish a connection to the database .
Provides simple error handling for fatal errors .
Returns :
True , if we could establish a connection , else False .""" | try :
self . connection = self . engine . connect ( )
return True
except sa . exc . OperationalError as opex :
LOG . fatal ( "Could not connect to the database. The error was: '%s'" , str ( opex ) )
return False |
def _escape_parameters ( self , char ) :
"""Parse parameters in an escape sequence . Parameters are a list of
numbers in ascii ( e . g . ' 12 ' , ' 4 ' , ' 42 ' , etc ) separated by a semicolon
( e . g . " 12;4;42 " ) .
See the [ vt102 user guide ] ( http : / / vt100 . net / docs / vt102 - ug / ) for more
d... | if char == ";" :
self . params . append ( int ( self . current_param ) )
self . current_param = ""
elif char == "?" :
self . state = "mode"
elif not char . isdigit ( ) :
if len ( self . current_param ) > 0 :
self . params . append ( int ( self . current_param ) )
# If we ' re in parameter pa... |
def modify_ack_deadline ( self , seconds ) :
"""Resets the deadline for acknowledgement .
New deadline will be the given value of seconds from now .
The default implementation handles this for you ; you should not need
to manually deal with setting ack deadlines . The exception case is
if you are implementi... | self . _request_queue . put ( requests . ModAckRequest ( ack_id = self . _ack_id , seconds = seconds ) ) |
def _setup ( self ) :
"""Generates _ field _ map , _ field _ ids and _ oid _ nums for use in parsing""" | cls = self . __class__
cls . _field_map = { }
cls . _field_ids = [ ]
cls . _precomputed_specs = [ ]
for index , field in enumerate ( cls . _fields ) :
if len ( field ) < 3 :
field = field + ( { } , )
cls . _fields [ index ] = field
cls . _field_map [ field [ 0 ] ] = index
cls . _field_ids . ... |
def update_token ( self ) :
"""Request a new token and store it for future use""" | logger . info ( 'updating token' )
if None in self . credentials . values ( ) :
raise RuntimeError ( "You must provide an username and a password" )
credentials = dict ( auth = self . credentials )
url = self . test_url if self . test else self . url
response = requests . post ( url + "auth" , json = credentials )
... |
def from_names ( cls , * names ) :
"""Create a new ` ChannelList ` from a list of names
The list of names can include comma - separated sets of names ,
in which case the return will be a flattened list of all parsed
channel names .""" | new = cls ( )
for namestr in names :
for name in cls . _split_names ( namestr ) :
new . append ( Channel ( name ) )
return new |
def add_text ( text , x = 0.01 , y = 0.01 , axes = "gca" , draw = True , ** kwargs ) :
"""Adds text to the axes at the specified position .
* * kwargs go to the axes . text ( ) function .""" | if axes == "gca" :
axes = _pylab . gca ( )
axes . text ( x , y , text , transform = axes . transAxes , ** kwargs )
if draw :
_pylab . draw ( ) |
from collections import defaultdict
def count_unique_keys ( input_list ) :
"""This function counts the unique keys for each value present in a tuple list .
> > > count _ unique _ keys ( [ ( 3 , 4 ) , ( 1 , 2 ) , ( 2 , 4 ) , ( 8 , 2 ) , ( 7 , 2 ) , ( 8 , 1 ) , ( 9 , 1 ) , ( 8 , 4 ) , ( 10 , 4 ) ] )
' { 4 : 4 , 2... | val_to_key_dict = defaultdict ( list )
for key_val in input_list :
val_to_key_dict [ key_val [ 1 ] ] . append ( key_val [ 0 ] )
output_dict = { }
for value , keys in val_to_key_dict . items ( ) :
output_dict [ value ] = len ( set ( keys ) )
return str ( output_dict ) |
def download_preview ( self , image , url_field = 'url' ) :
"""Downlaod the binary data of an image attachment at preview size .
: param str url _ field : the field of the image with the right URL
: return : binary image data
: rtype : bytes""" | return self . download ( image , url_field = url_field , suffix = 'preview' ) |
def addNoise ( vecs , percent = 0.1 , n = 2048 ) :
"""Add noise to the given sequence of vectors and return the modified sequence .
A percentage of the on bits are shuffled to other locations .""" | noisyVecs = [ ]
for vec in vecs :
nv = vec . copy ( )
for idx in vec :
if numpy . random . random ( ) <= percent :
nv . discard ( idx )
nv . add ( numpy . random . randint ( n ) )
noisyVecs . append ( nv )
return noisyVecs |
def _get_covered_instructions ( self ) -> int :
"""Gets the total number of covered instructions for all accounts in
the svm .
: return :""" | total_covered_instructions = 0
for _ , cv in self . coverage . items ( ) :
total_covered_instructions += sum ( cv [ 1 ] )
return total_covered_instructions |
def follow_double_underscores ( obj , field_name = None , excel_dialect = True , eval_python = False , index_error_value = None ) :
'''Like getattr ( obj , field _ name ) only follows model relationships through " _ _ " or " . " as link separators
> > > from django . contrib . auth . models import Permission
> ... | if not obj :
return obj
if isinstance ( field_name , list ) :
split_fields = field_name
else :
split_fields = re_model_instance_dot . split ( field_name )
if False and eval_python :
try :
return eval ( field_name , { 'datetime' : datetime , 'math' : math , 'collections' : collections } , { 'obj'... |
def reset_priorities ( self , dict_name , priority ) :
'''set all priorities in dict _ name to priority
: type priority : float or int''' | if self . _session_lock_identifier is None :
raise ProgrammerError ( 'must acquire lock first' )
# # see comment above for script in update
conn = redis . Redis ( connection_pool = self . pool )
script = conn . register_script ( '''
if redis.call("get", KEYS[1]) == ARGV[1]
then
local key... |
def fix_config ( self , options ) :
"""Fixes the options , if necessary . I . e . , it adds all required elements to the dictionary .
: param options : the options to fix
: type options : dict
: return : the ( potentially ) fixed options
: rtype : dict""" | opt = "incremental"
if opt not in options :
options [ opt ] = False
if opt not in self . help :
self . help [ opt ] = "Whether to load the dataset incrementally (bool)."
opt = "use_custom_loader"
if opt not in options :
options [ opt ] = False
if opt not in self . help :
self . help [ opt ] = "Whether t... |
def worker_status ( worker , profile = 'default' ) :
'''Return the state of the worker
CLI Examples :
. . code - block : : bash
salt ' * ' modjk . worker _ status node1
salt ' * ' modjk . worker _ status node1 other - profile''' | config = get_running ( profile )
try :
return { 'activation' : config [ 'worker.{0}.activation' . format ( worker ) ] , 'state' : config [ 'worker.{0}.state' . format ( worker ) ] , }
except KeyError :
return False |
def str_to_date ( date : str ) -> datetime . datetime :
"""Convert cbr . ru API date ste to python datetime
: param date : date from API response
: return : date like datetime
: rtype : datetime""" | date = date . split ( '.' )
date . reverse ( )
y , m , d = date
return datetime . datetime ( int ( y ) , int ( m ) , int ( d ) ) |
def get_factory_kwargs ( self ) :
"""Returns the keyword arguments for calling the formset factory""" | kwargs = { }
kwargs . update ( { 'can_delete' : self . can_delete , 'extra' : self . extra , 'exclude' : self . exclude , 'fields' : self . fields , 'formfield_callback' : self . formfield_callback , 'fk_name' : self . fk_name , } )
if self . formset_class :
kwargs [ 'formset' ] = self . formset_class
if self . chi... |
def change_bgcolor_enable ( self , state ) :
"""This is implementet so column min / max is only active when bgcolor is""" | self . dataModel . bgcolor ( state )
self . bgcolor_global . setEnabled ( not self . is_series and state > 0 ) |
def getWindow ( title , exact = False ) :
"""Return Window object if ' title ' or its part found in visible windows titles , else return None
Return only 1 window found first
Args :
title : unicode string
exact ( bool ) : True if search only exact match""" | titles = getWindows ( )
hwnd = titles . get ( title , None )
if not hwnd and not exact :
for k , v in titles . items ( ) :
if title in k :
hwnd = v
break
if hwnd :
return Window ( hwnd )
else :
return None |
def WriteEventBody ( self , event ) :
"""Writes the body of an event to the output .
Args :
event ( EventObject ) : event .""" | output_string = NativePythonFormatterHelper . GetFormattedEventObject ( event )
self . _output_writer . Write ( output_string ) |
def pauli_pow ( pauli : Pauli , exponent : int ) -> Pauli :
"""Raise an element of the Pauli algebra to a non - negative integer power .""" | if not isinstance ( exponent , int ) or exponent < 0 :
raise ValueError ( "The exponent must be a non-negative integer." )
if exponent == 0 :
return Pauli . identity ( )
if exponent == 1 :
return pauli
# https : / / en . wikipedia . org / wiki / Exponentiation _ by _ squaring
y = Pauli . identity ( )
x = pa... |
def K_swing_check_valve_Crane ( D = None , fd = None , angled = True ) :
r'''Returns the loss coefficient for a swing check valve as shown in [ 1 ] _ .
. . math : :
K _ 2 = N \ cdot f _ d
For angled swing check valves N = 100 ; for straight valves , N = 50.
Parameters
D : float , optional
Diameter of th... | if D is None and fd is None :
raise ValueError ( 'Either `D` or `fd` must be specified' )
if fd is None :
fd = ft_Crane ( D )
if angled :
return 100. * fd
return 50. * fd |
def parse_range_header ( self , header , resource_size ) :
"""Parses a range header into a list of two - tuples ( start , stop ) where
` start ` is the starting byte of the range ( inclusive ) and
` stop ` is the ending byte position of the range ( exclusive ) .
Args :
header ( str ) : The HTTP _ RANGE requ... | if not header or '=' not in header :
return None
ranges = [ ]
units , range_ = header . split ( '=' , 1 )
units = units . strip ( ) . lower ( )
if units != 'bytes' :
return None
for val in range_ . split ( ',' ) :
val = val . strip ( )
if '-' not in val :
return None
if val . startswith ( '-... |
def error_catcher ( self , extra_info : Optional [ str ] = None ) :
"""Context manager to catch , print and record InstaloaderExceptions .
: param extra _ info : String to prefix error message with .""" | try :
yield
except InstaloaderException as err :
if extra_info :
self . error ( '{}: {}' . format ( extra_info , err ) )
else :
self . error ( '{}' . format ( err ) )
if self . raise_all_errors :
raise |
def _parse_json_with_fieldnames ( self ) :
"""Parse the raw JSON with all attributes / methods defined in the class , except for the
ones defined starting with ' _ ' or flagged in cls . _ TO _ EXCLUDE .
The final result is stored in self . json""" | for key in dir ( self ) :
if not key . startswith ( '_' ) and key not in self . _TO_EXCLUDE :
self . fieldnames . append ( key )
value = getattr ( self , key )
if value :
self . json [ key ] = value
# Add OK attribute even if value is " False "
self . json [ 'ok' ] = self . ok |
def getNextService ( self , discover ) :
"""Return the next authentication service for the pair of
user _ input and session . This function handles fallback .
@ param discover : a callable that takes a URL and returns a
list of services
@ type discover : str - > [ service ]
@ return : the next available s... | manager = self . getManager ( )
if manager is not None and not manager :
self . destroyManager ( )
if not manager :
yadis_url , services = discover ( self . url )
manager = self . createManager ( services , yadis_url )
if manager :
service = manager . next ( )
manager . store ( self . session )
else... |
def connection ( self , collectionname , dbname = None ) :
"""Get a cursor to a collection by name .
raises ` DataError ` on names with unallowable characters .
: Parameters :
- ` collectionname ` : the name of the collection
- ` dbname ` : ( optional ) overide the default db for a connection""" | if not collectionname or ".." in collectionname :
raise DataError ( "collection names cannot be empty" )
if "$" in collectionname and not ( collectionname . startswith ( "oplog.$main" ) or collectionname . startswith ( "$cmd" ) ) :
raise DataError ( "collection names must not " "contain '$': %r" % collectionnam... |
def saveas ( self , filename , lineendings = 'default' , encoding = 'latin-1' ) :
"""Save the IDF as a text file with the filename passed .
Parameters
filename : str
Filepath to to set the idfname attribute to and save the file as .
lineendings : str , optional
Line endings to use in the saved file . Opti... | self . idfname = filename
self . save ( filename , lineendings , encoding ) |
def historical ( self , date , base = 'USD' ) :
"""Fetches historical exchange rate data from service
: Example Data :
disclaimer : " < Disclaimer data > " ,
license : " < License data > " ,
timestamp : 1358150409,
base : " USD " ,
rates : {
AED : 3.666311,
AFN : 51.2281,
ALL : 104.748751,
AMD :... | try :
resp = self . client . get ( self . ENDPOINT_HISTORICAL % date . strftime ( "%Y-%m-%d" ) , params = { 'base' : base } )
resp . raise_for_status ( )
except requests . exceptions . RequestException as e :
raise OpenExchangeRatesClientException ( e )
return resp . json ( parse_int = decimal . Decimal , p... |
def GetHostMemSwappedMB ( self ) :
'''Undocumented .''' | counter = c_uint ( )
ret = vmGuestLib . VMGuestLib_GetHostMemSwappedMB ( self . handle . value , byref ( counter ) )
if ret != VMGUESTLIB_ERROR_SUCCESS :
raise VMGuestLibException ( ret )
return counter . value |
def to_bqm ( self , model ) :
"""Given a pysmt model , return a bqm .
Adds the values of the biases as determined by the SMT solver to a bqm .
Args :
model : A pysmt model .
Returns :
: obj : ` dimod . BinaryQuadraticModel `""" | linear = ( ( v , float ( model . get_py_value ( bias ) ) ) for v , bias in self . linear . items ( ) )
quadratic = ( ( u , v , float ( model . get_py_value ( bias ) ) ) for ( u , v ) , bias in self . quadratic . items ( ) )
offset = float ( model . get_py_value ( self . offset ) )
return dimod . BinaryQuadraticModel ( ... |
def _create_child ( self , tag ) :
"""Create a new child element with the given tag .""" | return etree . SubElement ( self . _root , self . _get_namespace_tag ( tag ) ) |
def view ( url : str , ** kwargs ) -> bool :
"""View the page whether rendered properly . ( ensure the < base > tag to make external links work )
Args :
url ( str ) : The url of the site .""" | kwargs . setdefault ( 'headers' , DEFAULT_HEADERS )
html = requests . get ( url , ** kwargs ) . content
if b'<base' not in html :
repl = f'<head><base href="{url}">'
html = html . replace ( b'<head>' , repl . encode ( 'utf-8' ) )
fd , fname = tempfile . mkstemp ( '.html' )
os . write ( fd , html )
os . close ( ... |
def channels ( self ) :
"""Gets channels of current team
Returns :
list of Channel
Throws :
RTMServiceError when request failed""" | resp = self . _rtm_client . get ( 'v1/current_team.channels' )
if resp . is_fail ( ) :
raise RTMServiceError ( 'Failed to get channels of current team' , resp )
return resp . data [ 'result' ] |
def pow2_quantized_convolution ( inp , outmaps , kernel , pad = None , stride = None , dilation = None , group = 1 , w_init = None , b_init = None , base_axis = 1 , fix_parameters = False , rng = None , with_bias = True , quantize_w = True , with_zero_w = False , sign_w = True , n_w = 8 , m_w = 2 , ste_fine_grained_w =... | if w_init is None :
w_init = UniformInitializer ( calc_uniform_lim_glorot ( inp . shape [ base_axis ] , outmaps , tuple ( kernel ) ) , rng = rng )
if with_bias and b_init is None :
b_init = ConstantInitializer ( )
# Floating Weight
w = get_parameter_or_create ( "W" , ( outmaps , inp . shape [ base_axis ] // gro... |
def set_torrent_download_limit ( self , infohash_list , limit ) :
"""Set download speed limit of the supplied torrents .
: param infohash _ list : Single or list ( ) of infohashes .
: param limit : Speed limit in bytes .""" | data = self . _process_infohash_list ( infohash_list )
data . update ( { 'limit' : limit } )
return self . _post ( 'command/setTorrentsDlLimit' , data = data ) |
def _reinit_daq_daemons ( sender , instance , ** kwargs ) :
"""update the daq daemon configuration when changes be applied in the models""" | if type ( instance ) is Device :
try :
bp = BackgroundProcess . objects . get ( pk = instance . protocol_id )
except :
return False
bp . restart ( )
elif type ( instance ) is Variable :
try :
bp = BackgroundProcess . objects . get ( pk = instance . device . protocol_id )
exce... |
def get_airport_stats ( self , iata , page = 1 , limit = 100 ) :
"""Retrieve the performance statistics at an airport
Given the IATA code of an airport , this method returns the performance statistics for the airport .
Args :
iata ( str ) : The IATA code for an airport , e . g . HYD
page ( int ) : Optional ... | url = AIRPORT_DATA_BASE . format ( iata , str ( self . AUTH_TOKEN ) , page , limit )
return self . _fr24 . get_airport_stats ( url ) |
def build_extension ( self , ext ) :
"""Compile manually the py _ mini _ racer extension , bypass setuptools""" | try :
if not is_v8_built ( ) :
self . run_command ( 'build_v8' )
self . debug = True
if V8_PATH :
dest_filename = join ( self . build_lib , "py_mini_racer" )
copy_file ( V8_PATH , dest_filename , verbose = self . verbose , dry_run = self . dry_run )
else :
build_ext . bui... |
def _wrap ( self , meth , * args , ** kwargs ) :
"""Calls a given method with the appropriate arguments , or defers such
a call until the instance has been connected""" | if not self . connected :
return self . _connectSchedule ( self . _wrap , meth , * args , ** kwargs )
opres = meth ( self , * args , ** kwargs )
return self . defer ( opres ) |
def infer_ml_task ( y ) :
"""Infer the machine learning task to select for .
The result will be either ` ' regression ' ` or ` ' classification ' ` .
If the target vector only consists of integer typed values or objects , we assume the task is ` ' classification ' ` .
Else ` ' regression ' ` .
: param y : T... | if y . dtype . kind in np . typecodes [ 'AllInteger' ] or y . dtype == np . object :
ml_task = 'classification'
else :
ml_task = 'regression'
_logger . warning ( 'Infered {} as machine learning task' . format ( ml_task ) )
return ml_task |
def to_str ( self , separator = '' ) :
'''Build a string from the source sequence .
The elements of the query result will each coerced to a string and then
the resulting strings concatenated to return a single string . This
allows the natural processing of character sequences as strings . An
optional separa... | if self . closed ( ) :
raise ValueError ( "Attempt to call to_str() on a closed Queryable." )
return str ( separator ) . join ( self . select ( str ) ) |
async def edit ( self , ** fields ) :
"""| coro |
Edits the group .
Parameters
name : Optional [ : class : ` str ` ]
The new name to change the group to .
Could be ` ` None ` ` to remove the name .
icon : Optional [ : class : ` bytes ` ]
A : term : ` py : bytes - like object ` representing the new ico... | try :
icon_bytes = fields [ 'icon' ]
except KeyError :
pass
else :
if icon_bytes is not None :
fields [ 'icon' ] = utils . _bytes_to_base64_data ( icon_bytes )
data = await self . _state . http . edit_group ( self . id , ** fields )
self . _update_group ( data ) |
def define_flags ( self , parser ) :
"""Adds DebuggerPlugin CLI flags to parser .""" | group = parser . add_argument_group ( 'debugger plugin' )
group . add_argument ( '--debugger_data_server_grpc_port' , metavar = 'PORT' , type = int , default = - 1 , help = '''\
The port at which the non-interactive debugger data server should
receive debugging data via gRPC from one or more debugger-enabled
TensorFlow... |
def fetch_by_ids ( TableName , iso_id_list , numin , numax , ParameterGroups = [ ] , Parameters = [ ] ) :
"""INPUT PARAMETERS :
TableName : local table name to fetch in ( required )
iso _ id _ list : list of isotopologue id ' s ( required )
numin : lower wavenumber bound ( required )
numax : upper wavenumbe... | if type ( iso_id_list ) not in set ( [ list , tuple ] ) :
iso_id_list = [ iso_id_list ]
queryHITRAN ( TableName , iso_id_list , numin , numax , pargroups = ParameterGroups , params = Parameters )
iso_names = [ ISO_ID [ i ] [ ISO_ID_INDEX [ 'iso_name' ] ] for i in iso_id_list ]
Comment = 'Contains lines for ' + ',' ... |
def itemsize ( self ) :
"""Individual item sizes""" | return self . _items [ : self . _count , 1 ] - self . _items [ : self . _count , 0 ] |
def destroy ( name , conn = None , call = None ) :
'''Delete a single VM''' | if call == 'function' :
raise SaltCloudSystemExit ( 'The destroy action must be called with -d, --destroy, ' '-a or --action.' )
__utils__ [ 'cloud.fire_event' ] ( 'event' , 'destroying instance' , 'salt/cloud/{0}/destroying' . format ( name ) , args = { 'name' : name } , sock_dir = __opts__ [ 'sock_dir' ] , transp... |
def multi_split ( s , split ) : # type : ( S , Iterable [ S ] ) - > List [ S ]
"""Splits on multiple given separators .""" | for r in split :
s = s . replace ( r , "|" )
return [ i for i in s . split ( "|" ) if len ( i ) > 0 ] |
def pickTextColor ( self ) :
"""Prompts the user to select a text color .""" | clr = QColorDialog . getColor ( self . textColor ( ) , self . window ( ) , 'Pick Text Color' )
if clr . isValid ( ) :
self . setTextColor ( clr ) |
def get_rm_conf ( self ) :
"""Get excluded files config from remove _ file .""" | if not os . path . isfile ( self . remove_file ) :
return None
# Convert config object into dict
parsedconfig = ConfigParser . RawConfigParser ( )
parsedconfig . read ( self . remove_file )
rm_conf = { }
for item , value in parsedconfig . items ( 'remove' ) :
if six . PY3 :
rm_conf [ item ] = value . st... |
def _process_option ( self , tsocket , command , option ) :
"""For all telnet options , re - implement the default telnetlib behaviour
and refuse to handle any options . If the server expresses interest in
' terminal type ' option , then reply back with ' xterm ' terminal type .""" | if command == DO and option == TTYPE :
tsocket . sendall ( IAC + WILL + TTYPE )
tsocket . sendall ( IAC + SB + TTYPE + b"\0" + b"xterm" + IAC + SE )
elif command in ( DO , DONT ) :
tsocket . sendall ( IAC + WONT + option )
elif command in ( WILL , WONT ) :
tsocket . sendall ( IAC + DONT + option ) |
def Scalars ( self , run , tag ) :
"""Retrieve the scalar events associated with a run and tag .
Args :
run : A string name of the run for which values are retrieved .
tag : A string name of the tag for which values are retrieved .
Raises :
KeyError : If the run is not found , or the tag is not available ... | accumulator = self . GetAccumulator ( run )
return accumulator . Scalars ( tag ) |
def _check_data ( self ) :
"""Ensure that the data in the cache is valid .
If it ' s invalid , the cache is wiped .""" | if not self . cache_available ( ) :
return
parsed = self . _parse_data ( )
_LOGGER . debug ( 'Received new data from sensor: Temp=%.1f, Humidity=%.1f' , parsed [ MI_TEMPERATURE ] , parsed [ MI_HUMIDITY ] )
if parsed [ MI_HUMIDITY ] > 100 : # humidity over 100 procent
self . clear_cache ( )
return
if parsed ... |
def do_your_job ( self ) :
"""the goal of the explore agent is to move to the
target while avoiding blockages on the grid .
This function is messy and needs to be looked at .
It currently has a bug in that the backtrack oscillates
so need a new method of doing this - probably checking if
previously backtr... | y , x = self . get_intended_direction ( )
# first find out where we should go
if self . target_x == self . current_x and self . target_y == self . current_y : # print ( self . name + " : TARGET ACQUIRED " )
if len ( self . results ) == 0 :
self . results . append ( "TARGET ACQUIRED" )
self . lg_mv (... |
def draft ( self , ** kwargs ) :
'''Allows for easily re - drafting a policy
After a policy has been created , it was not previously possible
to re - draft the published policy . This method makes it possible
for a user with existing , published , policies to create drafts
from them so that they are modifia... | tmos_ver = self . _meta_data [ 'bigip' ] . _meta_data [ 'tmos_version' ]
legacy = kwargs . pop ( 'legacy' , False )
if LooseVersion ( tmos_ver ) < LooseVersion ( '12.1.0' ) or legacy :
raise DraftPolicyNotSupportedInTMOSVersion ( "Drafting on this version of BIG-IP is not supported" )
kwargs = dict ( createDraft = ... |
def run ( ) :
"""Execute the build process""" | args = parse ( )
build_results = [ build ( p ) for p in glob . iglob ( glob_path ) ]
if not args [ 'publish' ] :
return
for entry in build_results :
publish ( entry ) |
def init_from_datastore ( self ) :
"""Init list of submission from Datastore .
Should be called by each worker during initialization .""" | self . _attacks = { }
self . _targeted_attacks = { }
self . _defenses = { }
for entity in self . _datastore_client . query_fetch ( kind = KIND_SUBMISSION ) :
submission_id = entity . key . flat_path [ - 1 ]
submission_path = entity [ 'submission_path' ]
participant_id = { k : entity [ k ] for k in [ 'team_i... |
def validateProxy ( path ) :
"""Test that the proxy certificate is RFC 3820
compliant and that it is valid for at least
the next 15 minutes .""" | # load the proxy from path
try :
proxy = M2Crypto . X509 . load_cert ( path )
except Exception , e :
msg = "Unable to load proxy from path %s : %s" % ( path , e )
print >> sys . stderr , msg
sys . exit ( 1 )
# make sure the proxy is RFC 3820 compliant
# or is an end - entity X . 509 certificate
try :
... |
def extend_volume ( self , volume , size ) :
"""Extend a volume to a new , larger size .
: param volume : Name of the volume to be extended .
: type volume : str
: type size : int or str
: param size : Size in bytes , or string representing the size of the
volume to be created .
: returns : A dictionary... | return self . set_volume ( volume , size = size , truncate = False ) |
def calc_variances ( params ) :
'''This function calculates the variance of the sum signal and all population - resolved signals''' | depth = params . electrodeParams [ 'z' ]
# # # CSD # # #
for i , data_type in enumerate ( [ 'CSD' , 'LFP' ] ) :
if i % SIZE == RANK :
f_out = h5py . File ( os . path . join ( params . savefolder , ana_params . analysis_folder , data_type + ana_params . fname_variances ) , 'w' )
f_out [ 'depths' ] = ... |
def downsample_with_striding ( array , factor ) :
"""Downsample x by factor using striding .
@ return : The downsampled array , of the same type as x .""" | return array [ tuple ( np . s_ [ : : f ] for f in factor ) ] |
def calculate_array_feature_extractor_output_shapes ( operator ) :
'''Allowed input / output patterns are
1 . [ N , C ] - - - > [ N , C ' ]
C ' is the number of extracted features .''' | check_input_and_output_numbers ( operator , input_count_range = 1 , output_count_range = 1 )
check_input_and_output_types ( operator , good_input_types = [ FloatTensorType , Int64TensorType , StringTensorType ] )
N = operator . inputs [ 0 ] . type . shape [ 0 ]
extracted_feature_number = len ( operator . raw_operator .... |
def Reset ( self ) :
"""Reset the camera back to its defaults .""" | self . pan = self . world_center
self . desired_pan = self . pos |
def patch_data ( data , L = 100 , try_diag = True , verbose = False ) :
'''Patch ` ` data ` ` ( for example Markov chain output ) into parts of
length ` ` L ` ` . Return a Gaussian mixture where each component gets
the empirical mean and covariance of one patch .
: param data :
Matrix - like array ; the poi... | # patch data into length L patches
patches = _np . array ( [ data [ patch_start : patch_start + L ] for patch_start in range ( 0 , len ( data ) , L ) ] )
# calculate means and covs
means = _np . array ( [ _np . mean ( patch , axis = 0 ) for patch in patches ] )
covs = _np . array ( [ _np . cov ( patch , rowvar = 0 ) fo... |
def resolve_method ( state , method_name , class_name , params = ( ) , ret_type = None , include_superclasses = True , init_class = True , raise_exception_if_not_found = False ) :
"""Resolves the method based on the given characteristics ( name , class and
params ) The method may be defined in one of the supercla... | base_class = state . javavm_classloader . get_class ( class_name )
if include_superclasses :
class_hierarchy = state . javavm_classloader . get_class_hierarchy ( base_class )
else :
class_hierarchy = [ base_class ]
# walk up in class hierarchy , until method is found
for class_descriptor in class_hierarchy :
... |
def read_form_data ( self ) :
"""Attempt to read the form data from the request""" | if self . processed_data :
raise exceptions . AlreadyProcessed ( 'The data has already been processed for this form' )
if self . readonly :
return
if request . method == self . method :
if self . method == 'POST' :
data = request . form
else :
data = request . args
if self . submitte... |
def dicom2db ( file_path , file_type , is_copy , step_id , db_conn , sid_by_patient = False , pid_in_vid = False , visit_in_path = False , rep_in_path = False ) :
"""Extract some meta - data from a DICOM file and store in a DB .
Arguments :
: param file _ path : File path .
: param file _ type : File type ( s... | global conn
conn = db_conn
tags = dict ( )
logging . info ( "Extracting DICOM headers from '%s'" % file_path )
try :
dcm = dicom . read_file ( file_path )
dataset = db_conn . get_dataset ( step_id )
tags [ 'participant_id' ] = _extract_participant ( dcm , dataset , pid_in_vid )
if visit_in_path :
... |
def integrate_storage ( self , timeseries , position , ** kwargs ) :
"""Integrates storage into grid .
See : class : ` ~ . grid . network . StorageControl ` for more information .""" | StorageControl ( edisgo = self , timeseries = timeseries , position = position , ** kwargs ) |
def add_root_match ( self , lst_idx , root_idx ) :
"""Adds a match for the elements avaialble at lst _ idx and root _ idx .""" | self . root_matches [ lst_idx ] = root_idx
if lst_idx in self . in_result_idx :
return
self . not_in_result_root_match_idx . add ( lst_idx ) |
def reign_year_to_ad ( reign_year : int , reign : int ) -> int :
"""Reign year of Chakri dynasty , Thailand""" | if int ( reign ) == 10 :
ad = int ( reign_year ) + 2015
elif int ( reign ) == 9 :
ad = int ( reign_year ) + 1945
elif int ( reign ) == 8 :
ad = int ( reign_year ) + 1928
elif int ( reign ) == 7 :
ad = int ( reign_year ) + 1924
return ad |
def get_token_issuer ( token ) :
"""Issuer of a token is the identifier used to recover the secret
Need to extract this from token to ensure we can proceed to the signature validation stage
Does not check validity of the token
: param token : signed JWT token
: return issuer : iss field of the JWT token
:... | try :
unverified = decode_token ( token )
if 'iss' not in unverified :
raise TokenIssuerError
return unverified . get ( 'iss' )
except jwt . DecodeError :
raise TokenDecodeError |
def cosine ( brands , exemplars , weighted_avg = False , sqrt = False ) :
"""Return the cosine similarity betwee a brand ' s followers and the exemplars .""" | scores = { }
for brand , followers in brands :
if weighted_avg :
scores [ brand ] = np . average ( [ _cosine ( followers , others ) for others in exemplars . values ( ) ] , weights = [ 1. / len ( others ) for others in exemplars . values ( ) ] )
else :
scores [ brand ] = 1. * sum ( _cosine ( fol... |
def main_real ( usercode , netobj , options ) :
'''Entrypoint function for non - test ( " real " ) mode . At this point
we assume that we are running as root and have pcap module .''' | usercode_entry_point = import_or_die ( usercode , ( 'main' , 'switchy_main' ) )
if options . dryrun :
log_info ( "Imported your code successfully. Exiting dry run." )
netobj . shutdown ( )
return
try :
_start_usercode ( usercode_entry_point , netobj , options . codearg )
except Exception as e :
imp... |
def conf_budget ( self , budget ) :
"""Set limit on the number of conflicts .""" | if self . minicard :
pysolvers . minicard_cbudget ( self . minicard , budget ) |
def prod ( self , axis = None , skipna = None , level = None , numeric_only = None , min_count = 0 , ** kwargs ) :
"""Return the product of the values for the requested axis
Args :
axis : { index ( 0 ) , columns ( 1 ) }
skipna : boolean , default True
level : int or level name , default None
numeric _ onl... | axis = self . _get_axis_number ( axis ) if axis is not None else 0
data = self . _validate_dtypes_sum_prod_mean ( axis , numeric_only , ignore_axis = True )
return data . _reduce_dimension ( data . _query_compiler . prod ( axis = axis , skipna = skipna , level = level , numeric_only = numeric_only , min_count = min_cou... |
def calc_frequencies ( genomes , bp_table , min_cov , min_per ) :
"""print bp frequencies to table
genomes = { } # genomes [ genome ] [ contig ] [ sample ] = { ' bp _ stats ' : { } }""" | nucs = [ 'A' , 'T' , 'G' , 'C' , 'N' ]
if bp_table is not False :
bp_table = open ( bp_table , 'w' )
header = [ '#genome' , 'contig' , 'sample' , 'position' , 'reference' , 'ref. frequency' , 'consensus' , 'con. frequency' , 'A' , 'T' , 'G' , 'C' , 'N' , '# insertions' , '# deletions' ]
print ( '\t' . join ... |
def p_constant_declaration ( p ) :
'constant _ declaration : STRING EQUALS static _ scalar' | p [ 0 ] = ast . ConstantDeclaration ( p [ 1 ] , p [ 3 ] , lineno = p . lineno ( 1 ) ) |
def from_s3_json ( cls , bucket_name , key , json_path = None , key_mapping = None , aws_profile = None , aws_access_key_id = None , aws_secret_access_key = None , region_name = None ) : # pragma : no cover
"""Load database credential from json on s3.
: param bucket _ name : str
: param key : str
: param aws ... | import boto3
ses = boto3 . Session ( aws_access_key_id = aws_access_key_id , aws_secret_access_key = aws_secret_access_key , region_name = region_name , profile_name = aws_profile , )
s3 = ses . resource ( "s3" )
bucket = s3 . Bucket ( bucket_name )
object = bucket . Object ( key )
data = json . loads ( object . get ( ... |
def get_credentials ( cmd_args ) :
""": return : The email and api _ key to use to connect to TagCube . This
function will try to get the credentials from :
* Command line arguments
* Environment variables
* Configuration file
It will return the first match , in the order specified above .""" | # Check the cmd args , return if we have something here
cmd_credentials = cmd_args . email , cmd_args . key
if cmd_credentials != ( None , None ) :
cli_logger . debug ( 'Using command line configured credentials' )
return cmd_credentials
env_email , env_api_key = get_config_from_env ( )
if env_email is not None... |
def foldr ( f , seq , default = _no_default ) :
"""Fold a function over a sequence with right associativity .
Parameters
f : callable [ any , any ]
The function to reduce the sequence with .
The first argument will be the element of the sequence ; the second
argument will be the accumulator .
seq : iter... | return reduce ( flip ( f ) , reversed ( seq ) , * ( default , ) if default is not _no_default else ( ) ) |
def send_pgrp ( cls , sock , pgrp ) :
"""Send the PGRP chunk over the specified socket .""" | assert ( isinstance ( pgrp , IntegerForPid ) and pgrp < 0 )
encoded_int = cls . encode_int ( pgrp )
cls . write_chunk ( sock , ChunkType . PGRP , encoded_int ) |
def delete_relationship ( self , entity1_ilx : str , relationship_ilx : str , entity2_ilx : str ) -> dict :
"""Adds relationship connection in Interlex
A relationship exists as 3 different parts :
1 . entity with type term , cde , fde , or pde
2 . entity with type relationship that connects entity1 to entity2... | entity1_data = self . get_entity ( entity1_ilx )
if not entity1_data [ 'id' ] :
exit ( 'entity1_ilx: ' + entity1_data + ' does not exist' )
relationship_data = self . get_entity ( relationship_ilx )
if not relationship_data [ 'id' ] :
exit ( 'relationship_ilx: ' + relationship_ilx + ' does not exist' )
entity2_... |
def _ping_loop ( self ) :
"""This background task sends a PING to the server at the requested
interval .""" | self . pong_received = True
self . ping_loop_event . clear ( )
while self . state == 'connected' :
if not self . pong_received :
self . logger . info ( 'PONG response has not been received, aborting' )
if self . ws :
self . ws . close ( )
self . queue . put ( None )
break... |
def _convert ( self , dictlike ) :
"""Validate and convert a dict - like object into values for set ( ) ing .
This is called behind the scenes when a MappedCollection is replaced
entirely by another collection , as in : :
myobj . mappedcollection = { ' a ' : obj1 , ' b ' : obj2 } # . . .
Raises a TypeError ... | for incoming_key , valuelist in util . dictlike_iteritems ( dictlike ) :
for value in valuelist :
new_key = self . keyfunc ( value )
if incoming_key != new_key :
raise TypeError ( "Found incompatible key %r for value %r; this " "collection's " "keying function requires a key of %r for th... |
def _do_extraction ( df , column_id , column_value , column_kind , default_fc_parameters , kind_to_fc_parameters , n_jobs , chunk_size , disable_progressbar , distributor ) :
"""Wrapper around the _ do _ extraction _ on _ chunk , which calls it on all chunks in the data frame .
A chunk is a subset of the data , w... | data_in_chunks = generate_data_chunk_format ( df , column_id , column_kind , column_value )
if distributor is None :
if n_jobs == 0 :
distributor = MapDistributor ( disable_progressbar = disable_progressbar , progressbar_title = "Feature Extraction" )
else :
distributor = MultiprocessingDistribu... |
def parse_arguments ( argv ) :
"""Parse the command line arguments .""" | parser = argparse . ArgumentParser ( description = ( 'Train a regression or classification model. Note that if ' 'using a DNN model, --layer-size1=NUM, --layer-size2=NUM, ' 'should be used. ' ) )
# I / O file parameters
parser . add_argument ( '--train-data-paths' , type = str , action = 'append' , required = True )
pa... |
def _on_closed ( self ) :
"""Invoked by connections when they are closed .""" | self . _connected . clear ( )
if not self . _closing :
if self . _on_close_callback :
self . _on_close_callback ( )
else :
raise exceptions . ConnectionError ( 'closed' ) |
def assert_true ( expr , msg_fmt = "{msg}" ) :
"""Fail the test unless the expression is truthy .
> > > assert _ true ( " Hello World ! " )
> > > assert _ true ( " " )
Traceback ( most recent call last ) :
AssertionError : ' ' is not truthy
The following msg _ fmt arguments are supported :
* msg - the d... | if not expr :
msg = "{!r} is not truthy" . format ( expr )
fail ( msg_fmt . format ( msg = msg , expr = expr ) ) |
def _cast_to_stata_types ( data ) :
"""Checks the dtypes of the columns of a pandas DataFrame for
compatibility with the data types and ranges supported by Stata , and
converts if necessary .
Parameters
data : DataFrame
The DataFrame to check and convert
Notes
Numeric columns in Stata must be one of i... | ws = ''
# original , if small , if large
conversion_data = ( ( np . bool , np . int8 , np . int8 ) , ( np . uint8 , np . int8 , np . int16 ) , ( np . uint16 , np . int16 , np . int32 ) , ( np . uint32 , np . int32 , np . int64 ) )
float32_max = struct . unpack ( '<f' , b'\xff\xff\xff\x7e' ) [ 0 ]
float64_max = struct .... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.