signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def main ( arguments = None ) : """The main function used when ` ` directory _ script _ runner . py ` ` is run as a single script from the cl , or when installed as a cl command"""
# setup the command - line util settings su = tools ( arguments = arguments , docString = __doc__ , logLevel = "WARNING" , options_first = False , projectName = "fundmentals" ) arguments , settings , log , dbConn = su . setup ( ) # UNPACK REMAINING CL ARGUMENTS USING ` EXEC ` TO SETUP THE VARIABLE NAMES # AUTOMATICALLY...
def closest_point ( mesh , points ) : """Given a mesh and a list of points , find the closest point on any triangle . Parameters mesh : Trimesh object points : ( m , 3 ) float , points in space Returns closest : ( m , 3 ) float , closest point on triangles for each point distance : ( m , ) float , dista...
points = np . asanyarray ( points , dtype = np . float64 ) if not util . is_shape ( points , ( - 1 , 3 ) ) : raise ValueError ( 'points must be (n,3)!' ) # do a tree - based query for faces near each point candidates = nearby_faces ( mesh , points ) # view triangles as an ndarray so we don ' t have to recompute # t...
def wait ( self ) : '''This waits until the child exits . This is a blocking call . This will not read any data from the child , so this will block forever if the child has unread output and has terminated . In other words , the child may have printed output then called exit ( ) , but , the child is technic...
ptyproc = self . ptyproc with _wrap_ptyprocess_err ( ) : # exception may occur if " Is some other process attempting # " job control with our child pid ? " exitstatus = ptyproc . wait ( ) self . status = ptyproc . status self . exitstatus = ptyproc . exitstatus self . signalstatus = ptyproc . signalstatus self . te...
def compare_results ( save , best_hsp , tmp_results , tmp_gene_split ) : '''Function for comparing hits and saving only the best hit'''
# Get data for comparison hit_id = best_hsp [ 'hit_id' ] new_start_query = best_hsp [ 'query_start' ] new_end_query = best_hsp [ 'query_end' ] new_start_sbjct = int ( best_hsp [ 'sbjct_start' ] ) new_end_sbjct = int ( best_hsp [ 'sbjct_end' ] ) new_score = best_hsp [ 'cal_score' ] new_db_hit = best_hsp [ 'sbjct_header'...
def initiate ( self , callback = None ) : """Initiate an OAuth handshake with MediaWiki . : Parameters : callback : ` str ` Callback URL . Defaults to ' oob ' . : Returns : A ` tuple ` of two values : * a MediaWiki URL to direct the user to * a : class : ` ~ mwoauth . RequestToken ` representing an ac...
return initiate ( self . mw_uri , self . consumer_token , callback = callback or self . callback , user_agent = self . user_agent )
def query_framebuffer ( self , screen_id ) : """Queries the graphics updates targets for a screen . in screen _ id of type int return framebuffer of type : class : ` IFramebuffer `"""
if not isinstance ( screen_id , baseinteger ) : raise TypeError ( "screen_id can only be an instance of type baseinteger" ) framebuffer = self . _call ( "queryFramebuffer" , in_p = [ screen_id ] ) framebuffer = IFramebuffer ( framebuffer ) return framebuffer
def _AddPathSegments ( self , path , ignore_list ) : """Adds the path segments to the table . Args : path : a string containing the path . ignore _ list : a list of path segment indexes to ignore , where 0 is the index of the first path segment relative from the root ."""
path_segments = path . split ( self . _path_segment_separator ) for path_segment_index , path_segment in enumerate ( path_segments ) : if path_segment_index not in self . path_segments_per_index : self . path_segments_per_index [ path_segment_index ] = { } if path_segment_index not in ignore_list : ...
def get_loss ( config : LossConfig ) -> 'Loss' : """Returns a Loss instance . : param config : Loss configuration . : return : Instance implementing the Loss ."""
if config . name == C . CROSS_ENTROPY : return CrossEntropyLoss ( config , output_names = [ C . SOFTMAX_OUTPUT_NAME ] , label_names = [ C . TARGET_LABEL_NAME ] ) else : raise ValueError ( "unknown loss name: %s" % config . name )
def read_folder ( folder , ext = '*' , uppercase = False , replace_dot = '.' , parent = '' ) : """This will read all of the files in the folder with the extension equal to ext : param folder : str of the folder name : param ext : str of the extension : param uppercase : bool if True will uppercase all the f...
ret = { } if os . path . exists ( folder ) : for file in os . listdir ( folder ) : if os . path . isdir ( os . path . join ( folder , file ) ) : child = read_folder ( os . path . join ( folder , file ) , ext , uppercase , replace_dot , parent = parent + file + '/' ) ret . update ( ch...
def ParseFromString ( self , text , message ) : """Parses a text representation of a protocol message into a message ."""
if not isinstance ( text , str ) : text = text . decode ( 'utf-8' ) return self . ParseLines ( text . split ( '\n' ) , message )
def setcover_ilp ( candidate_sets_dict , items = None , set_weights = None , item_values = None , max_weight = None , verbose = False ) : """Set cover / Weighted Maximum Cover exact algorithm https : / / en . wikipedia . org / wiki / Maximum _ coverage _ problem"""
import utool as ut import pulp if items is None : items = ut . flatten ( candidate_sets_dict . values ( ) ) if set_weights is None : set_weights = { i : 1 for i in candidate_sets_dict . keys ( ) } if item_values is None : item_values = { e : 1 for e in items } if max_weight is None : max_weight = sum ( ...
def orbit ( component , ** kwargs ) : """Create parameters for a new orbit . Generally , this will be used as an input to the kind argument in : meth : ` phoebe . frontend . bundle . Bundle . add _ component ` : parameter * * kwargs : defaults for the values of any of the parameters : return : a : class : `...
params = [ ] # ~ params + = [ ObjrefParameter ( value = component ) ] params += [ FloatParameter ( qualifier = 'period' , timederiv = 'dpdt' , value = kwargs . get ( 'period' , 1.0 ) , default_unit = u . d , limits = ( 0.0 , None ) , description = 'Orbital period' ) ] params += [ FloatParameter ( qualifier = 'freq' , v...
def isotopic_variants ( composition , npeaks = None , charge = 0 , charge_carrier = PROTON ) : '''Compute a peak list representing the theoretical isotopic cluster for ` composition ` . Parameters composition : Mapping Any Mapping type where keys are element symbols and values are integers npeaks : int Th...
if npeaks is None : max_n_variants = max_variants ( composition ) npeaks = int ( sqrt ( max_n_variants ) - 2 ) npeaks = max ( npeaks , 3 ) else : # Monoisotopic Peak is not included npeaks -= 1 return IsotopicDistribution ( composition , npeaks ) . aggregated_isotopic_variants ( charge , charge_carrier ...
def append_note ( self , note , root , scale = 0 ) : """Append a note to quality : param str note : note to append on quality : param str root : root note of chord : param int scale : key scale"""
root_val = note_to_val ( root ) note_val = note_to_val ( note ) - root_val + scale * 12 if note_val not in self . components : self . components . append ( note_val ) self . components . sort ( )
def get_disabled ( ) : '''Return a set of services that are installed but disabled CLI Example : . . code - block : : bash salt ' * ' service . get _ disabled'''
( enabled_services , disabled_services ) = _get_service_list ( include_enabled = False , include_disabled = True ) return sorted ( disabled_services )
def conflicts_with ( self , section ) : "Returns True if the given section conflicts with this time range ."
for p in section . periods : t = ( p . int_days , p . start , p . end ) if t in self : return True return False
def p_field_id ( self , p ) : '''field _ id : INTCONSTANT ' : ' '''
if len ( p ) == 3 : if p [ 1 ] == 0 : # Prevent users from ever using field ID 0 . It ' s reserved for # internal use only . raise ThriftParserError ( 'Line %d: Field ID 0 is reserved for internal use.' % p . lineno ( 1 ) ) p [ 0 ] = p [ 1 ] else : p [ 0 ] = None
def parsed_to_ast ( parsed : Parsed , errors : Errors , component_type : str = "" ) : """Convert parsed data struct to AST dictionary Args : parsed : errors : component _ type : Empty string or ' subject ' or ' object ' to indicate that we are parsing the subject or object field input"""
ast = { } sorted_keys = sorted ( parsed . keys ( ) ) # Setup top - level tree for key in sorted_keys : if parsed [ key ] [ "type" ] == "Nested" : nested_component_stack = [ "subject" , "object" ] if component_type : component_stack = [ component_type ] else : component_stack = [ "subject" , "object"...
def _check_copy_conditions ( self , src , dst ) : # type : ( SyncCopy , blobxfer . models . azure . StorageEntity , # blobxfer . models . azure . StorageEntity ) - > UploadAction """Check for synccopy conditions : param SyncCopy self : this : param blobxfer . models . azure . StorageEntity src : src : param b...
# if remote file doesn ' t exist , copy if dst is None or dst . from_local : return SynccopyAction . Copy # check overwrite option if not self . _spec . options . overwrite : logger . info ( 'not overwriting remote file: {})' . format ( dst . path ) ) return SynccopyAction . Skip # check skip on options , M...
def FunctionalGroupColorMapping ( maptype = 'jet' , reverse = False ) : """Maps amino - acid functional groups to colors . Currently does not use the keyword arguments for * maptype * or * reverse * but accepts these arguments to be consistent with the other mapping functions , which all get called with the...
small_color = '#f76ab4' nucleophilic_color = '#ff7f00' hydrophobic_color = '#12ab0d' aromatic_color = '#84380b' acidic_color = '#e41a1c' amide_color = '#972aa8' basic_color = '#3c58e5' mapping_d = { 'G' : small_color , 'A' : small_color , 'S' : nucleophilic_color , 'T' : nucleophilic_color , 'C' : nucleophilic_color , ...
def _load_config ( self ) : "Load and parse config file , pass options to livestreamer"
config = SafeConfigParser ( ) config_file = os . path . join ( self . config_path , 'settings.ini' ) config . read ( config_file ) for option , type in list ( AVAILABLE_OPTIONS . items ( ) ) : if config . has_option ( 'DEFAULT' , option ) : if type == 'int' : value = config . getint ( 'DEFAULT' ...
def ping ( cls , host = None , count = 1 ) : """execute ping : param host : the host to ping : param count : the number of pings : return :"""
option = '-n' if platform . system ( ) . lower ( ) == 'windows' else '-c' return cls . execute ( 'ping' , "{option} {count} {host}" . format ( option = option , count = count , host = host ) )
def create_or_update_tags ( self , tags ) : """Creates new tags or updates existing tags for an Auto Scaling group . : type tags : List of : class : ` boto . ec2 . autoscale . tag . Tag ` : param tags : The new or updated tags ."""
params = { } for i , tag in enumerate ( tags ) : tag . build_params ( params , i + 1 ) return self . get_status ( 'CreateOrUpdateTags' , params , verb = 'POST' )
def del_cached_domain ( domains ) : '''Delete cached domains from the master CLI Example : . . code - block : : bash salt - run venafi . del _ cached _ domain domain1 . example . com , domain2 . example . com'''
cache = salt . cache . Cache ( __opts__ , syspaths . CACHE_DIR ) if isinstance ( domains , six . string_types ) : domains = domains . split ( ',' ) if not isinstance ( domains , list ) : raise CommandExecutionError ( 'You must pass in either a string containing one or more domains ' 'separated by commas, or a l...
def main ( as_module = False ) : """This is copy / paste of flask . cli . main to instanciate our own group"""
this_module = __package__ args = sys . argv [ 1 : ] if as_module : if sys . version_info >= ( 2 , 7 ) : name = 'python -m ' + this_module . rsplit ( '.' , 1 ) [ 0 ] else : name = 'python -m ' + this_module # This module is always executed as " python - m flask . run " and as such # we ne...
def show_toast ( self , msg , long = True ) : """Show a toast message for the given duration . This is an android specific api . Parameters msg : str Text to display in the toast message long : bool Display for a long or short ( system defined ) duration"""
from . android_toast import Toast def on_toast ( ref ) : t = Toast ( __id__ = ref ) t . show ( ) Toast . makeText ( self , msg , 1 if long else 0 ) . then ( on_toast )
def _get_best_subset ( self , ritz ) : '''Return candidate set with smallest goal functional .'''
# ( c , \ omega ( c ) ) for all considered subsets c overall_evaluations = { } def evaluate ( _subset , _evaluations ) : try : _evaluations [ _subset ] = self . subset_evaluator . evaluate ( ritz , _subset ) except utils . AssumptionError : # no evaluation possible - > move on pass # I in algo c...
def calculate_size ( name , entry_processor ) : """Calculates the request payload size"""
data_size = 0 data_size += calculate_size_str ( name ) data_size += calculate_size_data ( entry_processor ) return data_size
def render ( self , data , accepted_media_type = None , renderer_context = None ) : """Renders data to HTML , using Django ' s standard template rendering . The template name is determined by ( in order of preference ) : 1 . An explicit . template _ name set on the response . 2 . An explicit . template _ name...
renderer_context = renderer_context or { } view = renderer_context [ 'view' ] request = renderer_context [ 'request' ] response = renderer_context [ 'response' ] if response . exception : template = self . get_exception_template ( response ) else : template_names = self . get_template_names ( response , view ) ...
def add_alignment ( self , ref_seq , annotation ) -> Annotation : """add _ alignment - method for adding the alignment to an annotation : param ref _ seq : List of reference sequences : type ref _ seq : List : param annotation : The complete annotation : type annotation : Annotation : rtype : Annotation""...
seq_features = get_seqs ( ref_seq ) annoated_align = { } allele = ref_seq . description . split ( "," ) [ 0 ] locus = allele . split ( "*" ) [ 0 ] . split ( "-" ) [ 1 ] for feat in seq_features : if feat in annotation . annotation : if isinstance ( annotation . annotation [ feat ] , DBSeq ) : se...
def serialize_verifying_key ( vk ) : """Serialize a public key into SSH format ( for exporting to text format ) . Currently , NIST256P1 and ED25519 elliptic curves are supported . Raise TypeError on unsupported key format ."""
if isinstance ( vk , ed25519 . keys . VerifyingKey ) : pubkey = vk . to_bytes ( ) key_type = SSH_ED25519_KEY_TYPE blob = util . frame ( SSH_ED25519_KEY_TYPE ) + util . frame ( pubkey ) return key_type , blob if isinstance ( vk , ecdsa . keys . VerifyingKey ) : curve_name = SSH_NIST256_CURVE_NAME ...
def sign ( conf ) : """Sign in and get money ."""
try : v2ex = V2ex ( conf . config ) v2ex . login ( ) balance = v2ex . get_money ( ) click . echo ( balance ) except KeyError : click . echo ( 'Keyerror, please check your config file.' ) except IndexError : click . echo ( 'Please check your username and password.' )
def get_networks ( self , contents ) : """Process config contents with cdrouter - cli - print - networks - json . : param contents : Config contents as string . : return : : class : ` configs . Networks < configs . Networks > ` object : rtype : configs . Networks"""
schema = NetworksSchema ( ) resp = self . service . post ( self . base , params = { 'process' : 'networks' } , json = { 'contents' : contents } ) return self . service . decode ( schema , resp )
def leaky_relu ( x , name = None ) : """Creates a leaky _ relu . This is an alternate non - linearity to relu . The leaky part of the relu may prevent dead Neurons in a model since the gradient doesn ' t go completely to Args : x : The input tensor . name : Optional name for this op . Returns : x if x...
with tf . name_scope ( name , 'leaky_relu' , [ x ] ) as scope : x = tf . convert_to_tensor ( x , name = 'x' ) return tf . where ( tf . less ( x , 0.0 ) , 0.01 * x , x , name = scope )
def last_post ( self ) : """Returns the latest post associated with the node or one of its descendants ."""
posts = [ n . last_post for n in self . children if n . last_post is not None ] children_last_post = max ( posts , key = lambda p : p . created ) if posts else None if children_last_post and self . obj . last_post_id : return max ( self . obj . last_post , children_last_post , key = lambda p : p . created ) return ...
def send_stderr ( self , s ) : """Send data to the channel on the " stderr " stream . This is normally only used by servers to send output from shell commands - - clients won ' t use this . Returns the number of bytes sent , or 0 if the channel stream is closed . Applications are responsible for checking that...
size = len ( s ) self . lock . acquire ( ) try : size = self . _wait_for_send_window ( size ) if size == 0 : # eof or similar return 0 m = Message ( ) m . add_byte ( cMSG_CHANNEL_EXTENDED_DATA ) m . add_int ( self . remote_chanid ) m . add_int ( 1 ) m . add_string ( s [ : size ] ) fi...
def create_domain ( self , name , body ) : """创建域名 , 文档 https : / / developer . qiniu . com / fusion / api / 4246 / the - domain - name Args : name : 域名 , 如果是泛域名 , 必须以点号 . 开头 bosy : 创建域名参数 Returns :"""
url = '{0}/domain/{1}' . format ( self . server , name ) return self . __post ( url , body )
def get_first_comments_or_remarks ( recID = - 1 , ln = CFG_SITE_LANG , nb_comments = 'all' , nb_reviews = 'all' , voted = - 1 , reported = - 1 , user_info = None , show_reviews = False ) : """Gets nb number comments / reviews or remarks . In the case of comments , will get both comments and reviews Comments and...
_ = gettext_set_language ( ln ) warnings = [ ] voted = wash_url_argument ( voted , 'int' ) reported = wash_url_argument ( reported , 'int' ) # check recID argument if not isinstance ( recID , int ) : return ( ) # comment or review . NB : suppressed reference to basket ( handled in # webbasket ) if recID >= 1 : ...
def _coord2int ( lng , lat , dim ) : """Convert lon , lat values into a dim x dim - grid coordinate system . Parameters : lng : float Longitude value of coordinate ( - 180.0 , 180.0 ) ; corresponds to X axis lat : float Latitude value of coordinate ( - 90.0 , 90.0 ) ; corresponds to Y axis dim : int Number ...
assert dim >= 1 lat_y = ( lat + _LAT_INTERVAL [ 1 ] ) / 180.0 * dim # [0 . . . dim ) lng_x = ( lng + _LNG_INTERVAL [ 1 ] ) / 360.0 * dim # [0 . . . dim ) return min ( dim - 1 , int ( floor ( lng_x ) ) ) , min ( dim - 1 , int ( floor ( lat_y ) ) )
def dependent_phone_numbers ( self ) : """Access the dependent _ phone _ numbers : returns : twilio . rest . api . v2010 . account . address . dependent _ phone _ number . DependentPhoneNumberList : rtype : twilio . rest . api . v2010 . account . address . dependent _ phone _ number . DependentPhoneNumberList""...
if self . _dependent_phone_numbers is None : self . _dependent_phone_numbers = DependentPhoneNumberList ( self . _version , account_sid = self . _solution [ 'account_sid' ] , address_sid = self . _solution [ 'sid' ] , ) return self . _dependent_phone_numbers
def send_text_message ( self , recipient_id , message , notification_type = NotificationType . regular ) : """Send text messages to the specified recipient . https : / / developers . facebook . com / docs / messenger - platform / send - api - reference / text - message Input : recipient _ id : recipient id to...
return self . send_message ( recipient_id , { 'text' : message } , notification_type )
def get_string ( self ) : """Get a string representation of this single base error . : returns : report : rtype : string"""
ostr = '' ostr += 'BaseError for [' + self . _type + '] base: ' + self . get_base ( ) + "\n" if self . _observable . get_error_probability ( ) > 0 : ostr += ' Homopolymer set:' + "\n" ostr += ' ' + str ( self . get_homopolymer ( ) ) + "\n" ostr += ' Observable:' + "\n" ostr += ' type is: ' + str...
def create_table_sql ( cls , db ) : '''Returns the SQL command for creating a table for this model .'''
parts = [ 'CREATE TABLE IF NOT EXISTS `%s`.`%s` AS `%s`.`%s`' % ( db . db_name , cls . table_name ( ) , db . db_name , cls . engine . main_model . table_name ( ) ) ] engine_str = cls . engine . create_table_sql ( db ) parts . append ( engine_str ) return ' ' . join ( parts )
def _set_extend ( self , v , load = False ) : """Setter method for extend , mapped from YANG variable / overlay _ gateway / site / extend ( container ) If this variable is read - only ( config : false ) in the source YANG file , then _ set _ extend is considered as a private method . Backends looking to popul...
if hasattr ( v , "_utype" ) : v = v . _utype ( v ) try : t = YANGDynClass ( v , base = extend . extend , is_container = 'container' , presence = False , yang_name = "extend" , rest_name = "extend" , parent = self , path_helper = self . _path_helper , extmethods = self . _extmethods , register_paths = True , ext...
def _resolve_dependencies ( self , cur , dependencies ) : """Function checks if dependant packages are installed in DB"""
list_of_deps_ids = [ ] _list_of_deps_unresolved = [ ] _is_deps_resolved = True for k , v in dependencies . items ( ) : pgpm . lib . utils . db . SqlScriptsHelper . set_search_path ( cur , self . _pgpm_schema_name ) cur . execute ( "SELECT _find_schema('{0}', '{1}')" . format ( k , v ) ) pgpm_v_ext = tuple (...
def _unstack_extension_series ( series , level , fill_value ) : """Unstack an ExtensionArray - backed Series . The ExtensionDtype is preserved . Parameters series : Series A Series with an ExtensionArray for values level : Any The level name or number . fill _ value : Any The user - level ( not phys...
# Implementation note : the basic idea is to # 1 . Do a regular unstack on a dummy array of integers # 2 . Followup with a columnwise take . # We use the dummy take to discover newly - created missing values # introduced by the reshape . from pandas . core . reshape . concat import concat dummy_arr = np . arange ( len ...
def getReadGroupSetByName ( self , name ) : """Returns a ReadGroupSet with the specified name , or raises a ReadGroupSetNameNotFoundException if it does not exist ."""
if name not in self . _readGroupSetNameMap : raise exceptions . ReadGroupSetNameNotFoundException ( name ) return self . _readGroupSetNameMap [ name ]
def from_project_root ( cls , project_root , cli_vars ) : """Create a project from a root directory . Reads in dbt _ project . yml and packages . yml , if it exists . : param project _ root str : The path to the project root to load . : raises DbtProjectError : If the project is missing or invalid , or if t...
project_root = os . path . normpath ( project_root ) project_yaml_filepath = os . path . join ( project_root , 'dbt_project.yml' ) # get the project . yml contents if not path_exists ( project_yaml_filepath ) : raise DbtProjectError ( 'no dbt_project.yml found at expected path {}' . format ( project_yaml_filepath )...
def save_performance ( db , job_id , records ) : """Save in the database the performance information about the given job . : param db : a : class : ` openquake . server . dbapi . Db ` instance : param job _ id : a job ID : param records : a list of performance records"""
# NB : rec [ ' counts ' ] is a numpy . uint64 which is not automatically converted # into an int in Ubuntu 12.04 , so we convert it manually below rows = [ ( job_id , rec [ 'operation' ] , rec [ 'time_sec' ] , rec [ 'memory_mb' ] , int ( rec [ 'counts' ] ) ) for rec in records ] db . insert ( 'performance' , 'job_id op...
def reset ( self ) : """Reset all counters for this simulation . Args : None Returns : None"""
self . lattice . reset ( ) for atom in self . atoms . atoms : atom . reset ( )
def vol_prefactor ( n , p = 2. ) : """Returns the volume constant for an ` n ` - dimensional sphere with an : math : ` L ^ p ` norm . The constant is defined as : : f = ( 2 . * Gamma ( 1 . / p + 1 ) ) * * n / Gamma ( n / p + 1 . ) By default the ` p = 2 . ` norm is used ( i . e . the standard Euclidean norm )...
p *= 1. # convert to float in case user inputs an integer f = ( 2 * special . gamma ( 1. / p + 1. ) ) ** n / special . gamma ( n / p + 1 ) return f
def set_raw_tag_data ( filename , data , act = True , verbose = False ) : "Replace the ID3 tag in FILENAME with DATA ."
check_tag_data ( data ) with open ( filename , "rb+" ) as file : try : ( cls , offset , length ) = stagger . tags . detect_tag ( file ) except stagger . NoTagError : ( offset , length ) = ( 0 , 0 ) if length > 0 : verb ( verbose , "{0}: replaced tag with {1} bytes of data" . format (...
def create_commit ( self , message , tree , parents , author = { } , committer = { } ) : """Create a commit on this repository . : param str message : ( required ) , commit message : param str tree : ( required ) , SHA of the tree object this commit points to : param list parents : ( required ) , SHAs of th...
json = None if message and tree and isinstance ( parents , list ) : url = self . _build_url ( 'git' , 'commits' , base_url = self . _api ) data = { 'message' : message , 'tree' : tree , 'parents' : parents , 'author' : author , 'committer' : committer } json = self . _json ( self . _post ( url , data = data...
def process_row ( self , row ) : """Processes a row of AP election data to determine what model objects need to be created ."""
division = self . get_division ( row ) if not division : return None race = self . get_race ( row , division ) election = self . get_election ( row , race ) if not election : return None party = self . get_or_create_party ( row ) candidate = self . get_or_create_candidate ( row , party , race ) candidate_electi...
def get_station_by_name ( self , station_name , num_minutes = None , direction = None , destination = None , stops_at = None ) : """Returns all trains due to serve station ` station _ name ` . @ param station _ code @ param num _ minutes . Only trains within this time . Between 5 and 90 @ param direction Filt...
url = self . api_base_url + 'getStationDataByNameXML' params = { 'StationDesc' : station_name } if num_minutes : url = url + '_withNumMins' params [ 'NumMins' ] = num_minutes response = requests . get ( url , params = params , timeout = 10 ) if response . status_code != 200 : return [ ] trains = self . _par...
def __replace_capall ( sentence ) : """here we replace all instances of # CAPALL and cap the entire sentence . Don ' t believe that CAPALL is buggy anymore as it forces all uppercase OK ? : param _ sentence :"""
# print " \ nReplacing CAPITALISE : " if sentence is not None : while sentence . find ( '#CAPALL' ) != - 1 : # _ cap _ index = _ sentence . find ( ' # CAPALL ' ) sentence = sentence . upper ( ) sentence = sentence . replace ( '#CAPALL ' , '' , 1 ) if sentence . find ( '#CAPALL' ) == - 1 : ...
def dispatch ( self , * args , ** kwargs ) : """This decorator sets this view to have restricted permissions ."""
return super ( AnimalDelete , self ) . dispatch ( * args , ** kwargs )
def _set_show_ntp ( self , v , load = False ) : """Setter method for show _ ntp , mapped from YANG variable / brocade _ ntp _ rpc / show _ ntp ( rpc ) If this variable is read - only ( config : false ) in the source YANG file , then _ set _ show _ ntp is considered as a private method . Backends looking to po...
if hasattr ( v , "_utype" ) : v = v . _utype ( v ) try : t = YANGDynClass ( v , base = show_ntp . show_ntp , is_leaf = True , yang_name = "show-ntp" , rest_name = "show-ntp" , parent = self , path_helper = self . _path_helper , extmethods = self . _extmethods , register_paths = False , extensions = { u'tailf-co...
def _make_safe_id ( self , id ) : """Returns a modified id that has been made safe for SBML . Replaces or deletes the ones that aren ' t allowed ."""
substitutions = { '-' : '_DASH_' , '/' : '_FSLASH_' , '\\' : '_BSLASH_' , '(' : '_LPAREN_' , ')' : '_RPAREN_' , '[' : '_LSQBKT_' , ']' : '_RSQBKT_' , ',' : '_COMMA_' , '.' : '_PERIOD_' , "'" : '_APOS_' } id = re . sub ( r'\(([a-z])\)$' , '_\\1' , id ) for symbol , escape in iteritems ( substitutions ) : id = id . r...
def _should_fetch_reason ( self ) -> Tuple [ bool , str ] : '''Return info about whether the URL should be fetched . Returns : tuple : A two item tuple : 1 . bool : If True , the URL should be fetched . 2 . str : A short reason string explaining the verdict .'''
is_redirect = False if self . _strong_redirects : try : is_redirect = self . _web_client_session . redirect_tracker . is_redirect ( ) except AttributeError : pass return self . _fetch_rule . check_subsequent_web_request ( self . _item_session , is_redirect = is_redirect )
def get_repo_relpath ( repo , relpath ) : """Returns the absolute path to the ' relpath ' taken relative to the base directory of the repository ."""
from os import path if relpath [ 0 : 2 ] == "./" : return path . join ( repo , relpath [ 2 : : ] ) else : from os import chdir , getcwd cd = getcwd ( ) chdir ( path . expanduser ( repo ) ) result = path . abspath ( relpath ) chdir ( cd ) return result
def get_by_type ( self , key , conversion_func , default = None ) : u"""Возвращает значение , приведенное к типу с использованием переданной функции : param key : Имя параметра : param conversion _ func : callable объект , принимающий и возвращающий значение : param default : Значение по умолчанию : ...
if not self . has_param ( key ) : return default value = self . get ( key , default = default ) try : value = conversion_func ( value ) except Exception as exc : raise ConversionTypeError ( ( u'Произошла ошибка при попытке преобразования типа: {}' ) . format ( exc ) ) return value
def install_salt_support ( from_ppa = True ) : """Installs the salt - minion helper for machine state . By default the salt - minion package is installed from the saltstack PPA . If from _ ppa is False you must ensure that the salt - minion package is available in the apt cache ."""
if from_ppa : subprocess . check_call ( [ '/usr/bin/add-apt-repository' , '--yes' , 'ppa:saltstack/salt' , ] ) subprocess . check_call ( [ '/usr/bin/apt-get' , 'update' ] ) # We install salt - common as salt - minion would run the salt - minion # daemon . charmhelpers . fetch . apt_install ( 'salt-common' )
def _set_stp ( self , v , load = False ) : """Setter method for stp , mapped from YANG variable / protocol / spanning _ tree / stp ( container ) If this variable is read - only ( config : false ) in the source YANG file , then _ set _ stp is considered as a private method . Backends looking to populate this v...
if hasattr ( v , "_utype" ) : v = v . _utype ( v ) try : t = YANGDynClass ( v , base = stp . stp , is_container = 'container' , presence = True , yang_name = "stp" , rest_name = "stp" , parent = self , path_helper = self . _path_helper , extmethods = self . _extmethods , register_paths = True , extensions = { u...
def create ( cls , name , project , app , revision = None , batch_input = None , batch_by = None , inputs = None , description = None , run = False , disable_batch = False , interruptible = None , execution_settings = None , api = None ) : """Creates a task on server . : param name : Task name . : param project...
task_data = { } params = { } project = Transform . to_project ( project ) app_id = Transform . to_app ( app ) if revision : app_id = app_id + "/" + six . text_type ( revision ) else : if isinstance ( app , App ) : app_id = app_id + "/" + six . text_type ( app . revision ) task_inputs = { 'inputs' : Task...
def protected_view ( view , info ) : """allows adding ` protected = True ` to a view _ config `"""
if info . options . get ( 'protected' ) : def wrapper_view ( context , request ) : response = _advice ( request ) if response is not None : return response else : return view ( context , request ) return wrapper_view return view
def _last_of_quarter ( self , day_of_week = None ) : """Modify to the last occurrence of a given day of the week in the current quarter . If no day _ of _ week is provided , modify to the last day of the quarter . Use the supplied consts to indicate the desired day _ of _ week , ex . DateTime . MONDAY . : t...
return self . on ( self . year , self . quarter * 3 , 1 ) . last_of ( "month" , day_of_week )
def micro_indices ( self ) : """Indices of micro elements represented in this coarse - graining ."""
return tuple ( sorted ( idx for part in self . partition for idx in part ) )
def delete_entity ( self , table_name , partition_key , row_key , if_match = '*' , timeout = None ) : '''Deletes an existing entity in a table . Throws if the entity does not exist . When an entity is successfully deleted , the entity is immediately marked for deletion and is no longer accessible to clients . T...
_validate_not_none ( 'table_name' , table_name ) request = _delete_entity ( partition_key , row_key , if_match ) request . host = self . _get_host ( ) request . query += [ ( 'timeout' , _int_to_str ( timeout ) ) ] request . path = _get_entity_path ( table_name , partition_key , row_key ) self . _perform_request ( reque...
def write_version ( name = None , path = None ) : """Write the version info to . . / version . json , for setup . py . Args : name ( Optional [ str ] ) : this is for the ` ` write _ version ( name = _ _ name _ _ ) ` ` below . That ' s one way to both follow the ` ` if _ _ name _ _ = = ' _ _ main _ _ ' : ` `...
# Written like this for coverage purposes . # http : / / stackoverflow . com / questions / 5850268 / how - to - test - or - mock - if - name - main - contents / 27084447#27084447 if name in ( None , '__main__' ) : path = path or os . path . join ( os . path . dirname ( os . path . dirname ( os . path . abspath ( __...
def pystdlib ( ) : """Return a set of all module - names in the Python standard library ."""
curver = '.' . join ( str ( x ) for x in sys . version_info [ : 2 ] ) return ( set ( stdlib_list . stdlib_list ( curver ) ) | { '_LWPCookieJar' , '_MozillaCookieJar' , '_abcoll' , 'email._parseaddr' , 'email.base64mime' , 'email.feedparser' , 'email.quoprimime' , 'encodings' , 'genericpath' , 'ntpath' , 'nturl2path' , ...
def register_extension_class ( ext , base , * args , ** kwargs ) : """Instantiate the given extension class and register as a public attribute of the given base . README : The expected protocol here is to instantiate the given extension and pass the base object as the first positional argument , then unpack arg...
ext_instance = ext . plugin ( base , * args , ** kwargs ) setattr ( base , ext . name . lstrip ( '_' ) , ext_instance )
def float_format ( self , value ) : """Validate and set the upper case flag ."""
if isinstance ( value , str ) : # Duck - test the format string ; raise ValueError on fail '{0:{1}}' . format ( 1.23 , value ) self . _float_format = value else : raise TypeError ( 'Floating point format code must be a string.' )
def _graph_add_edge ( self , src_block_id , dst_block_id , ** kwargs ) : """Add an edge onto the graph . : param BlockID src _ block _ id : The block ID for source node . : param BlockID dst _ block _ id : The block Id for destination node . : param str jumpkind : The jumpkind of the edge . : param exit _ s...
dst_node = self . _graph_get_node ( dst_block_id , terminator_for_nonexistent_node = True ) if src_block_id is None : self . graph . add_node ( dst_node ) else : src_node = self . _graph_get_node ( src_block_id , terminator_for_nonexistent_node = True ) self . graph . add_edge ( src_node , dst_node , ** kwa...
def _FormatHostname ( self , event ) : """Formats the hostname . Args : event ( EventObject ) : event . Returns : str : formatted hostname field ."""
hostname = self . _output_mediator . GetHostname ( event ) return self . _SanitizeField ( hostname )
def to_dict ( self ) : """Returns the underlying data as a Python dict ."""
return { "state_size" : self . state_size , "chain" : self . chain . to_json ( ) , "parsed_sentences" : self . parsed_sentences if self . retain_original else None }
def beep ( self ) : """Make dimmer beep . Not all devices support this"""
self . logger . info ( "Dimmer %s beep" , self . device_id ) self . hub . direct_command ( self . device_id , '30' , '00' ) success = self . hub . check_success ( self . device_id , '30' , '00' ) return success
def create_floatingip ( self , context , floatingip ) : """Create floating IP . : param context : Neutron request context : param floatingip : data for the floating IP being created : returns : A floating IP object on success As the l3 router plugin asynchronously creates floating IPs leveraging the l3 ag...
return super ( CiscoRouterPlugin , self ) . create_floatingip ( context , floatingip , initial_status = bc . constants . FLOATINGIP_STATUS_DOWN )
def push ( self , index = None ) : """Push built documents to ElasticSearch . If ` ` index ` ` is specified , only that index will be pushed ."""
for ind in self . indexes : if index and not isinstance ( ind , index ) : continue ind . push ( )
def get_model ( self ) : """Get a model if the formula was previously satisfied ."""
if self . maplesat and self . status == True : model = pysolvers . maplesat_model ( self . maplesat ) return model if model != None else [ ]
def start ( self ) : """Creates and starts the Local Lambda Invoke service . This method will block until the service is stopped manually using an interrupt . After the service is started , callers can make HTTP requests to the endpoint to invoke the Lambda function and receive a response . NOTE : This is a b...
# We care about passing only stderr to the Service and not stdout because stdout from Docker container # contains the response to the API which is sent out as HTTP response . Only stderr needs to be printed # to the console or a log file . stderr from Docker container contains runtime logs and output of print # stateme...
def Versions ( ) : """Returns a string with version information . You would call this function if you want a string giving detailed information on the version of ` ` phydms ` ` and the associated packages that it uses ."""
s = [ 'Version information:' , '\tTime and date: %s' % time . asctime ( ) , '\tPlatform: %s' % platform . platform ( ) , '\tPython version: %s' % sys . version . replace ( '\n' , ' ' ) , '\tphydms version: %s' % phydmslib . __version__ , ] for modname in [ 'Bio' , 'cython' , 'numpy' , 'scipy' , 'matplotlib' , 'natsort'...
def apply_boundary_conditions ( self , ** kwargs ) : """Applies any boundary conditions to the given values ( e . g . , applying cyclic conditions , and / or reflecting values off of boundaries ) . This is done by running ` apply _ conditions ` of each bounds in self on the corresponding value . See ` boundar...
return dict ( [ [ p , self . _bounds [ p ] . apply_conditions ( val ) ] for p , val in kwargs . items ( ) if p in self . _bounds ] )
def convert_examples_to_features ( examples , tokenizer , max_seq_length , doc_stride , max_query_length , is_training ) : """Loads a data file into a list of ` InputBatch ` s ."""
unique_id = 1000000000 features = [ ] for ( example_index , example ) in enumerate ( examples ) : query_tokens = tokenizer . tokenize ( example . question_text ) if len ( query_tokens ) > max_query_length : query_tokens = query_tokens [ 0 : max_query_length ] tok_to_orig_index = [ ] orig_to_tok_...
def from_text ( text ) : """Convert the text format message into a message object . @ param text : The text format message . @ type text : string @ raises UnknownHeaderField : @ raises dns . exception . SyntaxError : @ rtype : dns . message . Message object"""
# ' text ' can also be a file , but we don ' t publish that fact # since it ' s an implementation detail . The official file # interface is from _ file ( ) . m = Message ( ) reader = _TextReader ( text , m ) reader . read ( ) return m
def context_list_users ( zap_helper , context_name ) : """List the users available for a given context ."""
with zap_error_handler ( ) : info = zap_helper . get_context_info ( context_name ) users = zap_helper . zap . users . users_list ( info [ 'id' ] ) if len ( users ) : user_list = ', ' . join ( [ user [ 'name' ] for user in users ] ) console . info ( 'Available users for the context {0}: {1}' . format ( conte...
def add_ssa_ir ( function , all_state_variables_instances ) : '''Add SSA version of the IR Args : function all _ state _ variables _ instances'''
if not function . is_implemented : return init_definition = dict ( ) for v in function . parameters : if v . name : init_definition [ v . name ] = ( v , function . entry_point ) function . entry_point . add_ssa_ir ( Phi ( LocalIRVariable ( v ) , set ( ) ) ) for v in function . returns : if v...
def _get_balances ( self ) : """Get all balances . . . todo : : IT SEEMS balances are shown ( MAIN _ URL ) in the same order that contracts in profile page ( PROFILE _ URL ) . Maybe we should ensure that ."""
balances = [ ] try : raw_res = yield from self . _session . get ( MAIN_URL , timeout = self . _timeout ) except OSError : raise PyHydroQuebecError ( "Can not get main page" ) # Parse html content = yield from raw_res . text ( ) soup = BeautifulSoup ( content , 'html.parser' ) solde_nodes = soup . find_all ( "di...
def calculate_rectangle_count ( rad : int ) -> int : """A python function that calculates the number of rectangles in a circle with radius r . Args : rad : The radius of the circle Returns : The calculated number of rectangles inside the circle Examples : > > > calculate _ rectangle _ count ( 2) > > >...
total_rectangles = 0 dia = 2 * rad square_of_dia = dia * dia for x in range ( 1 , dia ) : for y in range ( 1 , dia ) : if ( x * x + y * y ) <= square_of_dia : total_rectangles += 1 return total_rectangles
def add_oxidation_state_by_guess ( self , ** kwargs ) : """Decorates the structure with oxidation state , guessing using Composition . oxi _ state _ guesses ( ) Args : * * kwargs : parameters to pass into oxi _ state _ guesses ( )"""
oxid_guess = self . composition . oxi_state_guesses ( ** kwargs ) oxid_guess = oxid_guess or [ dict ( [ ( e . symbol , 0 ) for e in self . composition ] ) ] self . add_oxidation_state_by_element ( oxid_guess [ 0 ] )
def _call ( self , method , url , params , uploads ) : """Initiate resquest to server and handle outcomes ."""
try : data = self . _request ( method , url , params , uploads ) except Exception , e : self . _failed_cb ( e ) else : self . _completed_cb ( data )
def create_read_session ( self , table_reference , parent , table_modifiers = None , requested_streams = None , read_options = None , format_ = None , retry = google . api_core . gapic_v1 . method . DEFAULT , timeout = google . api_core . gapic_v1 . method . DEFAULT , metadata = None , ) : """Creates a new read ses...
# Wrap the transport method to add retry and timeout logic . if "create_read_session" not in self . _inner_api_calls : self . _inner_api_calls [ "create_read_session" ] = google . api_core . gapic_v1 . method . wrap_method ( self . transport . create_read_session , default_retry = self . _method_configs [ "CreateRe...
def delete_virtual_mfa_device ( serial , region = None , key = None , keyid = None , profile = None ) : '''Deletes the specified virtual MFA device . CLI Example : . . code - block : : bash salt myminion boto _ iam . delete _ virtual _ mfa _ device serial _ num'''
conn = __utils__ [ 'boto3.get_connection_func' ] ( 'iam' ) ( ) try : conn . delete_virtual_mfa_device ( SerialNumber = serial ) log . info ( 'Deleted virtual MFA device %s.' , serial ) return True except botocore . exceptions . ClientError as e : log . debug ( e ) if 'NoSuchEntity' in six . text_typ...
def getElementsWithAttrValues ( self , attrName , values , root = 'root' , useIndex = True ) : '''getElementsWithAttrValues - Returns elements with an attribute matching one of several values . For a single name / value combination , see getElementsByAttr @ param attrName < lowercase str > - A lowercase attribute...
( root , isFromRoot ) = self . _handleRootArg ( root ) _otherAttributeIndexes = self . _otherAttributeIndexes if useIndex is True and attrName in _otherAttributeIndexes : elements = TagCollection ( ) for value in values : elements += TagCollection ( _otherAttributeIndexes [ attrName ] . get ( value , [ ...
def import_string ( dotted_path ) : """Import a dotted module path and return the attribute / class designated by the last name in the path . Raise ImportError if the import failed ."""
try : module_path , class_name = dotted_path . rsplit ( '.' , 1 ) except ValueError : msg = "%s doesn't look like a module path" % dotted_path six . reraise ( ImportError , ImportError ( msg ) , sys . exc_info ( ) [ 2 ] ) module = import_module ( module_path ) try : return getattr ( module , class_name ...
def splititer ( self , string , * args , ** kwargs ) : """Apply ` splititer ` ."""
return self . _pattern . splititer ( string , * args , ** kwargs )
def is_supported ( value , check_all = False , filters = None , iterate = False ) : """Return True if the value is supported , False otherwise"""
assert filters is not None if value is None : return True if not is_editable_type ( value ) : return False elif not isinstance ( value , filters ) : return False elif iterate : if isinstance ( value , ( list , tuple , set ) ) : valid_count = 0 for val in value : if is_support...
def check ( self ) : """Returns False if no datasets exists or if one or more of the datasets are empty"""
if len ( self . status_datasets ) == 0 : return False if all ( self . status_datasets ) : return True return False
def _merge_DC_to_base ( self , X_DC , X_base , no_DC ) : """Merge DC components X _ DC to the baseline time series X _ base ( By baseline , this means any fixed nuisance regressors not updated during fitting , including DC components and any nuisance regressors provided by the user . X _ DC is always in t...
if X_base is not None : reg_sol = np . linalg . lstsq ( X_DC , X_base ) if not no_DC : if not np . any ( np . isclose ( reg_sol [ 1 ] , 0 ) ) : # No columns in X _ base can be explained by the # baseline regressors . So we insert them . X_base = np . concatenate ( ( X_DC , X_base ) ,...
def _tab ( content ) : """Helper funcation that converts text - based get response to tab separated values for additional manipulation ."""
response = _data_frame ( content ) . to_csv ( index = False , sep = '\t' ) return response