content
stringlengths
42
6.51k
def csim_to_scamp5(program, doubleShifts=False): """ Takes a CSIM program as a list of instructions (strings), and maps it to a SCAMP5 program. program: list of instructions, ['instr1', 'instr2', '// comment', ...]. Should be the exact output of AUKE (we here rely on its specific syntax, such as whitespace location etc.) doubleShifts: boolean, if True shifting instructions are replaced by double_shifting instructions (see macros in .hpp file) """ outputProgram = [] # Create prefix for shifting instructions if doubleShifts: shiftPrefix = 'double_' else: shiftPrefix = '' # Iterate on instructions for instr in program: # Remove _transform instructions if instr.startswith('_transform'): instr = '// ' + instr # Uncomment shifting instructions, and # add prefix if necessary elif (instr.startswith('// north') or instr.startswith('// east') or instr.startswith('// south') or instr.startswith('// west')): instr = shiftPrefix + instr[3:] # Uncomment division instruction elif instr.startswith('// div2'): instr = instr[3:] # Differentiate between inplace division, # and to a different target register if instr[5] == instr[8]: instr = 'div2_inplace' + instr[4:] # neg: differentiate between inplace or to a different target elif instr.startswith('neg'): if instr[4] == instr[7]: instr = 'neg_inplace' + instr[3:] # add: both sources different, and target and source2 different elif instr.startswith('add'): # If both sources are the same if instr[7] == instr[10]: instr = 'add_twice' + instr[3:] # If target = source2, swap them elif instr[4] == instr[10]: instr = instr[:7] + instr[10] + instr[8:10] + instr[7] + instr[11:] # sub: target and source2 different elif instr.startswith('sub'): if instr[4] == instr[10]: instr = 'sub_inplace' + instr[3:] outputProgram.append(instr) return outputProgram
def chunkify(lst, n): """ e.g. lst = range(13) & n = 3 return = [[0, 3, 6, 9, 12], [1, 4, 7, 10], [2, 5, 8, 11]] """ return [lst[i::n] for i in range(n)]
def sign_bit(p1): """Return the signedness of a point p1""" return p1[1] % 2 if p1 else 0
def sort_by_visibility(objs: list) -> list: """ Sort a list of object by their visibility value (decreasing). """ s = True while s: s = False for i in range(len(objs) - 1, 0, -1): if objs[i].get_visibility_value() > objs[i - 1].get_visibility_value(): # Swap the elements objs[i], objs[i - 1] = objs[i - 1], objs[i] # Set the flag to True so we'll loop again s = True return objs
def wsgi_to_bytes(s): """Convert a native string to a WSGI / HTTP compatible byte string.""" # Taken from PEP3333 return s.encode("iso-8859-1")
def AND(a, b): """ Returns a single character '0' or '1' representing the logical AND of bit a and bit b (which are each '0' or '1') >>> AND('0', '0') '0' >>> AND('0', '1') '0' >>> AND('1', '0') '0' >>> AND('1', '1') '1' """ if a == '1' and b == '1': return '1'; return '0'
def compute_fans(shape): """Computes the number of input and output units for a weight shape. Args: shape: Integer shape tuple or TF tensor shape. Returns: A tuple of scalars (fan_in, fan_out). """ if len(shape) < 1: # Just to avoid errors for constants. fan_in = fan_out = 1 elif len(shape) == 1: fan_in = fan_out = shape[0] elif len(shape) == 2: fan_in = shape[0] fan_out = shape[1] else: # Assuming convolution kernels (2D, 3D, or more). # kernel shape: (..., input_depth, depth) receptive_field_size = 1. for dim in shape[:-2]: receptive_field_size *= dim fan_in = shape[-2] * receptive_field_size fan_out = shape[-1] * receptive_field_size return fan_in, fan_out
def launchconfig_dialogs(context, request, launch_config=None, in_use=False, landingpage=False, delete_form=None): """ Modal dialogs for Launch configurations landing and detail page.""" return dict( launch_config=launch_config, in_use=in_use, landingpage=landingpage, delete_form=delete_form, )
def get_item(dictionary, key): """Accepts a dictionary and key and returns the contents. Used for referencing dictionary keys with variables. """ # Use `get` to return `None` if not found return dictionary.get(key)
def karatsuba(x, y, base=10): """ Function to multiply 2 numbers in a more efficient manner than the grade school algorithm.""" if len(str(x)) == 1 or len(str(y)) == 1: return x*y else: n = max(len(str(x)),len(str(y))) # that's suboptimal, and ugly, but it's quick to write nby2 = n // 2 # split x in b + 10^{n/2} a, with a and b of sizes at most n/2 a = x // base**(nby2) b = x % base**(nby2) # split y in d + 10^{n/2} c, with c and d of sizes at most n/2 c = y // base**(nby2) d = y % base**(nby2) # we make 3 calls to entries which are 2 times smaller ac = karatsuba(a, c) bd = karatsuba(b, d) # ad + bc = (a+b)(c+d) - ac - bd as (a+b)(c+d) = ac + ad + bc + bd ad_plus_bc = karatsuba(a + b, c + d) - ac - bd # x y = (b + 10^{n/2} a) (d + 10^{n/2} c) # ==> x y = bd + 10^{n/2} (ad_plus_bc) + 10^{n} (a c) # this little trick, writing n as 2*nby2 takes care of both even and odd n prod = ac * base**(2*nby2) + (ad_plus_bc * base**nby2) + bd return prod
def arn_has_slash(arn): """Given an ARN, determine if the ARN has a stash in it. Just useful for the hacky methods for parsing ARN namespaces. See http://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html for more details on ARN namespacing.""" if arn.count('/') > 0: return True else: return False
def grow_slice(slc, size): """ Grow a slice object by 1 in each direction without overreaching the list. Parameters ---------- slc: slice slice object to grow size: int list length Returns ------- slc: slice extended slice """ return slice(max(0, slc.start-1), min(size, slc.stop+1))
def get_team_list_from_match(match_data): """Extracts list of teams that played in the match with data given in match_data.""" teams = [] for alliance in ['red', 'blue']: for team in match_data['alliances'][alliance]['team_keys']: teams.append(int(team[3:])) return teams
def calculate_rtu_inter_char(baudrate): """calculates the interchar delay from the baudrate""" if baudrate <= 19200: return 11.0 / baudrate else: return 0.0005
def f1_score(cm): """ F1 score is the harmonic mean of precision and sensitivity F1 = 2 TP / (2 TP + FP + FN) """ return 2 * cm[1][1] / float(2 * cm[1][1] + cm[0][1] + cm[1][0])
def ConvertToRadian(degree): """ Converts degree to radian input: angle in degree output: angle in radian """ degree = float(degree) pi = 22 / 7 radian = float(degree * (pi / 180)) return radian
def get_vector10(): """ Return the vector with ID 10. """ return [ 0.4418200, 0.5000000, 0.3163389, ]
def node2geoff(node_name, properties, encoder): """converts a NetworkX node into a Geoff string. Parameters ---------- node_name : str or int the ID of a NetworkX node properties : dict a dictionary of node attributes encoder : json.JSONEncoder an instance of a JSON encoder (e.g. `json.JSONEncoder`) Returns ------- geoff : str a Geoff string """ if properties: return '({0} {1})'.format(node_name, encoder.encode(properties)) else: return '({0})'.format(node_name)
def calc_bsa(volume, bsainitial, samples): """calculate BSA""" bsa = (volume / bsainitial) * samples return bsa
def unified_diff(a: str, b: str, a_name: str, b_name: str) -> str: """ Return a unified diff string between strings `a` and `b`. :param a: The first string (e.g. before). :param b: The second string (e.g. after). :param a_name: The "filename" to display for the `a` string. :param b_name: The "filename" to display for the `b` string. :return: A `git diff` like diff of the two strings. """ import difflib a_lines = [line + "\n" for line in a.split("\n")] b_lines = [line + "\n" for line in b.split("\n")] return "".join( difflib.unified_diff(a_lines, b_lines, fromfile=a_name, tofile=b_name, n=5) )
def is_singleline_comment_end(code, idx=0): """Position in string ends a one-line comment.""" return idx >= 0 and idx+1 < len(code) and code[idx+1] == '\n'
def _is_valid_pdf(file_path): """ **Checks if given file is .pdf file.** Internal function. """ if file_path.endswith(".pdf"): return True else: return False
def isSizeZeroEdge(edge_location_pair): """ vertex1 = edge.getFirstVertex() vertex2 = edge.getSecondVertex() location1 = vertex1.getLocation() location2 = vertex2.getLocation() return location1 == location2 """ location1 = edge_location_pair[0] location2 = edge_location_pair[1] return location1 == location2
def get_article(word): """determine article based on first letter of word """ article = '' if word[0].lower() in 'aeiou': article = 'an' else: article = 'a' return article
def _evaluate_matcher(matcher_function, *args): """ Evaluate the result of a given matcher as a boolean with an assertion error message if any. It handles two types of matcher : - a matcher returning a boolean value. - a matcher that only makes an assert, returning None or raises an assertion error. """ assertion_message = None try: match = matcher_function(*args) match = True if match is None else match except AssertionError as e: match = False assertion_message = str(e) return match, assertion_message
def radboud_colon_concepts2labels(report_concepts): """ Convert the concepts extracted from reports to the set of pre-defined labels used for classification Params: report_concepts (dict(list)): the dict containing for each report the extracted concepts Returns: a dict containing for each report the set of pre-defined labels where 0 = abscence and 1 = presence """ report_labels = dict() # loop over reports for rid, rconcepts in report_concepts.items(): report_labels[rid] = dict() # assign pre-defined set of labels to current report report_labels[rid]['labels'] = {'cancer': 0, 'hgd': 0, 'lgd': 0, 'hyperplastic': 0, 'ni': 0} # textify diagnosis section diagnosis = ' '.join([concept[1].lower() for concept in rconcepts['concepts']['Diagnosis']]) # update pre-defined labels w/ 1 in case of label presence if 'colon adenocarcinoma' in diagnosis: # update cancer report_labels[rid]['labels']['cancer'] = 1 if 'dysplasia' in diagnosis: # diagnosis contains dysplasia if 'mild' in diagnosis: # update lgd report_labels[rid]['labels']['lgd'] = 1 if 'moderate' in diagnosis: # update lgd report_labels[rid]['labels']['lgd'] = 1 if 'severe' in diagnosis: # update hgd report_labels[rid]['labels']['hgd'] = 1 if 'hyperplastic polyp' in diagnosis: # update hyperplastic report_labels[rid]['labels']['hyperplastic'] = 1 if sum(report_labels[rid]['labels'].values()) == 0: # update ni report_labels[rid]['labels']['ni'] = 1 if 'slide_ids' in rconcepts: report_labels[rid]['slide_ids'] = rconcepts['slide_ids'] return report_labels
def remap_nested_keys(root, key_transform): """This remap ("recursive map") function is used to traverse and transform the dictionary keys of arbitrarily nested structures. List comprehensions do not recurse, making it tedious to apply transforms to all keys in a tree-like structure. A common issue for `moto` is changing the casing of dict keys: >>> remap_nested_keys({'KeyName': 'Value'}, camelcase_to_underscores) {'key_name': 'Value'} Args: root: The target data to traverse. Supports iterables like :class:`list`, :class:`tuple`, and :class:`dict`. key_transform (callable): This function is called on every dictionary key found in *root*. """ if isinstance(root, (list, tuple)): return [remap_nested_keys(item, key_transform) for item in root] if isinstance(root, dict): return { key_transform(k): remap_nested_keys(v, key_transform) for k, v in root.items() } return root
def is_unique_bis(x): """Do exactly what is_unique() does. Args: x ([list]): The list you want to test Returns: [bool]: True if every element in the list occurs only once """ return len(set(x)) == len(x)
def file_time(filename): """ Gives the date of the creation of the file, if exists. :param str filename: name of the file :returns: if the file exists, the date of the filename as per os.path.getmtime. Otherwise it returns 0 """ import os if os.path.isfile(filename): return os.path.getmtime(filename) else: return 0
def string_clean(s): """ Function will return the cleaned string """ cleaned_string = "" clean_from = "0123456789" for i in s: if i not in clean_from: cleaned_string += i return cleaned_string
def speed(params): """ Example of using all_wheels_on_track and speed """ # Read input variables all_wheels_on_track = params['all_wheels_on_track'] speed = params['speed'] # Set the speed threshold based your action space SPEED_THRESHOLD = 1.0 if not all_wheels_on_track: # Penalize if the car goes off track reward = 1e-3 elif speed < SPEED_THRESHOLD: # Penalize if the car goes too slow reward = 0.5 else: # High reward if the car stays on track and goes fast reward = 1.0 return reward
def namehack(field): """ This function is the meat of a hack to handle an issue where trying to filter by attribute or view led to a very strange-seeming error. The issue is that attribute names in records with attributes and view names in DNS records are represented using SlugRelatedFields so they appear with friendly names (like "Hardware type" in the former case and "public" in the latter case), but because of how this filter module is written, it will just attempt to search by the related field, confusing Django when it gets a query requesting a field with a string primary key like "public". """ if field.endswith(("attribute", "views")): return field + "__name" else: return field
def process_features(features): """ Use to implement custom feature engineering logic, e.g. polynomial expansion, etc. Default behaviour is to return the original feature tensors dictionary as-is. Args: features: {string:tensors} - dictionary of feature tensors Returns: {string:tensors}: extended feature tensors dictionary """ # examples - given: # 'x' and 'y' are two numeric features: # 'alpha' and 'beta' are two categorical features # create new features using custom logic # features['x_2'] = tf.pow(features['x'],2) # features['y_2'] = tf.pow(features['y'], 2) # features['xy'] = features['x'] * features['y'] # features['sin_x'] = tf.sin(features['x']) # features['cos_y'] = tf.cos(features['x']) # features['log_xy'] = tf.log(features['xy']) # features['sqrt_xy'] = tf.sqrt(features['xy']) # create boolean flags # features['x_grt_y'] = tf.cast(features['x'] > features['y'], tf.int32) # features['alpha_eq_beta'] = features['alpha'] == features['beta'] # add created features to metadata (if not already defined in metadata.py) # CONSTRUCTED_NUMERIC_FEATURE_NAMES += ['x_2', 'y_2', 'xy', ....] # CONSTRUCTED_CATEGORICAL_FEATURE_NAMES_WITH_IDENTITY['x_grt_y'] = 2 # CONSTRUCTED_CATEGORICAL_FEATURE_NAMES_WITH_IDENTITY['alpha_eq_beta'] = 2 return features
def future_value(interest, period, cash): """(float, int, int_or_float) => float Return the future value obtained from an amount of cash growing with a fix interest over a period of time. >>> future_value(0.5,1,1) 1.5 >>> future_value(0.1,10,100) 259.37424601 """ if not 0 <= interest <= 1: raise ValueError('"interest" must be a float between 0 and 1') for d in range(period): cash += cash * interest return cash
def FormForSave(tpl): """Form each elemnt to be saved. Keyword arguments: --tpl each elment of an RDD """ p= [] for ((tx ,lam),index) in tpl: p.append((tx,lam)) return p
def readableSize(byteSize: int, floating: int = 2, binary: bool = True) -> str: """Convert bytes to human-readable string (like `-h` option in POSIX). Args: size (int): Total bytes. floating (int, optional): Floating point length. Defaults to 2. binary (bool, optional): Format as XB or XiB. Defaults to True. Returns: str: Human-readable string of size. """ size = float(byteSize) unit = "B" if binary: for unit in ["B", "kiB", "MiB", "GiB", "TiB", "PiB"]: if size < 1024.0 or unit == "PiB": break size /= 1024.0 return f"{size:.{floating}f}{unit}" for unit in ["B", "kB", "MB", "GB", "TB", "PB"]: if size < 1000.0 or unit == "PB": break size /= 1000.0 return f"{size:.{floating}f}{unit}"
def get_change_dict(position, previous): """Return a dictionary that describes the change since last week using Ben Major's API format. One change from Ben Major's format is that new entries will show as an "up" change and the actual and amount parts will be computed as if the single or album was at #41 the previous week. Therefore an entry that is straight in at number 1, will show an amount and actual move of 40 places. >>> change_dict(11,16) >>> {"direction": "up", "amount": 5. "actual": 5} >>> change_dict(11,0) >>> {"direction": "up", "amount": 30. "actual": 30} >>> change_dict(16,11) >>> {"direction": "down", "amount": 0, "actual": -5} >>> change_dict(11,11) >>> {"direction": "none", "amount": 0, "actual": 0} Args: position (:py:class:`int`) : The position in the chart 1-40 previous (:py:class:`int`) : Last week's chart position Returns: change_dict (:py:class:`dict`) : A dictionary containing keys that describe the Change since last week """ actual = (previous if previous else 41) - position amount = abs(actual) if actual > 0: direction = "up" elif actual < 0: direction = "down" else: direction = "none" return dict(direction=direction, actual=actual, amount=amount)
def humanise(number): """Converts bytes to human-readable string.""" if number/2**10 < 1: return "{}".format(number) elif number/2**20 < 1: return "{} KiB".format(round(number/2**10, 2)) elif number/2**30 < 1: return "{} MiB".format(round(number/2**20, 2)) elif number/2**40 < 1: return "{} GiB".format(round(number/2**30, 2)) elif number/2**50 < 1: return "{} TiB".format(round(number/2**40, 2)) else: return "{} PiB".format(round(number/2**50, 2))
def count_most(lines, bit_idx): """input desire lines, bit index and output the most common bit""" count_bit = 0 for line in lines: if line[bit_idx] == 1: count_bit += 1 else: count_bit -= 1 most_bit = 1 if count_bit >= 0 else 0 return most_bit
def excludeListFromList(_list=[], _remove=[]): """ Builds a new list without items passed through as _remove. """ _remove = set(_remove) return [i for i in _list if i not in _remove]
def make_position_string(length): """ Takes the length of the state and returns a string 01234... to be displayed in the interaction to make it easier for the user to pick the position of the pair to be moved. make_position_string(int) -> string """ string = "" for i in range(0,length): if i < 10: string = string + str(i) else: string = string + str(i)[-1] return string
def exchangeDqsystem(): """Add docstring.""" ar = dict() ar["@type"] = "DQSystem" ar["@id"] = "d13b2bc4-5e84-4cc8-a6be-9101ebb252ff" ar["name"] = "US EPA - Flow Pedigree Matrix" return ar
def half_adder(a, b): """ A binary half adder -- performing addition only using logic operators, A half adder simply adds two bits and outputs a sum and carry """ # ^ is logical xor in python sum = a ^ b carry = a and b return carry, sum
def sort_stories_by_votes(hnlist): """Sort stories by total number of votes.""" print(f'Today\'s Top {len(hnlist)} Articles:\n') return sorted(hnlist, key=lambda k: k['votes'], reverse=True)
def _is_int_in_range(value, start, end): """Try to convert value to int and check if it lies within range 'start' to 'end'. :param value: value to verify :param start: start number of range :param end: end number of range :returns: bool """ try: val = int(value) except (ValueError, TypeError): return False return (start <= val <= end)
def merge(a, b): """ Helper function that sorts each of the smaller arrays from merge_sort. Help from: https://codereview.stackexchange.com/questions/154135/recursive-merge-sort-in-python. """ merged = [] i, j = 0, 0 while i < len(a) and j < len(b): if a[i] < b[j]: merged.append(a[i]) i += 1 else: merged.append(b[j]) j += 1 merged += a[i:] merged += b[j:] return merged
def maximum(str1: str, str2: str) -> int: """Return the maximum common lengths of two strings.""" return len(set(str1) & set(str2))
def euler_with_recount(xs, h, y0, f, **derivatives): """Euler with recount""" ys = [y0] for k in range(len(xs) - 1): subsidiary_y = ys[k] + f(xs[k], ys[k]) * h next_y = ys[k] + (f(xs[k], ys[k]) + f(xs[k], subsidiary_y)) * h / 2 ys.append(next_y) return ys
def fix_ical_datetime_format(dt_str): """ ICAL generation gives timezones in the format of 2018-06-30T14:00:00-04:00. The Timezone offset -04:00 has a character not recognized by the timezone offset code (%z). The being the colon in -04:00. We need it to instead be -0400 """ if dt_str and ":" == dt_str[-3:-2]: dt_str = dt_str[:-3] + dt_str[-2:] return dt_str return dt_str
def did_win(f_guess, f_correct_answer): """ Function to check player guess against the correct answer Params: f_guess: int or str f_correct_answer: int Returns: str """ try: f_guess = int(f_guess) if f_guess > f_correct_answer: return 'HINT: Lower Than {0}'.format(f_guess) elif f_guess < f_correct_answer: return 'HINT: Higher Than {0}'.format(f_guess) else: return 'You won!' except ValueError: return '\nRULES: Please enter a number between 1 and 9.'
def temp_from_ppm(delta): """ Calculates temperature from given chemical shift >>> from watertemp import temp_from_ppm >>> temp_from_ppm(4.7) 32.0 >>> temp_from_ppm(5.5) -40.0 """ return 455 - (90 * delta)
def stringify_keys(d): """Recursively convert a dict's keys to strings.""" if not isinstance(d, dict): return d def decode(k): if isinstance(k, str): return k try: return k.decode("utf-8") except Exception: return repr(k) return { decode(k): stringify_keys(v) for k, v in d.items() }
def _select_compcor(compcor_cols, n_compcor): """Retain a specified number of compcor components.""" # only select if not "auto", or less components are requested than there actually is if (n_compcor != "auto") and (n_compcor < len(compcor_cols)): compcor_cols = compcor_cols[0:n_compcor] return compcor_cols
def float_or_none(item): """ Tries to convert ``item`` to :py:func:`float`. If it is not possible, returns ``None``. :param object item: Element to convert into :py:func:`float`. >>> float_or_none(1) ... 1.0 >>> float_or_none("1") ... 1.0 >>> float_or_none("smth") ... None """ if isinstance(item, float): return item try: return float(item) except: return None
def _cgi_post(environ, content_type): """ Test if there is POST form data to handle. """ return (environ['REQUEST_METHOD'].upper() == 'POST' and ( content_type.startswith('application/x-www-form-urlencoded') or content_type.startswith('multipart/form-data')))
def get_sentence_relations(annotations, entities): """Get relations from annotation dictonary and combine it with information from the corresponding entities Args: annotations (dictionary): annotation dictionary (result of calling annotation_to_dict) entities (dictionary): entity annotation (result of get_sentence_entities) Returns: dictionary: extracted and enhanced relations """ ann_keys = list(entities.keys()) relations = {} for k, v in annotations['relations'].items(): if v['arg1'] in ann_keys and v['arg2'] in ann_keys: relations[k] = { 'label': v['label'], 'arg1_old': v['arg1'], 'arg2_old': v['arg2'], 'arg1': entities[v['arg1']]['string'], 'arg2': entities[v['arg2']]['string'], 'pos1': entities[v['arg1']]['new_beg'] if 'new_beg' in entities[v['arg1']] else entities[v['arg1']]['beg'], 'pos2': entities[v['arg2']]['new_beg'] if 'new_beg' in entities[v['arg2']] else entities[v['arg2']]['beg'], 'ent1': entities[v['arg1']]['idx'], 'ent2': entities[v['arg2']]['idx'] } elif (v['arg1'] in ann_keys and not v['arg2'] in ann_keys) or (v['arg2'] in ann_keys and not v['arg1'] in ann_keys): pass #print(RuntimeWarning("Relation {}: {} spans over two sentences".format(k, v))) return relations
def _ensure_str(s): """convert bytestrings and numpy strings to python strings""" return s.decode() if isinstance(s, bytes) else str(s)
def uncamel(name): """converts camelcase to underscore >>> uncamel('fooBar') 'foo_bar' >>> uncamel('FooBar') 'foo_bar' >>> uncamel('_fooBar') '_foo_bar' >>> uncamel('_FooBar') '__foo_bar' """ response, name = name[0].lower(), name[1:] for n in name: if n.isupper(): response += '_' + n.lower() else: response += n return response
def extractWordInString(strToParse, index): """ Exract word (space separated ) at current index""" i = index while i!=0 and strToParse[i-1] not in " \t\n&|": i = i-1 leftPart = strToParse[i:index] i = index while i!=len(strToParse) and strToParse[i] not in " \t\n&|": i = i+1 rightPart = strToParse[index:i] extractedWord = leftPart+rightPart #logging.debug(" [-] extracted Word: %s" % extractedWord) return extractedWord
def from_camel(string: str) -> str: """Converting a CamelCase string to non_camel_case""" assert isinstance(string, str), 'string must be a type of `str`' out = '' for i, c in enumerate(string): addition = c.lower() if c.isupper(): if i != 0: addition = '_' + addition out += addition return out
def remove_dups(extracted_image_data): """ So now that we spam and get loads and loads of stuff in our lists, we need to intelligently get rid of some of it. @param: extracted_image_data ([(string, string, list, list), (string, string, list, list),...]): the full list of images, captions, labels and contexts extracted from this file @return: extracted_image_data ([(string, string, list, list), (string, string, list, list),...)]: the same list, but if there are duplicate images contained in it, then their captions are condensed """ img_list = {} pared_image_data = [] # combine relevant captions for (image, caption, label, contexts) in extracted_image_data: if image in img_list: if not caption in img_list[image]: img_list[image].append(caption) else: img_list[image] = [caption] # order it (we know that the order in the original is correct) for (image, caption, label, contexts) in extracted_image_data: if image in img_list: pared_image_data.append((image, \ ' : '.join(img_list[image]), label, contexts)) del img_list[image] # else we already added it to the new list return pared_image_data
def sub(x1, x2): """Element-wise subtraction of 2 vectors where the second vector is subtracted from the first. Return `x1 - x2`. Args: x1 (list): First vector. 1 or 2 dimensional. x2 (list): Second vector. Same dimenions as `x1`. Returns: list: A element-wise subtracted list. Same dimensions as `x1`. """ assert len(x1) == len(x2) if isinstance(x1[0], list): # 2 dimensional assert len(x1[0]) == len(x2[0]) diff = [] for x1_i, x2_i in zip(x1, x2): diff_i = [x1_ij - x2_ij for x1_ij, x2_ij in zip(x1_i, x2_i)] diff.append(diff_i) return diff else: # 1 dimensional return [x1_i - x2_i for x1_i, x2_i in zip(x1, x2)]
def discard_sessions_by_scene(sessions, scene): """discard certain scenes, e.g., sleeping, which would then be treated as absence. Args: sessions: list of tuples scene: str Returns: filtered sessions as list of tuples """ return [ session for session in sessions if not session[0].startswith(scene) ]
def read_stars(st): """Reads stars from current line and returns the rest of line.""" star_num = 0 rest = st while rest.startswith('*'): star_num += 1 rest = rest[1:] return (star_num, rest.strip())
def main(): """Main test.""" print("Hello, world!") return 0
def add_two(one, two, **kwargs): """ Functions for iterative operations to accelerate the construction of graphs :param one: array or graph :param two: array or graph :returns: added object """ if one is None: return two return one + two
def _get_resource_name(user_id, name): """ Get resource name by resource type. :param str user_id: PipelineAI 8 character user id that uniquely identifies the user that created the resource for super users this user_id is not always the current user for non-super users this user_id is always the current user :param str name: User defined name for the resource :return: resource name - PipelineAI name (with user_id prefix) """ resource_name = user_id + name return resource_name
def phi_square_calc(chi_square, POP): """ Calculate Phi-squared. :param chi_square: chi squared :type chi_square: float :param POP: population or total number of samples :type POP: int :return: phi_squared as float """ try: return chi_square / POP except Exception: return "None"
def _create_error(property_name, title, description): """ """ return {"errors": [ { "property": property_name, "descriptions": [ { "title": title, "description": description } ] } ], "internalErrorCode": "xxx" }
def ABS(n): """Returns absolute value of a number.""" return n if n >= 0 else n * -1
def encode_color(rgb): """rgb to 8-color pallete""" r = "1" if rgb[0] > 127 else "0" g = "1" if rgb[1] > 127 else "0" b = "1" if rgb[2] > 127 else "0" for i in range(8): if r + g + b == format(i, '03b'): return i
def calcTopReward(top_action, gold_labels): """ Intermediate top reward. """ lenth = len(top_action) r = [0. for i in range(lenth)] rem = [0 for i in range(len(gold_labels))] for i in range(lenth)[::-1]: if top_action[i] > 0: ok = -1 for j, label in enumerate(gold_labels): if label['type'] == top_action[i]: if rem[j] == 0: ok = 1 rem[j] = 1 break else: ok = -0.2 r[i] = ok return r
def initialize_hyper_parameters(layer_acts, learning_rate): """ Initialize parameters for different levels of the network Arguments: layer_acts -- python array (list) containing the activation functions of each layer in the network learning_rate -- float value used as constant for gradient descent Returns: hyper_parameters -- python dictionary containing hyper_parameters (can be further extended) """ hyper_parameters = {} activations = {} L = len(layer_acts) # number of layers in the network for l in range(0, L): activations[l+1] = layer_acts[l] hyper_parameters["activations"] = activations hyper_parameters["learning_rate"] = learning_rate return hyper_parameters
def intToID(idnum, prefix): """ Returns the ID name for the given ID number, spreadsheet-style, i.e. from a to z, then from aa to az, ba to bz, etc., until zz. """ rid = '' while idnum > 0: idnum -= 1 rid = chr((idnum % 26) + ord('a')) + rid idnum = int(idnum / 26) return prefix + rid
def birch_murnaghan(V,E0,V0,B0,B01): """ Return the energy for given volume (V - it can be a vector) according to the Birch Murnaghan function with parameters E0,V0,B0,B01. """ r = (V0/V)**(2./3.) return (E0 + 9./16. * B0 * V0 * ( (r-1.)**3 * B01 + (r-1.)**2 * (6. - 4.* r)))
def finalize_variable_expression(result: str) -> str: """Return empty strings for undefined template variables.""" if result is None: return '' else: return result
def frustrator_function(choice_subject, choice_computer): """ Lets the computer always choose the opposite of the user Parameters ---------- choice_subject : str stores the decision of the subject between heads and tails of the current round. choice_computer : str stores the decision of the computer between heads and tails of the current round. Returns ------- choice_computer : str updated version of the choice_computer variable described above. Now always the opposite of choice_subject. """ if choice_subject == 'h': choice_computer = 't' else: choice_computer = 'h' return choice_computer
def CommandCompleterCd(console, unused_core_completer): """Command completer function for cd. Args: console: IPython shell object (instance of InteractiveShellEmbed). """ return_list = [] namespace = getattr(console, u'user_ns', {}) magic_class = namespace.get(u'PregMagics', None) if not magic_class: return return_list if not magic_class.console.IsLoaded(): return return_list registry_helper = magic_class.console.current_helper current_key = registry_helper.GetCurrentRegistryKey() for key in current_key.GetSubkeys(): return_list.append(key.name) return return_list
def Gini_impurity(splitted_sample=[]): """ For example: [194, 106] note: summation( p_j * (1 - p_j) ) = 1 - summation( p_j^2 ) """ denominator = sum(splitted_sample) if denominator == 0: return 0 Gini_index = 0 for numerator_i in range(len(splitted_sample)): p_i = splitted_sample[numerator_i]/denominator # p_j * (1 - p_j) is the likelihood of misclassifying a new instance Gini_index += p_i * (1 - p_i) return Gini_index
def get_list_representation(cflow_output): """Return a list object representation of the output from cflow Example: If cflow_output is: main() <int () at main.c:18>: f() <int () at main.c:4>: malloc() printf() Then this function will return: ['main() <int () at main.c:18>:', ['f() <int () at main.c:4>:', ['malloc()', 'printf()']]] Parameters: cflow_output: string """ from tokenize import NEWLINE, INDENT, DEDENT, tokenize import io stack = [[]] lastindent = len(stack) def push_new_list(): stack[-1].append([]) stack.append(stack[-1][-1]) return len(stack) readl = io.BytesIO(cflow_output.encode('utf-8')).readline for t in tokenize(readl): if t.type == NEWLINE: if lastindent != len(stack): stack.pop() lastindent = push_new_list() stack[-1].append(t.line.strip()) # add entire line to current list elif t.type == INDENT: lastindent = push_new_list() elif t.type == DEDENT: stack.pop() return stack[-1]
def max_profit_optimized(prices): """ input: [7, 1, 5, 3, 6, 4] diff : [X, -6, 4, -2, 3, -2] :type prices: List[int] :rtype: int """ cur_max, max_so_far = 0, 0 for i in range(1, len(prices)): cur_max = max(0, cur_max + prices[i] - prices[i-1]) max_so_far = max(max_so_far, cur_max) return max_so_far
def true_s2l(value: float) -> float: """Convert SRGB gamma corrected component to linear""" if value <= 0.04045: return value / 12.92 return ((value + 0.055) / 1.055) ** 2.4
def hex_to_rgb(value): """ converts a hex value to an rbg tuple. >>>hex_to_rgb('#FFFFFF') (255, 255, 255) """ value = value.lstrip('#') return tuple(int(value[i:i+2], 16) for i in range(0, 6, 2))
def _format_exception(exception): """Formats the exception into a string.""" exception_type = type(exception).__name__ exception_message = str(exception) if exception_message: return "{}: {}".format(exception_type, exception_message) else: return exception_type
def is_url(name: str) -> bool: """ Return true if name represents a URL :param name: :return: """ return '://' in name
def or_sum (phrase): """Returns TRUE iff one element in <phrase> is TRUE""" total = set() for x in phrase: total = total.union(x) return total
def predict_classify_details(img_path, ground_true, predict_code, conf): """ { "img_path": "img_full_path" , "ground_true": "code1" # , "predict_code": "code2", "conf": 0.8 # 0-1 float , } :return: """ data_list = [] data = {} data['ground_true'] = ground_true data['predict_code'] = predict_code data['conf'] = conf data_list.append(data) result = {} result['img_path'] = img_path result['info'] = data_list return [result]
def need_to_rotate_log(min_size, max_size, max_time_interval, log_size, time_interval): """Check if log match criteria for rotation""" return log_size >= max_size or (time_interval == max_time_interval and log_size >= min_size)
def get_prefix(text: str, prefix: str): """ If a string starts with prefix, return prefix and the text minus the first instance of prefix; otherwise return None and the text. """ if text.startswith(prefix): return prefix, text[len(prefix):].lstrip() return None, text
def round_to_005(x): """ rounds to nearest 0.005 and makes it pretty (avoids floating point 0.000001 nonsense) """ res = round(x * 200) / 200 return float('%.3f'%res)
def job_id(config: dict) -> str: """The ID for the current job""" return config["job_id"]
def write_stress_type(key, options, value, spaces=''): """ writes: - STRESS(SORT1) = ALL - GROUNDCHECK(PRINT,SET=(G,N,N+AUTOSPC,F,A),THRESH=1e-2,DATAREC=NO) = YES """ msg = '' str_options = ','.join(options) #print("str_options = %r" % (str_options)) #print("STRESS-type key=%s value=%s options=%s" #% (key, value, options)) if value is None: val = '' else: val = ' = %s' % value if len(str_options) > 0: msgi = '%s(%s)%s\n' % (key, str_options, val) if len(msgi) > 64: msgi = '%s(' % key msg_done = '' i = 0 while i < len(options): new_msgi = '%s,' % options[i] if (len(msgi) + len(new_msgi)) < 64: msgi += new_msgi else: msg_done += msgi + '\n' msgi = spaces + new_msgi i += 1 msg_done += msgi msgi = '' msg_done = msg_done.rstrip(' ,\n') + ')%s\n' % val assert len(msgi) < 68, 'len(msg)=%s; msg=\n%s' % (len(msgi), msgi) msg += msg_done else: assert len(msgi) < 68, 'len(msg)=%s; msg=\n%s' % (len(msgi), msgi) msg += msgi else: msgi = '%s%s\n' % (key, val) assert len(msgi) < 68, 'len(msg)=%s; msg=\n%s' % (len(msgi), msgi) msg += msgi msg = spaces + msg return msg
def maxBit(int_val): """Return power of 2 for highest bit set for integer""" length = 0 count = 0 while (int_val): count += (int_val & 1) length += 1 int_val >>= 1 return length - 1
def _to_url(host, port, cmd): """Convert a host, port and command to a url.""" return "http://{:s}:{:d}/{:s}".format(host, port, cmd)
def invert_dict(input_dict: dict, sort_keys: bool = False) -> dict: """Create a new dictionary swapping keys and values. Invert a given dictionary, creating a new dictionary where each key is created from a value of the original dictionary, and its value is the key that it was associated to in the original dictionary (e.g. invert_dict({1: ["A", "E"], 2: ["D", "G"]}) = {"A": 1, "E": 1, "D": 2, "G": 2}). It is also possible to return an inverted dictionary with keys in alphabetical order, although this makes little sense for intrinsically unordered data structures like dictionaries, but it may be useful when printing the results. Args: input_dict: original dictionary to be inverted sort_keys: sort the keys in the inverted dictionary in alphabetical order (default: False) Returns: new_dict: inverted dictionary """ new_dict = {el: x for x in input_dict for el in input_dict[x]} if sort_keys: return {el: new_dict[el] for el in sorted(new_dict)} return new_dict
def format_custom_attr(ddic): """ Format a dictionary of dictionaries in string format in the "custom attribute" syntax e.g. custom="readingOrder {index:1;} structure {type:heading;}" """ s = "" for k1, d2 in ddic.items(): if s: s += " " s += "%s" % k1 s2 = "" for k2, v2 in d2.items(): if s2: s2 += " " s2 += "%s:%s;" % (k2, v2) s += " {%s}" % s2 return s
def lossy_compresion(text: str, token_separator=" ") -> str: """Here we just remove every consecutive duplicate tokens, so we only track changes e.g text ABC ABC ABC EE A S X X SD will be compressed to: ABC EE A S X SD. Args: text (str): text to be compressed Returns: str: compressed text """ compressed = [] tokenized = text.split(token_separator) previous = None for token in tokenized: if token != previous: compressed.append(token) previous = token return " ".join(compressed)
def check_two_shapes_need_broadcast(shape_x, shape_y): """Check shape_y needs to be broadcast to shape_x.""" if any(j not in (i, 1) for i, j in zip(reversed(shape_x), reversed(shape_y))): raise ValueError(f"{shape_y} could not broadcast with {shape_x}.") return shape_y != shape_x
def get_curve_shape_name(name=""): """ return the name of the curves. :param name: <str> base name. :return: <str> curve shape name. """ return '{}Shape'.format(name)
def augmentToBeUnique(listOfItems): """ Given a list that may include duplicates, return a list of unique items Returns a list of [(x,index)] for each 'x' in listOfItems, where index is the number of times we've seen 'x' before. """ counts = {} output = [] if listOfItems is None: return [] for x in listOfItems: counts[x] = counts.setdefault(x, 0) + 1 output.append((x, counts[x] - 1)) return output