content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def lengthOfLIS(nums): """ :type nums: List[int] :rtype: int """ if len(nums) == 0: return 0 elif len(nums) == 1: return 1 else: longest_list = [] for i in range(len(nums)-1): temp_list = [nums[i]] print (nums[i]) for j in r...
144645f03d7740413e2df26ca2571986b7f06fbd
633,344
def get_images(data): """ Get all images from facebook JSON response, or return None if no data present. """ try: return data['data'] except KeyError: return []
eda4a99f801fd176f4ff514ae8a276c620d6b054
633,345
def process_template(buf: str, osmrelation: int) -> str: """Turns an overpass query template to an actual query.""" buf = buf.replace("@RELATION@", str(osmrelation)) # area is relation + 3600000000 (3600000000 == relation), see js/ide.js # in https://github.com/tyrasd/overpass-turbo buf = buf.replac...
8250d1e1be72182c10855d0dd4456aaf31a5f0d3
633,346
def dtype_sorter(dtype_str) -> int: """Sort by dtype maingroup.""" value = int(dtype_str.split("-")[1]) * 1000 try: value += int(dtype_str.split("-")[2]) except IndexError: pass return value
0e29f41814aca3d8ad8a6b13d0db0a6e5959a5f7
633,347
def _get_acf_params(p): """Get ACF parameters from the given parameter vector.""" return p[0], p[1], p[2], p[3] * p[2]
805bcbaac15a69321342f0748168dba2010ba505
633,348
def pad(str_float_value): """ Pad value with zeroes to 8 digits after dot """ return "%.8f"%float(str_float_value)
af10b81592a7957a6aa23c87f433ffde8da34705
633,350
def get_items(s3_client, bucket, prefix): """ input: S3 client, S3 bucket name, folder on S3 bucket output: names of images in the folder """ response = s3_client.list_objects(Bucket=bucket, Prefix=prefix) items = [content['Key'] for content in response['Contents']] return items
29278e24f6d745c6e082341877d503cc6e444cc0
633,351
import json def flatten_json(data_file, mode): """Flatten each article in training data.""" with open(data_file) as f: data = json.load(f)['data'] rows = [] for article in data: for paragraph in article['paragraphs']: context = paragraph['context'] for qa in par...
a385b80e51f673f92ab5fa197619d50ac8a25c09
633,352
def url_path(url): """ Construct a path string for a Hyperlink URL. :type url: hyperlink.URL :param url: URL. :rtype: unicode """ return (u'/' if url.rooted else u'') + u'/'.join(url.path)
977431e969e7903a728bf97a36c9a653ef11f6f1
633,353
import json def simple_create_keyspace(keyspace_name, replication_dict=None): """Given a keyspace name, produce the CQL3 statement that creates it. No schema set-up is done. Uses a simple replication strategy and a replication factor of 1. :param keyspace_name: what the name of the keyspace is to c...
b0eaa081726983b38e8c93b28157accc2a3d24ad
633,354
import argparse def _args_check_port(value): """Check argument for valid port number.""" min_port = 1 max_port = 65535 try: intvalue = int(value) except ValueError: raise argparse.ArgumentTypeError('"%s" is an invalid port number.' % value) if intvalue < min_port or intvalue ...
d98c59926bf34c35fa7bbfa1fac1ade395a6325a
633,355
def get_node_color_map(selected_events): """Generate color map for all organism groups in selected_events. This is done dynamically for each node-link diagram, because it minimizes collisions. :param selected_events: Specified organism_group-organism_group relationships inside nested dictionary. ...
2cec415755bc89c726141b82d7c2d125bd2b4c11
633,356
def send_message(service, message): """Sends an email message.""" return service.users().messages().send(userId="me", body=message).execute()
d36388ee2aa418953ad1b41c503d0660c3c400a4
633,359
from sys import stdout def get_boolean(prompt: str) -> bool: """ Process result of prompt to get boolean. Parameters: prompt (str): prompt to get True/False response. Returns: result (bool): True or FaLse. """ while True: result = input(prompt)[0].upper() if result...
01006c1ded7dd55a2885f27e9c5ac822ce122596
633,360
import pathlib def last_modified(path: pathlib.Path) -> float: """Returns the timestamp of the last modification of a file. Parameters ---------- path File path. """ path = pathlib.Path(path) return path.stat().st_mtime
0102fb79bff5808d38049501f04761d5ccfc80e0
633,361
def edge_to_list_dict(g): """ Convert a graph to a dictionary of edges """ ret = {} for source,sink in g.get_edgelist(): if source not in ret.keys(): ret[source] = [] ret[source].append(sink) return ret
e4104077b5015021d8bbbfed2b67c4cfc51f0c35
633,362
import os def is_checkout(path): """ Returns true if the path represents a git checkout. """ return os.path.exists(os.path.join(path, '.git'))
e9aa946f7ed5ad42920764dba7a6c3e7632ea0cd
633,363
def find_field(vfile, fld_name_lst): """ convenience function to get a field that could be called many things returns the first fld_name in the list that is in the file """ for fld_name in fld_name_lst: if fld_name in vfile: return vfile[fld_name] raise KeyError("file {0} contains no...
14f1924b249f38e0525a6c722a4e6654fa6af2fb
633,364
from pathlib import Path import subprocess def load_vars(dir: Path) -> dict: """Load environment vairables from .envrc in the given directory (or parent)""" print("Loading environment vairables from .envrc") try: result = subprocess.check_output( f'direnv exec "{dir}" python -m pytest...
4b27b7f680be154f4069ebbc424fbb17c6736ff7
633,365
def scrape_quotes_container(soup): """Get the quote container from a quote page. Args: soup (bs4.element.Tag): connection to the quote page. Returns: bs4.element.Tag """ return soup.findAll('div', attrs={'class': 'quotes'})
16a57fcce32969b7c8c29689cbe5ffe1a02b1a16
633,366
import subprocess def show_rofi(txt_body, txt_head): """Launch a rofi window Parameters ---------- txt_body : str Text to display in rofi window txt_head : str Text to display in rofi prompt Returns ------- str Rofi selected cell content """ cmd = sub...
e2390ae7cb0425e91561f8cfd804d90e81d60fa6
633,367
def formula_map(num): """ Creat formula map for parsing error in url """ formulamap = {18: "-I", 30: ".alpha-Pa", 39: ".beta-Po", 40: ".alpha-Hg", 41: ".alpha-As", 43: ".beta-O", 350: ".alpha-CO"...
4ac5bf085167e8f2032a847cf3fed9400ecea1c7
633,368
def read_from_tokens(tokens): """Converts the given set of tokens into an abstract syntax tree. Args: tokens (list): The tokens to convert. """ if len(tokens) == 0: raise SyntaxError('Unexpected end of input.') token = tokens.pop(0) if '(' == token: children = [] ...
f42e886d93da25ddbc1a03934f93fbf0f1aa78f2
633,370
def get_remote_url(remote_url): """ Takes a GitHub remote URL (e.g., `mozilla/fireplace`) and returns full remote URL (e.g., `git@github.com:mozilla/fireplace.git`). """ if ':' not in remote_url: remote_url = 'git@github.com:' + remote_url if not remote_url.endswith('.git'): rem...
d813a9b209280b35f260dab818542d220e79c277
633,371
import math def distance(p, q): """Calculates the euclidean distance between two points in a cartesian coordinate system. Args: p (tuple, list): first point as [x, y]-list. q (tuple, list): first point as [x, y]-list. Returns: float: the euclidean distance bet...
1d1d2460a4f19804c974bf3e6423f250c4a051e0
633,372
def _curl_https_get_code(host): """ Create a curl command for a given host that outputs HTTP status code. """ return ( '/opt/mesosphere/bin/curl ' '-s -o /dev/null -w "%{{http_code}}" ' 'https://{host}' ).format(host=host)
b9ac384e0cf0ab18fedbe619fc27c4ce4b8a3725
633,375
def is_open_access(record): """Returns True if permissions subject(s) is anyone (all).""" return record.get('permissions', '').startswith('all_')
6e7dec27e930ac10f4e4972342755c9ea2da9b72
633,376
def _(message, *args): """ NOOP implementation of sphinx.locale.get_translation shortcut. """ return message
b9290184daed84c52b462ab505c06fbca4b9dbdb
633,377
def mean(values): """Calculate the mean. Parameters ---------- values : list Values to find the mean of Returns ------- out : float The mean """ return sum(values)/float(len(values)) if len(values) > 0 else 0.0
de133de8916979ceedd7588c0fa2dea67a97d17d
633,378
def recurse(func, func_locals, *args, **kwargs): """for ad-hoc recursion - in case: manual insertion of original *args/**kwargs. Use it like recurse(myfunc,locals(),changed=changed-1,*args,**kwargs)""" co=func.func_code args = tuple([ kwargs.pop(co.co_varnames[i], func_locals[co.co_varnames[i]]) ...
598f1add01b9d6dc3049985a57a1f3870ad741cf
633,379
def remove_from_string(string, letters): """Given a string and a list of individual letters, returns a new string which is the same as the old one except all occurrences of those letters have been removed from it.""" for i in string: for j in letters: if i == j: strin...
cf594b682dbdeefbe159dfd666f6757caf1ee8ed
633,380
def remove_whitespace(s): """ https://stackoverflow.com/a/3739939/2465202 """ return ''.join(s.split())
0e1dc3cc8673ee1f33fde5d1b68d7a51c46dc0a5
633,381
def filename(value): """Return true if filename is valid, otherwise - false.""" return False
ea6dd8552b4221691e06807836e31450d4cec126
633,384
def n_air(lambda0, temperature=15): """ Calculate refractive index of air at atmospheric pressure. This follows the equation on page 4 of Smith, Modern Optical Engineering. Args: lambda0: wavelength in vacuum [m] temperature: degrees celsius Returns: index of refraction [--...
1b0c2ae9a25b1ed3a3c9f81b6eb80999c4d5e68d
633,385
import os def get_filename(file_path): """Returns filename with extension Parameters ---------- file_path: str Path to file :return: filename :rtyep: string """ return os.path.split(file_path)[1]
1a0b7deb7ed0c42b5707dcde47309ddfe086541e
633,386
import torch def index_points(points, idx): """ Input: points: input points data, [B, N, C] idx: sample index data, [B, D1, D2, ..., Dn] Return: new_points:, indexed points data, [B, D1, D2, ..., Dn, C] """ device = points.device B = points.shape[0] view_shape = lis...
88483a77a566b42db7073a41d6a1cb49a51a5164
633,387
async def ping() -> str: """health check""" return "pong"
95c730e4d05fbc5e86d66ffad6bbbab182ece9a4
633,388
def removeDuplicates(nums): """ TimeComplexity: O(n) SpaceComplexity: O(1) """ i = 0 for j in range(len(nums)): if nums[i] != nums[j]: i += 1 nums[i], nums[j] = nums[j], nums[i] return nums[0 : i + 1]
51eca610bd0151ff31db8db07dd48489b0a0a456
633,389
def W2(ws): """ c [w11y v1x v1y w12y v2x v2y ...] cfirst clast w11y v1x v1y """ widths = {} while ws: t = ws.pop() if isinstance(t, list): c = ws.pop() i = 0 while t: vy = t.pop() vx = t.pop() w =...
410bd0bb88707e230753e275c31deca8fa6b3722
633,390
def convert_codewords(codewords): """ Changes the codewords list of lists to a list of strings Parameters ---------- codewords : list allowed codewords for logical zero Returns ------- list_of_strings : list a list of strings Notes ----- No longer needed at pr...
dc108d997f5ff15e3394f479d4de683ea5114a36
633,391
def filter_characteristic_properties(characteristic_dict): """ Takes the dict from a charactistic, and spits out a string of all the properly formatted properties of that characteristic. """ property_name_mapping = {"@indicate": "indicate", "@notify": "notify", ...
cd86254ac6bb1cc02d2aaaf539c5f28fc7191144
633,392
from datetime import datetime def get_telapsed(last_draw_timestamp): """ Takes in a dictionary that shows last-draw timestamp for each card and uses that to compute Returns: Time elapsed dictionary that shows seconds elapsed since last time each card was drawn (Key is the cue and value i...
50b6cc12bcbbb9f80de6d59080329a6816f3a7a8
633,393
def combined_maintenance(*args): """ Takes any number of maintenance functions and returns one function that calls all of the given ones in the order they are given. """ def combined(net, task, result): nonlocal args for mf in args: mf(net, task, result) return combined
5d1044a33caddfe9d7b979f51683dce7414f40f4
633,394
def SUM(src_column): """ Builtin sum aggregator for groupby. Example: Get the sum of the rating column for each user. If src_column is of array type, if array's do not match in length a NoneType is returned in the destination column. >>> sf.groupby("user", ... {'rating_sum':tc.aggregate.SUM('...
18adf3b81e7cd15f603ebc60878598dcfd56144f
633,395
from typing import Dict from typing import Any import random def get_random_value(config: Dict[Any, Any]): """ Executes function from https://docs.python.org/3/library/random.html :param config: Config that contains type "get_random_value" with 'func' and 'args' :return: """ config_dict = conf...
80abc1bbe32140bee55bf64dffb24e82bc35e470
633,396
def df_to_joints(df): """ Return joint names from list of degrees of freedom. List of joint names is sorted alphabetically. :param df: List of degrees of freedom like ["joint.x",]. :type df: list :return: Joint names. :rtype: list """ joints = sorted(set((x.split('.')[0] for x in df if ...
6061b29001944f976c0657a8d14c3da12cba8205
633,397
from typing import List def permute_list(x: List, permutation_indices: List[int]) -> List: """Permute `x` according to the indices in `permutation_indices`""" return [x[i] for i in permutation_indices]
80c7007683b3cc69922a0e8fa2fa30e541fd70de
633,398
import os def get_test_config_dir(): """ Returns a path to a test config dir. """ return os.path.join(os.path.dirname(__file__), "config")
f0483fd25a9eb60624f6102c3df4f3d0179ea7c7
633,399
import textwrap import os import stat def project_tree(tmpdir_factory): """ :type tmpdir_factory: _pytest.tmpdir.TempdirFactory :rtype: py.path.local """ test_projects = tmpdir_factory.mktemp("test_projects") projects = { "root_a": ["dep_a.1", "dep_a.2"], "root_b": ["bs/dep_b.1...
bd47354f7d91a25d792a682c4b194e0ce1504a16
633,400
def funcao(a=''): """ Documentaçao da função onde tem variavel opcional :return: sem retorno """ global variavel variavel = 'Local' a = "nada" print(f'A variavel Local tem valor {variavel}') return variavel
38ae2cce32a7a7a10455935ef43b84c33c058f31
633,401
def text_(s, encoding='latin-1', errors='strict'): """ If ``s`` is an instance of ``bytes``, return ``s.decode(encoding, errors)``, otherwise return ``s``""" if isinstance(s, bytes): return s.decode(encoding, errors) return s
3aca002da7af1641909eebf489e33e37e0850c65
633,402
def _fix_package_name(package_name: str) -> str: """ Fix the package name so it could be placed in the __init__.py file. :param package_name: mystery package name. :type package_name: str :return: fixed mystery package name. :rtype: str """ # Transform to eligible package name. fixe...
c9091fb7f06043d17f3e83a2f76a134b62501020
633,403
def self_test_idiom(fn): """ Perform basic selftest. Returns: True: When everything is ok. Raises: AssertionError: When there is some problem. """ books = fn() assert len(books) > 0 for book in books: error = "Book doesn't have all required parameters!\n" ...
40cc6129b859cb7d379b63e5430612453a4412fa
633,405
import random def _construct_spanning_tree(nodes, edges): """ Construct spanning tree of edges graph using Prim's (also known as Jarník's) algorithm. """ nodes_to_process = set(nodes) first_edge = random.choice(edges) st_nodes = [first_edge[0], first_edge[1]] st_edges = [first_edge] ...
30bcba3ddb75bc5cb06cb7e3016de1a616d350a3
633,406
def plane_distance(p, plane): """Return signed distance to plane of point.""" x, y, z = p A, B, C, D = plane return A*x + B*y + C*z + D
e8c0570e794399eeca0ec647ad058da4c5d6a7aa
633,407
import re def get_glossy_test_conf(source_file="./glossy_test.c"): """Extract configuration define in the glossy_test.c file. Params: ------- source_path: The path to the glossy_test.c file """ RTIMER_SYMBOLIC = r"rtimer_second" # assume millisecond granularity # if this is not suff...
685f40f1230bd77a362fc0b30763a33f8561aa3e
633,408
import time def Now(): """Returns the current time in seconds since the epoch.""" return time.time()
b3988a6382b947c21d9781ed8b8363f53a50551e
633,409
def index_of_refraction(wl): """Bucholtz 95 eq(4 + 5) wl in nm""" wl *= 1e-3 if wl < 0.23: n = ((8060.51 + (2480990 / (132.274 - (1 / wl) ** 2)) + (17455.7 / (39.32957 - (1 / wl) ** 2))) * 1e-8) + 1 else: n = (((5791817 / (238.0185 - (1 / wl) ** 2)) + (167909 / (57.362 - (1 / wl) **...
73d0d19359534c3a0b56a05680391d6edcfef99b
633,410
import json import requests def default_handler(data, context): """A default inference request handler that directly send post request to TFS rest port with un-processed data and return un-processed response :param data: input data :param context: context instance that contains tfs_rest_uri :retu...
3bdd6e002630d860948f54bb3feca5a6047430b4
633,411
def request_headers(): """Return the headers that were sent in the test request.""" return {}
aaac9b5cb3d9edb51d261358f27660af324a5ada
633,412
def read_fai_file(fai_file_name): """ Get a dictionary of an FAI file (reference index). :param fai_file_name: Name of the file to read. :return: A dictionary keyed on the sequence names with one tuple of the record values per record (all integers). """ fai_record_dict = {} with open(fai...
297689a2c0e2ad68838d265932e1a70904067db6
633,413
import torch def torch_fast_mode(): """use `torch.inference_mode()` if torch version is high enough""" try: return torch.inference_mode() except AttributeError: return torch.no_grad()
1833e69d55dcb8484423aaccc54817562fd02733
633,414
import ast def check_deletevar(node): """ Check if there is a delete statement for a variable. Deletes for attributes and subscripts don't count. """ class Visitor(ast.NodeVisitor): def __init__(self): self.found = False def visit_Delete(self, node): ...
23ecface62374a9cd7ec3d53543dc385f91a1903
633,415
def _permissions(annotation): """ Return a permissions dict for the given annotation. Converts our simple internal annotation storage format into the legacy complex permissions dict format that is still used in some places. """ read = annotation.userid if annotation.shared: read = ...
5fb4b0a28023a1ec5b74cc8edaf680a27432a43f
633,416
from datetime import datetime def translate_date(str, in_format, out_format): """Convert a date to ISO8601 date format without time""" try: return datetime.strptime(str.strip(), in_format).date().strftime(out_format) except Exception: pass return ''
9b347a2b503aaafb05a56be93506d3decd4f7838
633,417
import colorsys def increase_saturation(r, g, b): """ Increase the saturation from rgb and return the new value as rgb tuple """ h, s, v = colorsys.rgb_to_hsv(r, g, b) s = min(s+0.3, 1.0) return colorsys.hsv_to_rgb(h, s, v)
7f61cf27c95546238d83dc55b5282ce0611e30f8
633,419
import subprocess def hmmsearch(seqdb, hmmfiles, hmmerpath, outdir): """searches the seqdb for housekeeping genes profiles seqdb string, name of the seqdb file returns ---------- hmmoutput = filename of parsable hmmsearch output """ hmmoutput = f"{outdir}hmmoutput.result.txt" t...
b77388770ff210f4ee23cafc66b00c034154e263
633,420
def find_index(my_in): """ This just for part 1 """ for i in range(len(my_in)): try: res = my_in.index(2020-my_in[i],i+1) if res: return my_in[i]*my_in[res] except: pass
4538a29c86c68e998beacc3a5282ebd2dd2c39c3
633,421
def make_18ee(pc): """アイテム検索結果""" return ""
d5edcd5c274cb23e9efb2c60fbc34fd3f8d6aaec
633,422
import contextlib import socket def is_port_open(host: str, port: int) -> bool: """Determines whether a port on a given host is open.""" with contextlib.closing( socket.socket(socket.AF_INET, socket.SOCK_STREAM) ) as s: return s.connect_ex((host, port)) == 0
d64233e3e2a55f024ea05f4fd8ca829913bacecb
633,423
import six def get_num_evts_per_merged_dataset(merged_datasets,num_evts_per_dataset): """ Return number of events per merged dataset Returns a dict `<merged_dataset>:<num_evts>'; see comments to function `merge_datasets' for an explanation of <merged_dataset>. """ num_evts_per_merged_dataset = {}...
e4533c1156359ffa87974dd13135e4d2fdccbbc4
633,424
import hashlib def _sha1_py3(msg): """Compute sha1 hash of a message. :param msg: string to hash :type msg: str :return: upper case hexdigest representation of a hash :type: str """ sha1hash = hashlib.sha1() sha1hash.update(msg.encode('utf-8')) return sha1hash.hexdigest().upper()
adb8e216b6075132d7a816fcabc013d994604006
633,425
import re import string def clean_punctuation(text): """ @text: is a text with/without the punctuation @return a text without punctuation """ re_punc = re.compile("[%s]" % re.escape(string.punctuation)) return re_punc.sub("", text)
05c34d79b3837b261a2366be85820d2e8dd38a6b
633,426
def giveFinalCommunities(partitionLevels, writeToFile=False): """ Retrieves the final community assignment for all nodes in the graph. Loops through a list of dictionaries. The first dictionary is { originalNodeName:communityID } Then each successive dictionary, the communityID from the previous one...
b4dd25a29702ae58d95ada33717ccd15a09106a3
633,427
import typing def extract_entity_types(line: dict) -> typing.List[str]: """Extracts the entity type(s) for an entity. Arguments: line: ``dict`` A line in the Wikidata dump. Returns: entity_types: ``list`` A list of entity types for the entity. Entity types are also QIDs in Wik...
fd8ead9c03bf63d0a0c8655a39ccd8d0bc105992
633,428
def MSEloss(y_actual, y_pred): """ Mean squared error: squared of actual target minus predicted target y_actual = expected output y_pred = predicted output """ return (y_actual - y_pred) ** 2
62c00fbd51aa12e49d5058f7e661290f93b8566c
633,429
import os import json def getIPs(ipsFile="ip_table.json"): """ carga el archivo de IPs """ ipsFilePath = os.path.join("..", "data", ipsFile) IPs = [] with open(ipsFilePath, "r") as file: IPs = json.load(file)["IPs"] return IPs
2e48bb6247f512216c43feb0200c0f07520cb6e2
633,430
from contextlib import suppress def flatten(lst): """ Flatten list. :param lst: A list to be flattened :type lst: ``list`` :return: Flattened list :rtype: ``list`` """ flattened = [] for element in lst: if isinstance(element, str): flattened.append(element) ...
135eec0779175734129c086e7434584ff60be4c2
633,432
def solution(): """ By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. What is the 10001st prime number? """ n = 64 p = 2 primes = [] while len(primes) < 10001: for i in range(2, p): if p % i == 0: ...
07262dc96c406fd731000ea1680c3e2e82885e2d
633,433
from typing import List def bool2args(data: bool) -> List[str]: """Convert a boolean value to command line argument (flag).""" return []
2750de9452aacf0f37d4b16a9abbff70cebe0dc2
633,434
def count_freq_elem(my_list, element): """helper function to calc the frequency of an element in a list""" counter = 0 for elem in my_list: if elem == element: counter += 1 return counter
30c8b4a5f24b3b0a4f631365a6f8300c9810b301
633,435
import unicodedata def remove_whitespace(u_string): """Removes unicode whitespace from a string. Arguments: string {string} -- String to remove any whitespace from. """ stripped = unicodedata.normalize("NFKC", u_string).strip() return stripped
1859b595998ec6c8266728c3ad816b249adbb000
633,436
def _limit(lower, upper): """Returns a regular expression quantifier with an upper and lower limit.""" if ((lower < 0) or (upper <= 0) or (upper < lower)): raise Exception("Illegal argument to _limit") return u"{%d,%d}" % (lower, upper)
f6f638518a0b89d1dd25083b98f7b17107164258
633,437
def get_file_len(f): """Get file length of file""" i = -1 for i, l in enumerate(f): pass return i + 1
1e43c71bd44ca0e18907806ffca603f78dc989f5
633,438
import json def read_json(filename): """ Read data from JSON file. Args: filename (str): Name of JSON file to be read. Returns: dict: Data stored in JSON file. """ with open(filename, 'r') as in_file: return json.load(in_file)
5c6ccfd56d476ed54b3ec176d0b338fd8309a5ab
633,439
def InsetLineColourRev(argument): """Reverse dictionary for switching colour argurments""" switcher = { 'k' : 'Black', 'dimgrey' : 'Dark Grey', 'darkgrey' : 'Grey', 'lightgrey' : 'Light Grey', 'white' : 'White' } return switcher.get(argument, 'k')
581b58fb0db2bc1edb63f5a66445aca4042e81c5
633,440
def is_phrase_in(ocrword, source_text): """ :param ocrword: The OCR word we have potentially cleaned :param source_text: The full OCR text we have cleaned :return: True if found """ if source_text.find(ocrword) > -1: return True return False
2efd61f9f43e92e122c3833b31c1a76aa66ec858
633,441
def _parse_options_from_cmd_args(args): """ Parse out build options from the command line. Args: args (Argparse obj): The output of 'ArgumentParser.parse_args()' Returns: dict of options. """ opts = {} if args.name is not None: opts['app_name'] = args.name ...
d421066945a2eee174f9a18e80a0697d33175d41
633,442
from typing import Dict from typing import Any def update_buffer(production: Dict[str, Any], buffer: str) -> Dict[str, str]: """Returns a pattern to update the given buffer with. Args: production: The production dict that specifies the buffer update. buffer: The name of the buffer to update. ...
264dc05b0a41bdea2d3ceb3f580ea24780d3d9d7
633,443
from pathlib import Path def getDir(*args): """ Returns a Path from $HOME/rl_results/ and the extra folders given as args. """ dr = Path.home() adds = ["rl_results", *args] for s in adds: dr /= s return dr
4383589d18f37fe4aa7c75d401fd4afc237a6dbd
633,445
def _height(current): """Calculate the height of a given node by descending recursively until there are no further child nodes. Return the number of children in the longest chain down. This is a helper function for the AVL class and BST.__str__(). Abandon hope all ye who modify this function. ...
360a274cef95ebbc5e8e29571a5c46f17b2d3b3c
633,446
def tau_sobol(dim_num): """ tau_sobol defines favorable starting seeds for Sobol sequences. Discussion: For spatial dimensions 1 through 13, this routine returns a "favorable" value TAU by which an appropriate starting point in the Sobol sequence can be determined. These starting p...
ecaf5151402998e192734e07d78e0873e80d2cc2
633,447
import argparse def AddClusterVersionFlag(parser, target, suppressed=False): """Adds a --cluster-version flag to the given parser.""" help_text = argparse.SUPPRESS if suppressed else """\ The Kubernetes version to use for the {target}. Defaults to server-specified. The default Kubernetes version are available us...
a61aecb7b2d0a7e9eee0f38ee1b3e0917871fda6
633,448
def intfs_only(s1code): """Given s1code, keep only interfaces (.h); ignore implementations (.f90).""" return [(l, f, c) for l, f, c in s1code if f.endswith(".h")]
2e43d16d87aa7b427f58622d973229c082e9a67d
633,449
def parse_log(): """ This function turns the log file into a more readable CSV The log file is given by 'log.txt', and we output the parsed result to 'log.csv' """ log_txt = 'log.txt' log_csv = 'log.csv' csv_out = open(log_csv, 'w') csv_out.write('ID,Model,Net Size,ES Epochs,K,Te...
b95a6c768634a7cd7bed927f292fd1974724e2a5
633,452
def process_img_paths(input): """Processes image paths If one path is entered, return list of length 1 containing location. If multiple (comma-separated) paths are entered, return list containing all paths. Args: input (str): string containing image path(s) Returns: paths (list...
53f693885d10c7631257583bb465c9147dc2dca7
633,454
def fst(x): """ Returns the first item of a collection. Examples -------- >>> fst([0, 1, 2]) 0 """ return x[0]
3287201eb82859a4dd275f2516f82c94f50ca816
633,455
import re def paste_urls_from_details(details): """Return list of URLs to objects from details page source.""" return re.findall( r'<a href="(http://localhost:\d+/html/[^"]+)"', details, )
53d034ae8625741968d3fb17757ef0d7b65a9bf9
633,456
import json def loadParamFile(file, dict): """ Given a JSON filename and a dictionary, return the dictionary with the file's fields merged into it. Example: if the initial dictionary is dict['bobAge'] = 90 and dict['samAge']=20 and the JSON data is {'age':{'bob':40, 'fred':35}} the returne...
886ee5a0adca051ac674cec924d695e42ee57cc0
633,457
import time def time_sort(long_format_list, index): """This function returns the sorted list of final output based on modified time of the files """ time_sorted_list=sorted(long_format_list, key = lambda x:x[index]) for entry in time_sorted_list: entry[index]=time.ctime(int(entry[index])) ...
3b3ead0a3a6826dc9dd23583c2665d6369a99325
633,458