content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def xor(x, y): """Return truth value of ``x`` XOR ``y``.""" return bool(x) != bool(y)
1eb05009886c677c4d514f2b80a0881766b54cbc
661,873
def fetch_production_configuration(service): """Safely fetches production configuration from 3scale""" return service.proxy.list().configs.list(env="production")
5627a73ca3b13815221fc91f9c3a1adbbbc2b3a5
661,874
import base64 def binary_to_base64(path: str) -> str: """ Transforms a binary file to base64 :param path: file's path :return: base code """ with open(path, 'rb') as binary_file: binary_file_data = binary_file.read() base64_encoded_data = base64.b64encode(binary_file_data) ...
6ecaf93ca1f124566bdc672205797f89a832b6c4
661,875
def chan_list_to_mask(chan_list): # type: (list[int]) -> int """ This function returns an integer representing a channel mask to be used with the MCC daqhats library with all bit positions defined in the provided list of channels to a logic 1 and all other bit positions set to a logic 0. Ar...
c64b10237a5407b6ad0e285dfccb7c73553ddc55
661,876
def greedy_cow_transport(cows,limit=10): """ Uses a greedy heuristic to determine an allocation of cows that attempts to minimize the number of spaceship trips needed to transport all the cows. The returned allocation of cows may or may not be optimal. The greedy heuristic should follow the followin...
0cc344ded49f80c3887504ca25d1f7afb42f6606
661,877
def learner_name(learner): """Return the value of `learner.name` if it exists, or the learner's type name otherwise""" return getattr(learner, "name", type(learner).__name__)
1da28e9c918df8e3bdf994df3cf2b7bbd6146d76
661,879
def is_skippable(string: str): """A string is skippable if it's empty or begins with a '#'""" return not string or string[0] == "#"
2fd9695c8118922ccd3d5b4d739e227b12e94b42
661,885
def get_24_bit_bg_color(r, g, b): """"Returns the 24 bit color value for the provided RGB values. Note: not all terminals support this""" return '48;2;%d;%d;%d' % (r, g, b)
a30a95acec239b878739710d895632ca50fb75ec
661,888
def merge(left, right, lt): """Assumes left and right are sorted lists. lt defines an ordering on the elements of the lists. Returns a new sorted(by lt) list containing the same elements as (left + right) would contain.""" result = [] i,j = 0, 0 while i < len(left) and j < len(right): ...
00a212db74cb2abf62b30ff1c3a67e426718e126
661,889
def compPubKey(keyObj): """ get public key from python-bitcoin key object :param keyObj: python-bitcoin key object :return: public bytes """ keyObj._cec_key.set_compressed(True) pubbits = keyObj._cec_key.get_pubkey() return pubbits
12eb5b1b59f76f80621067275bf93c73fccc4472
661,890
def make_backreference(namespace, elemid): """Create a backreference string. namespace -- The OSM namespace for the element. elemid -- Element ID in the namespace. """ return namespace[0].upper() + elemid
e8ac711b49a0b489e373ac691ddbaeef21d1787e
661,891
def _get_default_slot_value(spellbook, level): """ Get the default value of a slot maximum capacity: - the existing maximum capacity if the slot already exists - 0 in other cases """ try: return spellbook.slot_level(level).max_capacity except AttributeError: return 0
42175f6ce1bd2d36a419ee7c7516b495110ba7ae
661,892
def new_patch_description(pattern: str) -> str: """ Wrap the pattern to conform to the new commit queue patch description format. Add the commit queue prefix and suffix to the pattern. The format looks like: Commit Queue Merge: '<commit message>' into '<owner>/<repo>:<branch>' :param pattern: The...
1589e7be04252f16aeff40e08757b49b555fecc3
661,895
def same_neighbourhood_size(atom_index_1, molecule_1, atom_index_2, molecule_2): """ Checks whether the same atoms in two different molecules (e.g., reactant and product molecules) have the same neighbourhood size. """ if len(molecule_1.GetAtomWithIdx(atom_index_1).GetNeighbors()) != \ len(...
c767c6930375cf916fbf279a903cfac48233d441
661,896
def _FilterFile(affected_file): """Return true if the file could contain code requiring a presubmit check.""" return affected_file.LocalPath().endswith( ('.h', '.cc', '.cpp', '.cxx', '.mm'))
afe7971484bb80ca9ce5fd276aa1cab7138b915f
661,897
import decimal def prettyprint(x, baseunit): """ Just a function to round the printed units to nice amounts :param x: Input value :param baseunit: Units used :return: rounded value with correct unit prefix """ prefix = 'yzafpnµm kMGTPEZY' shift = decimal.Decimal('1E24') d = (decim...
a3b8b1bcd59ae654c8c319117569c53f74a7b70d
661,900
def get_prep_pobj_text(preps): """ Parameters ---------- preps : a list of spacy Tokens Returns ------- info : str The text from preps with its immediate children - objects (pobj) Raises ------ IndexError if any of given preps doesn't have any children """ ...
17c92ed818f4c1a6b4bc284ed0684c36a80ba5c2
661,901
import requests def api_retrieve_category_history(category_id): """ Allows the client to call "retrieve --all" method on the server side to retrieve the historical states of category from the ledger. Args: category_id (str): The uuid of the category Returns: type: str ...
6294e220edac1781764f547366ab36c8fef75f63
661,902
def is_in_roi(x, y, roi_x, roi_y, roi_width, roi_height): """ Returns true if in region of interest and false if not """ return ((x >= roi_x and x <= roi_x + roi_width) and (y >= roi_y and y <= roi_y + roi_height))
4aa89a2bed6ed79c0e6447d8f3c4a5d97c7e3a4d
661,904
from typing import Union def create_choice(value: Union[str, int], name: str): """ Creates choices used for creating command option. :param value: Value of the choice. :param name: Name of the choice. :return: dict """ return { "value": value, "name": name }
7fba604f4bf5a5bbbf15a602c767f4973befc3c3
661,907
def UD(value): """ Tags the given value with User Data tags. """ return "<ud>{0}</ud>".format(value)
472fc5b1390a292034c66bb6731cdbfb12b78041
661,908
def get_tokens(line): """tokenize a line""" return line.split()
8045f0cfcaa58ef1c94fa08313990028c47db129
661,913
def next_tag(el): """ Return next tag, skipping <br>s. """ el = el.getnext() while el.tag == 'br': el = el.getnext() return el
c58f65b109faad8595c0e920c117adebc0627df5
661,914
def isCacheInitialized(addr): """ Cache address is initialized if the first bit is set """ return (int.from_bytes(addr, byteorder='little') & 0x80000000) != 0
57266dfc4ef6a2319df290c9ecdd198dc528637e
661,917
import re def get_chr(bam_alignment, canonical=False): """Helper function to return canonical chromosomes from SAM/BAM header Arguments: bam_alignment (pysam.AlignmentFile): SAM/BAM pysam object canonical (boolean): Return only canonical chromosomes Returns: regions (list[str]): R...
f0c016d5f4f946b5553c3125a3e9fc8f0c7bf07b
661,929
import six def row_to_dict(row): """Convert a `pymssql` row object into a normal dictionary (removing integer keys). >>> returned = row_to_dict({1: 'foo', 'one': 'foo', 2: 'bar', 'two': 'bar'}) >>> returned == {'one': 'foo', 'two': 'bar'} True """ retval = dict() for key, value in six.iteritems(row): ...
5ef570e4b85a10bd4f4f9cfd2a78eba204360c03
661,930
def cve_harvest(text): """ looks for anything with 'CVE' inside a text and returns a list of it """ array = [] #look inside split by whitespace for word in text.split(): if 'CVE' in word: array.append(word) return array
b33e81d4be3ffd78f3962e7e78d796e79fa170c6
661,934
def _is_tuple_of_dyads(states): """Check if the object is a tuple or list of dyads """ def _is_a_dyad(dd): return len(dd) == 2 ret = False for st in states: if _is_a_dyad(st): ret = True else: ret = False break r...
100ff10fcc46134bfd25959eafc599da54a41ecf
661,936
def calculate_fitness(reference, population): """ Calculate how many binary digits in each solution are the same as our reference solution. """ # Create an array of True/False compared to reference identical_to_reference = population == reference # Sum number of genes that are identical to t...
cde3ba975d13e59e495240ce2dbb12b71b5706f2
661,937
def coin_amount_for_usd(coin: str, usd: float, tickers: dict) -> float: """ Get amount of {coin} for {usd} :param coin: coin symbol :param usd: amount in USD :param tickers: raw tickers fetched from binance :return: amount of coin for usd value as float """ price_in_btc = float(tickers[f...
a18b930393fd6a7997e6f47bbf8c459d60528109
661,943
import click def validate_user(context, param, value): """ Validates the existence of user by username. """ users = context.obj.api.users() user = next((u for u in users if u["username"] == value), None) if not user: raise click.BadParameter("User \"%s\" was not found" % value) re...
ab30ff53a83b8d6d9a5c5ab8b75e9121f58f5ed5
661,944
def parse_odbc(url): """ Parse Redshift ODBC URL ----------------------- :param url: Fully Qualified ODBC URL :type url: str :return parsed: ODBC fields parsed into respective fields. :rtype parsed: dict .. example:: Driver={Amazon Redshift (x64)}; Server=server_name...
cafabc765e1f0846d4f1f9ceca44d0d18bd95182
661,952
from typing import Union from typing import Dict from typing import List import json def read_json(filename: str) -> Union[Dict, List]: """Read a JSON object or list from the given output file. By convention, the Java wrapper for Metanome algorithms stores all algorithm as JSON seriaizations. Paramet...
0bddb80e047aca5b4bbbe955ac4b3b46f36beac3
661,954
def _ImportPythonModule(module_name): """Imports a Python module. Args: module_name (str): name of the module. Returns: module: Python module or None if the module cannot be imported. """ try: module_object = list(map(__import__, [module_name]))[0] except ImportError: return None # If t...
0288486bef88f028138f577e7561b2776b24d46f
661,957
def statistics(*args): """ Compute the average, minimum and maximum of a list of numbers. Input: a variable no of arguments (numbers). Output: tuple (average, min, max). """ # this function takes variable argument lists avg = 0; n = 0 # avg and n are local variables for term in args: ...
d737c9265456df32f91d982c8cd92d12bf865442
661,962
def get_invalid_keys(validation_warnings): """Get the invalid keys from a validation warnings list. Args: validation_warnings (list): A list of two-tuples where the first item is an iterable of string args keys affected and the second item is a string error message. Returns...
0eb0db053e505f696471e7166051d9b2e025d439
661,963
def _islinetype(line, testchar): """Checks for various kinds of line types based on line head""" return line.strip().startswith(testchar)
6b756278299fbac2955b527d7564f30a0085f9e4
661,964
import random import string def generate_random_string(length=7): """Generates random string""" return ''.join(random.SystemRandom().choice(string.ascii_letters + string.digits) for _ in range(length))
35939d445cde1fa0cc3f3194eedd21e6a39b19e2
661,968
def get_max(arr: list) -> int: """Returns the maximum value in an list Args: arr (list): the list to find the value in Returns: int: the value itself """ max_value = arr[0] for value in arr: if value > max_value: max_value = value return max_value
ddd007e509f79bcdd155906220413dec9d81dd21
661,971
def hyps2word(hyps): """ Converts a list of hyphens to a string. :param hyps: a list of strings (hyphens) :return: string of concatenated hyphens """ return ''.join(hyps)
28d007d70a66ac2efa212f4a58811f039e9a5fdf
661,972
import re def get_shorttext(text): """Get the initial 200 characters of text. Remove HTML and line breaks.""" shorttext = re.sub(r"<.*?>|\n|\t", " ", text) shorttext = shorttext.strip() shorttext = re.sub(r" ", " ", shorttext) return shorttext[:200]
7b2534c463b9cabba8539e96527bbb14f3e4ec56
661,974
def get_factors(n): """Return a list of the factors of a number n. Does not include 1 or the number n in list of factors because they're used for division questions. """ factors = [] for i in range(2, n): if n % i == 0: factors.append(i) return factors
7fe54e47f17a898164806d8109f1d803451ba9d6
661,979
from typing import List def sequence (lower:int, upper:int) -> List[int]: """ generate an integer sequence between two numbers. """ seq = [ ] current = lower while current <= upper: seq.append(current) current += 1 return seq
6a54c3b1234f108abd0a95fbbf0ab7fcb3d3f7f4
661,982
from redis.client import Redis def from_url(url, **kwargs): """ Returns an active Redis client generated from the given database URL. Will attempt to extract the database id from the path url fragment, if none is provided. """ return Redis.from_url(url, **kwargs)
c540436213b31fedc653596146667068430aac03
661,986
import base64 import uuid import re def generate_download_link(file, filename): """ Generates a download link for the given string; filename is what the output filename will be. This is made ad Streamlit does not support a download button natively. An adaption of https://discuss.streamlit.io/t/a-downl...
163efd7e59ea626c7adf9028ae86f5b33594aec5
661,994
from typing import Dict from typing import Any from typing import List def set_user_defined_results( fha: Dict[str, Any], results: List[float] ) -> Dict[str, Any]: """Set the user-defined results for the user-defined calculations. This allows the use of the results fields to be manually set to float ...
ca886e2221c0c5b0fcc8c3f00bbeff07182af6e4
661,996
def cria_copia_posicao(pos): """ cria_copia_posicao: posicao -> posicao Recebe uma posicao e devolve uma copia nova da posicao. """ return {'c': pos['c'], 'l': pos['l']}
d5178ceac5dda46c565fc974513578f283dd6bcb
662,001
def reg8_delta(a, b): """Determine 8-bit difference, allowing wrap-around""" delta = b - a if b > a else 256 + b - a return delta - 256 if delta > 127 else delta
eb0554e38e05ad37214c58242a41a910685da7be
662,002
def group_list(actions, agent_states, env_lens): """ Unflat the list of items by lens :param items: list of items :param lens: list of integers :return: list of list of items grouped by lengths """ grouped_actions = [] grouped_agent_states = [] cur_ofs = 0 for g_len in env_lens: ...
bc6199f5cc0efcdfde7e9c9085c1ccc95c535e30
662,003
def find_settings(element, alternate_name): """Given an ElementTree.Element and a string, searches the element for a subelement called "settings". If it doesn't find it, searches for a subelement using the alternate_name. Prior to Vespa 0.7.0, the settings in Analysis blocks had unique class and ...
9fae380cd64b64380d0770a20dd26aef5cd5cade
662,004
from typing import List from pathlib import Path import torch def average_checkpoints(filenames: List[Path]) -> dict: """Average a list of checkpoints. Args: filenames: Filenames of the checkpoints to be averaged. We assume all checkpoints are saved by :func:`save_checkpoint`. Retur...
d6a534dfa62d7d0d1dfab1d58f5261080e889bb9
662,005
def docs_append_to_section(docstring, section, add): """Append extra information to a specified section of a docstring. Parameters ---------- docstring : str Docstring to update. section : str Name of the section within the docstring to add to. add : str Text to append t...
c4c58d809aaeff2a9f68c193894dae155fa7a9dd
662,006
def denpify(f): """ Transforms a function over a tuple into a function over arguments. Suppose that `g` = ``denpify(f)``, then `g(a_1, a_2, ..., a_n) = f((a_1, a_2, ..., a_n))`. Examples -------- >>> flip((0, 1)) (1, 0) >>> f = denpify(flip) >>> f(0, 1) # note the the...
57ee3aa381352eab2823da0a30e6252d0377bdfe
662,007
import math def prob_no_match(n): """analytical result using integers - python can handle arb large numbers""" return math.factorial(n)*math.comb(365,n)/(365**n)
fe292657654c4413fd3d9751e6a10be7c38f2c19
662,011
import re def fuzzy_match_repo_url(one, other): """Compares two repository URLs, ignoring protocol and optional trailing '.git'.""" oneresult = re.match(r'.*://(?P<oneresult>.*?)(\.git)*$', one) otherresult = re.match(r'.*://(?P<otherresult>.*?)(\.git)*$', other) if oneresult and otherresult: ...
6346c411f0e20ad6a11723d531ce49014b0dfa62
662,019
def get_file_extension(url): """Return file extension""" file_extension = ''.join(('.', url.split('.')[-1:][0])) return file_extension
cad58d95e2aee0bc5103ae331d080d01497c64fe
662,022
def get_min_max_credits(day_count, max_credits_month): """ get the max and min credits with total avg :param day_count: days of the month :param max_credits_month: the maximum credits :return: max_credits and min credits """ avg_credit = max_credits_month / day_count max_credits = (3*avg...
b1ec030b378625b43fe0749e7111c4608b1c80ce
662,028
def comment_out_details(source): """ Given the source of a cell, comment out any lines that contain <details> """ filtered=[] for line in source.splitlines(): if "details>" in line: filtered.append('<!-- UNCOMMENT DETAILS AFTER RENDERING ' + line + ' END OF LINE TO UNCOMMENT -->...
95e34cfae18fb66de33c22eed5419dfe51b2e52a
662,035
def create_anc_lineage_from_id2par(id2par_id, ott_id): """Returns a list from [ott_id, ott_id's par, ..., root ott_id]""" curr = ott_id n = id2par_id.get(curr) if n is None: raise KeyError('The OTT ID {} was not found'.format(ott_id)) lineage = [curr] while n is not None: lineage...
bee459efd3c1ebb639aeee1433bfdde63c60fad7
662,040
import logging def _get_stream_handler() -> logging.StreamHandler: """ Define parameters of logging in the console. Returns: logging.StreamHandler: console handler of the logger. """ stream_handler = logging.StreamHandler() stream_handler.setLevel(logging.INFO) stream_handler.setF...
4b46e55b24399750f4063c19dfd268891eb08641
662,042
import torch def merge_list_feat(list_feat, list_batch_cnt): """ Merge a list of feat into a single feat Args: list_feat (list): each element is (N, C) list_batch_cnt (list): each element is (B) - [N0, N1, ...]; sum(Ni) == N Returns: merge_feat (torch.Tensor): (M, C) ...
2bd13e05655f0473430cb185bf11bb52840eb9fa
662,044
def format_error(ex): """Creates a human-readable error message for the given raised error.""" msg = 'Error occurred in the Google Cloud Storage Integration' if hasattr(ex, '__class__'): class_name = ex.__class__.__name__ details = str(ex) if isinstance(ex, BaseException) and detail...
cd15cfea87065f288970a4f3710a004b8642ec44
662,046
def py_slice2(obj,a,b): """ >>> [1,2,3][1:2] [2] >>> py_slice2([1,2,3], 1, 2) [2] >>> [1,2,3][None:2] [1, 2] >>> py_slice2([1,2,3], None, 2) [1, 2] >>> [1,2,3][None:None] [1, 2, 3] >>> py_slice2([1,2,3], None, None) [1, 2, 3] """ return obj[a:b]
454315e7f22936547cfffb5b4529358518ca292f
662,048
from typing import List def remove_ad_search_refs(response: List[dict]) -> List[dict]: """ Many LDAP queries in Active Directory will include a number of generic search references to say 'maybe go look here for completeness'. This is especially common in setups where there's trusted domains or other domai...
8b0bf322834e9fdbc8cf552def155f33b6da63bd
662,053
def get_non_text_messages_grouped(groups): """Filters and structures messages for each group and non-text message type. Args: groups (list of lists of MyMessage objects): Messages grouped. Returns: A list of message types grouped: [ { "groups": [list of ...
7ae67a38a3a5d3541ac0a443e69e21377b8e8fc0
662,055
def tn(n): """ This function calculates, for a given integer n, the result of the operation n*(n+1)/2 """ return n*(n+1)/2
35f9ce390c35a8528480def38f2d9dff06c6973a
662,056
def extract_content(soup): """Extract resources based on resource tags from a page.""" images = [ image.get('src') for image in soup.find_all('img') ] stylesheets = [ sheet.get('href') for sheet in soup.find_all('link') ] scripts = [ script.get('src') for script in soup.find_all('script') ] videos =...
db2b12d33015c81b9abba1dd9ab0c34c46a94229
662,059
import warnings def index_condensed_matrix(n, i, j): """ Return the index of an element in a condensed n-by-n square matrix by the row index i and column index j of the square form. Arguments --------- n: int Size of the squareform. i: int Row index of the...
eb51b6b4739de8c7058136e2a0f527629ff641f0
662,060
def to_repo(gh, owner, name): """Construct a Repo from a logged in Github object an owner and a repo name""" return gh.get_user(owner).get_repo(name)
7511afd4a2c67bcc5cea023f5d83acc939a78d44
662,061
def bubble_sort(a: list): """ Bubble sorting a list. Big-O: n^2 (average/worst) time; 1 on space. """ siz = len(a) for i in range(siz): swapped = False top = siz - i - 1 for j in range(top): if a[j] > a[j+1]: a[j], a[j+1] = a[j+1], a[j] ...
ce4ee8c937d3dde7708efd96abd5965a36da08dd
662,063
def parse_smi(files): """ Return parsed files as list of dicts. .. note: parse_smi uses the x and y coordinate of the left eye. Parameters ---------- files : sequence of str file names. For every subject one tab separated file. Returns ------- subjects : sequence o...
d1a24467dc9c29f3b72159e06a5e5b6a138ff091
662,067
from datetime import datetime def days_from_date(strdate): """ Returns the number of days between strdate and today. Add one to date as date caclulate is relative to time """ currentdate = datetime.today() futuredate = datetime.strptime(strdate, '%Y-%m-%d') delta = futuredate - currentdate ...
5aacdc8b0c5e3750bd635105364c500609a5e0b9
662,069
def next_zero(signal, x0, steps=1000, precision=10e-6, gamma=0.01): """ Finds a position of zero of a signal using Newton's method Args: signal (SignalExp): bandlimited function which will be searched for a zero x0 (float): starting point for the search steps (int): maximal possible...
2f4366d13bd22527cdd018c992eeaea40aa9f6d2
662,075
def getStr(target, pos): """ Get a string from a list/whatever. Returns the string if in-range, False if out of range. """ try: result=str(target[pos]) return result except IndexError: return False
8169228926a3b15177e71e478545cee81915130d
662,078
import json def get_netsel_urls(netsel_file): """Return list of CSK urls.""" # use sorted list of urls of the InSAR inputs to create hash with open(netsel_file) as f: netsel_json = json.load(f) urls = [] for i in netsel_json: for j in i: urls.append(j['url']) return urls
42bb95f73d6fff96685a950dc2a4f286f9d1e25e
662,079
def get_or_insert(etcd_cl, key, value, **kwargs): """ Performs atomic insert for a value if and only if it does not exists. If the value exists, no insert/update is performed. No exception is raised if value already exists. :param etcd_cl: :param key: :param value: :param kwargs: :r...
5d37e910b3c8662e834258dc398842bde0f57d52
662,080
def sum_squared_xy_derivative(xy_point, coeff_mat): """For a coordinate, and function, finds df/dx and df/dy and returns the sum of the squares Arguments: xy_point (tuple): (x,y) coeff_mat (np.array): Matrix of coefficients of the n order polynomial Returns: (float): (df/dx + d...
ad962444a67c0361256ea133911789901dc48fb3
662,081
def reversed_string(node): """ Print out string representation of linked list but in reverse order :param node: value of head node, start of list :return: string: string of linked list, comma delimited """ if node is not None and node.next_node is not None: # not last element in linked list ...
36161944a34523c3f90289a0f2262ab65ece4be9
662,083
def get_option_usage_string(name, option): """Returns a usage string if one exists else creates a usage string in the form of: -o option_name OPTIONNAME """ usage_str = option.get("usage") if not usage_str: usage_str = f"-o {name} {str.upper(name.replace('_',''))}" return usage_...
7c824d0b4488759fcf68af42f51d04eb40fcabeb
662,085
import re def split_execution_info_into_groups(execution_info): """Splits execution information into groups according to '--' separator. Args: execution_info: A textual representation of the execution_info. Returns: A grouped representation of the execution_info """ r...
ffbf1b62779443cfbdc1cfc1de47c1705ac0cf65
662,090
def is_short_option(argument): """ Check if a command line argument is a short option. :param argument: The command line argument (a string). :returns: ``True`` if the argument is a short option, ``False`` otherwise. """ return len(argument) >= 2 and argument[0] == '-' and argument[1] != '-'
d64497d9cfaa28957fda35cc644801b37af70f52
662,095
import logging def logger_for_transaction(name: str, t_id: int): """Provide a specific default_logger for a transaction. The provided transaction id will always be logged with every message. Parameters ---------- name: str The default_logger ID t_id: int Th...
1b2a205efacfacfc5a205d417b956d8019af4a78
662,096
def is_guess_good(word, guess): """Returns whether guess is in the word For example, is_guess_good('hello', 'e') should return True while is_guess_good('hello', 'p') should return False. Args: word: a string guess: a string Returns: bool: True if guess is in word, else returns ...
f61f58a2c90a0e48f149dff66b373ac3da2b7125
662,097
def match_resource(resource, bid, cid): """Helper that returns True if the specified bucket id and collection id match the given resource. """ resource_name, matchdict = resource resource_bucket = matchdict['id'] if resource_name == 'bucket' else matchdict['bucket_id'] resource_collection = matc...
edf2592cb6330781f79a31fba2f5147170013b77
662,100
from typing import List import heapq def kNN(distances: List[float], k: int): """ Computes k-nearest-neighbors. :param distances: A collection of distances from some point of interest. :param k: The number of neighbors to average over. :return: The mean of the smallest 'k' values in 'distances'. ...
745098bec253b701ef96ada02ffa5033a104743c
662,101
import random def randomer(n): """ Generate random DNA (not a randomer (NNNNN) which is a mix of random DNA) :param n: length :return: string """ alphabet = ['A', 'T', 'G', 'C'] return ''.join([random.choice(alphabet) for x in range(n)])
51515fe0d094993a15e7e30a05c4e0aca9a3b872
662,106
def get_field_meta(field): """ returns a dictionary with some metadata from field of a model """ out = { 'name' : field.name, 'is_relation' : field.is_relation, 'class_name' : field.__class__.__name__} if field.is_relation: out['related_model'] = "%s.%s" % (field.related_model._meta.app_labe...
7d9801c4c94babde5c88ec15184c2d820ffe7d87
662,107
def get_slurm_dict(arg_dict,slurm_config_keys): """Build a slurm dictionary to be inserted into config file, using specified keys. Arguments: ---------- arg_dict : dict Dictionary of arguments passed into this script, which is inserted into the config file under section [slurm]. slurm_conf...
99505e588911583d93ff32befc4a09092fd0e269
662,108
import time def Retry(retry_checker, max_retries, functor, sleep_multiplier, retry_backoff_factor, *args, **kwargs): """Conditionally retry a function. Args: retry_checker: A callback function which should take an exception instance and return True if functor(*args, *...
72db1202f30fcb79732d8171657353153c127647
662,109
def cleanse(tarinfo): """Cleanse sources of nondeterminism from tar entries. To be passed as the `filter` kwarg to `tarfile.TarFile.add`. Args: tarinfo: A `tarfile.TarInfo` object to be mutated. Returns: The same `tarinfo` object, but mutated. """ tarinfo.uid = 0 tarinfo.gid =...
d602288d95cde6e6a50ff2132dd68a58b1e49fe9
662,113
def get_states(event_data): """ Returns a tuple containing the old and new state names from a state_changed event. """ try: old_state = event_data["old_state"]["state"] except Exception as e: old_state = None try: new_state = event_data["new_state"]["state"] exce...
aa0938ab755943e58fe65243588fe8feac78302e
662,117
def inherits_from(obj, a_class): """ Return: True if obj is instance of class that it inherits from or is subcls of """ return (type(obj) is not a_class and issubclass(type(obj), a_class))
5d39ee3502e5b9d8abfa0857cbffa6e4c44be8d8
662,122
def num2filename(x,d): """ Takes a number and returns a string with the value of the number, but in a format that is writable into a filename. s = num2filename(x,d) Gets rid of decimal points which are usually inconvenient to have in a filename. If the number x is an integer, then s = s...
505b7917ba6a578302b467868ffe7f84c9004e3f
662,124
import unicodedata import re def clean(value): """Replaces non-ascii characters with their closest ascii representation and then removes everything but [A-Za-z0-9 ]""" normalized = unicodedata.normalize('NFKD', value) cleaned = re.sub(r'[^A-Za-z0-9 ]','',normalized) return cleaned
e9e11d4828f0b87a704b6f92ea2fd98058c8fd67
662,125
def filter_params(model, prefix): """Return a list of model parameters whose names begin with a prefix""" return [p for p in model.parameters if p.name.startswith(prefix)]
2d07d654e373a334bbf91ef60852ebf620bfc68b
662,126
from typing import List from typing import Optional from typing import Tuple from typing import Dict def make_dataset( paths: List[str], extensions: Optional[Tuple[str, ...]] = None, ) -> Tuple[List[Tuple[str, int]], Dict[bytes, int]]: """ Map folder+classnames into list of (imagepath, class_i...
1e33b85dc1b304e47a2a8000634a3bff73eb5dbc
662,130
def do_nothing(list_of_words): """Return the argument unchanged.""" return list_of_words
bf37ebf6f980d6df5633ac27ec3888667df9b0a9
662,131
def num_examples_per_epoch(split): """Returns the number of examples in the data set. Args: split: name of the split, "train" or "validation". Raises: ValueError: if split name is incorrect. Returns: Number of example in the split. """ if split.lower().startswith('train'): return 100000 el...
05362a25d28838994d3cf0b6dbc3818cff6a7e37
662,135
import re def find_(word, stream, ignore_case=True): """Find the `word` in the `stream`. :param word: str, word or pattern to be searched in stream :param stream: str, stream to be searched in :param ignore_case: whether to ignore the case :returns: the corresponding `word` (could be of different...
005b79edc262559386465ef2436c5d0841bdf822
662,136
def coroutine(func): """ A decorator to create our coroutines from generator definitions. Calling a generator function does not start running the function! Instead, it returns a generator object. All co-routines must be "primed" by calling ``next`` or ``send` to run up until the first ``yield``. ...
58ff0bd1f9597b8168d4bb35b794c039791623d3
662,139