signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def get_completed_tasks ( self ) : """Return a list of all completed tasks in this project . : return : A list of all completed tasks in this project . : rtype : list of : class : ` pytodoist . todoist . Task ` > > > from pytodoist import todoist > > > user = todoist . login ( ' john . doe @ gmail . com ' ,...
self . owner . sync ( ) tasks = [ ] offset = 0 while True : response = API . get_all_completed_tasks ( self . owner . api_token , limit = _PAGE_LIMIT , offset = offset , project_id = self . id ) _fail_if_contains_errors ( response ) response_json = response . json ( ) tasks_json = response_json [ 'items...
def _get_pod_by_metric_label ( self , labels ) : """: param labels : metric labels : iterable : return :"""
pod_uid = self . _get_pod_uid ( labels ) return get_pod_by_uid ( pod_uid , self . pod_list )
def _remove_outliers_from_hist ( hist : Hist , outliers_start_index : int , outliers_removal_axis : OutliersRemovalAxis ) -> None : """Remove outliers from a given histogram . Args : hist : Histogram to check for outliers . outliers _ start _ index : Index in the truth axis where outliers begin . outliers _...
# Use on TH1 , TH2 , and TH3 since we don ' t start removing immediately , but instead only after the limit if outliers_start_index > 0 : # logger . debug ( " Removing outliers " ) # Check for values above which they should be removed by translating the global index x = ctypes . c_int ( 0 ) y = ctypes . c_int (...
def qubit_pairs ( args , length ) : """Internally used ."""
if not isinstance ( args , tuple ) : raise ValueError ( "Control and target qubits pair(s) are required." ) if len ( args ) != 2 : raise ValueError ( "Control and target qubits pair(s) are required." ) controls = list ( slicing ( args [ 0 ] , length ) ) targets = list ( slicing ( args [ 1 ] , length ) ) if len ...
def get_share_stats ( self , share_name , timeout = None ) : '''Gets the approximate size of the data stored on the share , rounded up to the nearest gigabyte . Note that this value may not include all recently created or recently resized files . : param str share _ name : Name of existing share . : par...
_validate_not_none ( 'share_name' , share_name ) request = HTTPRequest ( ) request . method = 'GET' request . host_locations = self . _get_host_locations ( ) request . path = _get_path ( share_name ) request . query = { 'restype' : 'share' , 'comp' : 'stats' , 'timeout' : _int_to_str ( timeout ) , } return self . _perf...
def _is_suffix ( self , t ) : """Return true if t is a suffix ."""
return t not in NOT_SUFFIX and ( t . replace ( '.' , '' ) in SUFFIXES or t . replace ( '.' , '' ) in SUFFIXES_LOWER )
def _wait_and_except_if_failed ( self , event , timeout = None ) : """Combines waiting for event and call to ` _ except _ if _ failed ` . If timeout is not specified the configured sync _ timeout is used ."""
event . wait ( timeout or self . __sync_timeout ) self . _except_if_failed ( event )
def _sin ( x ) : '''sine with case for pi multiples'''
return 0. if np . isclose ( np . mod ( x , np . pi ) , 0. ) else np . sin ( x )
def finish_assessment_section ( self , assessment_section_id ) : """Indicates an assessment section is complete . Finished sections may or may not allow new or updated responses . arg : assessment _ section _ id ( osid . id . Id ) : ` ` Id ` ` of the ` ` AssessmentSection ` ` raise : IllegalState - ` ` has ...
if ( not self . has_assessment_section_begun ( assessment_section_id ) or self . is_assessment_section_over ( assessment_section_id ) ) : raise errors . IllegalState ( ) self . get_assessment_section ( assessment_section_id ) . finish ( )
def parse_args ( args = None ) : """Parses arguments , returns ( options , args ) ."""
import sys from argparse import ArgumentParser from path_helpers import path if args is None : args = sys . argv parser = ArgumentParser ( description = 'Example app for drawing shapes from ' 'dataframe, scaled to fit to GTK canvas while ' 'preserving aspect ratio (a.k.a., aspect fit).' ) parser . add_argument ( 's...
def get_qualifier ( self ) : """Return resource name qualifier for the current configuration . for example * ` ldpi - v4 ` * ` hdpi - v4 ` All possible qualifiers are listed in table 2 of https : / / developer . android . com / guide / topics / resources / providing - resources FIXME : This name might n...
res = [ ] mcc = self . imsi & 0xFFFF mnc = ( self . imsi & 0xFFFF0000 ) >> 16 if mcc != 0 : res . append ( "mcc%d" % mcc ) if mnc != 0 : res . append ( "mnc%d" % mnc ) if self . locale != 0 : res . append ( self . get_language_and_region ( ) ) screenLayout = self . screenConfig & 0xff if ( screenLayout & co...
def get_dimension ( data ) : """Get dimension of the data passed by argument independently if it ' s an arrays or dictionaries"""
result = [ 0 , 0 ] if isinstance ( data , list ) : result = get_dimension_array ( data ) elif isinstance ( data , dict ) : result = get_dimension_dict ( data ) return result
def create_analysis ( name , kernel , src_dir , scaffold_name ) : """Create analysis files ."""
# analysis folder folder = os . path . join ( os . getcwd ( ) , 'analyses' , name ) if not os . path . exists ( folder ) : os . makedirs ( folder ) else : log . warning ( 'Analysis folder {} already exists.' . format ( folder ) ) # copy all other files for f in os . listdir ( src_dir ) : if f in ( '__pycach...
def resume ( self , trigger_duration = 0 ) : """Resumes pulse capture after an optional trigger pulse ."""
if trigger_duration != 0 : self . _mq . send ( "t%d" % trigger_duration , True , type = 1 ) else : self . _mq . send ( "r" , True , type = 1 ) self . _paused = False
def terminal_cfg_line_sessionid ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) terminal_cfg = ET . SubElement ( config , "terminal-cfg" , xmlns = "urn:brocade.com:mgmt:brocade-terminal" ) line = ET . SubElement ( terminal_cfg , "line" ) sessionid = ET . SubElement ( line , "sessionid" ) sessionid . text = kwargs . pop ( 'sessionid' ) callback = kwargs . pop ( 'c...
def init ( context , reset , force ) : """Setup the database ."""
store = Store ( context . obj [ 'database' ] , context . obj [ 'root' ] ) existing_tables = store . engine . table_names ( ) if force or reset : if existing_tables and not force : message = f"Delete existing tables? [{', '.join(existing_tables)}]" click . confirm ( click . style ( message , fg = 'ye...
def compute_support ( self , x , y ) : # type : ( np . ndarray , np . ndarray ) - > np . ndarray """Calculate the support for the rules . The support of each rule is a list of ` n _ classes ` integers : [ l1 , l2 , . . . ] . Each integer represents the number of data of label i that is caught by this rule : p...
caught_matrix = self . caught_matrix ( x ) if np . sum ( caught_matrix . astype ( np . int ) ) != x . shape [ 0 ] : raise RuntimeError ( "The sum of the support should equal to the number of instances!" ) support_summary = np . zeros ( ( self . n_rules , self . n_classes ) , dtype = np . int ) for i , support in en...
def disassemble_string ( self , lpAddress , code ) : """Disassemble instructions from a block of binary code . @ type lpAddress : int @ param lpAddress : Memory address where the code was read from . @ type code : str @ param code : Binary code to disassemble . @ rtype : list of tuple ( long , int , str ,...
aProcess = self . get_process ( ) return aProcess . disassemble_string ( lpAddress , code )
def hide_elements ( self , selector , by = By . CSS_SELECTOR ) : """Hide all elements on the page that match the selector ."""
selector , by = self . __recalculate_selector ( selector , by ) selector = self . convert_to_css_selector ( selector , by = by ) hide_script = """jQuery('%s').hide()""" % selector self . safe_execute_script ( hide_script )
def diff ( var , key ) : '''calculate differences between values'''
global last_diff ret = 0 if not key in last_diff : last_diff [ key ] = var return 0 ret = var - last_diff [ key ] last_diff [ key ] = var return ret
def isfib ( number ) : """Check if a number is in the Fibonacci sequence . : type number : integer : param number : Number to check"""
num1 = 1 num2 = 1 while True : if num2 < number : tempnum = num2 num2 += num1 num1 = tempnum elif num2 == number : return True else : return False
def _expectation ( p , kern , feat , none2 , none3 , nghp = None ) : r"""Compute the expectation : < \ Sum _ i Ki _ { X , Z } > _ p ( X ) - \ Sum _ i Ki _ { . , . } : : Sum kernel : return : NxM"""
return functools . reduce ( tf . add , [ expectation ( p , ( k , feat ) , nghp = nghp ) for k in kern . kernels ] )
def focusOutEvent ( self , event ) : """Reimplement Qt method to send focus change notification"""
self . focus_changed . emit ( ) return super ( ControlWidget , self ) . focusOutEvent ( event )
def prompt_for_value ( self , ctx ) : """This is an alternative flow that can be activated in the full value processing if a value does not exist . It will prompt the user until a valid value exists and then returns the processed value as result ."""
# Calculate the default before prompting anything to be stable . default = self . get_default ( ctx ) if isinstance ( default , AutoDefault ) : return self . type_cast_value ( ctx , default . value ) # If this is a prompt for a flag we need to handle this # differently . if self . is_bool_flag : return confirm ...
def _prepare_default_dtype ( src_array , dtype ) : """Prepare the value of dtype if ` dtype ` is None . If ` src _ array ` is an NDArray , numpy . ndarray or scipy . sparse . csr . csr _ matrix , return src _ array . dtype . float32 is returned otherwise ."""
if dtype is None : if isinstance ( src_array , ( NDArray , np . ndarray ) ) : dtype = src_array . dtype elif spsp and isinstance ( src_array , spsp . csr . csr_matrix ) : dtype = src_array . dtype else : dtype = mx_real_t return dtype
def prelu ( inp , base_axis = 1 , shared = True , fix_parameters = False ) : """Parametrized Rectified Linear Unit function defined as . . math : : y _ i = \ max ( 0 , x _ i ) + w _ i \ min ( 0 , - x _ i ) where negative slope : math : ` w ` is learned and can vary across channels ( an axis specified with b...
shape = tuple ( ) if shared else ( inp . shape [ base_axis ] , ) w = get_parameter_or_create ( "slope" , shape , ConstantInitializer ( - 1 ) , True , not fix_parameters ) return F . prelu ( inp , w , base_axis )
def consume ( self , queue_name , prefetch = 1 , timeout = 5000 ) : """Create a new consumer for a queue . Parameters : queue _ name ( str ) : The queue to consume . prefetch ( int ) : The number of messages to prefetch . timeout ( int ) : The idle timeout in milliseconds . Returns : Consumer : A consum...
return _RedisConsumer ( self , queue_name , prefetch , timeout )
def cli ( obj ) : """Display client config downloaded from API server ."""
for k , v in obj . items ( ) : if isinstance ( v , list ) : v = ', ' . join ( v ) click . echo ( '{:20}: {}' . format ( k , v ) )
def _replace_envvar ( s , _ ) : """env : KEY or env : KEY : DEFAULT"""
e = s . split ( ":" ) if len ( e ) > 3 or len ( e ) == 1 or e [ 0 ] != "env" : raise ValueError ( ) elif len ( e ) == 2 : # Note : this can / should raise a KeyError ( according to spec ) . return os . environ [ e [ 1 ] ] else : # len ( e ) = = 3 return os . environ . get ( e [ 1 ] , e [ 2 ] )
def fake_decimal ( self , field_name ) : """Validate if the field has a ` max _ digits ` and ` decimal _ places ` And generating the unique decimal number . Usage : faker . fake _ decimal ( ' field _ name ' ) Example : 10.7 , 13041.00 , 200.000.000"""
return self . djipsum_fields ( ) . randomDecimalField ( self . model_class ( ) , field_name = field_name )
def transform_deprecated_concepts ( rdf , cs ) : """Transform deprecated concepts so they are in their own concept scheme ."""
deprecated_concepts = [ ] for conc in rdf . subjects ( RDF . type , SKOSEXT . DeprecatedConcept ) : rdf . add ( ( conc , RDF . type , SKOS . Concept ) ) rdf . add ( ( conc , OWL . deprecated , Literal ( "true" , datatype = XSD . boolean ) ) ) deprecated_concepts . append ( conc ) if len ( deprecated_concept...
def get ( self , request ) : """Called after the user is redirected back to our application . Tries to : - Complete the OAuth / OAuth2 flow - Redirect the user to another view that deals with login , connecting or user creation ."""
try : client = request . session [ self . get_client ( ) . get_session_key ( ) ] logger . debug ( "API returned: %s" , request . GET ) client . complete ( dict ( request . GET . items ( ) ) ) request . session [ self . get_client ( ) . get_session_key ( ) ] = client return HttpResponseRedirect ( sel...
def get_page_artid_for_publication_info ( publication_info , separator ) : """Return the page range or the article id of a publication _ info entry . Args : publication _ info ( dict ) : a publication _ info field entry of a record separator ( basestring ) : optional page range symbol , defaults to a single d...
if 'artid' in publication_info : return publication_info [ 'artid' ] elif 'page_start' in publication_info and 'page_end' in publication_info : page_start = publication_info [ 'page_start' ] page_end = publication_info [ 'page_end' ] return text_type ( '{}{}{}' ) . format ( page_start , text_type ( sepa...
def wrap_onspace ( self , text ) : '''When the text inside the column is longer then the width , will split by space and continue on the next line .'''
def _truncate ( line , word ) : return '{line}{part}{word}' . format ( line = line , part = ' \n' [ ( len ( line [ line . rfind ( '\n' ) + 1 : ] ) + len ( word . split ( '\n' , 1 ) [ 0 ] ) >= self . width ) ] , word = word ) return reduce ( _truncate , text . split ( ' ' ) )
def _num_values ( self ) : """Generate a valid num _ values string based off min _ values and max _ values : return : string"""
# Add min _ values to string num_values = str ( self . min_values ) if self . min_values else "0" # Handle infinite max _ values or finite max _ values if self . max_values is None or self . max_values == float ( "inf" ) : num_values += "+" else : num_values += ".." + str ( self . max_values ) # Return the num ...
def insert_arguments_into_sql_query ( compilation_result , arguments ) : """Insert the arguments into the compiled SQL query to form a complete query . Args : compilation _ result : CompilationResult , compilation result from the GraphQL compiler . arguments : Dict [ str , Any ] , parameter name - > value , f...
if compilation_result . language != SQL_LANGUAGE : raise AssertionError ( u'Unexpected query output language: {}' . format ( compilation_result ) ) base_query = compilation_result . query return base_query . params ( ** arguments )
def query_user_page ( url , retry = 10 ) : """Returns the scraped user data from a twitter user page . : param url : The URL to get the twitter user info from ( url contains the user page ) : param retry : Number of retries if something goes wrong . : return : Returns the scraped user data from a twitter user...
try : response = requests . get ( url , headers = HEADER ) html = response . text or '' user = User ( ) user_info = user . from_html ( html ) if not user_info : return None return user_info except requests . exceptions . HTTPError as e : logger . exception ( 'HTTPError {} while reque...
def merge ( self , img ) : """Use the provided image as background for the current * img * image , that is if the current image has missing data ."""
raise NotImplementedError ( "This method has not be implemented for " "xarray support." ) if self . is_empty ( ) : raise ValueError ( "Cannot merge an empty image." ) if self . mode != img . mode : raise ValueError ( "Cannot merge image of different modes." ) selfmask = self . channels [ 0 ] . mask for chn in s...
def export ( self , output , tight = False , concat = True , close_pdf = None , use_time = False , ** kwargs ) : """Exports the figures of the project to one or more image files Parameters output : str , iterable or matplotlib . backends . backend _ pdf . PdfPages if string or list of strings , those define t...
from matplotlib . backends . backend_pdf import PdfPages if tight : kwargs [ 'bbox_inches' ] = 'tight' if use_time : def insert_time ( s , attrs ) : time = attrs [ tname ] try : # assume a valid datetime . datetime instance s = pd . to_datetime ( time ) . strftime ( s ) excep...
def uninstall ( self ) : """Delete code inside NApp directory , if existent ."""
if self . is_installed ( ) : installed = self . installed_dir ( ) if installed . is_symlink ( ) : installed . unlink ( ) else : shutil . rmtree ( str ( installed ) )
def notification_sm_changed ( self , model , prop_name , info ) : """Remove references to non - existing state machines"""
for state_machine_id in list ( self . _expansion_state . keys ( ) ) : if state_machine_id not in self . model . state_machines : del self . _expansion_state [ state_machine_id ]
def read_single_knmi_file ( filename ) : """reads a single file of KNMI ' s meteorological time series data availability : www . knmi . nl / nederland - nu / klimatologie / uurgegevens Args : filename : the file to be opened Returns : pandas data frame including time series"""
hourly_data_obs_raw = pd . read_csv ( filename , parse_dates = [ [ 'YYYYMMDD' , 'HH' ] ] , date_parser = lambda yyyymmdd , hh : pd . datetime ( int ( str ( yyyymmdd ) [ 0 : 4 ] ) , int ( str ( yyyymmdd ) [ 4 : 6 ] ) , int ( str ( yyyymmdd ) [ 6 : 8 ] ) , int ( hh ) - 1 ) , skiprows = 31 , skipinitialspace = True , na_v...
def get_int ( self , key , default = None ) : """Same as : meth : ` dict . get ` , but the value is converted to an int ."""
value = self . get ( key , default ) return None if value is None else int ( value )
def stop_instance ( self , instance_id ) : """Stops the instance gracefully . : param str instance _ id : instance identifier"""
instance = self . _load_instance ( instance_id ) instance . delete ( ) del self . _instances [ instance_id ]
def concat ( self , axis , other , ** kwargs ) : """Concatenates two objects together . Args : axis : The axis index object to join ( 0 for columns , 1 for index ) . other : The other _ index to concat with . Returns : Concatenated objects ."""
return self . _append_list_of_managers ( other , axis , ** kwargs )
def reward_bonus ( self , assignment_id , amount , reason ) : """Reward the Turker for a specified assignment with a bonus ."""
try : return self . mturkservice . grant_bonus ( assignment_id , amount , reason ) except MTurkServiceException as ex : logger . exception ( str ( ex ) )
def String ( self , off ) : """String gets a string from data stored inside the flatbuffer ."""
N . enforce_number ( off , N . UOffsetTFlags ) off += encode . Get ( N . UOffsetTFlags . packer_type , self . Bytes , off ) start = off + N . UOffsetTFlags . bytewidth length = encode . Get ( N . UOffsetTFlags . packer_type , self . Bytes , off ) return bytes ( self . Bytes [ start : start + length ] )
def cluster ( self , input_fasta_list , reverse_pipe ) : '''cluster - Clusters reads at 100 % identity level and writes them to file . Resets the input _ fasta variable as the FASTA file containing the clusters . Parameters input _ fasta _ list : list list of strings , each a path to input fasta files to ...
output_fasta_list = [ ] for input_fasta in input_fasta_list : output_path = input_fasta . replace ( '_hits.aln.fa' , '_clustered.fa' ) cluster_dict = { } logging . debug ( 'Clustering reads' ) if os . path . exists ( input_fasta ) : reads = self . seqio . read_fasta_file ( input_fasta ) ...
def _convert_xml_to_ranges ( response ) : '''< ? xml version = " 1.0 " encoding = " utf - 8 " ? > < Ranges > < Range > < Start > Start Byte < / Start > < End > End Byte < / End > < / Range > < Range > < Start > Start Byte < / Start > < End > End Byte < / End > < / Range > < / Ranges >'''
if response is None or response . body is None : return None ranges = list ( ) ranges_element = ETree . fromstring ( response . body ) for range_element in ranges_element . findall ( 'Range' ) : # Parse range range = FileRange ( int ( range_element . findtext ( 'Start' ) ) , int ( range_element . findtext ( 'En...
def _DownloadUrl ( self , url , dest_dir ) : """Download a script from a given URL . Args : url : string , the URL to download . dest _ dir : string , the path to a directory for storing metadata scripts . Returns : string , the path to the file storing the metadata script ."""
dest_file = tempfile . NamedTemporaryFile ( dir = dest_dir , delete = False ) dest_file . close ( ) dest = dest_file . name self . logger . info ( 'Downloading url from %s to %s.' , url , dest ) try : urlretrieve . urlretrieve ( url , dest ) return dest except ( httpclient . HTTPException , socket . error , url...
def _to_ctfile_property_block ( self ) : """Create ctab properties block in ` CTfile ` format from atom - specific properties . : return : Ctab property block . : rtype : : py : class : ` str `"""
ctab_properties_data = defaultdict ( list ) for atom in self . atoms : for ctab_property_key , ctab_property_value in atom . _ctab_property_data . items ( ) : ctab_properties_data [ ctab_property_key ] . append ( OrderedDict ( zip ( self . ctab_conf [ self . version ] [ ctab_property_key ] [ 'values' ] , [ ...
def on_open_input_tool_clicked ( self ) : """Autoconnect slot activated when open input tool button is clicked ."""
input_path = self . input_path . text ( ) if not input_path : input_path = os . path . expanduser ( '~' ) # noinspection PyCallByClass , PyTypeChecker filename , __ = QFileDialog . getOpenFileName ( self , tr ( 'Input file' ) , input_path , tr ( 'Raw grid file (*.xml)' ) ) if filename : self . input_path . setT...
def input ( filename , ** kwargs ) : """Input file URL ( ffmpeg ` ` - i ` ` option ) Any supplied kwargs are passed to ffmpeg verbatim ( e . g . ` ` t = 20 ` ` , ` ` f = ' mp4 ' ` ` , ` ` acodec = ' pcm ' ` ` , etc . ) . To tell ffmpeg to read from stdin , use ` ` pipe : ` ` as the filename . Official docum...
kwargs [ 'filename' ] = filename fmt = kwargs . pop ( 'f' , None ) if fmt : if 'format' in kwargs : raise ValueError ( "Can't specify both `format` and `f` kwargs" ) kwargs [ 'format' ] = fmt return InputNode ( input . __name__ , kwargs = kwargs ) . stream ( )
def notify_user ( self , msg , level = "info" , rate_limit = 5 , title = None , icon = None ) : """Send a notification to the user . level must be ' info ' , ' error ' or ' warning ' . rate _ limit is the time period in seconds during which this message should not be repeated . icon must be an icon path or ...
module_name = self . _module . module_full_name if isinstance ( msg , Composite ) : msg = msg . text ( ) if title is None : title = "py3status: {}" . format ( module_name ) elif isinstance ( title , Composite ) : title = title . text ( ) # force unicode for python2 str if self . _is_python_2 : if isinst...
def toggle ( self , event = None ) : """Toggle value between Yes and No"""
if self . choice . get ( ) == "yes" : self . rbno . select ( ) else : self . rbyes . select ( ) self . widgetEdited ( )
def sort_key ( val ) : """Sort key for sorting keys in grevlex order ."""
return numpy . sum ( ( max ( val ) + 1 ) ** numpy . arange ( len ( val ) - 1 , - 1 , - 1 ) * val )
def get_context_dict ( self ) : """return a context dict of the desired state"""
context_dict = { } for s in self . sections ( ) : for k , v in self . manifest . items ( s ) : context_dict [ "%s:%s" % ( s , k ) ] = v for k , v in self . inputs . values ( ) . items ( ) : context_dict [ "config:{0}" . format ( k ) ] = v context_dict . update ( self . additional_context_variables . ite...
def _get ( self , name , interval , config , timestamp , ** kws ) : '''Get the interval .'''
i_bucket = config [ 'i_calc' ] . to_bucket ( timestamp ) fetch = kws . get ( 'fetch' ) process_row = kws . get ( 'process_row' ) or self . _process_row rval = OrderedDict ( ) if fetch : data = fetch ( self . _client . connect ( ) , self . _table , name , interval , i_bucket ) else : data = self . _type_get ( na...
def _del_cable_from_equipment_changes ( network , line ) : """Delete cable from the equipment changes if existing This is needed if a cable was already added to network . results . equipment _ changes but another node is connected later to this cable . Therefore , the cable needs to be split which changes the...
if line in network . results . equipment_changes . index : network . results . equipment_changes = network . results . equipment_changes . drop ( line )
def _get_combined_index ( indexes , intersect = False , sort = False ) : """Return the union or intersection of indexes . Parameters indexes : list of Index or list objects When intersect = True , do not accept list of lists . intersect : bool , default False If True , calculate the intersection between i...
# TODO : handle index names ! indexes = _get_distinct_objs ( indexes ) if len ( indexes ) == 0 : index = Index ( [ ] ) elif len ( indexes ) == 1 : index = indexes [ 0 ] elif intersect : index = indexes [ 0 ] for other in indexes [ 1 : ] : index = index . intersection ( other ) else : index =...
def astype ( self , dtype , copy = True ) : """Return a copy of the array after casting to a specified type . Parameters dtype : numpy . dtype or str The type of the returned array . copy : bool Default ` True ` . By default , astype always returns a newly allocated ndarray on the same context . If this...
if not copy and np . dtype ( dtype ) == self . dtype : return self res = zeros ( shape = self . shape , ctx = self . context , dtype = dtype , stype = self . stype ) self . copyto ( res ) return res
def add ( self , key , value , time = 0 , compress_level = - 1 ) : """Add a key / value to server ony if it does not exist . : param key : Key ' s name : type key : six . string _ types : param value : A value to be stored on server . : type value : object : param time : Time in seconds that your key will...
server = self . _get_server ( key ) return server . add ( key , value , time , compress_level )
def envs ( self , ignore_cache = False ) : '''Return a list of refs that can be used as environments'''
if not ignore_cache : cache_match = salt . fileserver . check_env_cache ( self . opts , self . env_cache ) if cache_match is not None : return cache_match ret = set ( ) for repo in self . remotes : repo_envs = repo . envs ( ) for env_list in six . itervalues ( repo . saltenv_revmap ) : r...
def lookup_instance ( name : str , instance_type : str = '' , image_name : str = '' , states : tuple = ( 'running' , 'stopped' , 'initializing' ) ) : """Looks up AWS instance for given instance name , like simple . worker . If no instance found in current AWS environment , returns None ."""
ec2 = get_ec2_resource ( ) instances = ec2 . instances . filter ( Filters = [ { 'Name' : 'instance-state-name' , 'Values' : states } ] ) prefix = get_prefix ( ) username = get_username ( ) # look for an existing instance matching job , ignore instances launched # by different user or under different resource name resul...
def spline_base2d ( width , height , nr_knots_x = 20.0 , nr_knots_y = 20.0 , spline_order = 5 , marginal_x = None , marginal_y = None ) : """Computes a set of 2D spline basis functions . The basis functions cover the entire space in height * width and can for example be used to create fixation density maps . ...
if not ( nr_knots_x < width and nr_knots_y < height ) : raise RuntimeError ( "Too many knots for size of the base" ) if marginal_x is None : knots_x = augknt ( np . linspace ( 0 , width + 1 , nr_knots_x ) , spline_order ) else : knots_x = knots_from_marginal ( marginal_x , nr_knots_x , spline_order ) if mar...
def get_constantvalue ( self ) : """the constant pool index for this field , or None if this is not a contant field reference : http : / / docs . oracle . com / javase / specs / jvms / se7 / html / jvms - 4 . html # jvms - 4.7.2"""
# noqa buff = self . get_attribute ( "ConstantValue" ) if buff is None : return None with unpack ( buff ) as up : ( cval_ref , ) = up . unpack_struct ( _H ) return cval_ref
def data_check ( self , participant ) : """Make sure each trial contains exactly one chosen info ."""
infos = participant . infos ( ) return len ( [ info for info in infos if info . chosen ] ) * 2 == len ( infos )
def cron_room_line ( self ) : """This method is for scheduler every 1min scheduler will call this method and check Status of room is occupied or available @ param self : The object pointer @ return : update status of hotel room reservation line"""
reservation_line_obj = self . env [ 'hotel.room.reservation.line' ] folio_room_line_obj = self . env [ 'folio.room.line' ] now = datetime . now ( ) curr_date = now . strftime ( dt ) for room in self . search ( [ ] ) : reserv_line_ids = [ reservation_line . id for reservation_line in room . room_reservation_line_ids...
def build_data_table ( energy , flux , flux_error = None , flux_error_lo = None , flux_error_hi = None , energy_width = None , energy_lo = None , energy_hi = None , ul = None , cl = None , ) : """Read data into data dict . Parameters energy : : class : ` ~ astropy . units . Quantity ` array instance Observed ...
table = QTable ( ) if cl is not None : cl = validate_scalar ( "cl" , cl ) table . meta [ "keywords" ] = { "cl" : { "value" : cl } } table [ "energy" ] = energy if energy_width is not None : table [ "energy_width" ] = energy_width elif energy_lo is not None and energy_hi is not None : table [ "energy_lo"...
def eotvos ( target , k , temperature = 'pore.temperature' , critical_temperature = 'pore.critical_temperature' , molar_density = 'pore.molar_density' ) : r"""Missing description Parameters target : OpenPNM Object The object for which these values are being calculated . This controls the length of the calcu...
Tc = target [ critical_temperature ] T = target [ temperature ] Vm = 1 / target [ molar_density ] value = k * ( Tc - T ) / ( Vm ** ( 2 / 3 ) ) return value
def search ( self , query , indices = None , doc_types = None , model = None , scan = False , headers = None , ** query_params ) : """Execute a search against one or more indices to get the resultset . ` query ` must be a Search object , a Query object , or a custom dictionary of search parameters using the que...
if isinstance ( query , Search ) : search = query elif isinstance ( query , ( Query , dict ) ) : search = Search ( query ) else : raise InvalidQuery ( "search() must be supplied with a Search or Query object, or a dict" ) if scan : query_params . setdefault ( "search_type" , "scan" ) query_params . ...
def segment ( self , document ) : """document : list [ str ] return list [ int ] , i - th element denotes whether exists a boundary right before paragraph i ( 0 indexed )"""
# ensure document is not empty and every element is an instance of str assert ( len ( document ) > 0 and len ( [ d for d in document if not isinstance ( d , str ) ] ) == 0 ) # step 1 , do preprocessing n = len ( document ) self . window = max ( min ( self . window , n / 3 ) , 1 ) cnts = [ Counter ( self . tokenizer . t...
def child_cardinality ( self , child ) : """Return the cardinality of a child element : param child : The name of the child element : return : The cardinality as a 2 - tuple ( min , max ) . The max value is either a number or the string " unbounded " . The min value is always a number ."""
for prop , klassdef in self . c_children . values ( ) : if child == prop : if isinstance ( klassdef , list ) : try : _min = self . c_cardinality [ "min" ] except KeyError : _min = 1 try : _max = self . c_cardinality [ "max" ...
def readCorpus ( location ) : """Returns the contents of a file or a group of files as a string . : param location : . txt file or a directory to read files from . : type location : str . : returns : A string of all contents joined together . : rtype : str . . . note : : This function takes a ` ` locati...
print ( "Reading corpus from file(s)..." ) corpus = '' if '.txt' in location : with open ( location ) as fp : corpus = fp . read ( ) else : dirFiles = listdir ( location ) nFiles = len ( dirFiles ) for f in tqdm ( dirFiles ) : with open ( location + "/" + f ) as fp : corpus +...
def _UpdateYear ( self , mediator , month ) : """Updates the year to use for events , based on last observed month . Args : mediator ( ParserMediator ) : mediates the interactions between parsers and other components , such as storage and abort signals . month ( int ) : month observed by the parser , where ...
if not self . _year_use : self . _year_use = mediator . GetEstimatedYear ( ) if not self . _maximum_year : self . _maximum_year = mediator . GetLatestYear ( ) if not self . _last_month : self . _last_month = month return # Some syslog daemons allow out - of - order sequences , so allow some leeway # to ...
def unbind ( meta , name = None , dynamo_name = None ) -> None : """Unconditionally remove any columns or indexes bound to the given name or dynamo _ name . . . code - block : : python import bloop . models class User ( BaseModel ) : id = Column ( String , hash _ key = True ) email = Column ( String , dyn...
if name is not None : columns = { x for x in meta . columns if x . name == name } indexes = { x for x in meta . indexes if x . name == name } elif dynamo_name is not None : columns = { x for x in meta . columns if x . dynamo_name == dynamo_name } indexes = { x for x in meta . indexes if x . dynamo_name ...
async def create ( cls , node : Union [ Node , str ] , interface_type : InterfaceType = InterfaceType . PHYSICAL , * , name : str = None , mac_address : str = None , tags : Iterable [ str ] = None , vlan : Union [ Vlan , int ] = None , parent : Union [ Interface , int ] = None , parents : Iterable [ Union [ Interface ,...
params = { } if isinstance ( node , str ) : params [ 'system_id' ] = node elif isinstance ( node , Node ) : params [ 'system_id' ] = node . system_id else : raise TypeError ( 'node must be a Node or str, not %s' % ( type ( node ) . __name__ ) ) if name is not None : params [ 'name' ] = name if tags is n...
def evaluate ( self , genomes , config ) : """Evaluate the genomes"""
if not self . working : self . start ( ) p = 0 for genome_id , genome in genomes : p += 1 self . inqueue . put ( ( genome_id , genome , config ) ) # assign the fitness back to each genome while p > 0 : p -= 1 ignored_genome_id , genome , fitness = self . outqueue . get ( ) genome . fitness = fit...
def configure_createfor ( self , ns , definition ) : """Register a create - for relation endpoint . The definition ' s func should be a create function , which must : - accept kwargs for the new instance creation parameters - return the created instance : param ns : the namespace : param definition : the ...
@ self . add_route ( ns . relation_path , Operation . CreateFor , ns ) @ request ( definition . request_schema ) @ response ( definition . response_schema ) @ wraps ( definition . func ) def create ( ** path_data ) : request_data = load_request_data ( definition . request_schema ) response_data = require_respon...
def find_user ( session , username ) : """Find user by name - returns user ID ."""
resp = _make_request ( session , FIND_USER_URL , username ) if not resp : raise VooblyError ( 'user not found' ) try : return int ( resp [ 0 ] [ 'uid' ] ) except ValueError : raise VooblyError ( 'user not found' )
def _complex_dtype ( dtype ) : """Patched version of : func : ` sporco . linalg . complex _ dtype ` ."""
dt = cp . dtype ( dtype ) if dt == cp . dtype ( 'float128' ) : return cp . dtype ( 'complex256' ) elif dt == cp . dtype ( 'float64' ) : return cp . dtype ( 'complex128' ) else : return cp . dtype ( 'complex64' )
def set_pre_handler ( self , handler ) : '''pre handler push return : ret _ error or ret _ ok'''
set_flag = False for protoc in self . _pre_handler_table : if isinstance ( handler , self . _pre_handler_table [ protoc ] [ "type" ] ) : self . _pre_handler_table [ protoc ] [ "obj" ] = handler return RET_OK if set_flag is False : return RET_ERROR
def resolve ( self , word , mandatory = True ) : '''composite mapping given f ( x ) and g ( x ) here : localtt & globaltt respectivly return g ( f ( x ) ) | g ( x ) | | f ( x ) | x in order of preference returns x on fall through if finding a mapping is not mandatory ( by default finding is mandatory ) . ...
assert word is not None # we may not agree with a remote sources use of our global term we have # this provides oppertunity for us to overide if word in self . localtt : label = self . localtt [ word ] if label in self . globaltt : term_id = self . globaltt [ label ] else : logging . info ( ...
def _set_gigabitethernet ( self , v , load = False ) : """Setter method for gigabitethernet , mapped from YANG variable / interface / gigabitethernet ( list ) If this variable is read - only ( config : false ) in the source YANG file , then _ set _ gigabitethernet is considered as a private method . Backends ...
if hasattr ( v , "_utype" ) : v = v . _utype ( v ) try : t = YANGDynClass ( v , base = YANGListType ( "name" , gigabitethernet . gigabitethernet , yang_name = "gigabitethernet" , rest_name = "GigabitEthernet" , parent = self , is_container = 'list' , user_ordered = True , path_helper = self . _path_helper , yan...
def compress_gz ( fname ) : """Compress the file with the given name and delete the uncompressed file . The compressed filename is simply the input filename with ' . gz ' appended . Arguments fname : str Name of the file to compress and delete . Returns comp _ fname : str Name of the compressed file p...
import shutil import gzip comp_fname = fname + '.gz' with codecs . open ( fname , 'rb' ) as f_in , gzip . open ( comp_fname , 'wb' ) as f_out : shutil . copyfileobj ( f_in , f_out ) os . remove ( fname ) return comp_fname
def get_mean_and_stddevs ( self , sites , rup , dists , imt , stddev_types ) : """See : meth : ` superclass method < . base . GroundShakingIntensityModel . get _ mean _ and _ stddevs > ` for spec of input and result values ."""
assert all ( stddev_type in self . DEFINED_FOR_STANDARD_DEVIATION_TYPES for stddev_type in stddev_types ) F , HW = self . _get_fault_type_hanging_wall ( rup . rake ) S = self . _get_site_class ( sites . vs30 ) # compute pga on rock ( used then to compute site amplification factor ) C = self . COEFFS [ PGA ( ) ] pga_roc...
def parse_docstring ( docstring ) : '''Parse a docstring into its parts . Currently only parses dependencies , can be extended to parse whatever is needed . Parses into a dictionary : ' full ' : full docstring , ' deps ' : list of dependencies ( empty list if none )'''
# First try with regex search for : depends : ret = { 'full' : docstring } regex = r'([ \t]*):depends:[ \t]+- (\w+)[^\n]*\n(\1[ \t]+- (\w+)[^\n]*\n)*' match = re . search ( regex , docstring , re . M ) if match : deps = [ ] regex = r'- (\w+)' for line in match . group ( 0 ) . strip ( ) . splitlines ( ) : ...
def open_bag ( dir_bag ) : """Open Bag at the given path : param str dir _ bag : Path to Bag : return obj : Bag"""
logger_bagit . info ( "enter open_bag" ) try : bag = bagit . Bag ( dir_bag ) logger_bagit . info ( "opened bag" ) return bag except Exception as e : print ( "Error: failed to open bagit bag" ) logger_bagit . debug ( "failed to open bag, {}" . format ( e ) ) return None
def setup ( channel , direction , initial = None , pull_up_down = None ) : """You need to set up every channel you are using as an input or an output . : param channel : the channel based on the numbering system you have specified ( : py : attr : ` GPIO . BOARD ` , : py : attr : ` GPIO . BCM ` or : py : attr : ...
if _mode is None : raise RuntimeError ( "Mode has not been set" ) if pull_up_down is not None : if _gpio_warnings : warnings . warn ( "Pull up/down setting are not (yet) fully supported, continuing anyway. Use GPIO.setwarnings(False) to disable warnings." , stacklevel = 2 ) if isinstance ( channel , lis...
def delete_state ( self , state ) : """Delete a specified state from the LRS : param state : State document to be deleted : type state : : class : ` tincan . documents . state _ document . StateDocument ` : return : LRS Response object : rtype : : class : ` tincan . lrs _ response . LRSResponse `"""
return self . _delete_state ( activity = state . activity , agent = state . agent , state_id = state . id , etag = state . etag )
def gym_space_spec ( gym_space ) : """Returns a reading spec of a gym space . NOTE : Only implemented currently for Box and Discrete . Args : gym _ space : instance of gym . spaces whose spec we want . Returns : Reading spec for that space . Raises : NotImplementedError : For spaces whose reading spec...
# First try to determine the type . try : tf_dtype = tf . as_dtype ( gym_space . dtype ) except TypeError as e : tf . logging . error ( "Cannot convert space's type [%s] to tf.dtype" , gym_space . dtype ) raise e # Now hand it over to the specialized functions . if isinstance ( gym_space , Box ) : retur...
def carmichael ( ) -> Iterator [ int ] : """Composite numbers n such that a ^ ( n - 1 ) = = 1 ( mod n ) for every a coprime to n . https : / / oeis . org / A002997"""
for m in composite ( ) : for a in range ( 2 , m ) : if pow ( a , m , m ) != a : break else : yield m
def update_security_group ( self , sec_grp , name = None , desc = None ) : '''Updates a security group'''
sec_grp_id = self . _find_security_group_id ( sec_grp ) body = { 'security_group' : { } } if name : body [ 'security_group' ] [ 'name' ] = name if desc : body [ 'security_group' ] [ 'description' ] = desc return self . network_conn . update_security_group ( sec_grp_id , body = body )
def load ( self , table : str ) : """Set the main dataframe from a table ' s data : param table : table name : type table : str : example : ` ` ds . load ( " mytable " ) ` `"""
if self . _check_db ( ) is False : return if table not in self . db . tables : self . warning ( "The table " + table + " does not exists" ) return try : self . start ( "Loading data from table " + table ) res = self . db [ table ] . all ( ) self . df = pd . DataFrame ( list ( res ) ) self . ...
def Create ( group , parent = None , description = '' , alias = None , location = None ) : """Creates a new group https : / / t3n . zendesk . com / entries / 20979861 - Create - Hardware - Group : param alias : short code for a particular account . If none will use account ' s default alias : param location :...
if alias is None : alias = clc . v1 . Account . GetAlias ( ) if location is None : location = clc . v1 . Account . GetLocation ( ) if description is None : description = '' if parent is None : parent = "%s Hardware" % ( location ) parents_uuid = Group . GetGroupUUID ( parent , alias , location ) r = clc...
def _parse_entity ( self ) : """Parse an HTML entity at the head of the wikicode string ."""
reset = self . _head try : self . _push ( contexts . HTML_ENTITY ) self . _really_parse_entity ( ) except BadRoute : self . _head = reset self . _emit_text ( self . _read ( ) ) else : self . _emit_all ( self . _pop ( ) )
def get_initial_state ( self ) : '''Return first state for this submission after upload , which depends on the kind of assignment .'''
if not self . assignment . attachment_is_tested ( ) : return Submission . SUBMITTED else : if self . assignment . attachment_test_validity : return Submission . TEST_VALIDITY_PENDING elif self . assignment . attachment_test_full : return Submission . TEST_FULL_PENDING
def image_name ( image , key = 'name' , clear = True ) : """{ { image | image _ name } } { { image | image _ name : " description " } } { { image | image _ name : " default _ caption " } } { { image | image _ name : " default _ caption " False } } Return translation or image name"""
if hasattr ( image , 'translation' ) and image . translation : return getattr ( image . translation , key ) if hasattr ( image , key ) and getattr ( image , key ) : return getattr ( image , key ) try : name = IMAGE_NAME . match ( image . original_filename ) . group ( ) except IndexError : return '' else...
def _config_net_topology ( self , conf ) : """Initialize and populate all the network related elements , like reserving ips and populating network specs of the given confiiguration spec Args : conf ( dict ) : Configuration spec to initalize Returns : None"""
conf = self . _init_net_specs ( conf ) mgmts = self . _select_mgmt_networks ( conf ) self . _validate_netconfig ( conf ) allocated_subnets , conf = self . _allocate_subnets ( conf ) try : self . _add_mgmt_to_domains ( conf , mgmts ) self . _register_preallocated_ips ( conf ) self . _allocate_ips_to_nics ( c...
def get_frame_src ( f : Frame ) -> str : '''inspects a frame and returns a string with the following < src - path > : < src - line > - > < function - name > < source - code >'''
path , line , src , fn = _get_frame ( inspect . getframeinfo ( f ) ) return '{}:{} -> {}\n{}' . format ( path . split ( os . sep ) [ - 1 ] , line , fn , repr ( src [ 0 ] [ : - 1 ] ) # shave off \ n )