content
stringlengths
42
6.51k
def getKFold(rows): """ param1: pandas.DataFrame return : integer Function returns number of kfold to consider for Cross validation on the basis of dataset row counts """ if(rows>100 and rows<300):k=2 elif(rows>300 and rows<=500): k=4 elif(rows>500 and rows <=5000 ):k=5 elif(rows...
def newlinesToSpace(text): """ Replace any number of newlines with a single space character. """ return ' '.join(text.replace('\n', ' ').split())
def calc(num1, op, num2): """Return a result for operation between num1 and num2 Examples and Doctest : >>> calc(2, "+", 3) 5 >>> calc(2, "-", 3) -1 >>> calc(2, "*", 3) 6 >>> calc(2, "/", 2) 1.0 """ if op == "+": return num1 + num2 elif op == "-": re...
def normalize_values(value): """ Set all string values (including keys and values of dictionaries) to lower case :param value: the values :return: normalized values """ def normalize(value): if isinstance(value, str): return value.lower() return value if isinstan...
def yaml_variables_subst(yaml_raw, variables=None): """ Performs variables substitute on a provided raw YAML content :type yaml_raw str :type variables dict :rtype:str """ if variables is None: return yaml_raw # replace "${VAR_NAME}" for key, value in variables.items(): ...
def convert_conflict_merge(conflict_merge_preference): """ convert between user, generated, interactive to first, second, interactive options :param conflict_merge_preference: conflict merge pref from command line :return: the conflict merge preference that dictionary merging will understand """ ...
def _merge_errors(create_errors, update_errors): """Merge errors for bulk update and create.""" if create_errors is None: errors = [] if update_errors is None else update_errors else: errors = create_errors.extend(update_errors) \ if update_errors else create_errors return errors
def build_dag_id(partner_id): """Builds the DAG ID for the given Airflow variable. Args: partner_id: Partner ID to build the dag_id for. Returns: The DAG ID. """ dag_name = 'algo_readiness_reporting_%s_dag' % partner_id return dag_name
def _find_vios(vios_list, lpar_id): """ Returns the corresponding VioServer in the vios_list for the lpar_id :param vios_list: The list of VioServer objects. :param lpar_id: The lpar_id to find. :return: The VioServer from the vios_list that matches that lpar_id. If one does not exis...
def font_size_norm(x): """the web font size is different from the game client's - try to approximate how it would look without having to know the actual value.""" try: x = int(x) except ValueError: return "100%" ratio = x / 24 return f"{int(ratio * 100)}%"
def capture_stdout(func, *args, **kwargs): """Capture standard output to a string buffer""" from contextlib import redirect_stdout import io stdout_string = io.StringIO() with redirect_stdout(stdout_string): func(*args, **kwargs) return stdout_string.getvalue()
def downsampling(data, interval): """Downsampling data with interval. Args: data: a list. interval: a int type number. Returns: a new list with downsampling """ length = len(data) assert interval > 0 ret = [] for idx in range(0, length, interval): ret.append(data[idx]) return ret
def remove_punctuation(line, punctuation): """Returns the line without punctuation Param: line (unicode) punctuation (unicode) Returns: line without start and end punctuation """ return_line = line.translate(str.maketrans('', '', punctuation)) if return_line != line: ...
def _pretty_print_label(d): """Internal utility to pretty print point label info.""" s = " %s: "%repr(d[0]) entry_keys = list(d[1].keys()) ki = 0 kimax = len(entry_keys) for k in entry_keys: keys = list(d[1][k].keys()) if len(keys) == 0: s += "{%s: {}}"%k else...
def is_numeric(value) -> bool: """Test if a value is numeric. Args: value: Any value. Returns: True if the value is an int or float. False otherwise. """ return isinstance(value, int) or isinstance(value, float)
def _AndroidAbiToCpuArch(android_abi): """Return the Chromium CPU architecture name for a given Android ABI.""" _ARCH_MAP = { 'armeabi': 'arm', 'armeabi-v7a': 'arm', 'arm64-v8a': 'arm64', 'x86_64': 'x64', } return _ARCH_MAP.get(android_abi, android_abi)
def promptstr(prompt=u'', value=u''): """Prefix a non-empty string with a prompt, or return empty.""" ret = u'' if value: ret = prompt + u' ' + value return ret
def parse_zmatrix(multistring): """\ Parse a multiline string into zmatrix format. >>> parse_zmatrix("H") [['H']] >>> parse_zmatrix('H\\nH 1 0.7') [['H'], ['H', 1, 0.7]] """ parsers = [str,int,float,int,float,int,float] lines = [] for line in multistring.splitlines(): wo...
def limited_repr(obj, limit=40): """ Return the repr() of obj. Limit the returned string length to limit chars. """ try: r = repr(obj) except: r = '<repr-error>' if len(r) > limit: r = r[:limit] + '...' return r
def add_element_to_dict(dictionary, element): """ Adds an element to a dictionary. If not in dictionary, adds a new key to dictionary. :param dictionary: dictionary :param element: string :return: updated dictionary """ if len(element) == 1: return dictionary if element not in dict...
def sign(number): """ Sign of a number INPUT parameter: number : number that's sign is to be calculated (numeric) OUTPUT: value of sign(number) (-1, 0, 1) """ if number>0.0: return 1 elif number<0.0: return -1 else: return 0
def full_community(community_owner): """Full community data as dict coming from the external world.""" return { "access": { "visibility": "public", "member_policy": "open", "record_policy": "open", }, "id": "my_community_id", "metadata": { ...
def find_cross(ln1, ln2): """ finds cross points of 2 lines. Lines are defined as (a,b): ax+by=1 :param ln1: :param ln2: :return: (x,y) """ d = ln1[0]*ln2[1] - ln2[0]*ln1[1] return (ln2[1]-ln1[1])/d, (ln1[0]-ln2[0])/d
def stripNamespaceFromName(name): """ Args: name: Returns: """ return name.split('::')[-1]
def phex(num): """ convert int to 2 characters hex string which not contain '0x' in begin or 'L' in end """ num = hex(int(num))[2:].upper() if num[-1].lower() == 'L': num = num[:-1] return num.zfill(2)
def getRecord(record_line): """ Split records out by dynamic position. By finding the space, we can determine the location to split the record for extraction. To learn more about this, uncomment the print statements and see what the code is doing behind the scenes! """ # print "Line: ", ...
def rgba_to_hsva(r, g, b, alpha=1.0): """Converts a color given by its RGBA coordinates to HSVA coordinates (hue, saturation, value, alpha). Each of the RGBA coordinates must be in the range [0, 1]. """ # This is based on the formulae found at: # http://en.literateprograms.org/RGB_to_HSV_color_...
def get_unique_words_in_each_text(text): """ Keeps unique words in each text Params: text (tuple): tuple of words Returns: unique_text """ unique_text = [] text = list(text) [unique_text.append(x) for x in text if x not in unique_text] return tuple(unique_text)
def predeceleration(time, aa, mm, t0, **kwargs): """ :param time: time array in seconds :param aa: amplitude term for powerlaw :param mm: deceleration powerlaw gradient; typically 3 but depends on physics :param t0: time GRB went off. :param kwargs: None :return: deceleration powerlaw; units...
def _check_should_restart(line: str) -> bool: """Check if the line indicates that the upload should be re-run on failure. :param line: The output line to check :returns: True if it indicates a restart would help, False otherwise """ for match in [ "Error: Server returned an invalid MIME t...
def text_to_utf8(text): """ Utility function to "translate" the text taken from an html page with all the utf-8 chars encoded into a decoded text """ return text.encode('ascii').decode('unicode-escape').encode('latin-1').decode('utf-8')
def isanyinstance(obj, typelist): """ Returns true if object `obj` is of any of the types list in `typelist` :param obj: object :param typelist: list of types :return: bool """ return any([isinstance(obj, t) for t in typelist])
def construct_sliding_windows(sequence_length: int, sliding_window_size: int): """ construct sliding windows for BERT processing :param sequence_length: e.g. 9 :param sliding_window_size: e.g. 4 :return: [(0, 4, [1, 1, 1, 0]), (2, 6, [0, 1, 1, 0]), (4, 8, [0, 1, 1, 0]), (6, 9, [0, 1, 1])] """ ...
def mix(x, y, a): """Return x * (1 - a) + y * a, with x, y floats or float vectors. A can be a float-vector or float (also if x and y are vectors). """ return x * (1 - a) + y * a
def convert_name(name, to_version=False): """This function centralizes converting between the name of the OVA, and the version of software it contains. The naming convention is ``router-<software>-<version>.ova``, like router-vyos-1.1.8.ova :param name: The thing to covert :type name: String ...
def honor_type(obj, generator): """ Cast a generator to the same type as obj (list, tuple or namedtuple) """ # There is no direct check whether an object if of type namedtuple sadly, this is a workaround. if isinstance(obj, tuple) and hasattr(obj, "_fields"): # Can instantiate a namedtuple f...
def is_img_tweet(tweet: dict): """determine img tweet. Returns: bool: """ try: media = tweet['entities']['media'] if len(media) > 0: if media[0]['type'] == 'photo': return True except Exception: pass return False
def update_symbols(data, obj_names, type_names): """Return a deep copy of [data] with all symbols replaced with their corresponding in-game values. Object symbols (prefixed with '$') are updated by [obj_names]. Type symbols (prefixed with '^') are updated by [type_names]. Raises KeyError if a symb...
def get_feature_class(row, quantile_list): """ Helper method for stratification. Returns class label based on quantile boundaries. Parameters: -------------- row: int, data point or series entry quantile_list: list with quantile measures Returns: --------------...
def format_hex(i, num_bytes=4, prefix='0x'): """ Format hexidecimal string from decimal integer value >>> format_hex(42, num_bytes=8, prefix=None) '0000002a' >>> format_hex(23) '0x0017' """ prefix = str(prefix or '') i = int(i or 0) return prefix + '{0:0{1}x}'.format(i, num_bytes)
def get_site_table(hpo_id, table): """ Return hpo table for site :param hpo_id: identifies the hpo site as str :param table: identifies the cdm table as str :return: cdm table name for the site as str """ return f'{hpo_id}_{table}'
def to_str(x) -> str: """ return str(x) if x else '' :param x: any :return: str(x) if x else '' """ return str(x) if x else ''
def _try_format_numeric(text): """remove leading/trailing zeros, leading "+", etc. from numbers. Non numeric values are left untouched.""" try: numeric = float(text) if int(numeric) == numeric: # remove trailing .0 numeric = int(numeric) text = str(numeric) except ValueE...
def isFull(board): """ Check if all the cells in the board are filled (the sudoku is completed). """ res = True for i in board: res = res and not (0 in i) return res
def is_ticket_name_valid(ticket_name): """ Checks if the ticket name is valid according to the specifications. :param ticket_name: the name of the ticket to be tested :returns: True if the ticket name satisfies all requirements """ return (ticket_name[0].isalnum()) and \ (ticket_name[-1]...
def long_repeat(line): """ length the longest substring that consists of the same char """ count = ['', 0] maxCount = 0 for i in list(line): if i == count[0]: count[1] += 1 else: count[0] = i count[1] = 1 if count[1] > maxCount: ...
def _armijo_backtrack( fobj, x, eta0=1., fgrad=None, args=(), arm_alpha=0.5, arm_gamma=0.8 ): """Compute step size using Armijo backtracking rule for gradient updates. See docstring of nag_solver for details on unlisted parameters. Parameters ---------- x : numpy.ndarra...
def create_contact(company, first_name, last_name, email, phone_number, where_we_met, notes, date_added, date_last_contacted, second_most_recent_date, date_of_last_notification): """ Creates contact based on the inputs """ dictionary = {"company":company,"first_name": first_name , "last_name" : last_name...
def _massage_groups_out(appstruct): """Opposite of '_massage_groups_in': remove 'groups:' prefix and split 'groups' into 'roles' and 'groups'. """ d = appstruct groups = [ g.split("group:")[1] for g in d.get("groups", "") if g and g.startswith("group:") ] roles = [r f...
def get_parsed_bounds(bounds: str): """ Parse bounds querystring :param bounds: NE-SW lng-lat bounds separated by commas :return: bounds as list of floats """ lngNE, latNE, lngSW, latSW = [float(b) for b in bounds.split(",")] return { "lngNE": lngNE, "latNE": latNE, ...
def to_bytes(text, encoding=None, errors='strict'): """Return the binary representation of ``text``. If ``text`` is already a bytes object, return it as-is.""" if isinstance(text, bytes): return text if not isinstance(text, str): raise TypeError('to_bytes must receive a str or bytes ' ...
def get_next_name(names, base): """Figure out a new name starting with base that doesn't appear in given list of names. >>> get_next_name(["alist", "adict1", "adict2"], "adict") 'adict3' """ base_length = len(base) def has_right_base(name): return name.startswith(base) def get_i...
def checkNewFollowers(new_list, old_list): """ Checks if elements in the new list are present in the old one if not present, saves it into a list of new users (that is, new followers) :param new_list: A list of followers generated in this execution :param old_list: A list of followers generated ...
def str_padding(length, val): """Formats value giving it a right space padding up to a total length of 'length'""" return '{0:<{fill}}'.format(val, fill=length)
def convert_to_list(subject_codes): """If value is a dict, return in list, otherwise return value""" if isinstance(subject_codes, str): return [subject_codes] return subject_codes
def pick_wm_prob_0(probability_maps): """ Returns the csf probability map from the list of segmented probability maps Parameters ---------- probability_maps : list (string) List of Probability Maps Returns ------- file : string Path to segment_prob_0.nii.gz is return...
def gen_endpoint(endpoint_name, endpoint_config_name): """ Generate the endpoint resource """ endpoint = { "SagemakerEndpoint": { "Type": "AWS::SageMaker::Endpoint", "DependsOn": "SagemakerEndpointConfig", "Properties": { "EndpointConfigName": ...
def length_hint(obj, default=0): """ Return an estimate of the number of items in obj. This is useful for presizing containers when building from an iterable. If the object supports len(), the result will be exact. Otherwise, it may over- or under-estimate by an arbitrary amount. The result will be...
def expand(x, add_size): """ function to exand one peak :param x: :param add_size: :return: """ x['start'] = max([x['start'] - add_size, 0]) x['stop'] += add_size return x
def checkbit(packedint, offset): """ Check for a bit flag in a given int value. Args: packedint: bit packed int offset: binary offset to check Returns: bool """ bit = 1 << offset return (packedint & bit) > 0
def add_items(inventory, items): """ :param inventory: dict - dictionary of existing inventory. :param items: list - list of items to update the inventory with. :return: dict - the inventory dictionary update with the new items. """ for item in items: if item in inventory: ...
def get_auth_token(config): """Ensures an auth token exists. If a token is already present in the config, returns the token Otherwise prompts the user to create one or set one manually. Args: config |{str:str}| = A dictionary of settings from the configuration file. Returns: auth_token |str| = The use...
def aweg(data): """ AWEG - Request the distance traveled """ # business logic here # compare with history data in redis # get equipment status and send to heka #print ("data: %s" % (data) ) return data
def create_search_criterion_by_uid(uid): """Return a search criteria for UID. .. versionadded: 0.4 """ return 'UID {}'.format(uid)
def naive_forecast(past, t=-1, horizon=1, seasonal_period=1): """ Simple forecast method which predicts the next value by taking the current value (i.e. value at the end of the past array) using the default parameter. By tuning the default parameter it is possible to use the seasonal version of this...
def convert_bytes(num): """ this function will convert bytes to MB.... GB... etc """ for x in ['bytes', 'KB', 'MB', 'GB', 'TB']: if num < 1024.0: return "%3.1f %s" % (num, x) num /= 1024.0
def get_code_count(row, column): """ Figure out how many times we have to generate codes in order to reach the row/column position specified. """ return sum(range(row + column - 1)) + column
def get_full_intent(intent_json): """recovers the full intent json from standalized intent. Basically we will add fields that are omitted becauase their values are all or 2 back to the intent json. """ # dep/ret time if 'departure_time' not in intent_json: intent_json['departure_time'] = 'all' if 're...
def equals(values, puzzle_input): """if the first parameter is equal to the second parameter, it stores 1 in the position given by the third parameter. Otherwise, it stores 0. """ if values[0] == values[1]: puzzle_input[values[2]] = 1 else: puzzle_input[values[2]] = 0 return puzz...
def inject_text(htmltext, intext): """ Insert text from a file into an html string. Arguments: htmltext -- string where text will be added. intext -- input file Returns: text with intext added between <p></p> characters """ parts = htmltext.split('<p></p>') with open(intext...
def smart_truncate(content, length=160, suffix='.'): """ Returns string :param content: :param length: :param suffix: :return: """ if len(content) <= length: return content else: return ' '.join(content[:length+1].split(' ')[0:-1]) + suffix
def dict_reorder(item: dict) -> dict: """ Sorts dict by keys, including nested dicts :param item: dict to sort """ if isinstance(item, dict): item = {k: item[k] for k in sorted(item.keys())} for k, v in item.items(): if isinstance(v, dict): item[k] = dict_...
def test_3(input): """ >>> test_3("abbceffg") True >>> test_3("abbcegjk") False >>> test_3("abcdffaa") True >>> test_3("ghjaabcc") True """ alphabet = "abcdefghijklmnopqrstuvwxyz" count = 0 for c in alphabet: if c + c in input: count += 1 ...
def GetWinLinkRuleNameSuffix(embed_manifest): """ Returns the suffix used to select an appropriate linking rule depending on whether the manifest embedding is enabled. """ return '_embed' if embed_manifest else ''
def recite(start_verse, end_verse): """ Create the song based on the starting and ending verses. :param str Starting verse. :param str Ending verse. """ def build_verse(verse): verses = { 'first': 'and a Partridge in a Pear Tree.', 'second': 'two Turtle Doves, '...
def _mondict(n_hem=True): """ Get a dictionary of season and month string. Parameters ---------- n_hem : Boolean Default True. Indicates hemisphere of parcel launch and thus actual season. Returns ------- season_month_dict : dictionary Dictionary keyed by month...
def merge_dicts(dict1, dict2): """ Recursively merges dict2 into dict1 """ if not isinstance(dict1, dict) or not isinstance(dict2, dict): return dict1 for k in dict2: if k in dict1: dict1[k] = merge_dicts(dict1[k], dict2[k]) else: dict1[k] = dict2[k] retur...
def _decode_label(label): """Convert a list label into a tuple. Works recursively on nested lists.""" if isinstance(label, list): return tuple(_decode_label(v) for v in label) return label
def protege_data(datas_str, sens): """ Used to crypt/decrypt data before saving locally. Override if securit is needed. bytes -> str when decrypting str -> bytes when crypting :param datas_str: When crypting, str. when decrypting bytes :param sens: True to crypt, False to decrypt """ ...
def _parse_until_delim(ctx, fld, delim): """ Return False unless delim exists in ctx['str']. Assign ctx['str'] excluding delim to ctx[fld] and assign ctx[str] to the remainder, excluding delim, and return True otherwise.""" i = ctx['str'].find(delim) if (i == -1): return False ctx[fld] = ctx['...
def dict_param_to_nsmlib_bin_str(params): """A simple function to convert a dictionary of params to a string that can be understood by NMSLIB binary. :param params: a dictionary of parameters, e.g., {'M': 30, 'indexThreadQty': 4} :return: a string, e.g., M=30,indexThreadQty=4 """ return ','...
def get_median_watch_time(event): """Computes the median watch time based on LA1-provided mapping from watch times to number of unique viewers. NOTE: This data is only available at 5 minute granularities.""" times = [] for m, v in event['geodata']['watchTimes'].items(): times += [int(m)] * v...
def listAxes(axd): """ make a list of the axes from the dictionary of axes Parameters ---------- axd : dict a dict of axes, whose values are returned in a list Returns ------- list : a list of the axes """ if type(axd) is not dict: if type(axd) is l...
def ansi(code_r, bold=""): """ANSI Colours for printing (Because why not?) Code can be 30-37. In order of colours, these are black, red, green, yellow, blue, magnenta, cyan, and white. After every colour print, print ansi(0) to clear colour attributes. (Copied from psilib.utils.ansi) """ ...
def generate_subject(softwarerelease, osversion): """ Generate message subject. :param softwarerelease: Software version. :type softwarerelease: str :param osversion: OS version. :type osversion: str """ return "SW {0} - OS {1} available!".format(softwarerelease, osversion)
def validate_email_address(emailaddress): """ Checks if an email address is syntactically correct. Args: emailaddress (str): Email address to validate. Returns: is_valid (bool): If this is a valid email or not. Notes. (This snippet was adapted from http://commandli...
def field_identifier(field): """ Given a ``field`` of the format {'name': NAME, 'type': TYPE}, this function converts it to ``TYPE NAME`` """ return "{0} {1}".format(field["type"], field["name"])
def _get_token(retrieve_result): """Get token from results to obtain next set of results. :retrieve_result: Result from the RetrievePropertiesEx API :return: Token to obtain next set of results. None if no more results. """ return getattr(retrieve_result, 'token', None)
def resolve_multi_lang_embed(language,sparknlp_reference): """Helper Method for resolving Multi Lingual References to correct embedding""" if language == 'ar' and 'glove' in sparknlp_reference : return 'arabic_w2v_cc_300d' else : return sparknlp_reference
def transport_file_name(node_id, transport_type): """ Create name for a transport xml file. :param int node_id: node id to generate transport file name for :param str transport_type: transport type to generate transport file :return: """ return "n%strans%s.xml" % (node_id, transport_type)
def isNumber(sText): """ :param sText: a text string :return: returns TRUE if sText is a number """ if len(sText) == 0: return False if str(sText[0]).isdigit(): try: iValue = int(sText) return True except: try: fVal...
def convert_longitude(long_EW): """ Function to convert deg m E/W longitude to DD.dddd (decimal degrees) Arguments: long_EW : tuple representing longitude in format of MicroGPS gps.longitude Returns: float representing longtidue in DD.dddd """ re...
def splitany(s, sep=" \011\012\013\014\015", maxsplit=None, negate=0): """splitany(s [,sep [,maxsplit [,negate]]]) -> list of strings Split a string. Similar to string.split, except that this considers any one of the characters in sep to be a delimiter. If negate is true, then everything but sep will...
def rounded(n, base): """Round a number to the nearest number designated by base parameter.""" return int(round(n/base) * base)
def set_fragment_indicies(x): """ Returns the indicees without leading and trailing gaps. Parameters ---------- x = string sequence Returns ------- list of start index and end index with the first and last non gap character """ e = len(x) ei = e si = 0 for ...
def grow(s, limit, max_r, max_c, ignore): """Grow a slice of pizza in each direction while possible. Args: s: Slice of pizza to expand. limit: Maximum amount of pieces a slice can be made of. max_r: Height of the pizza. max_c: Width of the pizza. ignore: Boolean matrix w...
def _instance_zone(instance_data): """Removes most of a zone URI and returns the 'canonical' zone identifier situated at the very end of the URI path..""" zone = instance_data.get('zone', None) assert zone return zone[zone.rindex("/") + 1:] if '/' in zone else zone
def Fahrenheit_K(Kelvin): """Usage: Convert to Fahrenheit from Kelvin Fahrenheit_K(Kelvin)""" return (Kelvin-273.15)*9/5 + 32
def anagram_checker(str1, str2): """ Check if the input strings are anagrams of each other Args: str1(string),str2(string): Strings to be checked Returns: bool: Indicates whether strings are anagrams """ str1 = str1.lower() str2 = str2.lower() for character in str1: ...
def tlv_data_text(tlv_dump): """Return the text dump for the test tree as bytes.""" return tlv_dump.encode("utf-8")