signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def display_results ( results , detailed = False ) : """Display the results from the validator in a brief or detailed output : param list results : API results , sorted by dataset name ( multiple ) : param bool detailed : Detailed results on or off : return none :"""
# print ( " \ nVALIDATOR RESULTS " ) # print ( " = = = = = \ n " ) if not detailed : print ( 'FILENAME......................................... STATUS..........' ) for entry in results : try : if detailed : print ( "\n{}" . format ( entry [ "filename" ] ) ) print ( create_detaile...
def neighbors ( self , type = None , direction = "to" , failed = None ) : """Get a node ' s neighbors - nodes that are directly connected to it . Type specifies the class of neighbour and must be a subclass of Node ( default is Node ) . Connection is the direction of the connections and can be " to " ( defa...
# get type if type is None : type = Node if not issubclass ( type , Node ) : raise ValueError ( "{} is not a valid neighbor type," "needs to be a subclass of Node." . format ( type ) ) # get direction if direction not in [ "both" , "either" , "from" , "to" ] : raise ValueError ( "{} not a valid neighbor con...
def change_attributes ( self , ** kwargs ) : '''Change an attribute of this track and return a new copy .'''
new_track = Track ( self . viewconf [ 'type' ] ) new_track . position = self . position new_track . tileset = self . tileset new_track . viewconf = json . loads ( json . dumps ( self . viewconf ) ) new_track . viewconf = { ** new_track . viewconf , ** kwargs } return new_track
def net_graph ( block = None , split_state = False ) : """Return a graph representation of the current block . Graph has the following form : { node1 : { nodeA : edge1A , nodeB : edge1B } , node2 : { nodeB : edge2B , nodeC : edge2C } , aka : edge = graph [ source ] [ dest ] Each node can be either a logic...
# FIXME : make it not try to add unused wires ( issue # 204) block = working_block ( block ) from . wire import Register # self . sanity _ check ( ) graph = { } # add all of the nodes for net in block . logic : graph [ net ] = { } wire_src_dict , wire_dst_dict = block . net_connections ( ) dest_set = set ( wire_src...
def _get_authenticated_client ( self , wsdl ) : """Return an authenticated SOAP client . Returns : zeep . Client : Authenticated API client ."""
return zeep . Client ( wsdl % quote ( self . username ) , transport = zeep . Transport ( session = self . _get_authenticated_session ( ) , ) , )
def start ( self ) -> None : """Connect websocket to deCONZ ."""
if self . config : self . websocket = self . ws_client ( self . loop , self . session , self . host , self . config . websocketport , self . async_session_handler ) self . websocket . start ( ) else : _LOGGER . error ( 'No deCONZ config available' )
def askopenfilename ( ** kwargs ) : """Return file name ( s ) from Tkinter ' s file open dialog ."""
try : from Tkinter import Tk import tkFileDialog as filedialog except ImportError : from tkinter import Tk , filedialog root = Tk ( ) root . withdraw ( ) root . update ( ) filenames = filedialog . askopenfilename ( ** kwargs ) root . destroy ( ) return filenames
def full_path ( base , fmt ) : """Return the full path for the notebook , given the base path"""
ext = fmt [ 'extension' ] suffix = fmt . get ( 'suffix' ) prefix = fmt . get ( 'prefix' ) full = base if prefix : prefix_dir , prefix_file_name = os . path . split ( prefix ) notebook_dir , notebook_file_name = os . path . split ( base ) # Local path separator ( \ \ on windows ) sep = base [ len ( noteb...
def name ( name , validator = None ) : """Set a name on a validator callable . Useful for user - friendly reporting when using lambdas to populate the [ ` Invalid . expected ` ] ( # invalid ) field : ` ` ` python from good import Schema , name Schema ( lambda x : int ( x ) ) ( ' a ' ) # - > Invalid : inva...
# Decorator mode if validator is None : def decorator ( f ) : f . name = name return f return decorator # Direct mode validator . name = name return validator
def target_heating_level ( self ) : """Return target heating level ."""
try : if self . side == 'left' : level = self . device . device_data [ 'leftTargetHeatingLevel' ] elif self . side == 'right' : level = self . device . device_data [ 'rightTargetHeatingLevel' ] return level except TypeError : return None
def filter_macro ( func , * args , ** kwargs ) : """Promotes a function that returns a filter into its own filter type . Example : : @ filter _ macro def String ( ) : return Unicode | Strip | NotEmpty # You can now use ` String ` anywhere you would use a regular Filter : ( String | Split ( ' : ' ) ) . a...
filter_partial = partial ( func , * args , ** kwargs ) class FilterMacroMeta ( FilterMeta ) : @ staticmethod def __new__ ( mcs , name , bases , attrs ) : # This is as close as we can get to running # ` ` update _ wrapper ` ` on a type . for attr in WRAPPER_ASSIGNMENTS : if hasattr ( func...
def triangle_strips_to_faces ( strips ) : """Given a sequence of triangle strips , convert them to ( n , 3 ) faces . Processes all strips at once using np . concatenate and is significantly faster than loop - based methods . From the OpenGL programming guide describing a single triangle strip [ v0 , v1 , v2...
# save the length of each list in the list of lists lengths = np . array ( [ len ( i ) for i in strips ] ) # looping through a list of lists is extremely slow # combine all the sequences into a blob we can manipulate blob = np . concatenate ( strips ) # preallocate and slice the blob into rough triangles tri = np . zer...
def css_property ( self ) -> str : """Generate a random snippet of CSS that assigns value to a property . : return : CSS property . : Examples : ' background - color : # f4d3a1'"""
prop = self . random . choice ( list ( CSS_PROPERTIES . keys ( ) ) ) val = CSS_PROPERTIES [ prop ] if isinstance ( val , list ) : val = self . random . choice ( val ) elif val == 'color' : val = self . __text . hex_color ( ) elif val == 'size' : val = '{}{}' . format ( self . random . randint ( 1 , 99 ) , s...
def _insert_job ( self , body_object ) : """Submit a job to BigQuery Direct proxy to the insert ( ) method of the offical BigQuery python client . Able to submit load , link , query , copy , or extract jobs . For more details , see : https : / / google - api - client - libraries . appspot . com / document...
logger . debug ( 'Submitting job: %s' % body_object ) job_collection = self . bigquery . jobs ( ) return job_collection . insert ( projectId = self . project_id , body = body_object ) . execute ( num_retries = self . num_retries )
def _validate_condition_keys ( self , field , value , error ) : """Validates that all of the keys in one of the sets of keys are defined as keys of ` ` value ` ` ."""
if 'field' in value : operators = self . nonscalar_conditions + self . scalar_conditions matches = sum ( 1 for k in operators if k in value ) if matches == 0 : error ( field , 'Must contain one of {}' . format ( operators ) ) return False elif matches > 1 : error ( field , 'Must ...
def get_estimates_without_scope_in_month ( self , customer ) : """It is expected that valid row for each month contains at least one price estimate for customer , service setting , service , service project link , project and resource . Otherwise all price estimates in the row should be deleted ."""
estimates = self . get_price_estimates_for_customer ( customer ) if not estimates : return [ ] tables = { model : collections . defaultdict ( list ) for model in self . get_estimated_models ( ) } dates = set ( ) for estimate in estimates : date = ( estimate . year , estimate . month ) dates . add ( date ) ...
def to_slice ( arr ) : """Test whether ` arr ` is an integer array that can be replaced by a slice Parameters arr : numpy . array Numpy integer array Returns slice or None If ` arr ` could be converted to an array , this is returned , otherwise ` None ` is returned See Also get _ index _ from _ co...
if isinstance ( arr , slice ) : return arr if len ( arr ) == 1 : return slice ( arr [ 0 ] , arr [ 0 ] + 1 ) step = np . unique ( arr [ 1 : ] - arr [ : - 1 ] ) if len ( step ) == 1 : return slice ( arr [ 0 ] , arr [ - 1 ] + step [ 0 ] , step [ 0 ] )
def coerce ( self , value ) : """Cast a string into this key type"""
if self . type == Style : return value elif self . type == list : return self . type ( map ( self . subtype , map ( lambda x : x . strip ( ) , value . split ( ',' ) ) ) ) elif self . type == dict : rv = { } for pair in value . split ( ',' ) : key , val = pair . split ( ':' ) key = key . ...
def update ( self , data , decayFactor , timeUnit ) : """Update the centroids , according to data : param data : RDD with new data for the model update . : param decayFactor : Forgetfulness of the previous centroids . : param timeUnit : Can be " batches " or " points " . If points , then the decay facto...
if not isinstance ( data , RDD ) : raise TypeError ( "Data should be of an RDD, got %s." % type ( data ) ) data = data . map ( _convert_to_vector ) decayFactor = float ( decayFactor ) if timeUnit not in [ "batches" , "points" ] : raise ValueError ( "timeUnit should be 'batches' or 'points', got %s." % timeUnit ...
def clean ( ctx , node = False , translations = False , all = False ) : '''Cleanup all build artifacts'''
header ( 'Clean all build artifacts' ) patterns = [ 'build' , 'dist' , 'cover' , 'docs/_build' , '**/*.pyc' , '*.egg-info' , '.tox' , 'udata/static/*' ] if node or all : patterns . append ( 'node_modules' ) if translations or all : patterns . append ( 'udata/translations/*/LC_MESSAGES/udata.mo' ) for pattern in...
def Fourar_Bories ( x , mul , mug , rhol , rhog ) : r'''Calculates a suggested definition for liquid - gas two - phase flow viscosity in internal pipe flow according to the form in [ 1 ] _ and shown in [ 2 ] _ and [ 3 ] _ . . . math : : \ mu _ m = \ rho _ m \ left ( \ sqrt { x \ nu _ g } + \ sqrt { ( 1 - x ...
rhom = 1. / ( x / rhog + ( 1. - x ) / rhol ) nul = mul / rhol # = nu _ mu _ converter ( rho = rhol , mu = mul ) nug = mug / rhog # = nu _ mu _ converter ( rho = rhog , mu = mug ) return rhom * ( ( x * nug ) ** 0.5 + ( ( 1. - x ) * nul ) ** 0.5 ) ** 2
def conv_block ( name , x , mid_channels , dilations = None , activation = "relu" , dropout = 0.0 ) : """2 layer conv block used in the affine coupling layer . Args : name : variable scope . x : 4 - D or 5 - D Tensor . mid _ channels : Output channels of the second layer . dilations : Optional , list of i...
with tf . variable_scope ( name , reuse = tf . AUTO_REUSE ) : x_shape = common_layers . shape_list ( x ) is_2d = len ( x_shape ) == 4 num_steps = x_shape [ 1 ] if is_2d : first_filter = [ 3 , 3 ] second_filter = [ 1 , 1 ] else : # special case when number of steps equal 1 to avoid ...
def make_twitter_request ( url , user_id , params = { } , request_type = 'GET' ) : """Generically make a request to twitter API using a particular user ' s authorization"""
if request_type == "GET" : return requests . get ( url , auth = get_twitter_auth ( user_id ) , params = params ) elif request_type == "POST" : return requests . post ( url , auth = get_twitter_auth ( user_id ) , params = params )
def hll_count ( expr , error_rate = 0.01 , splitter = None ) : """Calculate HyperLogLog count : param expr : : param error _ rate : error rate : type error _ rate : float : param splitter : the splitter to split the column value : return : sequence or scalar : Example : > > > df = DataFrame ( pd . Dat...
# to make the class pickled right by the cloudpickle with open ( os . path . join ( path , 'lib' , 'hll.py' ) ) as hll_file : local = { } six . exec_ ( hll_file . read ( ) , local ) HyperLogLog = local [ 'HyperLogLog' ] return expr . agg ( HyperLogLog , rtype = types . int64 , args = ( error_rate , spli...
def pkg_not_found ( self , bol , pkg , message , eol ) : """Print message when package not found"""
print ( "{0}No such package {1}: {2}{3}" . format ( bol , pkg , message , eol ) )
def from_charmm ( cls , path , positions = None , forcefield = None , strict = True , ** kwargs ) : """Loads PSF Charmm structure from ` path ` . Requires ` charmm _ parameters ` . Parameters path : str Path to PSF file forcefield : list of str Paths to Charmm parameters files , such as * . par or * . str...
psf = CharmmPsfFile ( path ) if strict and forcefield is None : raise ValueError ( 'PSF files require key `forcefield`.' ) if strict and positions is None : raise ValueError ( 'PSF files require key `positions`.' ) psf . parmset = CharmmParameterSet ( * forcefield ) psf . loadParameters ( psf . parmset ) return...
def memoize ( func ) : """Cache decorator for functions inside model classes"""
def model ( cls , energy , * args , ** kwargs ) : try : memoize = cls . _memoize cache = cls . _cache queue = cls . _queue except AttributeError : memoize = False if memoize : # Allow for dicts or tables with energy column , Quantity array or # Quantity scalar try...
def get ( self , url , ignore_access_time = False ) : """Try to retrieve url from cache if available : param url : Url to retrieve : type url : str | unicode : param ignore _ access _ time : Should ignore the access time : type ignore _ access _ time : bool : return : ( data , CacheInfo ) None , None - ...
key = hashlib . md5 ( url ) . hexdigest ( ) accessed = self . _cache_meta_get ( key ) if not accessed : # not previously cached self . debug ( "From inet {}" . format ( url ) ) return None , None if isinstance ( accessed , dict ) : cached = CacheInfo . from_dict ( accessed ) else : cached = CacheInfo ( ...
async def close ( self ) : """Close the connection ."""
# stop consent freshness tests if self . _query_consent_handle and not self . _query_consent_handle . done ( ) : self . _query_consent_handle . cancel ( ) try : await self . _query_consent_handle except asyncio . CancelledError : pass # stop check list if self . _check_list and not self . _c...
def validate_basic_smoother ( ) : """Run Friedman ' s test from Figure 2b ."""
x , y = sort_data ( * smoother_friedman82 . build_sample_smoother_problem_friedman82 ( ) ) plt . figure ( ) # plt . plot ( x , y , ' . ' , label = ' Data ' ) for span in smoother . DEFAULT_SPANS : my_smoother = smoother . perform_smooth ( x , y , span ) friedman_smooth , _resids = run_friedman_smooth ( x , y , ...
def _unicode_decode_extracted_tb ( extracted_tb ) : """Return a traceback with the string elements translated into Unicode ."""
return [ ( _decode ( file ) , line_number , _decode ( function ) , _decode ( text ) ) for file , line_number , function , text in extracted_tb ]
def main ( ) : """Runs a clusterer from the command - line . Calls JVM start / stop automatically . Use - h to see all options ."""
parser = argparse . ArgumentParser ( description = 'Performs clustering from the command-line. Calls JVM start/stop automatically.' ) parser . add_argument ( "-j" , metavar = "classpath" , dest = "classpath" , help = "additional classpath, jars/directories" ) parser . add_argument ( "-X" , metavar = "heap" , dest = "he...
def all_days ( boo ) : """Return a list of all dates from 11/12/2015 to the present . Args : boo : if true , list contains Numbers ( 20151230 ) ; if false , list contains Strings ( " 2015-12-30 " ) Returns : list of either Numbers or Strings"""
earliest = datetime . strptime ( ( '2015-11-12' ) . replace ( '-' , ' ' ) , '%Y %m %d' ) latest = datetime . strptime ( datetime . today ( ) . date ( ) . isoformat ( ) . replace ( '-' , ' ' ) , '%Y %m %d' ) num_days = ( latest - earliest ) . days + 1 all_days = [ latest - timedelta ( days = x ) for x in range ( num_day...
def experiments_predictions_update_state_success ( self , experiment_id , run_id , result_file ) : """Update state of given prediction to success . Create a function data resource for the given result file and associate it with the model run . Parameters experiment _ id : string Unique experiment identifier...
# Get prediction to ensure that it exists model_run = self . experiments_predictions_get ( experiment_id , run_id ) if model_run is None : return None # Create new resource for model run result funcdata = self . funcdata . create_object ( result_file ) # Update predition state return self . predictions . update_sta...
def gen_binary ( table , output , ascii_props = False , append = False , prefix = "" ) : """Generate binary properties ."""
categories = [ ] binary_props = ( ( 'DerivedCoreProperties.txt' , None ) , ( 'PropList.txt' , None ) , ( 'DerivedNormalizationProps.txt' , ( 'Changes_When_NFKC_Casefolded' , 'Full_Composition_Exclusion' ) ) ) binary = { } for filename , include in binary_props : with codecs . open ( os . path . join ( HOME , 'unico...
def _to_reader_frame ( self ) : """Navigate to the KindleReader iframe ."""
reader_frame = 'KindleReaderIFrame' frame_loaded = lambda br : br . find_elements_by_id ( reader_frame ) self . _wait ( ) . until ( frame_loaded ) self . switch_to . frame ( reader_frame ) # pylint : disable = no - member reader_loaded = lambda br : br . find_elements_by_id ( 'kindleReader_header' ) self . _wait ( ) . ...
def send_at ( self , value ) : """A unix timestamp specifying when your email should be delivered . : param value : A unix timestamp specifying when your email should be delivered . : type value : SendAt , int"""
if isinstance ( value , SendAt ) : if value . personalization is not None : try : personalization = self . _personalizations [ value . personalization ] has_internal_personalization = True except IndexError : personalization = Personalization ( ) has_i...
def create_returns_tear_sheet ( factor_data , long_short = True , group_neutral = False , by_group = False ) : """Creates a tear sheet for returns analysis of a factor . Parameters factor _ data : pd . DataFrame - MultiIndex A MultiIndex DataFrame indexed by date ( level 0 ) and asset ( level 1 ) , containi...
factor_returns = perf . factor_returns ( factor_data , long_short , group_neutral ) mean_quant_ret , std_quantile = perf . mean_return_by_quantile ( factor_data , by_group = False , demeaned = long_short , group_adjust = group_neutral ) mean_quant_rateret = mean_quant_ret . apply ( utils . rate_of_return , axis = 0 , b...
def update_exif_for_rotated_image ( exif ) : """Modifies the Exif tag if rotation has been performed . 0th , 1st ImageWidth = 256 ImageLength = 257 XResolution = 282 YResolution = 283 TileWidth = 322 TileLength = 323 Exif PixelXDimension = 40962 PixelYDimension = 40963 Args : exif ( dict ) :...
orientation_value = exif . get ( '0th' , ) . get ( piexif . ImageIFD . Orientation , exif . get ( '1st' , ) . get ( piexif . ImageIFD . Orientation , None ) ) if orientation_value is not None : # Update orientation . exif [ '0th' ] [ piexif . ImageIFD . Orientation ] = 1 if exif . get ( '1st' , { } ) . get ( pi...
def get_valid_cwd ( ) : """Determine and check the current working directory for validity . Typically , an directory arises when you checkout a different branch on git that doesn ' t have this directory . When an invalid directory is found , a warning is printed to the screen , but the directory is still retu...
try : cwd = _current_dir ( ) except : warn ( "Your current directory is invalid. If you open a ticket at " + "https://github.com/milkbikis/powerline-shell/issues/new " + "we would love to help fix the issue." ) sys . stdout . write ( "> " ) sys . exit ( 1 ) parts = cwd . split ( os . sep ) up = cwd whil...
def contains ( self , ra , dec , keep_inside = True ) : """Returns a boolean mask array of the positions lying inside ( or outside ) the MOC instance . Parameters ra : ` astropy . units . Quantity ` Right ascension array dec : ` astropy . units . Quantity ` Declination array keep _ inside : bool , optio...
depth = self . max_order m = np . zeros ( nside2npix ( 1 << depth ) , dtype = bool ) pix_id = self . _best_res_pixels ( ) m [ pix_id ] = True if not keep_inside : m = np . logical_not ( m ) hp = HEALPix ( nside = ( 1 << depth ) , order = 'nested' ) pix = hp . lonlat_to_healpix ( ra , dec ) return m [ pix ]
def __registerStructStr ( ) : """helper method to register str and repr methods for structures"""
structs = ( LockerInfo , DevCommandInfo , AttributeDimension , CommandInfo , DeviceInfo , DeviceAttributeConfig , AttributeInfo , AttributeAlarmInfo , ChangeEventInfo , PeriodicEventInfo , ArchiveEventInfo , AttributeEventInfo , AttributeInfoEx , PipeInfo , DeviceAttribute , DeviceAttributeHistory , DeviceData , Device...
def dispatch ( self , message : Message ) -> Iterator [ Any ] : """Yields handlers matching the routing of the incoming : class : ` slack . events . Message ` Args : message : : class : ` slack . events . Message ` Yields : handler"""
if "text" in message : text = message [ "text" ] or "" elif "message" in message : text = message [ "message" ] . get ( "text" , "" ) else : text = "" msg_subtype = message . get ( "subtype" ) for subtype , matchs in itertools . chain ( self . _routes [ message [ "channel" ] ] . items ( ) , self . _routes [...
def run ( self , scenario = None , only = None , ** kwargs ) : """Run MAGICC and parse the output . As a reminder , putting ` ` out _ parameters = 1 ` ` will cause MAGICC to write out its parameters into ` ` out / PARAMETERS . OUT ` ` and they will then be read into ` ` output . metadata [ " parameters " ] ` ...
if not exists ( self . root_dir ) : raise FileNotFoundError ( self . root_dir ) if self . executable is None : raise ValueError ( "MAGICC executable not found, try setting an environment variable `MAGICC_EXECUTABLE_{}=/path/to/binary`" . format ( self . version ) ) if scenario is not None : kwargs = self . ...
def mode ( self ) : """Get alarm mode ."""
mode = self . get_value ( 'mode' ) . get ( self . device_id , None ) return mode . lower ( )
def grid_search_cmd ( argv = sys . argv [ 1 : ] ) : # pragma : no cover """Grid search parameters for the model . Uses ' dataset _ loader _ train ' , ' model ' , and ' grid _ search ' from the configuration to load a training dataset , and run a grid search on the model using the grid of hyperparameters . U...
arguments = docopt ( grid_search_cmd . __doc__ , argv = argv ) initialize_config ( __mode__ = 'fit' ) grid_search ( save_results = arguments [ '--save-results' ] , persist_best = arguments [ '--persist-best' ] , )
def _validate_query_parameters ( self , query , action_spec ) : """Check the query parameter for the action specification . Args : query : query parameter to check . action _ spec : specification of the action . Returns : True if the query is valid ."""
processed_params = [ ] for param_name , param_value in query . items ( ) : if param_name in action_spec [ 'parameters' ] . keys ( ) : processed_params . append ( param_name ) # Check array if action_spec [ 'parameters' ] [ param_name ] [ 'type' ] == 'array' : if not isinstance ( ...
def location_for ( self , city_name ) : """Returns the * Location * object corresponding to the first city found that matches the provided city name . The lookup is case insensitive . : param city _ name : the city name you want a * Location * for : type city _ name : str : returns : a * Location * instance...
line = self . _lookup_line_by_city_name ( city_name ) if line is None : return None tokens = line . split ( "," ) return Location ( tokens [ 0 ] , float ( tokens [ 3 ] ) , float ( tokens [ 2 ] ) , int ( tokens [ 1 ] ) , tokens [ 4 ] )
def _run ( self , circuit : circuits . Circuit , param_resolver : study . ParamResolver , repetitions : int , ) -> Dict [ str , List [ np . ndarray ] ] : """See definition in ` cirq . SimulatesSamples ` ."""
circuit = protocols . resolve_parameters ( circuit , param_resolver ) _verify_xmon_circuit ( circuit ) # Delegate to appropriate method based on contents . if circuit . are_all_measurements_terminal ( ) : return self . _run_sweep_sample ( circuit , repetitions ) else : return self . _run_sweep_repeat ( circuit ...
def do_execute ( self ) : """The actual execution of the actor . : return : None if successful , otherwise error message : rtype : str"""
result = None evl = self . input . payload pltclassifier . plot_prc ( evl , class_index = self . resolve_option ( "class_index" ) , title = self . resolve_option ( "title" ) , key_loc = self . resolve_option ( "key_loc" ) , outfile = self . resolve_option ( "outfile" ) , wait = bool ( self . resolve_option ( "wait" ) )...
def create ( zone , name , ttl , rdtype , data , keyname , keyfile , nameserver , timeout , port = 53 , keyalgorithm = 'hmac-md5' ) : '''Create a DNS record . The nameserver must be an IP address and the master running this runner must have create privileges on that server . CLI Example : . . code - block : :...
if zone in name : name = name . replace ( zone , '' ) . rstrip ( '.' ) fqdn = '{0}.{1}' . format ( name , zone ) request = dns . message . make_query ( fqdn , rdtype ) answer = dns . query . udp ( request , nameserver , timeout , port ) rdata_value = dns . rdatatype . from_text ( rdtype ) rdata = dns . rdata . from...
def check_array ( array , force_2d = False , n_feats = None , ndim = None , min_samples = 1 , name = 'Input data' , verbose = True ) : """tool to perform basic data validation . called by check _ X and check _ y . ensures that data : - is ndim dimensional - contains float - compatible data - types - has a...
# make array if force_2d : array = make_2d ( array , verbose = verbose ) ndim = 2 else : array = np . array ( array ) # cast to float dtype = array . dtype if dtype . kind not in [ 'i' , 'f' ] : try : array = array . astype ( 'float' ) except ValueError as e : raise ValueError ( '{} ...
def hex2rgb ( h ) : """Convert hex colors to RGB tuples Parameters h : str String hex color value > > > hex2rgb ( " # ff0033 " ) '255,0,51'"""
if not h . startswith ( '#' ) or len ( h ) != 7 : raise ValueError ( "Does not look like a hex color: '{0}'" . format ( h ) ) return ',' . join ( map ( str , ( int ( h [ 1 : 3 ] , 16 ) , int ( h [ 3 : 5 ] , 16 ) , int ( h [ 5 : 7 ] , 16 ) , ) ) )
def pretty_print ( rows , keyword , domain ) : """rows is list when get domains dict when get specific domain"""
if isinstance ( rows , dict ) : pretty_print_domain ( rows , keyword , domain ) elif isinstance ( rows , list ) : pretty_print_zones ( rows )
def _sample_as_dict ( self , sample ) : """Convert list - like ` ` sample ` ` ( list / dict / dimod . SampleView ) , ` ` list : var ` ` , to ` ` map : idx - > var ` ` ."""
if isinstance ( sample , dict ) : return sample if isinstance ( sample , ( list , numpy . ndarray ) ) : sample = enumerate ( sample ) return dict ( sample )
def statistics ( self ) : """Access the statistics : returns : twilio . rest . taskrouter . v1 . workspace . worker . workers _ statistics . WorkersStatisticsList : rtype : twilio . rest . taskrouter . v1 . workspace . worker . workers _ statistics . WorkersStatisticsList"""
if self . _statistics is None : self . _statistics = WorkersStatisticsList ( self . _version , workspace_sid = self . _solution [ 'workspace_sid' ] , ) return self . _statistics
def load_uri ( self , uri ) : """Load a single resource into the graph for this object . Approach : try loading into a temporary graph first , if that succeeds merge it into the main graph . This allows to deal with the JSONLD loading issues which can solved only by using a ConjunctiveGraph ( https : / / github ....
# if self . verbose : printDebug ( " - - - - - " ) if self . verbose : printDebug ( "Reading: <%s>" % uri , fg = "green" ) success = False sorted_fmt_opts = try_sort_fmt_opts ( self . rdf_format_opts , uri ) for f in sorted_fmt_opts : if self . verbose : printDebug ( ".. trying rdf serialization: <%s>" ...
def getEdges ( self , edges , inEdges = True , outEdges = True , rawResults = False ) : """returns in , out , or both edges linked to self belonging the collection ' edges ' . If rawResults a arango results will be return as fetched , if false , will return a liste of Edge objects"""
try : return edges . getEdges ( self , inEdges , outEdges , rawResults ) except AttributeError : raise AttributeError ( "%s does not seem to be a valid Edges object" % edges )
def copy ( self ) : """Copies the selected items to the clipboard ."""
text = [ ] for item in self . selectedItems ( ) : text . append ( nativestring ( item . text ( ) ) ) QApplication . clipboard ( ) . setText ( ',' . join ( text ) )
def show_vcs_output_virtual_ipv6_address ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) show_vcs = ET . Element ( "show_vcs" ) config = show_vcs output = ET . SubElement ( show_vcs , "output" ) virtual_ipv6_address = ET . SubElement ( output , "virtual-ipv6-address" ) virtual_ipv6_address . text = kwargs . pop ( 'virtual_ipv6_address' ) callback = kwargs . pop ( 'callbac...
def _map_shapes_and_ancestors ( self , topoTypeA , topoTypeB , topologicalEntity ) : '''using the same method @ param topoTypeA : @ param topoTypeB : @ param topologicalEntity :'''
topo_set = set ( ) _map = TopTools_IndexedDataMapOfShapeListOfShape ( ) topexp_MapShapesAndAncestors ( self . myShape , topoTypeA , topoTypeB , _map ) results = _map . FindFromKey ( topologicalEntity ) if results . IsEmpty ( ) : yield None topology_iterator = TopTools_ListIteratorOfListOfShape ( results ) while top...
def count_hexa_primes ( hexa_num ) : """Takes in a hexadecimal string and counts the occurrence of the hexadecimal prime numbers in that string . A hexadecimal prime number is a prime number that is also a hexadecimal digit , i . e . , 2 , 3 , 5 , 7 , ' B ' ( = decimal 11 ) , ' D ' ( = decimal 13 ) . Note :...
hex_prime_digits = ( '2' , '3' , '5' , '7' , 'B' , 'D' ) hex_prime_count = 0 for hexa in hexa_num : if hexa in hex_prime_digits : hex_prime_count += 1 return hex_prime_count
def _dict_merge_right ( dict_left , dict_right , merge_method ) : """See documentation of mpu . datastructures . dict _ merge ."""
new_dict = deepcopy ( dict_left ) for key , value in dict_right . items ( ) : if key not in new_dict : new_dict [ key ] = value else : recurse = ( merge_method == 'take_right_deep' and isinstance ( dict_left [ key ] , dict ) and isinstance ( dict_right [ key ] , dict ) ) if recurse : ...
def var ( self ) : """Variance value as a result of an uncertainty calculation"""
mn = self . mean vr = np . mean ( ( self . _mcpts - mn ) ** 2 ) return vr
def create_casting_method ( op , klass ) : """Creates a new univariate special method , such as A . _ _ float _ _ ( ) < = > float ( A . value ) , for target class . The method is called _ _ op _ name _ _ ."""
# This function will become the actual method . def new_method ( self , op = op ) : if not check_special_methods ( ) : raise NotImplementedError ( 'Special method %s called on %s, but special methods have been disabled. Set pymc.special_methods_available to True to enable them.' % ( op_name , str ( self ) )...
def dens_in_meanmatterdens ( vo , ro , H = 70. , Om = 0.3 ) : """NAME : dens _ in _ meanmatterdens PURPOSE : convert density to units of the mean matter density INPUT : vo - velocity unit in km / s ro - length unit in kpc H = ( default : 70 ) Hubble constant in km / s / Mpc Om = ( default : 0.3 ) Om...
return dens_in_criticaldens ( vo , ro , H = H ) / Om
def parse ( self , data = None , table_name = None ) : """Parse the lines from index i : param data : optional , store the parsed result to it when specified : param table _ name : when inside a table array , it is the table name"""
temp = self . dict_ ( ) sub_table = None is_array = False line = '' while True : line = self . _readline ( ) if not line : self . _store_table ( sub_table , temp , is_array , data = data ) break # EOF if BLANK_RE . match ( line ) : continue if TABLE_RE . match ( line ) : ...
def array_to_schedule ( array , events , slots ) : """Convert a schedule from array to schedule form Parameters array : np . array An E by S array ( X ) where E is the number of events and S the number of slots . Xij is 1 if event i is scheduled in slot j and zero otherwise events : list or tuple of :...
scheduled = np . transpose ( np . nonzero ( array ) ) return [ ScheduledItem ( event = events [ item [ 0 ] ] , slot = slots [ item [ 1 ] ] ) for item in scheduled ]
def evaluate ( self , verbose = False , decode = True , passes = None , num_threads = 1 , apply_experimental = True ) : """Evaluates by creating a DataFrame containing evaluated data and index . See ` LazyResult ` Returns DataFrame DataFrame with evaluated data and index ."""
evaluated_index = self . index . evaluate ( verbose , decode , passes , num_threads , apply_experimental ) evaluated_data = OrderedDict ( ( column . name , column . evaluate ( verbose , decode , passes , num_threads , apply_experimental ) ) for column in self . _iter ( ) ) return DataFrame ( evaluated_data , evaluated_...
def validate_document_class ( option , value ) : """Validate the document _ class option ."""
if not issubclass ( value , ( collections . MutableMapping , RawBSONDocument ) ) : raise TypeError ( "%s must be dict, bson.son.SON, " "bson.raw_bson.RawBSONDocument, or a " "sublass of collections.MutableMapping" % ( option , ) ) return value
def getrawtransaction ( self , txid : str , decrypt : int = 0 ) -> dict : '''Returns raw transaction representation for given transaction id . decrypt can be set to 0 ( false ) or 1 ( true ) .'''
q = 'getrawtransaction?txid={txid}&decrypt={decrypt}' . format ( txid = txid , decrypt = decrypt ) return cast ( dict , self . api_fetch ( q ) )
def create_sb_pool ( self , zone_name , owner_name , ttl , pool_info , rdata_info , backup_record_list ) : """Creates a new SB Pool . Arguments : zone _ name - - The zone that contains the RRSet . The trailing dot is optional . owner _ name - - The owner name for the RRSet . If no trailing dot is supplied ,...
rrset = self . _build_sb_rrset ( backup_record_list , pool_info , rdata_info , ttl ) return self . rest_api_connection . post ( "/v1/zones/" + zone_name + "/rrsets/A/" + owner_name , json . dumps ( rrset ) )
def alias_function ( fun , name , doc = None ) : '''Copy a function'''
alias_fun = types . FunctionType ( fun . __code__ , fun . __globals__ , str ( name ) , # future lint : disable = blacklisted - function fun . __defaults__ , fun . __closure__ ) alias_fun . __dict__ . update ( fun . __dict__ ) if doc and isinstance ( doc , six . string_types ) : alias_fun . __doc__ = doc else : ...
def brier_skill_score ( self ) : """Calculate the Brier Skill Score"""
reliability , resolution , uncertainty = self . brier_score_components ( ) return ( resolution - reliability ) / uncertainty
def get_units ( username ) : """Return all units of user ' username '"""
connection , ldap_base = _get_LDAP_connection ( ) # Search the user dn connection . search ( search_base = ldap_base , search_filter = '(uid={}@*)' . format ( username ) , ) # For each user dn give me the unit dn_list = [ connection . response [ index ] [ 'dn' ] for index in range ( len ( connection . response ) ) ] un...
def create_pool ( hostname , username , password , name , members = None , allow_nat = None , allow_snat = None , description = None , gateway_failsafe_device = None , ignore_persisted_weight = None , ip_tos_to_client = None , ip_tos_to_server = None , link_qos_to_client = None , link_qos_to_server = None , load_balanc...
ret = { 'name' : name , 'changes' : { } , 'result' : False , 'comment' : '' } if __opts__ [ 'test' ] : return _test_output ( ret , 'create' , params = { 'hostname' : hostname , 'username' : username , 'password' : password , 'name' : name , 'members' : members , 'allow_nat' : allow_nat , 'allow_snat' : allow_snat ,...
def save_array_types ( self , fname ) : '''Save array type registry to a file Args : fname ( str ) : Name of file to save array database to'''
type_defs = { 'arrays' : sorted ( list ( self . array_types ) ) } with open ( fname , 'wt' ) as fh : pprint ( type_defs , stream = fh )
def create_or_login ( resp ) : """This is called when login with OpenID succeeded and it ' s not necessary to figure out if this is the users ' s first login or not . This function has to redirect otherwise the user will be presented with a terrible URL which we certainly don ' t want ."""
session [ 'openid' ] = resp . identity_url user = User . query . filter_by ( openid = resp . identity_url ) . first ( ) if user is not None : flash ( u'Successfully signed in' ) g . user = user return redirect ( oid . get_next_url ( ) ) return redirect ( url_for ( 'create_profile' , next = oid . get_next_ur...
def convertToDate ( fmt = "%Y-%m-%d" ) : """Helper to create a parse action for converting parsed date string to Python datetime . date Params - - fmt - format to be passed to datetime . strptime ( default = ` ` " % Y - % m - % d " ` ` ) Example : : date _ expr = pyparsing _ common . iso8601 _ date . copy (...
def cvt_fn ( s , l , t ) : try : return datetime . strptime ( t [ 0 ] , fmt ) . date ( ) except ValueError as ve : raise ParseException ( s , l , str ( ve ) ) return cvt_fn
def MAVOL_serial ( self , days , rev = 0 ) : """see make _ serial ( ) 成較量移動平均 list 化 , 資料格式請見 def make _ serial ( )"""
return self . make_serial ( self . stock_vol , days , rev = 0 )
def register_dn ( self ) : """Called by WorkerThread objects to register themselves . Acquire the condition variable for the WorkerThread objects . Decrement the running - thread count . If we are the last thread to start , release the ThreadPool thread , which is stuck in start ( )"""
with self . regcond : self . runningcount -= 1 tid = thread . get_ident ( ) self . tids . remove ( tid ) self . logger . debug ( "register_dn: count_dn is %d" % self . runningcount ) self . logger . debug ( "register_dn: remaining: %s" % str ( self . tids ) ) if self . runningcount == 0 : ...
def method_call_if_def ( obj , attr_name , m_name , default , * args , ** kwargs ) : """Calls the provided method if it is defined . Returns default if not defined ."""
try : attr = getattr ( obj , attr_name ) except AttributeError : return default else : return getattr ( attr , m_name ) ( * args , ** kwargs )
def open_asset_path ( self , * args , ** kwargs ) : """Open the currently selected asset in the filebrowser : returns : None : rtype : None : raises : None"""
f = self . asset_path_le . text ( ) d = os . path . dirname ( f ) osinter = get_interface ( ) osinter . open_path ( d )
def asset_view_asset ( self , ) : """View the task that is currently selected on the asset page : returns : None : rtype : None : raises : None"""
if not self . cur_asset : return i = self . asset_asset_treev . currentIndex ( ) item = i . internalPointer ( ) if item : asset = item . internal_data ( ) if isinstance ( asset , djadapter . models . Asset ) : self . view_asset ( asset )
def dump ( self ) : """Item as a JSON representation ."""
return json . dumps ( self . primitive , sort_keys = True , ensure_ascii = False , separators = ( ',' , ':' ) )
def get_windows_if_list ( extended = False ) : """Returns windows interfaces through GetAdaptersAddresses . params : - extended : include anycast and multicast IPv6 ( default False )"""
# Should work on Windows XP + def _get_mac ( x ) : size = x [ "physical_address_length" ] if size != 6 : return "" data = bytearray ( x [ "physical_address" ] ) return str2mac ( bytes ( data ) [ : size ] ) def _get_ips ( x ) : unicast = x [ 'first_unicast_address' ] anycast = x [ 'first_...
def object ( self ) : """Return the changed object ."""
if self . type == EntryType . category : return self . category elif self . type == EntryType . event : return self . event elif self . type == EntryType . session : return self . session elif self . type == EntryType . contribution : return self . contribution elif self . type == EntryType . subcontrib...
def loadcell ( self , raw_files , cellpy_file = None , mass = None , summary_on_raw = False , summary_ir = True , summary_ocv = False , summary_end_v = True , only_summary = False , only_first = False , force_raw = False , use_cellpy_stat_file = None ) : """Loads data for given cells . Args : raw _ files ( list...
# This is a part of a dramatic API change . It will not be possible to # load more than one set of datasets ( i . e . one single cellpy - file or # several raw - files that will be automatically merged ) self . logger . info ( "started loadcell" ) if cellpy_file is None : similar = False elif force_raw : simila...
def transformNull ( requestContext , seriesList , default = 0 , referenceSeries = None ) : """Takes a metric or wildcard seriesList and replaces null values with the value specified by ` default ` . The value 0 used if not specified . The optional referenceSeries , if specified , is a metric or wildcard serie...
def transform ( v , d ) : if v is None : return d else : return v if referenceSeries : defaults = [ default if any ( v is not None for v in x ) else None for x in zip_longest ( * referenceSeries ) ] else : defaults = None for series in seriesList : if referenceSeries : series...
def validNormalizeAttributeValue ( self , elem , name , value ) : """Does the validation related extra step of the normalization of attribute values : If the declared value is not CDATA , then the XML processor must further process the normalized attribute value by discarding any leading and trailing space ...
if elem is None : elem__o = None else : elem__o = elem . _o ret = libxml2mod . xmlValidNormalizeAttributeValue ( self . _o , elem__o , name , value ) return ret
def date_to_delorean ( year , month , day ) : """Converts date arguments to a Delorean instance in UTC Args : year : int between 1 and 9999. month : int between 1 and 12. day : int between 1 and 31. Returns : Delorean instance in UTC of date ."""
return Delorean ( datetime = dt ( year , month , day ) , timezone = 'UTC' )
def _glob ( self , curdir , this , rest ) : """Handle glob flow . There are really only a couple of cases : - File name . - File name pattern ( magic ) . - Directory . - Directory name pattern ( magic ) . - Extra slashes ` / / / / ` . - ` globstar ` ` * * ` ."""
is_magic = this . is_magic dir_only = this . dir_only target = this . pattern is_globstar = this . is_globstar if is_magic and is_globstar : # Glob star directory ` * * ` . # Throw away multiple consecutive ` globstars ` # and acquire the pattern after the ` globstars ` if available . this = rest . pop ( 0 ) if res...
def price ( self , minimum : float = 10.00 , maximum : float = 1000.00 ) -> str : """Generate a random price . : param minimum : Max value of price . : param maximum : Min value of price . : return : Price ."""
price = self . random . uniform ( minimum , maximum , precision = 2 ) return '{0} {1}' . format ( price , self . currency_symbol ( ) )
def format_status ( self , width = None , label_width = None , progress_width = None , summary_width = None ) : """Generate the formatted status bar string ."""
if width is None : # pragma : no cover width = shutil . get_terminal_size ( ) [ 0 ] if label_width is None : label_width = len ( self . label ) if summary_width is None : summary_width = self . summary_width ( ) if progress_width is None : progress_width = width - label_width - summary_width - 2 if len ...
def insertValue ( self , pos , configValue , displayValue = None ) : """Will insert the configValue in the configValues and the displayValue in the displayValues list . If displayValue is None , the configValue is set in the displayValues as well"""
self . _configValues . insert ( pos , configValue ) self . _displayValues . insert ( pos , displayValue if displayValue is not None else configValue )
def start_poll ( args ) : """Starts a poll ."""
if args . type == 'privmsg' : return "We don't have secret ballots in this benevolent dictatorship!" if not args . msg : return "Polls need a question." ctrlchan = args . config [ 'core' ] [ 'ctrlchan' ] poll = Polls ( question = args . msg , submitter = args . nick ) args . session . add ( poll ) args . sessio...
def store_meta ( self , meta ) : "Inplace method that adds meta information to the meta dictionary"
if self . meta is None : self . meta = { } self . meta . update ( meta ) return self
def _parse_abbreviation ( uri_link ) : """Returns a team ' s abbreviation . A school or team ' s abbreviation is generally embedded in a URI link which contains other relative link information . For example , the URI for the New England Patriots for the 2017 season is " / teams / nwe / 2017 . htm " . This f...
abbr = re . sub ( r'/[0-9]+\..*htm.*' , '' , uri_link ( 'a' ) . attr ( 'href' ) ) abbr = re . sub ( r'/.*/schools/' , '' , abbr ) abbr = re . sub ( r'/teams/' , '' , abbr ) return abbr . upper ( )
def make_file_cm ( filename , mode = 'a' ) : '''Open a file for appending and yield the open filehandle . Close the filehandle after yielding it . This is useful for creating a context manager for logging the output of a ` Vagrant ` instance . filename : a path to a file mode : The mode in which to open the...
@ contextlib . contextmanager def cm ( ) : with open ( filename , mode = mode ) as fh : yield fh return cm
def global_variables ( self ) : """Return an iterator over this module ' s global variables . The iterator will yield a ValueRef for each global variable . Note that global variables don ' t include functions ( a function is a " global value " but not a " global variable " in LLVM parlance )"""
it = ffi . lib . LLVMPY_ModuleGlobalsIter ( self ) return _GlobalsIterator ( it , dict ( module = self ) )