signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def _toMathInfo ( self , guidelines = True ) : """Subclasses may override this method ."""
import fontMath # A little trickery is needed here because MathInfo # handles font level guidelines . Those are not in this # object so we temporarily fake them just enough for # MathInfo and then move them back to the proper place . self . guidelines = [ ] if guidelines : for guideline in self . font . guidelines ...
def process_request ( self , request ) : """Sets the current request ' s ` ` urlconf ` ` attribute to the urlconf associated with the subdomain , if it is listed in ` ` settings . SUBDOMAIN _ URLCONFS ` ` ."""
super ( SubdomainURLRoutingMiddleware , self ) . process_request ( request ) subdomain = getattr ( request , 'subdomain' , UNSET ) if subdomain is not UNSET : urlconf = settings . SUBDOMAIN_URLCONFS . get ( subdomain ) if urlconf is not None : logger . debug ( "Using urlconf %s for subdomain: %s" , repr...
def signature_base ( self ) : """Get the signature base of this transaction envelope . Return the " signature base " of this transaction , which is the value that , when hashed , should be signed to create a signature that validators on the Stellar Network will accept . It is composed of a 4 prefix bytes fo...
network_id = self . network_id tx_type = Xdr . StellarXDRPacker ( ) tx_type . pack_EnvelopeType ( Xdr . const . ENVELOPE_TYPE_TX ) tx_type = tx_type . get_buffer ( ) tx = Xdr . StellarXDRPacker ( ) tx . pack_Transaction ( self . tx . to_xdr_object ( ) ) tx = tx . get_buffer ( ) return network_id + tx_type + tx
def enable_logging ( self , bucket_name , object_prefix = "" ) : """Enable access logging for this bucket . See https : / / cloud . google . com / storage / docs / access - logs : type bucket _ name : str : param bucket _ name : name of bucket in which to store access logs : type object _ prefix : str : p...
info = { "logBucket" : bucket_name , "logObjectPrefix" : object_prefix } self . _patch_property ( "logging" , info )
def _get_or_load_domain ( self , domain ) : '''Return a domain if one already exists , or create a new one if not . Args : domain ( str , dict ) : Can be one of : - The name of the Domain to return ( fails if none exists ) - A path to the Domain configuration file - A dictionary containing configuration i...
if isinstance ( domain , six . string_types ) : if domain in self . domains : return self . domains [ domain ] elif exists ( domain ) : with open ( domain , 'r' ) as fobj : domain = json . load ( fobj ) else : raise ValueError ( "No domain could be found/loaded from input...
def run ( self , executable_input , project = None , folder = None , name = None , tags = None , properties = None , details = None , instance_type = None , stage_instance_types = None , stage_folders = None , rerun_stages = None , cluster_spec = None , depends_on = None , allow_ssh = None , debug = None , delay_worksp...
# stage _ instance _ types , stage _ folders , and rerun _ stages are # only supported for workflows , but we include them # here . Applet - based executables should detect when they # receive a truthy workflow - specific value and raise an error . run_input = self . _get_run_input ( executable_input , project = projec...
def engine_data ( engine ) : """Get important performance data and metadata from rTorrent ."""
views = ( "default" , "main" , "started" , "stopped" , "complete" , "incomplete" , "seeding" , "leeching" , "active" , "messages" ) methods = [ "throttle.global_up.rate" , "throttle.global_up.max_rate" , "throttle.global_down.rate" , "throttle.global_down.max_rate" , ] # Get data via multicall proxy = engine . open ( )...
def fit_track_models ( self , model_names , model_objs , input_columns , output_columns , output_ranges , ) : """Fit machine learning models to predict track error offsets . model _ names : model _ objs : input _ columns : output _ columns : output _ ranges :"""
print ( "Fitting track models" ) groups = self . data [ "train" ] [ "member" ] [ self . group_col ] . unique ( ) for group in groups : group_data = self . data [ "train" ] [ "combo" ] . loc [ self . data [ "train" ] [ "combo" ] [ self . group_col ] == group ] group_data = group_data . dropna ( ) group_data ...
def _mkstemp_inner ( dir , pre , suf , flags ) : """Code common to mkstemp , TemporaryFile , and NamedTemporaryFile ."""
names = _get_candidate_names ( ) for seq in range ( TMP_MAX ) : name = next ( names ) file = _os . path . join ( dir , pre + name + suf ) try : fd = _os . open ( file , flags , 0o600 ) return ( fd , _os . path . abspath ( file ) ) except FileExistsError : continue # try a...
def add_m_list ( self , matrix_sum , m_list ) : """This adds an m _ list to the output _ lists and updates the current minimum if the list is full ."""
if self . _output_lists is None : self . _output_lists = [ [ matrix_sum , m_list ] ] else : bisect . insort ( self . _output_lists , [ matrix_sum , m_list ] ) if self . _algo == EwaldMinimizer . ALGO_BEST_FIRST and len ( self . _output_lists ) == self . _num_to_return : self . _finished = True if len ( self...
def restoredata ( filename = None ) : """Restore the state of the credolib workspace from a pickle file ."""
if filename is None : filename = 'credolib_state.pickle' ns = get_ipython ( ) . user_ns with open ( filename , 'rb' ) as f : d = pickle . load ( f ) for k in d . keys ( ) : ns [ k ] = d [ k ]
def OnGridSelection ( self , event ) : """Event handler for grid selection in selection mode adds text"""
current_table = copy ( self . main_window . grid . current_table ) post_command_event ( self , self . GridActionTableSwitchMsg , newtable = self . last_table ) if is_gtk ( ) : try : wx . Yield ( ) except : pass sel_start , sel_stop = self . last_selection shape = self . main_window . grid . code...
def decompress ( self , value : bytes , max_length : int = 0 ) -> bytes : """Decompress a chunk , returning newly - available data . Some data may be buffered for later processing ; ` flush ` must be called when there is no more input data to ensure that all data was processed . If ` ` max _ length ` ` is g...
return self . decompressobj . decompress ( value , max_length )
def _call ( self , cmd , get_output ) : """Calls a command through the SSH connection . Remote stderr gets printed to this program ' s stderr . Output is captured and may be returned ."""
server_err = self . server_logger ( ) chan = self . get_client ( ) . get_transport ( ) . open_session ( ) try : logger . debug ( "Invoking %r%s" , cmd , " (stdout)" if get_output else "" ) chan . exec_command ( '/bin/sh -c %s' % shell_escape ( cmd ) ) output = b'' while True : r , w , e = select...
def _cleanupConnections ( senderkey , signal ) : """Delete any empty signals for senderkey . Delete senderkey if empty ."""
try : receivers = connections [ senderkey ] [ signal ] except : pass else : if not receivers : # No more connected receivers . Therefore , remove the signal . try : signals = connections [ senderkey ] except KeyError : pass else : del signals [ sig...
def is_key ( sarg ) : """Check if ` sarg ` is a key ( eg . - foo , - - foo ) or a negative number ( eg . - 33 ) ."""
if not sarg . startswith ( "-" ) : return False if sarg . startswith ( "--" ) : return True return not sarg . lstrip ( "-" ) . isnumeric ( )
def get_instance ( self , payload ) : """Build an instance of TaskInstance : param dict payload : Payload response from the API : returns : twilio . rest . taskrouter . v1 . workspace . task . TaskInstance : rtype : twilio . rest . taskrouter . v1 . workspace . task . TaskInstance"""
return TaskInstance ( self . _version , payload , workspace_sid = self . _solution [ 'workspace_sid' ] , )
def build_taxonomy ( self , level , namespace , predicate , value ) : """: param level : info , safe , suspicious or malicious : param namespace : Name of analyzer : param predicate : Name of service : param value : value : return : dict"""
return { 'level' : level , 'namespace' : namespace , 'predicate' : predicate , 'value' : value }
def _convert_angle_from_pypot ( angle , joint , ** kwargs ) : """Converts an angle to a PyPot - compatible format"""
angle_internal = angle + joint [ "offset" ] if joint [ "orientation-convention" ] == "indirect" : angle_internal = - 1 * angle_internal # UGLY if joint [ "name" ] . startswith ( "l_shoulder_x" ) : angle_internal = - 1 * angle_internal angle_internal = ( angle_internal / 180 * np . pi ) return angle_internal
def l2_regression_loss ( y , target , name = None ) : """Calculates the square root of the SSE between y and target . Args : y : the calculated values . target : the desired values . name : the name for this op , defaults to l2 _ regression Returns : A tensorflow op ."""
with tf . name_scope ( name , 'l2_regression' , [ y , target ] ) as scope : y = tf . convert_to_tensor ( y , name = 'y' ) target = tf . convert_to_tensor ( target , name = 'target' ) return tf . sqrt ( l2_regression_sq_loss ( y , target , name = scope ) )
def set_auto_page_break ( self , auto , margin = 0 ) : "Set auto page break mode and triggering margin"
self . auto_page_break = auto self . b_margin = margin self . page_break_trigger = self . h - margin
def as_data ( self ) : """If obj [ % data _ key _ name ] exists , Return obj [ % data _ key _ name ] otherwise base64 encoded string of obj [ % file _ key _ name ] file content ."""
use_file_if_no_data = not self . _data and self . _file if use_file_if_no_data : with open ( self . _file ) as f : if self . _base64_file_content : self . _data = bytes . decode ( base64 . standard_b64encode ( str . encode ( f . read ( ) ) ) ) else : self . _data = f . read (...
def geist_replay ( wrapped , instance , args , kwargs ) : """Wraps a test of other function and injects a Geist GUI which will enable replay ( set environment variable GEIST _ REPLAY _ MODE to ' record ' to active record mode ."""
path_parts = [ ] file_parts = [ ] if hasattr ( wrapped , '__module__' ) : module = wrapped . __module__ module_file = sys . modules [ module ] . __file__ root , _file = os . path . split ( module_file ) path_parts . append ( root ) _file , _ = os . path . splitext ( _file ) file_parts . append (...
def create_artist ( self ) : """decides whether the artist should be visible or not in the current axis current _ axis : names of x , y axis"""
verts = self . coordinates if not self . tracky : trans = self . ax . get_xaxis_transform ( which = 'grid' ) elif not self . trackx : trans = self . ax . get_yaxis_transform ( which = 'grid' ) else : trans = self . ax . transData self . artist = pl . Line2D ( [ verts [ 0 ] ] , [ verts [ 1 ] ] , transform = ...
def get_parser ( ) : """Initialize the parser for the command line interface and bind the autocompletion functionality"""
# initialize the parser parser = argparse . ArgumentParser ( description = ( 'Command line tool for extracting text from any document. ' ) % locals ( ) , ) # define the command line options here parser . add_argument ( 'filename' , help = 'Filename to extract text.' , ) . completer = argcomplete . completers . FilesCom...
def get_image_performance_info ( self , userid ) : """Get CPU and memory usage information . : userid : the zvm userid to be queried"""
pi_dict = self . image_performance_query ( [ userid ] ) return pi_dict . get ( userid , None )
def is_repository_directory ( cls , path ) : # type : ( str ) - > bool """Return whether a directory path is a repository directory ."""
logger . debug ( 'Checking in %s for %s (%s)...' , path , cls . dirname , cls . name ) return os . path . exists ( os . path . join ( path , cls . dirname ) )
def updateBoostStrength ( self ) : """Update boost strength using given strength factor during training"""
if self . training : self . boostStrength = self . boostStrength * self . boostStrengthFactor
def exists_alias ( self , alias_name , index_name = None ) : """Check whether or not the given alias exists : return : True if alias already exist"""
return self . _es_conn . indices . exists_alias ( index = index_name , name = alias_name )
def p_lpartselect_plus ( self , p ) : 'lpartselect : identifier LBRACKET expression PLUSCOLON expression RBRACKET'
p [ 0 ] = Partselect ( p [ 1 ] , p [ 3 ] , Plus ( p [ 3 ] , p [ 5 ] ) , lineno = p . lineno ( 1 ) ) p . set_lineno ( 0 , p . lineno ( 1 ) )
def get_band_gap ( self ) : '''Compute the band gap from the DOS'''
dosdata = self . get_dos ( ) if type ( dosdata ) == type ( None ) : return None # cannot find DOS else : energy = dosdata . conditions . scalars dos = dosdata . scalars step_size = energy [ 1 ] . value - energy [ 0 ] . value not_found = True ; l = 0 ; bot = 10 ** 3 ; top = - 10 ** 3 ...
def pull_dependencies ( collector , image , ** kwargs ) : """Pull an image ' s dependent images"""
for dep in image . commands . dependent_images : kwargs [ "image" ] = dep pull_arbitrary ( collector , ** kwargs )
def build_asset_array ( assets_by_site , tagnames = ( ) , time_event = None ) : """: param assets _ by _ site : a list of lists of assets : param tagnames : a list of tag names : returns : an array ` assetcol `"""
for assets in assets_by_site : if len ( assets ) : first_asset = assets [ 0 ] break else : # no break raise ValueError ( 'There are no assets!' ) loss_types = [ ] occupancy_periods = [ ] for name in sorted ( first_asset . values ) : if name . startswith ( 'occupants_' ) : period = na...
def show_fact ( term ) : """Shows a fact stored for a given term , using a case - insensitive search . If a fact has an author , it will be shown . If it has a timestamp , that will also be shown ."""
logger . info ( 'Showing fact %s' , term ) record = db . facts . find_one ( { 'term' : term_regex ( term ) } ) if record is None : return None # Fix double spacing in older facts if record [ 'fact' ] : record [ 'fact' ] = record [ 'fact' ] . replace ( ' ' , ' ' ) # If it isn ' t authored if not record . get ( ...
def conv2d ( inputs , num_filters_out , kernel_size , stride = 1 , padding = 'SAME' , activation = tf . nn . relu , stddev = 0.01 , bias = 0.0 , weight_decay = 0 , batch_norm_params = None , is_training = True , trainable = True , restore = True , scope = None , reuse = None ) : """Adds a 2D convolution followed by...
with tf . variable_scope ( scope , 'Conv' , [ inputs ] , reuse = reuse ) : kernel_h , kernel_w = _two_element_tuple ( kernel_size ) stride_h , stride_w = _two_element_tuple ( stride ) num_filters_in = inputs . get_shape ( ) [ - 1 ] weights_shape = [ kernel_h , kernel_w , num_filters_in , num_filters_out...
def draw_key ( self , surface , key ) : """Default drawing method for key . Draw the key accordingly to it type . : param surface : Surface background should be drawn in . : param key : Target key to be drawn ."""
if isinstance ( key , VSpaceKey ) : self . draw_space_key ( surface , key ) elif isinstance ( key , VBackKey ) : self . draw_back_key ( surface , key ) elif isinstance ( key , VUppercaseKey ) : self . draw_uppercase_key ( surface , key ) elif isinstance ( key , VSpecialCharKey ) : self . draw_special_ch...
def add_molecular_graph ( self , molecular_graph , atom_types = None , charges = None , split = True , molecule = None ) : """Add the molecular graph to the data structure Argument : | ` ` molecular _ graph ` ` - - a MolecularGraph instance Optional arguments : | ` ` atom _ types ` ` - - a list with atom ty...
# add atom numbers and molecule indices new = len ( molecular_graph . numbers ) if new == 0 : return prev = len ( self . numbers ) offset = prev self . numbers . resize ( prev + new ) self . numbers [ - new : ] = molecular_graph . numbers if atom_types is None : atom_types = [ periodic [ number ] . symbol for n...
def doDup ( self , WHAT = { } , ** params ) : """This function will perform the command - dup ."""
if hasattr ( WHAT , '_modified' ) : for key , value in WHAT . _modified ( ) : if WHAT . __new2old__ . has_key ( key ) : self . _addDBParam ( WHAT . __new2old__ [ key ] . encode ( 'utf-8' ) , value ) else : self . _addDBParam ( key , value ) self . _addDBParam ( 'RECORDID'...
def get_app_submodules ( submodule_name ) : """From wagtail . utils Searches each app module for the specified submodule yields tuples of ( app _ name , module )"""
for name , module in get_app_modules ( ) : if module_has_submodule ( module , submodule_name ) : yield name , import_module ( '%s.%s' % ( name , submodule_name ) )
def world_coords ( self ) : """: return : world coordinates of mate . : rtype : : class : ` CoordSystem < cqparts . utils . geometry . CoordSystem > ` : raises ValueError : if ` ` . component ` ` does not have valid world coordinates . If ` ` . component ` ` is ` ` None ` ` , then the ` ` . local _ coords ` `...
if self . component is None : # no component , world = = local return copy ( self . local_coords ) else : cmp_origin = self . component . world_coords if cmp_origin is None : raise ValueError ( "mate's component does not have world coordinates; " "cannot get mate's world coordinates" ) return cm...
def _attach_objects_post_save_hook ( self , cls , data , pending_relations = None ) : """Gets called by this object ' s create and sync methods just after save . Use this to populate fields after the model is saved . : param cls : The target class for the instantiated object . : param data : The data dictiona...
unprocessed_pending_relations = [ ] if pending_relations is not None : for post_save_relation in pending_relations : object_id , field , id_ = post_save_relation if self . id == id_ : # the target instance now exists target = field . model . objects . get ( id = object_id ) s...
def try_catch ( func , * args , ** kwargs ) : '''Wrap call of provided function with try / except block and debug log statements . If an instance of ' Exception ' ( or one of its subclasses ) is thrown by ' func ' , it is caught , and the exception object itself is return as a result .'''
try : return log_debug ( func , * args , ** kwargs ) except Exception as exc : logging . debug ( 'Error in "%s" in thread %s: %s' , func . __name__ , current_thread ( ) , exc ) return exc
def extract_angular ( fileobj , keywords , comment_tags , options ) : """Extract messages from angular template ( HTML ) files . It extract messages from angular template ( HTML ) files that use angular - gettext translate directive as per https : / / angular - gettext . rocketeer . be / : param fileobj : t...
parser = AngularGettextHTMLParser ( ) for line in fileobj : parser . feed ( encodeutils . safe_decode ( line ) ) for string in parser . strings : yield ( string )
def G ( self , y , t ) : """Noise coefficient matrix G of the complete network system dy = f ( y , t ) dt + G ( y , t ) . dot ( dW ) ( for an ODE network system without noise this function is not used ) Args : y ( array of shape ( d , ) ) : where d is the dimension of the overall state space of the comple...
if self . _independent_noise : # then G matrix consists of submodel Gs diagonally concatenated : res = np . zeros ( ( self . dimension , self . nnoises ) ) offset = 0 for j , m in enumerate ( self . submodels ) : slicej = slice ( self . _si [ j ] , self . _si [ j + 1 ] ) ix = ( slicej , slic...
def from_raw_message ( cls , rawmessage ) : """Create a message from a raw byte stream ."""
return AllLinkComplete ( rawmessage [ 2 ] , rawmessage [ 3 ] , rawmessage [ 4 : 7 ] , rawmessage [ 7 ] , rawmessage [ 8 ] , rawmessage [ 9 ] )
def customize_lexer_priority ( file_name , accuracy , lexer ) : """Customize lexer priority"""
priority = lexer . priority lexer_name = lexer . name . lower ( ) . replace ( 'sharp' , '#' ) if lexer_name in LANGUAGES : priority = LANGUAGES [ lexer_name ] elif lexer_name == 'matlab' : available_extensions = extensions_in_same_folder ( file_name ) if '.mat' in available_extensions : accuracy += ...
def _get_read_preference ( read_preference ) : """Converts read _ preference from string to pymongo . ReadPreference value . Args : read _ preference : string containig the read _ preference from the config file Returns : A value from the pymongo . ReadPreference enum Raises : Exception : Invalid read...
read_preference = getattr ( pymongo . ReadPreference , read_preference , None ) if read_preference is None : raise ValueError ( 'Invalid read preference: %s' % read_preference ) return read_preference
def p_declare_list ( p ) : '''declare _ list : STRING EQUALS static _ scalar | declare _ list COMMA STRING EQUALS static _ scalar'''
if len ( p ) == 4 : p [ 0 ] = [ ast . Directive ( p [ 1 ] , p [ 3 ] , lineno = p . lineno ( 1 ) ) ] else : p [ 0 ] = p [ 1 ] + [ ast . Directive ( p [ 3 ] , p [ 5 ] , lineno = p . lineno ( 2 ) ) ]
def download_local_file ( filename , download_to_file ) : """Copies a local file to Invenio ' s temporary directory . @ param filename : the name of the file to copy @ type filename : string @ param download _ to _ file : the path to save the file to @ type download _ to _ file : string @ return : the pat...
# Try to copy . try : path = urllib2 . urlparse . urlsplit ( urllib . unquote ( filename ) ) [ 2 ] if os . path . abspath ( path ) != path : msg = "%s is not a normalized path (would be %s)." % ( path , os . path . normpath ( path ) ) raise InvenioFileCopyError ( msg ) allowed_path_list = cu...
def render_choicefield ( field , attrs , choices = None ) : """Render ChoiceField as ' div ' dropdown rather than select for more customization ."""
# Allow custom choice list , but if no custom choice list then wrap all # choices into the ` wrappers . CHOICE _ TEMPLATE ` if not choices : choices = format_html_join ( "" , wrappers . CHOICE_TEMPLATE , get_choices ( field ) ) # Accessing the widget attrs directly saves them for a new use after # a POST request fi...
def _build_predict ( self , Xnew , full_cov = False ) : """Compute the mean and variance of the latent function at some new points Xnew . For a derivation of the terms in here , see the associated SGPR notebook ."""
num_inducing = len ( self . feature ) err = self . Y - self . mean_function ( self . X ) Kuf = features . Kuf ( self . feature , self . kern , self . X ) Kuu = features . Kuu ( self . feature , self . kern , jitter = settings . numerics . jitter_level ) Kus = features . Kuf ( self . feature , self . kern , Xnew ) sigma...
def summarize ( self ) : '''Print a summary of the contents of this object .'''
self . speak ( 'Here is a brief summary of {}.' . format ( self . nametag ) ) s = '\n' + pprint . pformat ( self . __dict__ ) print ( s . replace ( '\n' , '\n' + ' ' * ( len ( self . _prefix ) + 1 ) ) + '\n' )
def adaptive_universal_transformer_multilayer_hard ( ) : """Multi - layer config for adaptive Transformer with hard attention ."""
hparams = adaptive_universal_transformer_multilayer_tpu ( ) hparams . batch_size = 256 hparams . hard_attention_k = 8 hparams . add_step_timing_signal = True # hparams . add _ sru = True # This is very slow on GPUs , does it help ? hparams . self_attention_type = "dot_product_relative_v2" hparams . max_relative_positio...
def parse_name_from_config ( self , config ) : """Banana banana"""
self . project_name = config . get ( 'project_name' , None ) if not self . project_name : error ( 'invalid-config' , 'No project name was provided' ) self . project_version = config . get ( 'project_version' , None ) if not self . project_version : error ( 'invalid-config' , 'No project version was provided' ) ...
def _encrypt_entity ( entity , key_encryption_key , encryption_resolver ) : '''Encrypts the given entity using AES256 in CBC mode with 128 bit padding . Will generate a content - encryption - key ( cek ) to encrypt the properties either stored in an EntityProperty with the ' encrypt ' flag set or those specif...
_validate_not_none ( 'entity' , entity ) _validate_not_none ( 'key_encryption_key' , key_encryption_key ) _validate_key_encryption_key_wrap ( key_encryption_key ) # AES256 uses 256 bit ( 32 byte ) keys and always with 16 byte blocks content_encryption_key = os . urandom ( 32 ) entity_initialization_vector = os . urando...
def start ( self ) : """Start a thread to handle SocketIO notifications ."""
if not self . _thread : _LOGGER . info ( "Starting SocketIO thread..." ) self . _thread = threading . Thread ( target = self . _run_socketio_thread , name = 'SocketIOThread' ) self . _thread . deamon = True self . _thread . start ( )
def find_enclosing_bracket_left ( self , left_ch , right_ch , start_pos = None ) : """Find the left bracket enclosing current position . Return the relative position to the cursor position . When ` start _ pos ` is given , don ' t look past the position ."""
if self . current_char == left_ch : return 0 if start_pos is None : start_pos = 0 else : start_pos = max ( 0 , start_pos ) stack = 1 # Look backward . for i in range ( self . cursor_position - 1 , start_pos - 1 , - 1 ) : c = self . text [ i ] if c == right_ch : stack += 1 elif c == left_...
def train_language_model_from_dataset ( self , dataset_id , name , token = None , url = API_TRAIN_LANGUAGE_MODEL ) : """Trains a model given a dataset and its ID . : param dataset _ id : string , the ID for a dataset you created previously . : param name : string , name for your model . returns : a request ob...
auth = 'Bearer ' + self . check_for_token ( token ) dummy_files = { 'name' : ( None , name ) , 'datasetId' : ( None , dataset_id ) } h = { 'Authorization' : auth , 'Cache-Control' : 'no-cache' } the_url = url r = requests . post ( the_url , headers = h , files = dummy_files ) return r
def OnInit ( self , profile = None , memoryProfile = None ) : """Initialise the application"""
wx . Image . AddHandler ( self . handler ) frame = MainFrame ( config_parser = load_config ( ) ) frame . Show ( True ) self . SetTopWindow ( frame ) if profile : wx . CallAfter ( frame . load , * [ profile ] ) elif sys . argv [ 1 : ] : if sys . argv [ 1 ] == '-m' : if sys . argv [ 2 : ] : wx...
def fragment ( self , value = None ) : """Return or set the fragment ( hash ) : param string value : the new fragment to use : returns : string or new : class : ` URL ` instance"""
if value is not None : return URL . _mutate ( self , fragment = value ) return unicode_unquote ( self . _tuple . fragment )
def find_loops ( record , index , stop_types = STOP_TYPES , open = None , seen = None ) : """Find all loops within the index and replace with loop records"""
if open is None : open = [ ] if seen is None : seen = set ( ) for child in children ( record , index , stop_types = stop_types ) : if child [ 'type' ] in stop_types or child [ 'type' ] == LOOP_TYPE : continue if child [ 'address' ] in open : # loop has been found start = open . index ( c...
def sim_network ( network , ds = None , index = None , mean = 0 , std = 1 ) : """Simulate / activate a Network on a SupervisedDataSet and return DataFrame ( columns = [ ' Output ' , ' Target ' ] ) The DataSet ' s target and output values are denormalized before populating the dataframe columns : denormalized _ ...
# just in case network is a trainer or has a Module - derived instance as one of it ' s attribute # isinstance ( network . module , ( networks . Network , modules . Module ) ) if hasattr ( network , 'module' ) and hasattr ( network . module , 'activate' ) : # may want to also check : isinstance ( network . module , ( n...
def getEthernetStatistic ( self , lanInterfaceId = 1 , timeout = 1 ) : """Execute GetStatistics action to get statistics of the Ethernet interface . : param int lanInterfaceId : the id of the LAN interface : param float timeout : the timeout to wait for the action to be executed : return : statisticss of the ...
namespace = Lan . getServiceType ( "getEthernetStatistic" ) + str ( lanInterfaceId ) uri = self . getControlURL ( namespace ) results = self . execute ( uri , namespace , "GetStatistics" , timeout = timeout ) return EthernetStatistic ( results )
def sync ( self , hooks = True , async_hooks = True ) : """Synchronize user repositories . : param bool hooks : True for syncing hooks . : param bool async _ hooks : True for sending of an asynchronous task to sync hooks . . . note : : Syncing happens from GitHub ' s direction only . This means that we ...
active_repos = { } github_repos = { repo . id : repo for repo in self . api . repositories ( ) if repo . permissions [ 'admin' ] } for gh_repo_id , gh_repo in github_repos . items ( ) : active_repos [ gh_repo_id ] = { 'id' : gh_repo_id , 'full_name' : gh_repo . full_name , 'description' : gh_repo . description , } ...
def make_client ( host , project_name , api_key , create_project ) : """Instantiate the grano client based on environment variables or command line settings ."""
if host is None : raise click . BadParameter ( 'No grano server host is set' , param = host ) if project_name is None : raise click . BadParameter ( 'No grano project slug is set' , param = project_name ) if api_key is None : raise click . BadParameter ( 'No grano API key is set' , param = api_key ) client ...
def genlmsg_parse ( nlh , hdrlen , tb , maxtype , policy ) : """Parse Generic Netlink message including attributes . https : / / github . com / thom311 / libnl / blob / libnl3_2_25 / lib / genl / genl . c # L191 Verifies the validity of the Netlink and Generic Netlink headers using genlmsg _ valid _ hdr ( ) and...
if not genlmsg_valid_hdr ( nlh , hdrlen ) : return - NLE_MSG_TOOSHORT ghdr = genlmsghdr ( nlmsg_data ( nlh ) ) return int ( nla_parse ( tb , maxtype , genlmsg_attrdata ( ghdr , hdrlen ) , genlmsg_attrlen ( ghdr , hdrlen ) , policy ) )
def integer_entry ( self , prompt , message = None , min = None , max = None , rofi_args = None , ** kwargs ) : """Prompt the user to enter an integer . Parameters prompt : string Prompt to display to the user . message : string , optional Message to display under the entry line . min , max : integer , ...
# Sanity check . if ( min is not None ) and ( max is not None ) and not ( max > min ) : raise ValueError ( "Maximum limit has to be more than the minimum limit." ) def integer_validator ( text ) : error = None # Attempt to convert to integer . try : value = int ( text ) except ValueError : ...
def request_session ( token , url = None ) : """Requests a WebSocket session for the Real - Time Messaging API . Returns a SessionMetadata object containing the information retrieved from the API call ."""
if url is None : api = SlackApi ( ) else : api = SlackApi ( url ) response = api . rtm . start ( token = token ) return SessionMetadata ( response , api , token )
def _get_token_type ( self , char ) : """Returns a 2 - tuple ( behaviour , type ) . behaviours : 0 - join 1 - split 2 - ignore"""
if char in '()' : return self . SPLIT , 0 elif char == ',' : return self . SPLIT , 1 elif char in '<>' : return self . IGNORE , 2 elif char == '.' : return self . JOIN , 3 elif char . isdigit ( ) : return self . JOIN , 4 elif char . isalpha ( ) : return self . JOIN , 5 elif char == '^' : ret...
def inform_of_short_bin_name ( cls , binary ) : """Historically , we had " devassistant " binary , but we chose to go with shorter " da " . We still allow " devassistant " , but we recommend using " da " ."""
binary = os . path . splitext ( os . path . basename ( binary ) ) [ 0 ] if binary != 'da' : msg = '"da" is the preffered way of running "{binary}".' . format ( binary = binary ) logger . logger . info ( '*' * len ( msg ) ) logger . logger . info ( msg ) logger . logger . info ( '*' * len ( msg ) )
def delete ( self ) : """delete pod from the Kubernetes cluster : return : None"""
body = client . V1DeleteOptions ( ) try : status = self . core_api . delete_namespaced_pod ( self . name , self . namespace , body ) logger . info ( "Deleting Pod %s in namespace %s" , self . name , self . namespace ) self . phase = PodPhase . TERMINATING except ApiException as e : raise ConuException (...
def plot_mean_field_conv ( N = 1 , n = 0.5 , Uspan = np . arange ( 0 , 3.6 , 0.5 ) ) : """Generates the plot on the convergenge of the mean field in single site spin hamiltonian under with N degenerate half - filled orbitals"""
sl = Spinon ( slaves = 2 * N , orbitals = N , avg_particles = 2 * n , hopping = [ 0.5 ] * 2 * N , orbital_e = [ 0 ] * 2 * N ) hlog = solve_loop ( sl , Uspan , [ 0. ] ) [ 1 ] f , ( ax1 , ax2 ) = plt . subplots ( 2 , sharex = True ) for field in hlog : field = np . asarray ( field ) ax1 . semilogy ( abs ( field [...
def getTypeDefinition ( cls , namespaceURI , name , lazy = False ) : '''Grab a type definition , returns a typecode class definition because the facets ( name , minOccurs , maxOccurs ) must be provided . Parameters : namespaceURI - - name - -'''
klass = cls . types . get ( ( namespaceURI , name ) , None ) if lazy and klass is not None : return _Mirage ( klass ) return klass
def save_favorite_query ( arg , ** _ ) : """Save a new favorite query . Returns ( title , rows , headers , status )"""
usage = 'Syntax: \\fs name query.\n\n' + favoritequeries . usage if not arg : return [ ( None , None , None , usage ) ] name , _ , query = arg . partition ( ' ' ) # If either name or query is missing then print the usage and complain . if ( not name ) or ( not query ) : return [ ( None , None , None , usage + '...
def get_account ( self , address , id = None , endpoint = None ) : """Look up an account on the blockchain . Sample output : Args : address : ( str ) address to lookup ( in format ' AXjaFSP23Jkbe6Pk9pPGT6NBDs1HVdqaXK ' ) id : ( int , optional ) id to use for response tracking endpoint : ( RPCEndpoint , opti...
return self . _call_endpoint ( GET_ACCOUNT_STATE , params = [ address ] , id = id , endpoint = endpoint )
def price ( usr , item , searches = 2 , method = "AVERAGE" , deduct = 0 ) : """Searches the shop wizard for given item and determines price with given method Searches the shop wizard x times ( x being number given in searches ) for the given item and collects the lowest price from each result . Uses the given ...
if not method in ShopWizard . methods : raise invalidMethod ( ) if isinstance ( item , Item ) : item = item . name prices = [ ] dets = { } for x in range ( 0 , searches ) : results = ShopWizard . search ( usr , item ) # Set to - 1 if not found if not results : prices . append ( - 1 ) ...
def from_uncharted_json_file ( cls , file ) : """Construct an AnalysisGraph object from a file containing INDRA statements serialized exported by Uncharted ' s CauseMos webapp ."""
with open ( file , "r" ) as f : _dict = json . load ( f ) return cls . from_uncharted_json_serialized_dict ( _dict )
def _clob_end_handler_factory ( ) : """Generates the handler for the end of a clob value . This includes anything from the data ' s closing quote through the second closing brace ."""
def action ( c , ctx , prev , res , is_first ) : if is_first and ctx . is_self_delimiting and c == _DOUBLE_QUOTE : assert c is prev return res _illegal_character ( c , ctx ) return _lob_end_handler_factory ( IonType . CLOB , action )
def setHeader ( self , fileHeader ) : """Sets the file header"""
self . technician = fileHeader [ "technician" ] self . recording_additional = fileHeader [ "recording_additional" ] self . patient_name = fileHeader [ "patientname" ] self . patient_additional = fileHeader [ "patient_additional" ] self . patient_code = fileHeader [ "patientcode" ] self . equipment = fileHeader [ "equip...
def get_dsl_by_hash ( self , node_hash : str ) -> Optional [ BaseEntity ] : """Look up a node by the hash and returns the corresponding PyBEL node tuple ."""
node = self . get_node_by_hash ( node_hash ) if node is not None : return node . as_bel ( )
def to_code ( self , stacksize = None ) : """Convert to code ."""
if stacksize is None : stacksize = self . compute_stacksize ( ) bc = self . to_bytecode ( ) return bc . to_code ( stacksize = stacksize )
def pypi_register ( server = 'pypitest' ) : """Register and prep user for PyPi upload . . . note : : May need to weak ~ / . pypirc file per issue : http : / / stackoverflow . com / questions / 1569315"""
base_command = 'python setup.py register' if server == 'pypitest' : command = base_command + ' -r https://testpypi.python.org/pypi' else : command = base_command _execute_setup_command ( command )
def restore ( self , url , tags = None ) : """Full restore of a container backup . This restore method will recreate an exact copy of the backedup container ( including same network setup , and other configurations as defined by the ` create ` method . To just restore the container data , and use new configur...
args = { 'url' : url , } return JSONResponse ( self . _client . raw ( 'corex.restore' , args , tags = tags ) )
def _quadratic_costs ( self , generators , ipol , nxyz , base_mva ) : """Returns the quadratic cost components of the objective function ."""
npol = len ( ipol ) rnpol = range ( npol ) gpol = [ g for g in generators if g . pcost_model == POLYNOMIAL ] if [ g for g in gpol if len ( g . p_cost ) > 3 ] : logger . error ( "Order of polynomial cost greater than quadratic." ) iqdr = [ i for i , g in enumerate ( generators ) if g . pcost_model == POLYNOMIAL and ...
def setFilename ( self , filename ) : """Set the filename of the pattern ' s image ( and load it )"""
# # Loop through image paths to find the image found = False for image_path in sys . path + [ Settings . BundlePath , os . getcwd ( ) ] + Settings . ImagePaths : full_path = os . path . join ( image_path , filename ) if os . path . exists ( full_path ) : # Image file not found found = True break...
def _raw_predict ( self , Xnew , full_cov = False , kern = None ) : """Make a prediction for the latent function values"""
if kern is None : kern = self . kern # compute mean predictions Kmn = kern . K ( Xnew , self . X ) alpha_kron = self . posterior . alpha mu = np . dot ( Kmn , alpha_kron ) mu = mu . reshape ( - 1 , 1 ) # compute variance of predictions Knm = Kmn . T noise = self . likelihood . variance V_kron = self . posterior . V...
def extract_call ( self , call , from_name , settings ) : '''Creates CallEdge from call file ( i . e . trigger - builds ) Returns a list of calls'''
call = defaultdict ( lambda : None , call [ 0 ] ) try : call [ 'section' ] = settings [ 'section' ] except KeyError : call [ 'section' ] = '' project = call [ 'project' ] # If there is more than one call in a single file if type ( project ) == list : calls = [ ] for name in project : calls . app...
def DecimalField ( default = NOTHING , required = True , repr = True , cmp = True , key = None ) : """Create new decimal field on a model . : param default : any decimal value : param bool required : whether or not the object is invalid if not provided . : param bool repr : include this field should appear in...
default = _init_fields . init_default ( required , default , None ) validator = _init_fields . init_validator ( required , Decimal ) return attrib ( default = default , converter = lambda x : Decimal ( x ) , validator = validator , repr = repr , cmp = cmp , metadata = dict ( key = key ) )
def validate ( self , data ) : """Check that the start is before the end ."""
if 'start' in data and 'end' in data and data [ 'start' ] >= data [ 'end' ] : raise serializers . ValidationError ( _ ( 'End must occur after start.' ) ) return data
def _parse_field ( self ) : """Parse a Field ."""
name = self . _next_token ( ) if self . _next_token ( ) == '=' : value = self . _parse_value ( ) return name , value
def local_path ( self , url , filename = None , decompress = False , download = False ) : """What will the full local path be if we download the given file ?"""
if download : return self . fetch ( url = url , filename = filename , decompress = decompress ) else : filename = self . local_filename ( url , filename , decompress ) return join ( self . cache_directory_path , filename )
def update_redirect ( self ) : """Update the parent redirect to the current last child . This method should be called on the parent PID node . Use this method when the status of a PID changed ( ex : draft changed from RESERVED to REGISTERED )"""
if self . last_child : self . _resolved_pid . redirect ( self . last_child ) elif any ( map ( lambda pid : pid . status not in [ PIDStatus . DELETED , PIDStatus . REGISTERED , PIDStatus . RESERVED ] , super ( PIDNodeVersioning , self ) . children . all ( ) ) ) : raise PIDRelationConsistencyError ( "Invalid rela...
def available_ports ( low = 1024 , high = 65535 , exclude_ranges = None ) : """Returns a set of possible ports ( excluding system , ephemeral and well - known ports ) . Pass ` ` high ` ` and / or ` ` low ` ` to limit the port range ."""
if exclude_ranges is None : exclude_ranges = [ ] available = utils . ranges_to_set ( UNASSIGNED_RANGES ) exclude = utils . ranges_to_set ( ephemeral . port_ranges ( ) + exclude_ranges + [ SYSTEM_PORT_RANGE , ( SYSTEM_PORT_RANGE [ 1 ] , low ) , ( high , 65536 ) ] ) return available . difference ( exclude )
def _twofilter_smoothing_ON ( self , t , ti , info , phi , lwinfo , return_ess , modif_forward , modif_info ) : """O ( N ) version of two - filter smoothing . This method should not be called directly , see twofilter _ smoothing ."""
if modif_info is not None : lwinfo += modif_info Winfo = rs . exp_and_normalise ( lwinfo ) I = rs . multinomial ( Winfo ) if modif_forward is not None : lw = self . wgt [ t ] . lw + modif_forward W = rs . exp_and_normalise ( lw ) else : W = self . wgt [ t ] . W J = rs . multinomial ( W ) log_omega = sel...
def _stack_bands ( one , other ) : # type : ( _ Raster , _ Raster ) - > _ Raster """Merges two rasters with non overlapping bands by stacking the bands ."""
assert set ( one . band_names ) . intersection ( set ( other . band_names ) ) == set ( ) # We raise an error in the bands are the same . See above . if one . band_names == other . band_names : raise ValueError ( "rasters have the same bands, use another merge strategy" ) # Apply " or " to the mask in the same way r...
def _frank_help ( alpha , tau ) : """Compute first order debye function to estimate theta ."""
def debye ( t ) : return t / ( np . exp ( t ) - 1 ) debye_value = integrate . quad ( debye , EPSILON , alpha ) [ 0 ] / alpha return 4 * ( debye_value - 1 ) / alpha + 1 - tau
def p_common_scalar_lnumber ( p ) : 'common _ scalar : LNUMBER'
if p [ 1 ] . startswith ( '0x' ) : p [ 0 ] = int ( p [ 1 ] , 16 ) elif p [ 1 ] . startswith ( '0' ) : p [ 0 ] = int ( p [ 1 ] , 8 ) else : p [ 0 ] = int ( p [ 1 ] )
def is_possible_type ( self , abstract_type : GraphQLAbstractType , possible_type : GraphQLObjectType ) -> bool : """Check whether a concrete type is possible for an abstract type ."""
possible_type_map = self . _possible_type_map try : possible_type_names = possible_type_map [ abstract_type . name ] except KeyError : possible_types = self . get_possible_types ( abstract_type ) possible_type_names = { type_ . name for type_ in possible_types } possible_type_map [ abstract_type . name ...
def get_formatted ( self , key ) : """Return formatted value for context [ key ] . If context [ key ] is a type string , will just format and return the string . If context [ key ] is a special literal type , like a py string or sic string , will run the formatting implemented by the custom tag represente...
val = self [ key ] if isinstance ( val , str ) : try : return self . get_processed_string ( val ) except KeyNotInContextError as err : # Wrapping the KeyError into a less cryptic error for end - user # friendliness raise KeyNotInContextError ( f'Unable to format \'{val}\' at context[\'{key}\...
def addFeatureToGraph ( self , add_region = True , region_id = None , feature_as_class = False ) : """We make the assumption here that all features are instances . The features are located on a region , which begins and ends with faldo : Position The feature locations leverage the Faldo model , which has a ...
if feature_as_class : self . model . addClassToGraph ( self . fid , self . label , self . ftype , self . description ) else : self . model . addIndividualToGraph ( self . fid , self . label , self . ftype , self . description ) if self . start is None and self . stop is None : add_region = False if add_regi...