content
stringlengths
39
9.28k
sha1
stringlengths
40
40
id
int64
8
710k
def _is_sub_partition(sets, other_sets): """ Checks if all the sets in one list are subsets of one set in another list. Used by get_ranked_trajectory_partitions Parameters ---------- sets : list of python sets partition to check other_sets : list of python sets partition to check against Returns ------- bool whether all sets are included in other_sets """ for set_ in sets: if not any(map(set_.issubset, other_sets)): #here if at least one set is not fully included in another set in the other partition return False return True
b2a1d60245a8d2eca1f753f998ac1d69c8ff9d08
646,120
import json def load_json(filename): """Load dictionary from JSON file.""" with open(filename, 'r') as f: mybooks = json.load(f) return(mybooks)
3edd21661886ea783e1e9d9c4f4c65561e35f060
646,551
import csv def load_label(filename): """ process the .csv label file Args: filename: /path/to/file/of/csvlabel/ (csv) Return: dirname_label_map: a hashmap {dirname <--> label} (dict: str->list[int]) Example: {..., INDEX10097: [3, 7] ,} """ dirname_label_map = {} with open(filename,'r') as cfile: reader = csv.reader(cfile) for row in reader: name = row[0] label = (row[1]).split(';') int_label = [int(lab) for lab in label] dirname_label_map[name] = int_label return dirname_label_map
e932f36a82969f2ac9bb65406d09a20895671a8f
495,883
async def simple_json(req) -> dict: """Returns simple json.""" return { "message": "Hello, world!" }
df01ded04586c8242ec8cb959557de28b9acef12
262,355
def id_from_string(hpo_string: str) -> int: """ Formats the HPO-type Term-ID into an integer id Parameters ---------- hpo_string: HPO term ID. (e.g.: HP:000001) Returns ------- int Integer representation of provided HPO ID (e.g.: 1) """ idx = hpo_string.split('!')[0].strip() return int(idx.split(':')[1].strip())
17de4c0b651d5f003dec21c29eac21f0b31ae607
449,569
def transverseWidgets(layout): """Get all widgets inside of the given layout and the sub-layouts""" w_lists = [] for i in range(layout.count()): item = layout.itemAt(i) if item.layout(): # if type(item) == QtGui.QLayoutItem: w_lists.extend(transverseWidgets(item.layout())) # if type(item) == QtGui.QWidgetItem: if item.widget(): w = item.widget() w_lists.append(w) if w.layout(): w_lists.extend(transverseWidgets(w.layout())) return w_lists
57c6d12e901f5248eb3e08b3d6f8e131d4e16a64
85,428
import re def rx(pat): """Helper to compile regexps with IGNORECASE option set.""" return re.compile(pat, flags=re.IGNORECASE)
7cae6aeff40dff0242c39c0961aace7cd042a0b6
594,134
def is_callable(x): """Tests if something is callable""" return callable(x)
72584deb62ac5e34e69325466236792c5299a51b
2,064
def _find_exon(subexon_table, subexon_id_cluster): """Return a list with the 'ExonID's of a particular subexon.""" return subexon_table.loc[subexon_table['SubexonIDCluster'] == subexon_id_cluster, 'ExonIDCluster'].unique( ).tolist()
09a2963d000f9ca31a03fe7ffe79d75c37d0bfde
198,519
def linear(input_value: float) -> float: """Simple linear activation function. Args: input_value (float): Input value to map. Returns: float: Mapped value. """ return input_value
7431612e2836b10c2a1d6433e27d8fec569b2612
376,937
def test(pre=None, post=None): """Decorator to execute tests and print useful information The method being tested must have an <assert> pre is a function without arguments to execute before the test starts post is a function without arguments to execute after the test has finished """ def inner(func): def wrap(*args, **kwargs): if pre: pre() print(func.__name__,":", end="") try: func() print("OK!") except AssertionError: print("ASSERTION ERROR!") except Exception as exc: print("ERROR!", exc) if post: post() return wrap return inner
2e2358244475f4ce64a81ecc924172216aeb9821
564,339
import re def parse_error(err): """ "Parse" error string (formats) raised by (simple)json: '%s: line %d column %d (char %d)' '%s: line %d column %d - line %d column %d (char %d - %d)' """ return re.match(r"""^ (?P<msg>.+):\s+ line\ (?P<lineno>\d+)\s+ column\ (?P<colno>\d+)\s+ (?:-\s+ line\ (?P<endlineno>\d+)\s+ column\ (?P<endcolno>\d+)\s+ )? \(char\ (?P<pos>\d+)(?:\ -\ (?P<end>\d+))?\) $""", err, re.VERBOSE)
ca00993ce96abe1c64c5564862b47086f1dee300
326,376
def bar_label_formatter(x, pos): """Return tick label for bar chart.""" return int(x)
b1e6d1534d1a5b403d7ca037eb8f445771c26683
55,142
def party_planner(cookies, people): """This function will calculate how many cookies each person will get in the party and also gives out leftovers ARGS: cookies: int, no of cookies is going to be baked people: int, no of people are attending this party_planner Returns: tuple of cookies per person and leftovers""" leftovers = None num_each = None try: num_each = cookies // people leftovers = cookies % people except ZeroDivisionError as e: print('People cannot be zero. {}'.format(e)) return(num_each, leftovers)
b4d4545710f689f2b048ba4a1637647b80aac451
72,866
def ode_schnakenberg(t, y, a_prod, b_prod): """Derivatives to be called into solve_ivp This returns an array of derivatives y' = [A', B'], for a given state [A, B] at a time t. This is based on the classical Schnakenberg system. Params: t [float] - the time at which the derivative is evaluated y [array] - the current state of the system, in the form [A, B] """ return [y[0]**2 * y[1] - y[0] + a_prod, -y[0]**2 * y[1] + b_prod]
a4e403e55a3f8c89efb71a677a93c0b3178325b1
261,880
def _resolve_subkeys(key, separator='.'): """Resolve a potentially nested key. If the key contains the ``separator`` (e.g. ``.``) then the key will be split on the first instance of the subkey:: >>> _resolve_subkeys('a.b.c') ('a', 'b.c') >>> _resolve_subkeys('d|e|f', separator='|') ('d', 'e|f') If not, the subkey will be :data:`None`:: >>> _resolve_subkeys('foo') ('foo', None) Args: key (str): A string that may or may not contain the separator. separator (str): The namespace separator. Defaults to `.`. Returns: Tuple[str, str]: The key and subkey(s). """ parts = key.split(separator, 1) if len(parts) > 1: return parts else: return parts[0], None
f7b749a0645a71048aaa3ffa693540c97772653a
661,489
def lowercase_set(sequence): """ Create a set from sequence, with all entries converted to lower case. """ return set((x.lower() for x in sequence))
23f55bd4ad1c9ec19b9d360f87a3b310ad619114
662,890
def invert_y_and_z_axis(input_matrix_or_vector): """Invert the y and z axis of a given matrix or vector. Many SfM / MVS libraries use coordinate systems that differ from Blender's coordinate system in the y and the z coordinate. This function inverts the y and the z coordinates in the corresponding matrix / vector entries, which is equivalent to a rotation by 180 degree around the x axis. """ output_matrix_or_vector = input_matrix_or_vector.copy() output_matrix_or_vector[1] = -output_matrix_or_vector[1] output_matrix_or_vector[2] = -output_matrix_or_vector[2] return output_matrix_or_vector
d220e7b8e6868663a75896826ad559195bd0f994
491,493
def tabular_tex( body_df, footer_df, notes_tex, render_options, custom_index_names, custom_model_names, left_decimals, sig_digits, show_footer, ): """Return estimation table in LaTeX format as string. Args: body_df (pandas.DataFrame): the processed dataframe with parameter values and precision (if applied) as strings. footer_df (pandas.DataFrame): the processed dataframe with summary statistics as strings. notes_tex (str): a string with LaTex code for the notes section render_options(dict): the pd.to_latex() kwargs to apply if default options need to be updated. lef_decimals (int): see main docstring sig_digits (int): see main docstring show_footer (bool): see main docstring Returns: latex_str (str): the string for LaTex table script. """ n_levels = body_df.index.nlevels n_columns = len(body_df.columns) # here you add all arguments of df.to_latex for which you want to change the default default_options = { "index_names": False, "escape": False, "na_rep": "", "column_format": "l" * n_levels + "S[table-format ={}.{}]".format(left_decimals, sig_digits) * n_columns, "multicolumn_format": "c", } if custom_index_names: default_options.update({"index_names": True}) if render_options: default_options.update(render_options) if not default_options["index_names"]: body_df.index.names = [None] * body_df.index.nlevels latex_str = body_df.to_latex(**default_options) if custom_model_names: temp_str = "\n" for k in custom_model_names: max_col = max(custom_model_names[k]) + n_levels + 1 min_col = min(custom_model_names[k]) + n_levels + 1 temp_str += f"\\cmidrule(lr){{{min_col}-{max_col}}}" temp_str += "\n" latex_str = ( latex_str.split("\\\\", 1)[0] + "\\\\" + temp_str + latex_str.split("\\\\", 1)[1] ) latex_str = latex_str.split("\\bottomrule")[0] if show_footer: stats_str = footer_df.to_latex(**default_options) stats_str = ( "\\midrule" + stats_str.split("\\midrule")[1].split("\\bottomrule")[0] ) latex_str += stats_str latex_str += notes_tex latex_str += "\\bottomrule\n\\end{tabular}\n" if latex_str.startswith("\\begin{table}"): latex_str += "\n\\end{table}\n" return latex_str
5858b6334f33cf68bbd737a15117fec6e16c1c76
75,143
def _get_opt_first_name(a): """ Get the first of an action's option names. """ return a.option_strings[0]
bbd5f42ea152ab839156d5a026621b93639e8ba9
544,625
def get_region(context): """ Return the AWS account region for the executing lambda function. Args: context: AWS lambda Context Object http://docs.aws.amazon.com/lambda/latest/dg/python-context-object.html Returns: str : AWS Account Region """ return str(context.invoked_function_arn.split(":")[3])
220a63aef52d97ec8bd5bc6803b7a33803cdaf2f
671,349
import re def valid_uuid(possible_uuid): """ Checks that a possible UUID4 string is a valid UUID4. """ regex = re.compile('^[a-f0-9]{8}-?[a-f0-9]{4}-?4[a-f0-9]{3}-?[89ab][a-f0-9]{3}-?[a-f0-9]{12}\Z', re.I) match = regex.match(possible_uuid) return bool(match)
d20d764362d82fb05dd6554710e471c56786c074
175,077
from typing import Dict from typing import Any from typing import Optional def _get_driver_kwargs( platform_details: Dict[str, Any], variant: Optional[str], _async: bool = False ) -> Dict[str, Any]: """ Parent get driver method Args: platform_details: dict of details about community platform from scrapli_community library variant: optional name of variant of community platform _async: True/False this is for an asyncio transport driver Returns: final_platform_kwargs: dict of final driver kwargs Raises: N/A """ platform_kwargs = platform_details["defaults"] if variant: variant_kwargs = platform_details["variants"][variant] final_platform_kwargs = {**platform_kwargs, **variant_kwargs} else: final_platform_kwargs = platform_kwargs if not _async: # remove unnecessary asyncio things final_platform_kwargs.pop("async_on_open") final_platform_kwargs.pop("async_on_close") # rename sync_on_(open|close) keys to just "on_open"/"on_close" final_platform_kwargs["on_open"] = final_platform_kwargs.pop("sync_on_open") final_platform_kwargs["on_close"] = final_platform_kwargs.pop("sync_on_close") else: # remove unnecessary sync things final_platform_kwargs.pop("sync_on_open") final_platform_kwargs.pop("sync_on_close") # rename sync_on_(open|close) keys to just "on_open"/"on_close" final_platform_kwargs["on_open"] = final_platform_kwargs.pop("async_on_open") final_platform_kwargs["on_close"] = final_platform_kwargs.pop("async_on_close") return final_platform_kwargs
2f29f4290a0b41b9e032976cde5aa70622cf266b
130,301
def delete_node(manager, handle_id): """ Deletes the node and all its relationships. :param manager: Neo4jDBSessionManager :param handle_id: Unique id :rtype: bool """ q = """ MATCH (n:Node {handle_id: {handle_id}}) OPTIONAL MATCH (n)-[r]-() DELETE n,r """ with manager.session as s: s.run(q, {'handle_id': handle_id}) return True
124281e6d0d3c2fa1f6deab05c22c2540e56b603
239,723
def get_speakers(items): """Returns a sorted, unique list of speakers in a given dataset.""" speakers = {e[2] for e in items} return sorted(speakers)
451c10463a34f40839bec6cf8b017dfa4018b342
610,064
def hhmmss_to_sec(hhmmss): """Parses a HH:MM:SS-string and returns the corresponding number of seconds after midnight. Args: hhmmss (str): HH:MM:SS-string Returns: int: number of seconds after midnight. """ h, m, s = hhmmss.split(':') return int(h) * 3600 + int(m) * 60 + int(s)
5ceb6b1d3ac1809ebb8b54227a7a99f6575d9c19
233,832
def get_metadata_namespaces(metadata): """ Utility function to get all the namespaces from a metadata document and return them as a set() :param metadata: the metadata document :type metadata: schema.Edmx :return: the namespace """ metadata_namespaces = set() for reference in metadata.References: for include in reference.Includes: metadata_namespaces.add(include.Namespace) return metadata_namespaces
7532e38a50500fe40d4ea0c72b84ef2b5032a3fa
276,946
def p(n, d): """ Helper to calculate the percentage of n / d, returning 0 if d == 0. """ if d == 0: return 0.0 return float(n) / d
2b009b7059af7e2897a9e4d92246f8c0c883e7e1
568,844
def PowersOf(logbase, count, lower=0, include_zero=True): """Returns a list of count powers of logbase (from logbase**lower).""" if not include_zero: return [logbase ** i for i in range(lower, count+lower)] else: return [0] + [logbase ** i for i in range(lower, count+lower)]
708e46dbff1b838fdfb0c9ca2c354ccc21bd453d
285,113
def remove_end_same_as_start_transitions(df, start_col, end_col): """Remove rows corresponding to transitions where start equals end state. Millington 2009 used a methodology where if a combination of conditions didn't result in a transition, this would be represented in the model by specifying a transition with start and end state being the same, and a transition time of 0 years. AgroSuccess will handle 'no transition' rules differently, so these dummy transitions should be excluded. """ def start_different_to_end(row): if row[start_col] == row[end_col]: return False else: return True return df[df.apply(start_different_to_end, axis=1)]
f4b3ddca74e204ed22c75a4f635845869ded9988
3,243
def get_diff(throw, target): """ Determines the difference between a throw and a target E.g. between '111344' and '111144' Here, the difference is 1, dice to keep is '11144', to remove is '3' """ diff = 0 remove = [] keep = [] for i, j in zip(throw, target): if i != j: diff += 1 remove.append(i) else: keep.append(i) return diff, ''.join(keep), ''.join(remove)
6c0dfe395cc7fbfbf5f2e745cde9a61d81b045f8
55,518
import re def GetSizeAnnotationToDraw(annotationList):#{{{ """Get the size of annotation field""" maxSize = 0 for anno in annotationList: m1 = re.search("nTM\s*=\s*[0-9]*", anno) m2 = re.search("group of [0-9]*", anno) m3 = re.search("[^\s]+", anno) pos1 = 0 pos2 = 0 pos3 = 0 if m1: pos1 = m1.end(0) if m2: pos2 = m2.end(0) if m3: pos3 = m3.end(0) size = max(pos1,pos2, pos3) if size > maxSize: maxSize = size return maxSize
f45ff9153718c5fedb254fa3716d2d66fc7d60f2
67,387
def expected(vertices: int, colors: int) -> int: """Compute expected colorings with chromatic polynomial.""" return (colors - 1)**vertices + (-1)**vertices * (colors - 1)
6b1c8fc638b792a0c1ac2c2b59b8ce3973b44d58
348,556
def _getWordCategory(word, words_category_index): """ Retrieves the category of a word :param word: :param words_category_index: :return: """ if word in words_category_index: return words_category_index[word] else: return None
f9fd5701d4df5582ced02f51773fdcb158521114
587,419
def strip_transient(nb): """Strip transient values that shouldn't be stored in files. This should be called in *both* read and write. """ nb.metadata.pop('orig_nbformat', None) nb.metadata.pop('orig_nbformat_minor', None) nb.metadata.pop('signature', None) for cell in nb.cells: cell.metadata.pop('trusted', None) return nb
560a06532273c2a983692c17e898351c4a78130b
73,315
def linear_segment(x0, x1, y0, y1, t): """Return the linear function interpolating the given points.""" return y0 + (t - x0) / (x1 - x0) * (y1 - y0)
de8bb06a7b294e0f0eb62f471da553a58e65fc49
44,109
def clsn(obj): """Short-hand to get class name. Intended for use in __repr__ and such.""" if isinstance(obj, str): return obj else: return obj.__class__.__name__
e030359e86cf07db8e6869c219575c74c620de6a
650,096
import json def parse_entanglement_header(header): """ Parse the entanglement header encoded as a JSON string. Args: header(str): JSON encoded entanglement header Returns: list((path, int)): The deseralized entanglement header """ return json.loads(header)
11f6a7948f7ceacfa2f7780dd6e54759e1b3a41a
230,325
def get_valid_base_urls(order=None): """ Return a list of valid base URLs from where the user analysis transform may be downloaded from. If order is defined, return given item first. E.g. order=http://atlpan.web.cern.ch/atlpan -> ['http://atlpan.web.cern.ch/atlpan', ...] NOTE: the URL list may be out of date. :param order: order (string). :return: valid base URLs (list). """ valid_base_urls = [] _valid_base_urls = ["http://www.usatlas.bnl.gov", "https://www.usatlas.bnl.gov", "http://pandaserver.cern.ch", "http://atlpan.web.cern.ch/atlpan", "https://atlpan.web.cern.ch/atlpan", "http://classis01.roma1.infn.it", "http://atlas-install.roma1.infn.it"] if order: valid_base_urls.append(order) for url in _valid_base_urls: if url != order: valid_base_urls.append(url) else: valid_base_urls = _valid_base_urls return valid_base_urls
8d1bcd1fcd9a7774e19d903a178fabdc69da4b6b
269,661
def perm_conjugate(p, s): """ Return the conjugate of the permutation `p` by the permutation `s`. INPUT: two permutations of {0,..,n-1} given by lists of values OUTPUT: a permutation of {0,..,n-1} given by a list of values EXAMPLES:: sage: from sage.combinat.constellation import perm_conjugate sage: perm_conjugate([3,1,2,0], [3,2,0,1]) [0, 3, 2, 1] """ q = [None] * len(p) for i in range(len(p)): q[s[i]] = s[p[i]] return q
a30fe25812709db4944cd7e00d21a9c889e15f0a
441,160
import lzma def compress_lzma(data: bytes) -> bytes: """compresses data via lzma (unity specific) The current static settings may not be the best solution, but they are the most commonly used values and should therefore be enough for the time being. :param data: uncompressed data :type data: bytes :return: compressed data :rtype: bytes """ ec = lzma.LZMACompressor( format=lzma.FORMAT_RAW, filters=[ {"id": lzma.FILTER_LZMA1, "dict_size": 524288, "lc": 3, "lp": 0, "pb": 2, } ], ) ec.compress(data) return b"]\x00\x00\x08\x00" + ec.flush()
06a476a2753be7d591051b9707cf5dbf58556086
692,205
from typing import Counter def contains_duplicate(items): """ Returns True if items contains a duplicate (or more) element """ counter = Counter(items) for freq in counter.values(): if freq > 1: return True return False
769eb5e52a7e32aa2645917118678de796c9e893
134,676
import hashlib def _text_checksum(text): """Calculate a digest string unique to the text content""" return hashlib.sha1(text).hexdigest()
eebdb85139b2b7e9cba8adea3d396458ab6aba3d
395,664
def _xyz_to_uv(x: float, y: float, z: float) -> tuple[float, float]: """Convert the color from CIEXYZ coordinates to uv chromaticity coordinates.""" if x == y == 0: return 0, 0 d = x + 15 * y + 3 * z return 4 * x / d, 9 * y / d
70bf86e81fcd298873bd094bdccf0e9856c360b7
358,872
from typing import OrderedDict def process_condition(row): """ row: a string of the form 'a=b;c=d;...' where each RHS can be converted to float. Returns: a dictionary derived from row, plus the key 'Device' with value device. """ d = OrderedDict() if "=" not in row: return d conditions = row.split(";") for cond in conditions: els = cond.split("=") d[els[0]] = float(els[1]) return d
7783e5e906eb6f6fd2b0c3e2f2271597b34a822b
286,866
import time def repeat_execution(fct, every_second=1, stop_after_second=5, verbose=0, fLOG=None, exc=True): """ Runs a function on a regular basis. The function is not multithreaded, it returns when all execution are done. @param fct function to run @param every_second every second @param stop_after_second stop after a given time or never if None @param verbose prints out every execution @param fLOG logging function @param exc if False, catch exception, else does not catch them @return results of the function if *stop_after_second* is not None """ iter = 0 start = time.monotonic() end = None if stop_after_second is None else start + stop_after_second current = start res = [] while end is None or current < end: iter += 1 if exc: r = fct() if verbose > 0 and fLOG is not None: fLOG("[repeat_execution] iter={} time={} end={}".format( iter, current, end)) if stop_after_second is not None: res.append(r) else: try: r = fct() if verbose > 0 and fLOG is not None: fLOG("[repeat_execution] iter={} time={} end={}".format( iter, current, end)) if stop_after_second is not None: res.append(r) except Exception as e: if verbose > 0 and fLOG is not None: fLOG("[repeat_execution] iter={} time={} end={} error={}".format( iter, current, end, str(e))) while current <= time.monotonic(): current += every_second while time.monotonic() < current: time.sleep(every_second / 2) return res if res else None
832c95cbb9285a68708dd90e8dbd7b8e7c09a6d1
39,418
def window_neighborhood(radius=1.0): """Window neighborhood kernel function. Parameters ---------- radius : float (default = 1.0) radius of the window. Returns ------- neighborhood_fun : (d : int) => float in [0,1] neighborhood function. """ def neighborhood_fun(d): return 1.0 if d <= radius else 0.0 return neighborhood_fun
7d1c3b3cdf87e75d8304b32fdf3ee2646ffe8f2e
514,563
import math def long2net(arg): """Convert long to netmask""" if (arg <= 0 or arg >= 0xFFFFFFFF): raise ValueError("illegal netmask value", hex(arg)) return 32 - int(round(math.log(0xFFFFFFFF - arg, 2)))
1f17505290c1a48f4cb4b84c39ffedf47614702a
244,299
def mock_get_env_vars(env_vars_exists): """Mock the call to os.getenv in get_credentials""" expecteds = ('partner_id', 'shop_id', 'key', 'sandbox') credentials = dict().fromkeys(expecteds) if env_vars_exists: for expected in expecteds: credentials.update({expected: 'XXX'}) return credentials
8cead493f0b26f05fe96511dbf642101393916df
402,651
import re def normalize_ipv4(ip): """ Remove the network mask from the ip address. e.g. 0.0.0.0/24 -> 0.0.0.0 """ regex = r'(\d+)[.](\d+)[.](\d+)[.](\d+)[/](\d+)' if not re.findall(regex, ip): return ip p = re.split(regex, ip) return "%s.%s.%s.%s" % (p[1], p[2], p[3], p[4])
97091617bf527b2a125715e04fe47604ad95f4ee
550,381
def get_port_from_usb( first_usb_index, second_usb_index ): """ Based on last two USB location index, provide the port number """ acroname_port_usb_map = {(4, 4): 0, (4, 3): 1, (4, 2): 2, (4, 1): 3, (3, 4): 4, (3, 3): 5, (3, 2): 6, (3, 1): 7, } return acroname_port_usb_map[(first_usb_index, second_usb_index)]
37a236ac3a6a16a67f55b123c1c650e8ff0b685c
125,771
def solved(values): """Checks if a sudoku puzzle is solved or unsolvable, returns -1 if unsolvable, 1 if solved and 0 if not solved""" for u in values: if len(values[u]) < 1: return -1 elif len(values[u]) > 1: return 0 return 1
9ef2dd1fd07f60e8e36b8bafeb59ff68f8032727
536,192
def _slugify(text: str) -> str: """Turns the given text into a slugified form.""" return text.replace(" ", "-").replace("_", "-")
78a034e07215e7964ebf1fc66162942d7b4ae85e
668,870
import re def Language_req(description): """Create a function that captures the language requirements from the job description""" description = description.lower() matches = re.findall(r"\benglish\sand\sgerman\b|\bgerman\sand\senglish\b\benglisch\sund\sdeutsch\b|\benglish\b|\benglisch\b|\bgerman\b|\bdeutsch\b", description) for item in matches: return item
cb6ce14d3cba497f668c701d16c13fdfd78f5dc5
8,314
def bulk_data(json_string, bulk): """ Check if json has bulk data/control messages. The string to check are in format: ``{key : [strings]}``. If the key/value is found return True else False :param dict json_string: :param dict bulk: :returns: True if found a control message and False if not. :rtype: bool """ for key, value in bulk.items(): if key in json_string.keys(): for line in value: if json_string.get(key) == line: return True return False
3b2cf4dde75951b48688bb516475e778eac28ce2
540,406
def create_perturbable_texels(texels_map, mask_map, initial_value=0., sign_grad=True): """ Creates perturbable texels using mask to define perturbable area. Will also initialize perturbable area to some value. If no mask is specified for texel, we treat the entire texel as not perturbable. Gradients of these perturbable texels will be masked and magnitudeless, if sign_grad=True. Parameters: texels_map (dict[str -> torch.Tensor[N, C, H, W]]): Dictionaries of texels. mask_map (dict[str -> torch.Tensor[M, 1, H, W]]): Dictionary of masks. initial_value (float or torch.Tensor): Initial value to set perturbable area, must be broadcastable to mask. sign_grad (bool): Whether to remove gradient magnitude for the gradient of perturable texel. Returns: dict(str -> torch.Tensor[N, C, H, W]): List of perturbable texels that require gradients. """ perturbed_texels_map = {} for name, texels in texels_map.items(): if name in mask_map: texels_rgb = texels[:3, :, :] mask = mask_map[name] perturbed_texels = texels_rgb*(1 - mask) + initial_value*mask perturbed_texels.requires_grad_(True) perturbed_texels.register_hook(lambda grad: grad*mask) if sign_grad: perturbed_texels.register_hook(lambda grad: grad.sign()) else: perturbed_texels = texels perturbed_texels_map[name] = perturbed_texels return perturbed_texels_map
467aca12b8308e362857409e0092a8cbf74b94a2
390,590
def strMakeComma(categories): """ Make comma seperate string i.e: a, b, c """ result = "" for catg in categories: result += catg["name"] + ", " if len(result) > 0: result = result[:len(result) - 2] return result
fb829e331b494ca373167191f59d787ae1762343
496,627
import torch def texture_loss(img_pred, img_gt, mask_gt): """ Input: img_pred, img_gt: B x 3 x H x W mask_pred, mask_gt: B x H x W """ mask_gt = mask_gt.unsqueeze(1) return torch.nn.L1Loss()(img_pred * mask_gt, img_gt * mask_gt)
54c9894e63b355829cea374ae96ae959c8612070
298,246
import re def get_task_path_and_exc(file_path): """Get the task path and exception from the file by using its file path""" with open(file_path, 'r') as f: for line in f: reg = re.search('Task (.*) with id (?:[0-9a-f\-]+) raised ' 'exception:', line) if reg: task_name = reg.group(1) return task_name, f.readline().strip()
30b94c1c0b72055aef83325b2f27f2810586b03e
619,617
import sqlite3 def get_win_rate(num_moves=None, num_trials=None): """Get the win rate for a specified configuration of num_moves and num_trials Args: num_moves (int, optional): The value for num_moves which printed trials must match. Defaults to None. num_trials (int, optional): The value for num_trials which printed trials must match. Defaults to None. Returns: float: The win rate of all the valid trials """ conn = sqlite3.connect("2048_AI_results.db") cursor = conn.cursor() if num_moves and num_trials: cursor.execute("SELECT AVG(did_win) FROM results WHERE num_moves = ? AND num_trials = ?", (num_moves, num_trials)) else: cursor.execute("SELECT AVG(did_win) FROM results") win_rate = round(cursor.fetchone()[0] * 100, 2) print(f"WIN RATE: {win_rate}%") conn.close() return win_rate
466d2bf1a6c3dd1d737564b0731d3067acdab417
125,474
def check_incompatible(dict_in, inc_list): """ Check any conflicting keys in the dictionary """ for incomp in inc_list: c = 0 for k in dict_in: if k in incomp: c += 1 if c > 1: return incomp return
42d596a3dbf69c4d8696eb0ec8ea62a096130c7e
631,701
import math def PSucLB(sigma,n,d,param): """ Compute the lower bound given by Theorem 2 in the paper. param corrersponds to Rmax in the paper. """ sigma = sigma**2 return .5 + (d*sigma)/(2*n*param) - math.exp(-param/(2*sigma))*(1+(2*sigma)/param)
d4135229648c11a75b969d3df29baac52536e124
150,828
def normalize_windows(win_data): """ Normalize a window Input: Window Data Output: Normalized Window Note: Run from load_data() Note: Normalization data using n_i = (p_i / p_0) - 1, denormalization using p_i = p_0(n_i + 1) """ norm_data = [] for w in win_data: norm_win = [((float(p) / float(w[0])) - 1) for p in w] norm_data.append(norm_win) return norm_data
101d142e28a742b7c7814292977eaf3904f8eb91
536,392
def euclidean_distance_nosqrt(x1, x2): """ 欧氏距离,不对结果开方 Args: x1: [B, N] or [N] x2: same shape as x1 Returns: [B] vector or scalar """ return (x1 - x2).pow(2).sum(-1)
cd9fd3a4e567d7a2923eb4f4f0ef60482be7f2ea
482,278
def fibonacci_loop(n): """Calculate the nth Fibonacci number using a loop""" nn = n - 2 #Already done 1st and second vals fib = [1, 1] while nn > 0: tmp = fib[0] fib[0] = fib[1] fib[1] +=tmp nn -= 1 #If even, return the first val, else, the second return fib[n%2]
5356a1a904cc45621a8165065d4733a7961fb518
71,795
def split(walker, number=2): """Split (AKA make multiple clones) of a single walker. Creates multiple new walkers that have the same state as the given walker with weight evenly divided between them. Parameters ---------- walker : object implementing the Walker interface The walker to split/clone number : int The number of clones to make of the walker (Default value = 2) Returns ------- cloned_walkers : list of objects implementing the Walker interface """ # calculate the weight of all child walkers split uniformly split_prob = walker.weight / (number) # make the clones clones = [] for i in range(number): clones.append(type(walker)(walker.state, split_prob)) return clones
2b6941dd5976b31733bbd93cc60243635f639bce
558,927
def get_layer(model, name): """ Gets a layer from a model. # Arguments: model: A keras model name: A string, name of a layer in the model # Returns: A keras layer """ assert name in model.layers for l in model.layers: if l.name == name: return l
b8054684d1822f2186ab5ea612ec0c4a44ffa6e1
393,483
def constructor_is_method_name(constructor: str) -> bool: """Decides wheter given constructor is a method name. Cipher is not a method name Cipher.getInstance is a method name getS is a method name """ found_index = constructor.find(".") method_start_i = found_index + 1 return len(constructor) > method_start_i and constructor[method_start_i].islower()
ee410e1c8df218235fe60ba028dd61bb93cda67b
110,019
def onedim_conversion(length_or_speed: float, mm_per_pixel: float): """ :param length_or_speed: in [px] or [px/s] :param mm_per_pixel: in [mm/px] :return: length i [mm] or speed in [mm/s] """ return length_or_speed * mm_per_pixel
0eb707b0946fb917a7f93df62819a15b28135170
634,235
def split_paragraphs(string): """ Split `string` into a list of paragraphs. A paragraph is delimited by empty lines, or lines containing only whitespace characters. """ para_list = [] curr_para = [] for line in string.splitlines(keepends=True): if line.strip(): curr_para.append(line) else: para_list.append(''.join(curr_para)) curr_para = [] if curr_para: para_list.append(''.join(curr_para)) return para_list
4e321d263beecf37efe1da34c503da314a97b894
113,500
import string def shift_letter(letter: str, amount: int) -> str: """Shift a letter forward in the alphabet by a certain amount.""" sv_alfabet = string.ascii_lowercase + "åäö" new_position = (amount + sv_alfabet.index(letter)) % len(sv_alfabet) return sv_alfabet[new_position]
f91213198b6bac7dd78ade0340bbb201ea2a5c6d
379,223
def unknown_char(char_name, id_ep): """Transforms character name into unknown version.""" if "#unknown#" in char_name:#trick when re-processing already processed files return char_name return f"{char_name}#unknown#{id_ep}"
061683efd275335e58129225fe4bc9dabc044c9b
694,707
def weighted_sum(pdf, col_name): """ Return weighted sum of Pandas DataFrame col_name items. """ return (pdf[col_name] * pdf['s006']).sum()
e9954ca2ee7e09f58abbf2420da9824a2e079d3a
603,321
def event_url(event): """ Returns the URL for a Pyvo event. """ return "https://pyvo.cz/{event.series.slug}/{event.slug}/".format(event=event)
91ed2424748f16aedda40c11a5f6e24eabef71f5
386,553
def format_counts(counts): """Formats the contents of the counts dictionary into a string suitable for output. Args: counts - dictionary containing the attendance statistics Returns: string containing the counts formatted for output """ fstr = ("Attendance Figures:\n" " Registrations: {0}\n" " Total Attendees: {1}\n" " Registered No Shows: {2}\n" " Non-registered Attendees: {3}\n") return fstr.format(counts['registrants'] ,counts['attendees'] ,counts['reg_no_attend'] ,counts['attend_no_reg'])
9161a38ea65ddf99a4141b6528342ffd9b1cb67b
99,572
def list_of_first_n(v, n): """Given an iterator v, return first n elements it produces as a list.""" if not hasattr(v, 'next'): v = v.__iter__() w = [] while n > 0: try: w.append(v.next()) except StopIteration: return w n -= 1 return w
ac98423187b1a45f5c1e5e47b215245ecb30ef6c
612,768
from typing import Dict def wrap_single_element_in_list(data: Dict, many_element: str): """Make a specified field a list if it isn't already a list.""" if not isinstance(data[many_element], list): data[many_element] = [data[many_element]] return data
1c1c2b1ff5e65af37f86c7ee1d4dd7a38ab0faf4
122,928
def sum_word(word: str) -> str: """Sum the ordinal values of a word.""" return str(sum([ord(char) for char in word if char.isalnum()]))
c3ac1c488fb6f1e09a2e5cae8f60d9677bdbadce
198,701
def findpeptide(pep, seq, returnEnd = False): """Find pep in seq ignoring gaps but returning a start position that counts gaps pep must match seq exactly (otherwise you should be using pairwise alignment) Parameters ---------- pep : str Peptide to be found in seq. seq : str Sequence to be searched. returnEnd : bool Flag to return the end position such that: seq[startPos:endPos] = pep Returns ------- startPos : int Start position (zero-indexed) of pep in seq or -1 if not found""" ng = seq.replace('-', '') ngInd = ng.find(pep) ngCount = 0 pos = 0 """Count the number of gaps prior to the non-gapped position. Add them to it to get the gapped position""" while ngCount < ngInd or seq[pos] == '-': if not seq[pos] == '-': ngCount += 1 pos += 1 startPos = ngInd + (pos - ngCount) if returnEnd: if startPos == -1: endPos = -1 else: count = 0 endPos = startPos while count < len(pep): if not seq[endPos] == '-': count += 1 endPos += 1 return startPos, endPos else: return startPos
3af5afa60fd29f28fd5d3d7ebfbd727c60db3948
680,968
def find (possible): """Returns `(key, index)` such that `possible[key] = [ index ]`.""" for name, values in possible.items(): if len(values) == 1: return name, values[0]
6fb98eb6baf4756210f0e8fa38783a3498cf3093
663,651
def is_valid_color(color, threshold): """ Return True if each component of the given color (r, g, b, a) is above threshold """ if color[0] > threshold and color[1] > threshold and color[2] > threshold: return True return False
3391779e0977225f7340f50a823610b4dd22876b
49,158
def _translate(num_time): """Translate number time to str time""" minutes, remain_time = num_time // 60, num_time % 60 str_minute, str_second = map(str, (round(minutes), round(remain_time, 2))) str_second = (str_second.split('.')[0].rjust(2, '0'), str_second.split('.')[1].ljust(2, '0')) str_time = str_minute.rjust(2, '0') + f':{str_second[0]}.{str_second[1]}' return str_time
af49424d3b9c6dfb660955b604c33e9a31e1c3de
31,992
def trim_bst(root, min, max): """Select a range from a binary search tree between ``min`` and ``max``. Arguments: root (binary search tree): The root of a binary search tree. A binary tree is either a 3-tuple ``(data, left, right)`` where ``data`` is the value of the root node and ``left`` and ``right`` are the left and right subtrees or ``None`` for the empty tree. A binary search tree is a binary tree whose in-order traversal is sorted. min: The minimum value of the trim. max: The maximum value of the trim. Returns: new_root (binary search tree): A new binary search tree that is like the input, but only contains nodes with values between ``min`` and ``max``, inclusive. """ if root is None: return None (data, left, right) = root if data < min: return trim_bst(right, min, max) elif max < data: return trim_bst(left, min, max) else: new_left = trim_bst(left, min, max) new_right = trim_bst(right, min, max) return (data, new_left, new_right)
47e65cd44cd22ea70214ec5036fc066aa225b074
301,800
from typing import List def cast_trailing_nulls(series: List) -> List: """ Cast trailing None's in a list series to 0's """ for i, x in reversed(list(enumerate(series))): if x is None: series[i] = 0 else: return series return series
3a7f7d53dcb7ed9b892b9b423c3650a339af26e2
627,957
def delete_default_service_account(context, api_names_list): """ Delete the default service account. """ resource = [ { 'name': '{}-delete-default-sa'.format(context.env['name']), # https://cloud.google.com/iam/reference/rest/v1/projects.serviceAccounts/delete 'action': 'gcp-types/iam-v1:iam.projects.serviceAccounts.delete', 'metadata': { 'dependsOn': api_names_list, 'runtimePolicy': ['CREATE'] }, 'properties': { 'name': 'projects/$(ref.{}-project.projectId)/serviceAccounts/$(ref.{}-project.projectNumber)-compute@developer.gserviceaccount.com'.format(context.env['name'], context.env['name']) # pylint: disable=line-too-long } } ] return resource
fcc76629f92cd860dc42d01acb1ca99423c17c95
324,362
def parse_timedelta_from_api(data_dict, key_root): """Returns a dict with the appropriate key for filling a two-part timedelta field where the fields are named <key_root>_number and <key_root>_units. Parameters ---------- data_dict: dict API json response containing a key matching the key_root argument. key_root: str The prefix used to identify the timedelta `<input>` elements. This should match the metadata dictionaries key for accessing the value. Returns ------- dict dict with keys <key_root>_number and <key_root>_units set to the appropriate values. Raises ------ TypeError If the interval length key is set to a non-numeric value or does not exist. """ interval_minutes = data_dict.get(key_root) # set minutes as default interval_units, as these are returned by the API interval_units = 'minutes' if interval_minutes % 1440 == 0: interval_units = 'days' interval_value = int(interval_minutes / 1440) elif interval_minutes % 60 == 0: interval_units = 'hours' interval_value = int(interval_minutes / 60) else: interval_value = int(interval_minutes) return { f'{key_root}_number': interval_value, f'{key_root}_units': interval_units, }
467130e50d3d5d0a224eed83822d352713ef11c2
623,095
def check_point(point): """Validates a 2-d point with an intensity. Parameters ---------- point : array_like (x, y, [intensity]) Coordinates of the point to add. If optional `intensity` is not supplied, it will be set to `None`. Returns ------- point : :obj:tuple of :obj:float The same point converted to floats, assuming no errors were raised. """ if len(point) != 2: intensity = point[-1] point = point[:-1] else: intensity = None if len(point) != 2: raise ValueError("Coordinates must be two-dimensional.") try: point = tuple([float(p) for p in point]) # Convert everything to floats. except ValueError: raise ValueError("Coordinates must be convertible to floats.") return point + tuple((intensity,))
c2e56e2fa3fd0750570eb46b24dffbd1c30f9a6b
264,313
from typing import List import html import re def get_links(text: str) -> List[str]: """Extract all the links in the given text string Args: text (str): The text provided Returns: List[str]: List of http links """ return [ html.unescape("".join(item).strip(".")) for item in re.findall(r'(http|https)(:\/\/)([^ \'"\s]*)', text) ]
7cfb541ff2e702b6999f034ef8fb51a4ed6b38f7
390,138
def parse_punishment(argument): """Converts a punishment name to its code""" punishments = { "none": 0, "note": 1, "warn": 1, "mute": 2, "kick": 3, "ban": 4 } return punishments[argument.lower()]
9ca9ad052c5636dd58f1b375296137de8b55712b
700,136
import re def parse_str(num): """ Parse a string that is expected to contain a number. :param num: str. the number in string. :return: float or int. Parsed num. """ if not isinstance(num, str): # optional - check type raise TypeError('num should be a str. Got {}.'.format(type(num))) if re.compile('^\s*\d+\s*$').search(num): return int(num) if re.compile('^\s*(\d*\.\d+)|(\d+\.\d*)\s*$').search(num): return float(num) raise ValueError('num is not a number. Got {}.'.format(num))
42b46e054c24d946536e99e427052e1777f5561e
294,652
def _calculate_configuration(*, bin_dir_path): """Calculates a configuration string from `ctx.bin_dir`. Args: bin_dir_path: `ctx.bin_dir.path`. Returns: A string that represents a configuration. """ path_components = bin_dir_path.split("/") if len(path_components) > 2: return path_components[1] return ""
b10ee4abc083a0199302379229796d5c7be3eb6a
340,585
def ask(message): """Ask user a question""" if not message.endswith('?'): message += ' ?' message += ' Y/N: ' while True: inp = input(message).lower() if inp == 'y': return True elif inp == 'n' or inp == '': return False else: print('Invalid character.')
cf79e5a0ccdddd26fd6a52ab2e5c016ed6b69208
328,092
def swegen_link(variant_obj): """Compose link to SweGen Variant Frequency Database.""" url_template = ( "https://swegen-exac.nbis.se/variant/{this[chromosome]}-" "{this[position]}-{this[reference]}-{this[alternative]}" ) return url_template.format(this=variant_obj)
d55d177290297306b8367fff386984c4f8ab1bf6
205,910
import re def xxd_output_to_bytes(input_cc_file): """Converts xxd output C++ source file to bytes (immutable) Args: input_cc_file: Full path name to th C++ source file dumped by xxd Raises: RuntimeError: If input_cc_file path is invalid. IOError: If input_cc_file cannot be opened. Returns: A bytearray corresponding to the input cc file array. """ # Match hex values in the string with comma as separator pattern = re.compile(r'\W*(0x[0-9a-fA-F,x ]+).*') model_bytearray = bytearray() with open(input_cc_file) as file_handle: for line in file_handle: values_match = pattern.match(line) if values_match is None: continue # Match in the parentheses (hex array only) list_text = values_match.group(1) # Extract hex values (text) from the line # e.g. 0x1c, 0x00, 0x00, 0x00, 0x54, 0x46, 0x4c, values_text = filter(None, list_text.split(',')) # Convert to hex values = [int(x, base=16) for x in values_text] model_bytearray.extend(values) return bytes(model_bytearray)
644f8e92b1318e38ff4ee7415585ee21588eb9a3
375,028
def camel_to_snake_case(value: str) -> str: """Converts strings in camelCase to snake_case. :param str value: camalCase value. :return: snake_case value. :rtype: str """ return "".join(["_" + char.lower() if char.isupper() else char for char in value]).lstrip("_")
200892fb89e4b4e54ba47afb52d119021dad139a
314,667
def factorial(number): """ This recursive function calculates the factorial of a number In math, the factorial function is represented by (!) exclamation mark. Example: 3! = 3 * 2 * 1 = (6) * 1 3! = 6 """ if not isinstance(number, int): raise Exception("Enter an integer number to find the factorial") if number == 1 or number == 0: return 1 else: return number * factorial(number - 1)
797d4e79c132ad9a4644da4504326ebd49479acb
206,486
def get_email(obj): """ Returns the email address for a user """ return obj.user.email
30b4ec834e46b31384d79b448fc96417d29fe10d
545,068
def reduce_score_to_chords(score): """ Reforms score into a chord-duration list: [[chord_notes], duration_of_chord] and returns it """ new_score = [] new_chord = [[], 0] # [ [chord notes], duration of chord ] for event in score: new_chord[0].append(event[1]) # Append new note to the chord if event[0] == 0: continue # Add new notes to the chord until non-zero duration is hit new_chord[1] = event[0] # This is the duration of chord new_score.append(new_chord) # Append chord to the list new_chord = [[], 0] # Reset the chord return new_score
cbc363b4f7318bf1cf7823281ace8da61fac2195
676,537
def fscr_score(ftr_t_1, ftr_t, n): """Feature Selection Change Rate The percentage of selected features that changed with respect to the previous time window :param ftr_t_1: selected features in t-1 :param ftr_t: selected features in t (current time window) :param n: number of selected features :return: fscr :rtype: float """ c = len(set(ftr_t_1).difference(set(ftr_t))) fscr = c/n return fscr
f7598633d4082a416d4a9676292b7f26d2f36ea9
66,976
import json import yaml def loadModel(catalog_path, schema_path): """Loads the dbt catalog and schema. The schema selected is the one that will be used to generate the ERD diagram. Args: catalog_path (Path): Path to dbt catalog schema_path (Path): Path to dbt schema Returns: dict, dict: Return schema and catalog dicts. """ with open(catalog_path) as f: catalog = json.load(f) with open(schema_path, 'r') as f: schema = yaml.safe_load(f) return catalog, schema
00e9f60d47ef7846673121eeaea02fa6f2f9625a
164,915