content
stringlengths
42
6.51k
def get_catalog_record_embargo_available(cr): """Get access rights embargo available date as string for a catalog record. Args: cr (dict): A catalog record Returns: str: The embargo available for a dataset. Id not found then ''. """ return cr.get('research_dataset', {}).get('acces...
def subset_to_seq(subset_sol): """Convert subset solution (e.g.: [[0,1],[0,0,1]]) into sequence solution (e.g.: ['r2','c3'])""" m = len(subset_sol[0]) n = len(subset_sol[1]) seq_sol = list() for i in range(m): if subset_sol[0][i]: seq_sol.append(f"r{i+1}") for j in range(n): ...
def _is_quantity(obj): """Test for _units and _magnitude attrs. This is done in place of isinstance(Quantity, arg), which would cause a circular import. Parameters ---------- obj : Object Returns ------- bool """ return hasattr(obj, "_units") and hasattr(obj, "_magnitude")
def _dims_to_strings(dims): """ Convert dims that may or may not be strings to strings. """ return [str(dim) for dim in dims]
def feq(a, b, max_relative_error=1e-12, max_absolute_error=1e-12): """ Returns True if a==b to the given relative and absolute errors, otherwise False. """ # if the numbers are close enough (absolutely), then they are equal if abs(a-b) < max_absolute_error: return True # if not, they...
def reference_sibling(py_type: str) -> str: """ Returns a reference to a python type within the same package as the current package. """ return f'"{py_type}"'
def cTypeReplacements(tex): """ Replace the Latex command "\CONST{<argument>}" with just argument. """ while (tex.find("\\CTYPE") != -1): index = tex.find("\\CTYPE") startBrace = tex.find("{", index) endBrace = tex.find("}", startBrace) tex = tex[:index] + tex[star...
def _center_coordinates(frag, center_atoms=0): """ normalize centroids of multiple lists of [x,y,z] to the origin, (0,0,0) """ cx,cy,cz = 0.0,0.0,0.0 # collect the sum for i in range(len(frag)): cx, cy, cz = cx+frag[i][0], cy+frag[i][1], cz+frag[i][2] points = len(frag) x,y,z = cx/points...
def get_dict_value(dictionary, key): """ return the value of a dictionary key """ try: return dictionary[key] except (KeyError, IndexError): return ''
def glissando_rate(times, start_freq, freq_rate): """returns frequency array to represent glissando from start at a given rate""" return (start_freq + (times*freq_rate))
def integerize_arg(value): """Convert value received as a URL arg to integer. Args: value: Value to convert Returns: result: Value converted to iteger """ # Try edge case if value is True: return None if value is False: return None # Try conversion ...
def find_totals_dimensions(dimensions, share_dimensions): """ WRITEME :param dimensions: :param share_dimensions: :return: """ return [dimension for dimension in dimensions if dimension.is_rollup or dimension in share_dimensions]
def _amount(amount, asset='SBD'): """Return a steem-style amount string given a (numeric, asset-str).""" assert asset == 'SBD', 'unhandled asset %s' % asset return "%.3f SBD" % amount
def standard_field(input_name): """Returns a standard form of data field name""" return input_name.lower()
def possible_bipartition(dislikes): """ Will return True or False if the given graph can be bipartitioned without neighboring nodes put into the same partition. Time Complexity: O(N+E) Space Complexity: O(N) """ if not dislikes: return True if len(dislikes[0]) > ...
def unparse_color(r, g, b, a, type): """ Take the r, g, b, a color values and give back a type css color string. This is the inverse function of parse_color """ if type == '#rgb': # Don't lose precision on rgb shortcut if r % 17 == 0 and g % 17 == 0 and b % 17 == 0: retur...
def ps_new_query(tags=[], options = "all"): """ Query from PostgreSQL Args: tags: list of tags options: 'all' means the posting must contains all the tags while 'any' means that the posting needs to contain at least one of the tags Returns: job postings containing the tag...
def keys_to_str(to_convert): """ Replaces all non str keys by converting them. Useful because python yaml takes numerical keys as integers """ if not isinstance(to_convert, dict): return to_convert return {str(k): keys_to_str(v) for k, v in to_convert.items()}
def azure_file_storage_account_settings(sdv, sdvkey): # type: (dict, str) -> str """Get azure file storage account link :param dict sdv: shared_data_volume configuration object :param str sdvkey: key to sdv :rtype: str :return: storage account link """ return sdv[sdvkey]['storage_account...
def _heaviside(x1: float, x2: float) -> float: """A custom Heaviside function for Numba support. Parameters ---------- x1 : float The value at which to calculate the function. x2 : float The value of the function at 0. Typically, this is 0.5 although 0 or 1 are also used. Retu...
def render_emoji(emoji): """Given norm_emoji, output text style emoji.""" if emoji[0] == ":": return "<%s>" % emoji return emoji
def dispatch(result): """DB query result parser""" return [row for row in result]
def getGroupings(dimnames, groupings): """ see Schema.getGroupings above """ assert isinstance(groupings, dict), "groupings must be a dictionary" assert isinstance(dimnames, list), "dimnames must be a list" index_groupings = {} for dim, groups in groupings.items(): index_groupings[di...
def is_property(class_to_check, name): """Determine if the specified name is a property on a class""" if hasattr(class_to_check, name) and isinstance(getattr(class_to_check, name), property): return True return False
def true_g(x): """ Compute the expected values of a point. Parameters ---------- x : tuple of int A feasible point Returns ------- tuple of float The objective values """ chi2mean = 1 chi2mean2 = 3 obj1 = (x[0]**2)/100 - 4*x[0]/10 + (x[1]**2)/100 - 2*x[1...
def matchesType(value, expected): """ Returns boolean for whether the given value matches the given type. Supports all basic JSON supported value types: primitive, integer/int, float, number/num, string/str, boolean/bool, dict/map, array/list, ... """ result = type(value) expected = expecte...
def _str_real(x): """Get a simplified string representation of a real number x.""" out = str(x) return "({})".format(out) if '/' in out else out
def deduplicate(iterable): """ Removes duplicates in the passed iterable. """ return type(iterable)( [i for i in sorted(set(iterable), key=lambda x: iterable.index(x))])
def compare_settings(local_config_vars, remote_config_vars): """Compare local and remote settings and return the diff. This function takes two dictionaries, and compares the two. Any given setting will have one of the following statuses: '=' In both, and same value for both (no action required) '!...
def f(x): """ Quadratic function. It's easy to see the minimum value of the function is 5 when is x=0. """ return x**2 + 5
def fromSQLName(text): """ """ return text.replace('_', ' ').title()
def _read_bdf_global(instream): """Read global section of BDF file.""" # read global section bdf_props = {} x_props = {} comments = [] parsing_x = False nchars = -1 for line in instream: line = line.strip('\r\n') if not line: continue elif line.startsw...
def jaccard_distance(text1, text2): """ Measure the jaccard distance of two different text. ARGS: text1,2: list of tokens RETURN: score(float): distance between two text """ intersection = set(text1).intersection(set(text2)) union = set(text1).union(set(text2)) return 1 -...
def permutate(seq): """permutate a sequence and return a list of the permutations""" if not seq: return [seq] # is an empty sequence else: temp = [] for k in range(len(seq)): part = seq[:k] + seq[k+1:] #print k, part # test for m in permutate(part...
def s3_backup_mode_extended_s3_validator(x): """ Property: ExtendedS3DestinationConfiguration.S3BackupMode """ valid_types = ["Disabled", "Enabled"] if x not in valid_types: raise ValueError("S3BackupMode must be one of: %s" % ", ".join(valid_types)) return x
def sideeffect_python_found(*args, **kwargs): # pylint: disable=unused-argument """Custom side effect for patching subprocess.check_output.""" if 'sourceanalyzer' in args[0]: return "Nothing to see here" return ""
def replace_underscore_with_space(original_string): """ Another really simple method to remove underscores and replace with spaces for titles of plots. Args: original_string: String with underscores Returns: replaced_string: String with underscores replaced """ return original_...
def part2(course): """Find the end position of the submarine""" aim, depth, horizontal = 0, 0, 0 for value in course: command, unit = value.split(" ") if command == "forward": horizontal += int(unit) depth += aim * int(unit) elif command == "up": a...
def twgoExpirationFacts(msg): """Used by :func:`twgoExpirationTime` to find latest stop time, and if all records have one. Finds the latest stop time in a message and also if all records have a stop time (if all records don't have a stop time, knowing the latest is moot). Args: msg (di...
def is_float(value, return_value=False): """ Return value as float, if possible """ try: value = float(value) except ValueError: if not return_value: return False if return_value: return value return True
def gcd(a, b): """ given a and b, return the greatest common divisor >>> gcd(75, 21) 3 >>> gcd(52, 81) 1 >>> gcd(27, 18) 9 >>> gcd(300, 42) 6 >>> gcd(254, 60) 2 """ while b != 0: (a, b) = (b, a % b) return a
def _validate_output_feature_name_from_test_stats( output_feature_name, test_stats_per_model ): """Validate prediction output_feature_name from model test stats and return it as list. :param output_feature_name: output_feature_name containing ground truth :param test_stats_per_model: list o...
def _check_value(remote_value, local_value): """ Validates if both parameters are equal. :param remote_value: :param local_value: :return: True if both parameters hold the same value, False otherwise :rtype: bool """ if isinstance(remote_value, bool) or isinstance(local_value, bool): ...
def sec_played(time): """Converts mm:ss time format to total seconds""" minutes_and_sec = time.split(':') return int(minutes_and_sec[0]) * 60 + int(minutes_and_sec[1])
def is_file_like(v): """ Return True if this object is file-like or is a tuple in a format that the requests library would accept for uploading. """ # see http://docs.python-requests.org/en/latest/user/quickstart/#more-complicated-post-requests return hasattr(v, 'read') or ( isinstance(v...
def mapparms(old, new) : """ Linear map parameters between domains. Return the parameters of the linear map ``offset + scale*x`` that maps `old` to `new` such that ``old[i] -> new[i]``, ``i = 0, 1``. Parameters ---------- old, new : array_like Domains. Each domain must (successfull...
def update_lease(leases, entry): """ Update a dictionary of DHCP leases with a new entry. The dictionary should be indexed by MAC address. The new entry will be added to the dictionary unless it would replace an entry for the same MAC address from a more recent lease file. """ mac_addr = en...
def variant_size(variant): """ Can only call this function on a vcf variant dict """ return abs(len(variant['ALT']) - len(variant['REF']))
def get_clevr_pblock_op(block): """ Return the operation of a CLEVR program block. """ if 'type' in block: return block['type'] assert 'function' in block return block['function']
def convert_numeric_list(str_list): """ try to convert list of string to list of integer(preferred) or float :param str_list: list of string :return: list of integer or float or string """ assert isinstance(str_list, list) if not str_list: return str_list try: return l...
def validate_instance(in_instance): """ Check that the user provided a valid instance """ if not in_instance: return "dev" else: i = in_instance.lower() if i in ["prod", "test", "dev"]: return i else: raise IOError("Invalid instance. Must be de...
def list_to_string(list, separator=", "): """Returns a new string created by converting each items in `list` to a new string, where each word is separated by `separator`. :param list: list of iterable items to covert to a string. :param separator: character to use as a separator between the list items....
def action_tuple_to_str(action): """ Converts the provided action tuple to a string. :param action: the action :return: a string representation of the action tuple """ if action is None: return None return str(action[0]) + str(action[1]) + action[2]
def deleteSpecChars(text, specialChars): """ This function removes special characters from a string and returns a new string INPUT: text: string specialChars: List of characters to be removed OUTPUT: newTextList: type <list> Each element in list is a string """ ...
def isVariableCandidate(atomsList): """ Check is atoms list from an atom term is variable or not. It checks if the atoms are in decrease order. Parameters ---------- atomsList : list Bonded term list of atoms Returns ------- variable : bool True if are a variable c...
def is_positive_number(*arr): """Check if the numbers are positive number. :param arr: number array :return: True if are positive number, or False if not """ for n in arr: if n <= 0: return False return True
def quick_sort(integers): """Perform a quick sort on a list of integers, selecting a pivot point, partition all elements into a first and second part while looping so all elements < pivot are in first part, any elements > then pivot are in seconds part, recursively sort both half's and combine. ...
def decode_database_key(s): """Extract Guage_id, Reading_type, Datestr form provided keystring. """ lst = s.split("-") gid = lst[0] rdng = lst[1] dstr = lst[2] return (gid, rdng, dstr)
def splitext( filename ): """ Return the filename and extension according to the first dot in the filename. This helps date stamping .tar.bz2 or .ext.gz files properly. """ index = filename.find('.') if index == 0: index = 1+filename[1:].find('.') if index == -1: return filen...
def is_instance(list_or_dict): """Converts dictionary to list""" if isinstance(list_or_dict, list): make_list = list_or_dict else: make_list = [list_or_dict] return make_list
def _get_opt_attr(obj, attr_path): """Returns the value at attr_path on the given object if it is set.""" attr_path = attr_path.split('.') for a in attr_path: if not obj or not hasattr(obj, a): return None obj = getattr(obj, a) return obj
def flatten_list(l): """Flatten list of lists""" return [item for sublist in l for item in sublist]
def _bool_to_bool(data): """ Converts *Javascript* originated *true* and *false* strings to `True` or `False`. Non-matching data will be passed untouched. Parameters ---------- data : unicode Data to convert. Returns ------- True or False or unicode Converted data. ...
def parse_url(url): """ Parse a 'swift://CONTAINER/OBJECT' style URL :param url: :return: dictionary with "container" and "obj" keys """ url = url.replace("swift://", "") if url.find("/") == -1: raise ValueError("Swift url must be 'swift://container/object'") pieces = url.split("...
def contains(sequence, value): """A recursive version of the 'in' operator. """ for i in sequence: if i == value or (hasattr(i, '__iter__') and contains(i, value)): return True return False
def jump(current_command): """Return Jump Mnemonic of current C-Command""" #jump exists after ; if ; in string. Always the last part of the command if ";" in current_command: command_list = current_command.split(";") return command_list[-1] else: return ""
def binary_sum(S, start, stop): """Return the sum of the numbers in implicit slice S[start:stop].""" if start >= stop: # zero elements in slice return 0 elif start == stop-1: # one element in slice return S[start] else: # two or more...
def mean(array): """ Calculates the mean of an array/vector """ import numpy as np array=np.array(array) result= np.mean(array) return result
def isiterable(obj): """Return True iff an object is iterable.""" try: iter(obj) except Exception: return False else: return True
def get_git_sha_from_dockerurl(docker_url: str, long: bool = False) -> str: """ We encode the sha of the code that built a docker image *in* the docker url. This function takes that url as input and outputs the sha. """ parts = docker_url.split("/") parts = parts[-1].split("-") sha = parts[-1] ...
def get_image(images, image_name): """Get the image config for the given image_name, or None.""" for image in images: if image["name"] == image_name: return image return None
def fix_tract(t): """Clean up census tract names. :param t: Series of string tract names :returns: Series of cleaned tract names """ if type(t) == str: return t return str(t).rstrip("0").rstrip(".")
def icontains(header_value: str, rule_value: str) -> bool: """ Case insensitive implementation of str-in-str lookup. Parameters ---------- header_value : str String to look within. rule_value : str String to look for. Returns ------- bool Whether *rule* exis...
def same_fringe(tree1, tree2): """ Detect is the given two trees have the same fringe. A fringe is a list of leaves sorted from left to right. """ def is_leaf(node): return len(node['children']) == 0 def in_order_traversal(node): if node == None: return [] if is...
def CheckUpperLimitWithNormalization(value, upperLimit, normalization=1, slack=1.e-3): """Upper limit check with slack. Check if value is no more than upperLimit with slack. Args: value (float): Number to be checked. upperLimit (float): Upper limit. normalization (float): normalizat...
def is_id_in_annotation(xml_id, annotation_id): """is_id_in_annotation :param xml_id: list of id occured in xml files :param annotation_id: list of id which used for annotation """ not_in_anno = [x for x in xml_id if x not in annotation_id] not_in_xml = [x for x in annotation_id if x not in xml...
def ru(v, n = 100.0): """Round up, to the nearest even 100""" import math n = float(n) return math.ceil(v/n) * int(n)
def winner(board): """ Returns the winner of the game, if there is one. """ for i in board: if i[0] != None: if i[0] == i[1] == i[2]: return i[0] for i in range(3): if board[0][i] != None: if board[0][i] == board[1][i] == board[2][i]: ...
def DER_SNR(flux): # ===================================================================================== """ DESCRIPTION This function computes the signal to noise ratio DER_SNR following the definition set forth by the Spectral Container Working Group of ST-ECF, MAST and CADC. ...
def is_palindrome1(str): """ Create slice with negative step and confirm equality with str. """ return str[::-1] == str
def strip_newlines(s): """ Strip new lines and replace with spaces """ return s.replace('\n', ' ').replace('\r', '')
def der_allele(var): """ Returns the derived allele of this SNP variant. Args: var: A variant string representing a SNP Returns: The derived base as uppercase """ var = var.rstrip(')!') return var[-1].upper()
def __parseConnectionString(connectionString): """ Parses the queue connection string. Returns a dict of parameters found. """ return dict(item.split('=') for item in connectionString.split(';'))
def tally_letters(string): """Given a string of lowercase letters, returns a dictionary mapping each letter to the number of times it occurs in the string.""" count_char = {} for char in string: count = 0 if char not in count_char: for c in string: if char == ...
def text(el, strip=True): """ Return the text of a ``BeautifulSoup`` element """ if not el: return "" text = el.text if strip: text = text.strip() return text
def mhdistsq(a, b): """ The function computes the 'Squared Manhattan Distance' in two dimensions """ return ((a[0] - b[0])**2 + (a[1] - b[1])**2)
def find_tweets_with_keywords_idf(tweets, keywords, idf, idf_treshold=5): """ Tries to find tweets that have at least one of the keywords in them :param tweets: The to be checked tweets :param article: The article :param idf_treshold: The minimal som of mathing idf values that need to be in the tweet to...
def plot_kwargs(kwargs): """ Specializes proc_kwargs for plots. """ plt_args = {'alpha': None, 'color': None, 'linestyle': None, 'linewidth': None, 'marker': None, 'markersize': None, 'label': None ...
def invalid_shape(current_shape): """ :param tuple current_shape: The current shape of the data after a convolution is applied. :return: True if the shape is invalid, that is, a negative or 0 components exists. Else, it returns False. :rtype: bool """ # check all components ...
def are_equal(drive_list, partition_infos): """Checks whether partitions in a drive fit to the expected partition infos. """ if len(drive_list) == len(partition_infos): for drive_info, partition_info in zip(drive_list, partition_infos): if drive_info[0] != partition_info[0]: ...
def count_syllables(lang, word): """ Detect syllables in words Thanks to http://codegolf.stackexchange.com/questions/47322/how-to-count-the-syllables-in-a-word """ if lang == 'en': cnt = len(''.join(" x"[c in"aeiouy"]for c in(word[:-1]if'e' == word[-1]else word)).split()) else: c...
def _check_key(node_index, key): """Checks that node ordinal key is equal to provided integer key and raise ValueError if not. """ if node_index != key: raise ValueError( "Nodes of the networkx.OrderedMultiDiGraph must have sequential integer keys consistent with the order" "...
def func_mass_foundation_onshore(height: float, diameter: float) -> float: """ Returns mass of onshore turbine foundations :param height: tower height (m) :param diameter: rotor diameter (m) :return: """ return 1696e3 * height / 80 * diameter ** 2 / (100 ** 2)
def skalarprodukt (vec1, vec2): """bildet das Skalarprodukt aus zwei Vektoren Vektor (Eingabe + Ausgabe): Liste der Form [x1, x2, x3]""" result = vec1[0]*vec2[0] + vec1[1]*vec2[1] + vec1[2]*vec2[2] return result
def load_dict_from_file(path): """Loads key=value pairs from |path| and returns a dict.""" d = {} with open(path, 'r', encoding='utf-8') as f: for line in f: line = line.strip() if not line or line.startswith('#'): continue if '=' in line: ...
def unique_courses(slots_table): """Obtain list of unique courses from slot listing. Arguments: slots_table (list of dict) : TA slot records Returns: (list of str) : sorted list of course numbers """ # obtain list of unique course numbers course_set = set() for slot i...
def array_split(ary,n): """ >>> data = [1,2,3,4,5] >>> array_split(data,3) [[1, 2], [3, 4], [5]] >>> grps = array_split(range(0,1121),8) >>> total_len = 0 >>> for grp in grps: total_len += len(grp) >>> assert(total_len == len(range(0,1121))) """ step = int(round(len(ary)/float(n)...
def parser_valid_description(myadjs, mynouns, objadjs, objnouns) : """Checks whether (myadjs, mynouns) is a valid description for (objadjs,objnouns).""" if not myadjs and not mynouns : return False for madj in myadjs : if madj not in objadjs : return False for mnoun in my...
def funkcija(f, domena, kodomena): """Je li f:domena->kodomena?""" return f.keys() == domena and set(f.values()) <= kodomena
def get_available_setup_commands(): """ Returns the list of commands :epkg:`pyquickhelper` implements or allows. """ commands = ['bdist_egg', 'bdist_msi', 'bdist_wheel', 'bdist_wininst', 'build27', 'build_ext', 'build_script', 'build_sphinx', 'clean_pyd', 'clean_space', ...