content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def lower(input_string: str) -> str: """Convert the complete string to lowercase.""" return input_string.lower()
1ad7c0da84dbe926e5d21aa67d8cf6eee43ba268
72,603
def generate_comment(stored_location, comment_body): """ Purpose of file is to produce a JSON object for an comment. Pulled JSON object from Jama SwaggeUI instance on creating an comment. @params: stored_location: The item id which should be comment comment_body -> The contain of the comment """ return { "body": { "text": comment_body, }, "commentType": "GENERAL", "location": { "item": stored_location } }
8efba2c0d43e5e0af7ef0db67e8a1863bed8fbba
72,605
def CFMtom3sec(VCFM): """ Convertie le debit volumique en CFM vers m3/sec Conversion: 2118.8799727597 CFM = 1 m3/sec :param VCFM: Debit volumique [CFM] :return Vm3sec: Debit volumique [m3/sec] """ Vm3sec = VCFM / 2118.8799727597 return Vm3sec
bc5212a5dbc4036b03359ac53411657dbe862ad0
72,606
def isiterable(it): """Return True if 'it' is iterable else return False.""" try: iter(it) except: return False else: return True
62ab293bdef239fd404c63ce29ed6a78e883381a
72,608
from typing import Iterable def humanize_list(iterable: Iterable[str]) -> str: """Return a grammatically correct English phrase of a list of items. Parameters ---------- iterable : iterable of str Any list of items. Returns ------- phrase : str A grammatically correct way of saying the iterable. Examples -------- >>> humanize_list(['tomato']) 'tomato' >>> humanize_list(['tomato', 'cabbage']) 'tomato and cabbage' >>> humanize_list(['tomato', 'cabbage', 'lettuce']) 'tomato, cabbage, and lettuce' Note ---- Any list with length greater than two will, of course, use an Oxford comma. """ iterable = list(map(str, iterable)) if len(iterable) == 1: return ''.join(iterable) elif len(iterable) == 2: return ' and '.join(iterable) else: iterable[-1] = f'and {iterable[-1]}' return ', '.join(iterable)
a8b10c7d1c15ca415ef4215160d4f26b25a57167
72,611
def pairFR(L): """In : L (list of states) Out: List of pairs with L[0] paired with each state in L[1:], with the distinguishability distance initialized to -1. Helper for generating state_combos. """ return list(map(lambda x: ((L[0], x), -1), L[1:]))
8e6ed142a1fcf48f01cb1b50b0516580a36fac07
72,615
import collections def align (crabs, cost): """Aligns the crab positions `crabs` (array) to the same position using the least fuel, according to the given `cost` function. The `cost` function takes a single parameter, the number of steps to move, i.e. `cost(steps)`. Returns `(pos, fuel)`. """ fuel = collections.defaultdict(int) for moveto in range( max(crabs) ): for crab in crabs: fuel[moveto] += cost( abs(crab - moveto) ) return min(fuel.items(), key=lambda pair: pair[1])
577bacf52cac36155a372fca139040ba1d96e1a7
72,616
def str_to_bool(param): """Check if a string value should be evaluated as True or False.""" if isinstance(param, bool): return param return param.lower() in ("true", "yes", "1")
1e8f3d8da23b1a6de1055788b48012c24fbe55a6
72,624
def extract_keyword(key, dict, default=None, conv=None): """Extracts an attribute from a dictionary. KEY is the attribute name to look up in DICT. If KEY is missing or cannot be converted, then DEFAULT is returned, otherwise the converted value is returned. CONV is the conversion function. """ if dict.has_key(key): if conv: try: return conv(dict[key]) except: return default return dict[key] return default
60ed8323f36bb02dd046284cd0ca3b7904161e37
72,626
def prune_resort_key(scene): """ Used by prune_scenerios to extract the original ordering key for sorting. """ return scene[1]['_order']
2e566af3f6bb06a3c8caccbba5e6f16114eafc8a
72,631
import requests def error_parser(resp_err: requests.Response, api: str = 'graph') -> str: """ Parses Microsoft API error message from Requests response :param resp_err: response with error :param api: API to query (graph/bot) :return: string of error """ try: response: dict = resp_err.json() if api == 'graph': error: dict = response.get('error', {}) err_str: str = f"{error.get('code', '')}: {error.get('message', '')}" if err_str: return err_str elif api == 'bot': error_description: str = response.get('error_description', '') if error_description: return error_description # If no error message raise ValueError() except ValueError: return resp_err.text
23fbe9605fe8c19d1d11a8a3c3f81bf3ba734c31
72,633
def dict_print(d): """convert a dictionary to a string that can be print nicely Args: d (dictionary): the dictionary to be printed """ def listToString(s): str1 = " " return str1.join(s) s = [] counter = 0 for key, value in d.items(): counter += 1 if counter < len(d): s.append(f"{key}: {value}; ") else: s.append(f"{key}: {value}") return listToString(s)
451cd58aa8722fcace2524093fe18ba6153753d9
72,634
import typing import inspect def repr_callable(callable: typing.Callable) -> str: """ Build a string representation of a callable, including the callable's :attr:``__name__``, its :class:`inspect.Parameter`s and its ``return type`` usage:: >>> repr_callable(repr_callable) 'repr_callable(callable: Callable) -> str' :param callable: a Python callable to build a string representation of :returns: the string representation of the function """ # pylint: disable=W0622, redefined-builtin sig = inspect.signature(callable) name = getattr(callable, '__name__', str(callable)) return '{}{}'.format(name, sig)
188b53b54c15868e7c00dac43dd6f96cf107f791
72,635
def format_collapse(ttype, dims): """ Given a type and a tuple of dimensions, return a struct of [[[ttype, dims[-1]], dims[-2]], ...] >>> format_collapse(int, (1, 2, 3)) [[[<class 'int'>, 3], 2], 1] """ if len(dims) == 1: return [ttype, dims[0]] else: return format_collapse([ttype, dims[-1]], dims[:-1])
4d30356db721b6a63caed5a4594f9b56ca769488
72,640
def first_index(target, it): """The first index in `it` where `target` appears; -1 if it is missing.""" for idx, elt in enumerate(it): if elt == target: return idx return -1
cb1ece5a42bcde85afe79c10b587695c2e9dd815
72,642
def nfiles_str(nfiles: int) -> str: """Format `n files`.""" if nfiles == 0: return "no files" elif nfiles == 1: return "1 file" else: return f"{nfiles} files"
cc55bcfc37d6c5c1deff08d285b2af3daa9f00ad
72,646
def serialize(model, callbacks=None, datasets=None, dump_weights=True, keep_states=True): """ Serialize the model, callbacks and datasets. Arguments: model (Model): Model object callbacks (Callbacks, optional): Callbacks datasets (iterable, optional): Datasets dump_weights (bool, optional): Ignored keep_states (bool, optional): Whether to save optimizer states too. Returns: dict: Model data, callbacks and datasets """ pdict = model.serialize(fn=None, keep_states=keep_states) if callbacks is not None: pdict['callbacks'] = callbacks.serialize() if datasets is not None: pdict['datasets'] = datasets.serialize() return pdict
aa003f5c537659ee8febe90754a0ee0dd973490a
72,650
def count_vowels(phrase: str) -> int: """Count the number of vowels in the phrase. :param phrase: text to be examined :return: number of vowels in phrase """ return len([x for x in phrase.lower() if x in 'aeiou'])
0f099819dfa242f52ad560b88b280f9d3c38292b
72,653
import torch def box_denormalize(boxes, img_h, img_w): """ Denormalizes bounding box with coordinates between 0 and 1 to have coordinates in original image height and width. Bounding boxes are expected to have format [x0, y0, x1, y1] or [x0, y0, w, h] or [x_center, y_center, w, h]. :param boxes: List of bounding boxes each with format [x0, y0, x1, y1] or [x0, y0, w, h] or [x_center, y_center, w, h] :type boxes: list[list] or tensorflow.Tensor :param img_h: The height of the image the bounding box belongs to. :type img_h: int or tensorflow.Tensor :param img_w: The width of the image the bounding box belongs to. :type img_w: int or tensorflow.Tensor :return: Normalized bounding boxes. :rtype: tensorflow.Tensor """ boxes = boxes * torch.tensor([img_w, img_h, img_w, img_h], dtype=torch.float32) # boxes * [h, w, h, w] return boxes
54cc710b530846db7c216dea38a6dc66e31cf3d0
72,654
def lorentz_factor(v): """Returns the lorentz factor for velocity v.""" return (1 - v**2)**(-1/2)
37907b7af90a0162b95ecda9a138c2e85393761b
72,662
def build_results_dict(tournament_results): """ builds results. Returns an object of the following form: { team-1: { matches_played: int, wins: int, draws: int, losses: int, points: int, } team-2: { ... } ... team-n: { ... } } """ if tournament_results == '': return {} team_stats_dict = {} array_of_input = [] lines = tournament_results.split('\n') for line in lines: array_of_input.append(line.split(';')) for result in array_of_input: for team in result[0:2]: if team not in team_stats_dict: team_stats_dict[team] = {'matches_played': 0, 'wins': 0, 'draws': 0, 'losses': 0, 'points': 0,} if result[2] == "win": team_stats_dict[result[0]]['wins'] += 1 team_stats_dict[result[0]]['points'] += 3 team_stats_dict[result[1]]['losses'] += 1 elif result[2] == "loss": team_stats_dict[result[0]]['losses'] += 1 team_stats_dict[result[1]]['wins'] += 1 team_stats_dict[result[1]]['points'] += 3 elif result[2] == "draw": team_stats_dict[result[0]]['draws'] += 1 team_stats_dict[result[1]]['draws'] += 1 team_stats_dict[result[0]]['points'] += 1 team_stats_dict[result[1]]['points'] += 1 team_stats_dict[result[0]]['matches_played'] += 1 team_stats_dict[result[1]]['matches_played'] += 1 return team_stats_dict
a10b4eda003745c8dfe726a718eb47a98d2c9d10
72,664
from datetime import datetime def has_no_date(at): """Returns True if the given object is an ``adatetime`` where ``year``, ``month``, and ``day`` are all None. """ if isinstance(at, datetime): return False return at.year is None and at.month is None and at.day is None
299300540ff228740e8e76200a91fe035f2a70f8
72,665
def halve(x: float): """Divide a number by 2""" return x / 2
acc35096f989b9738055ced9f4e191701b121728
72,666
def _create_ad_text_asset(client, text): """Creates an ad text asset with the given text value. Args: client: an initialized GoogleAdsClient instance. text: a str for the text value of the ad text asset. Returns: an ad text asset. """ ad_text_asset = client.get_type("AdTextAsset") ad_text_asset.text = text return ad_text_asset # [END add_local_campaign_3]
fbc140ba86bbad3019370bd05ce19d4cde3238bb
72,667
def check_standard(graph, first, second): """ Standard rewiring conditions as in original theory. """ # curiously the conditions for switching unidirectional and bidirectional # links are the same for just slightly different reasons if first == second: return False # prevent creation of self-links if first[0] == second[1]: return False if second[0] == first[1]: return False # check if we would create a parallel edge if second[1] in graph[first[0]]: return False if first[1] in graph[second[0]]: return False # check if we would create a bidirectional link # or cover existing reverse link in double link switching if first[0] in graph[second[1]]: return False if second[0] in graph[first[1]]: return False return True
d5042db33abb874aca68663dcb40caaff05781a9
72,676
def decorateTitle(title, options): """ Add a marker to TITLE if the TITLE is sorted on. """ if title.lower() == options.sortCategory: return "%s*" % title else: return title
7a0c3842375fe2a0c2b26d231e9735d91d4718b2
72,678
from typing import Dict from typing import Any import time def process_work(worker: int, carrier: Dict[str, Any]) -> int: """Do child process's work.""" print(carrier) time.sleep(1) return worker
c3eeab0b3969bf6d674468e85386a29d45648259
72,685
def latexify(string_item): """Recursive function to turn a string, or sympy.latex to a latex equation. Args: string_item (str): string we want to make into an equation Returns: equation_item (str): a latex-able equation. """ if isinstance(string_item, list): return "\n".join([latexify(item) for item in string_item]) else: return "\\begin{equation}" + str(string_item) + "\\end{equation} \\\\"
2f0efbbbb2e627904eabb7a0ec56d3109950e8a3
72,690
from typing import Tuple import logging async def get_current_turn(queue_array: list) -> Tuple[int, str, int]: """Get the person whose turn it is to do the chore in a queue. Returns ------- Tuple[int, str, int] A tuple of form: (user_id, user_name, index_position) """ for index, member in enumerate(queue_array): if member["current_turn"]: data: Tuple[int, str, int] = (member["user_id"], member["name"], index) return data logging.error("Current turn person not found.") return (0, "", 0)
4b28c820a858d65b967be78f7e2377622e5afec3
72,692
def get_piece(x, y, board): """ Utility function that gets the piece at a given (x,y) coordinate on the given board Returns the piece if the request was valid and None if the request was not valid Arg x: integer - x coordinate Arg y: integer - y coordinate Arg board: board - the board you wish to get the piece from """ #Ensure that x and y are both integers (use assert) assert type(x) == int and type(y) == int, "Error: not an integer" #What does this do? # finds the length of the board N = len(board) #Checking that the (x,y) coordinates given are valid for the N x N board if not (x >= 0 and x < N and y >= 0 and y < N): return None #Getting the piece on the board return board[y][x]
821c7ec20e88419810533de19e8382c9865edcf2
72,699
def to_string(node_chain): """ Purpose: Create a string representation of the node chain. E.g., [ 1 | *-]-->[ 2 | *-]-->[ 3 | / ] Pre-conditions: :param node_chain: A node-chain, possibly empty (None) Post_conditions: None Return: A string representation of the nodes. """ # special case: empty node chain if node_chain is None: result = 'EMPTY' else: # walk along the chain walker = node_chain value = walker.get_data() # print the data result = '[ {} |'.format(str(value)) while walker.get_next() is not None: walker = walker.get_next() value = walker.get_data() # represent the next with an arrow-like figure result += ' *-]-->[ {} |'.format(str(value)) # at the end of the chain, use '/' result += ' / ]' return result
e3a756465c12444e11eeaa10cf95e099fe22ceac
72,700
def minutes(time): """Convert a race time into minutes given a time in the format hh:mm:ss, return the number of minutes""" parts = [int(x) for x in time.split(':')] return parts[0] * 60 + parts[1] + parts[2]/60.
e5193638223d01b5fae4c2d2d0f7f3f33100f1d0
72,702
def get_photo_path(instance, filename): """Define the upload path for saving the current user's photo to disk.""" user_slug = "{}{}".format( instance.user.username, instance.user.id ) upload_path = "photos/{}/{}".format(user_slug, filename) return upload_path
685790494d1c5bf1a0b15a0b8f3d9ace4f981c5d
72,705
import io def image_to_bytes(image): """ Converts PIL image to bytes :param image: PIL.Image :return: bytes """ bytes_buffer = io.BytesIO() image.save(bytes_buffer, format='PNG') return bytes_buffer.getvalue()
b142fa512b3e7b7719772553b79eee01b33f40d1
72,706
def num_set_bits(mask): """Return a count of set bits in a given mask.""" return bin(mask).count("1")
5c44ceaf898772198bd707d225fc4265347a5fea
72,707
import re def _shell_quote(arg): """Shell-quotes a string with minimal noise such that it is still reproduced exactly in a bash/zsh shell. """ if arg == '': return "''" # Normal shell-printable string without quotes if re.match(r'[-+,./0-9:@A-Z_a-z]+$', arg): return arg # Printable within regular single quotes. if re.match('[\040-\176]+$', arg): return "'%s'" % arg.replace("'", "'\\''") # Something complicated, printable within special escaping quotes. return "$'%s'" % arg.encode('string_escape')
4ccd1ecd90901dbd2318ed4b979fb0cf22ec73f1
72,708
import random def create_set() -> list: """ Create domino set""" dominos = [] for i in range(7): for j in range(7): if [j, i] in dominos: continue else: dominos.append([i, j]) random.shuffle(dominos) return dominos
8e3d12eaf1071de8ae2de40f4cf26ca7fdf74c65
72,712
import json def load_style(style: str) -> dict: """Load a json file containing the keyword arguments to use for plot styling Parameters: style: path to json file containing matplotlib style keyword arguments Returns: dictionary of matplotlib keyword arguments """ with open(style, 'r') as styles_src: styles = json.load(styles_src) return styles
4c78f492f4e17e9540af1ae687a7d89c69fb2652
72,713
def is_valid_manifest(manifest_json, required_keys): """ Returns True if the manifest.json is a list of the form [{'k' : v}, ...], where each member dictionary contains an object_id key. Otherwise, returns False """ for record in manifest_json: record_keys = record.keys() if not set(required_keys).issubset(record_keys): return False return True
fb100e10d75f19a10fefa63204783c9e0efeb9f0
72,715
def skip_first_line(value): """Returns everything after the first newline in the string.""" parts = value.split("\n", 1) return parts[1] if len(parts) == 2 else ''
bfd1d19f654afc963c7f27e4368f709e86984dad
72,720
def reSubObject(pattern, string, repl=None): """ like re.sub, but replacements don't have to be text; returns an array of alternating unmatched text and match objects instead. If repl is specified, it's called with each match object, and the result then shows up in the array instead. """ lastEnd = 0 pieces = [] for match in pattern.finditer(string): pieces.append(string[lastEnd : match.start()]) if repl: pieces.append(repl(match)) else: pieces.append(match) lastEnd = match.end() pieces.append(string[lastEnd:]) return pieces
3e59d54a7a28f5793df71be53cbd39ddd3248548
72,721
def _build_self_message(msg, start, end, batch_size, total): """Creates a JSON object for batch processing. The function builds the message with all the details to be able to process the batch data when received. The aim of this message is this very same cloud function. Args: msg: A JSON object representing the message to modify function start: An integer representing the start index from the total ocurrences end: An integer representing the end index from the total ocurrences batch_size: An integer representing the amount of ocurrences in the batch total: An integer representing the total amount of ocurrences Returns: The incoming msg JSON object containing all the input parameters together. """ msg['start_index'] = start msg['end_index'] = end msg['batch_size'] = batch_size msg['total'] = total return msg
5799175465c84d581a731d7e874f1ab3c3c0ddc8
72,725
def tp(x0,U,lam=2,L=3): """ tp means (t)ime to escape right with (p)ositive initial vel. """ return ((2*(L - x0))/U + ((L - x0)*(L + x0)*lam)/U**2 + L/(U + L*lam) - x0/(U + x0*lam))/3.
d50b723de1a98ef93f9e74a57b642d726564a5c8
72,727
from pathlib import Path import hashlib def md5_hash_file(path: Path) -> str: """ Get md5 hash of a file. Args: path (Path): Absolute path or relative to current directory of the file. Returns: str: The md5 hash of the file. """ m = hashlib.md5() with path.open("rb") as f: m.update(f.read()) return m.hexdigest()
de398edd1476bf03cd78a3ddfd3e3c4ce8e14e1e
72,728
def cipher(text, shift, encrypt=True): """This cipher takes string data and 'ciphers' it by shifting each letter by the number of positions specified in the alphabet. Args: text: Input string data to be encrypted / ciphered shift: Number of positions in the alphabet to shift in the right direction encrypt: True/False indicator defining whether or not the string is to be encrypted by this function Returns: Ciphered text with input string data 'text' shifted the number of units defined by 'shift' input. Typical usage example: >>> print([cipher('coding',5)]) 'htinsl' """ alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' new_text = '' for c in text: index = alphabet.find(c) if index == -1: new_text += c else: new_index = index + shift if encrypt == True else index - shift new_index %= len(alphabet) new_text += alphabet[new_index:new_index+1] return new_text
2dd7da5c45c9d24928c1a5906f06cb7e954bbdac
72,733
import re def filter_lines_regex(lines, regex, substitute): """ Substitutes `substitute` for every match to `regex` in each line of `lines`. Parameters ---------- lines : iterable of strings regex, substitute : str """ return [re.sub(regex, substitute, line) for line in lines]
2ed639d60b58447ca26acb75e1c190371c3974d0
72,734
from typing import Dict from pathlib import Path def read_image_to_bytes(filename: str) -> Dict: """ Function that reads in a video file as a bytes array Parameters ---------- filename : str Path to image file Returns ------- JSON Object containing "filename" and bytes array """ with open(filename, "rb") as file: bytes_array = file.read() file_info = {} file_info["filename"] = Path(filename).stem file_info["data"] = bytes_array return file_info
d90721ff1231e7f1e0d2f7ea4bcf81facd2b1686
72,735
def is_nth_bit_is_set(n: int, i: int) -> bool: """ Test if the n-th bit is set. >>> is_nth_bit_is_set(0b1010, 0) False >>> is_nth_bit_is_set(0b1010, 1) True >>> is_nth_bit_is_set(0b1010, 3) True >>> is_nth_bit_is_set(0b1010, 5) False """ return bool(n & (1 << i))
14832450712bb43991bf488f72c659e98b7a5d95
72,738
def remove_quotes(val): """ Remove surrounding quotes from a string. :param val: The string to remove quotes from. :type val: str :returns: str """ if val.startswith(('"', "'",)) and val.endswith(('"', "'",)): val = val[1:-1] return val
8fc71e6eebae968ca122707aecc4094bce4c243b
72,742
def map_tcp_flags(bitmap): """ Maps text names of tcp flags to values in bitmap :param bitmap: array[8] :return: dictionary with keynames as names of the flags """ result = {} result["FIN"] = bitmap[7] result["SYN"] = bitmap[6] result["RST"] = bitmap[5] result["PSH"] = bitmap[4] result["ACK"] = bitmap[3] result["URG"] = bitmap[2] result["ECE"] = bitmap[1] result["CRW"] = bitmap[0] return result
f6388e3aa6a7540df8b26ba2061be5807f6c19be
72,749
def unique(iterable): """Remove duplicates from `iterable`.""" return type(iterable)(x for x in dict.fromkeys(iterable))
d4ac674105ed55ba9c969134a507838790770d77
72,750
from pathlib import Path def parent_dir(filepath): """Get parent directory path from filepath""" return Path(filepath).resolve().parent
6b9fc56ebe248b64b2080b25efc1a335dafdda56
72,752
def get_default_parameters(args): """Build a default parameters dictionary from the content of the YAML file.""" return {name: values["default"] for name, values in args.items()}
934af26ad4e19e483f7cc3fb6224f9dc5b3155b8
72,754
import heapq def eigvec2str(eigvec, m, n, nctr, nvis = 6, npc = 6, iws = ' '): """ Output some prominent matrix elements for an eigenvector matrix eigvec is given as a 1D array: [ <B_1|1k>, <B_1|2k>, <B_2|1k>, <B_2|2k>] which corresponds to such a matrix (m rows x n cols): <B_1|1k> <B_1|2k> <B_2|1k> <B_2|2k> nctr: list states around the center nctr nvis: number of printed out states npc: number of principal components iws: initial white spaces for indentation """ resstr = iws + '{0:<10}{1}\n'.format('norm', 'principal components') # guarantee len(eigvec) = n * m for j in range(max(0, nctr - int(nvis / 2) + 1), min(n, nctr + int(nvis / 2) + 1)): eabs = [ abs(eigvec[i * n + j]) ** 2 for i in range(m) ] norm = sum(eabs) # print out the norm resstr += iws + '{0:<10.5f}'.format(norm) # the wavefunction to print: |nk> = ... resstr += '|n={0:>4},k> = '.format(j) # Find the npc elements with the largest norm indices = heapq.nlargest(npc, range(len(eabs)), key = lambda i : eabs[i]) for i in indices: resstr += '({0:11.3f})|B_{1}> + '.format(eigvec[i * n + j], i) # resstr = resstr[:-3] # delete the last + resstr += '... \n' return resstr
450dadd2d4f33681b21229c5c3b18a14b4266f81
72,765
def validate_slug_format(proposed_slug): """Raise an error if the proposed slug is invalid For example, if contains a slash.""" # a regex would run faster, but getting the quoting right for a literal # backslash probably isn’t worth it FORBIDDEN_SLUG_CHARS = "/\\ " if any(c in FORBIDDEN_SLUG_CHARS for c in proposed_slug): raise Exception( f"{proposed_slug=!r} contains one of the forbidden slug chars {FORBIDDEN_SLUG_CHARS!r}" ) return proposed_slug
14458e9fde2aff66346e55bf40e0edfbfdb80de1
72,769
from typing import Dict import json def load_config_file(file_name: str) -> Dict: """ Reads the configs/config.json file and parse as a dictionary :param file_name: name of the config file :return: config dictionary """ try: with open(f'{file_name}') as f: conf: Dict = json.load(f) return conf except FileNotFoundError: raise FileNotFoundError(f'{file_name} Not found')
827c4af5059f6db1fc8ef4f195ef1de32ce80fb2
72,770
def get_selected_attrs(stream): """ List down user selected fields requires [ "selected": true ] inside property metadata """ list_attrs = list() for md in stream.metadata: if md["breadcrumb"]: if md["metadata"].get("selected", False) or md["metadata"].get("inclusion") == "automatic": list_attrs.append(md["breadcrumb"][-1]) return list_attrs
b0df8a2f655f49250cd34219f785b5a8d4538643
72,773
import binascii def pubkey_to_redeem(pubkey): """ Convert the public key to the redeemscript format. Args: pubkey (bytes): public key. Returns: bytes: redeemscript. """ return binascii.unhexlify(b'21' + pubkey + b'ac')
318849b22b9b2813c9c0235ec00f3f87d3e3ee32
72,774
import random def rectangles_unif_side(n: int, m: int): """Return list of `n` rec. with random side lengths `unif{0, m}`""" return [(random.randint(1, m), random.randint(1, m)) for _ in range(n)]
3cf48b22ed9a11766010af20ec5bf8ce28c9f9e8
72,780
import typing import re def to_snake(d: typing.Dict[str, typing.Any]) -> typing.Dict[str, typing.Any]: """Converts dictionary keys from camel case to snake case.""" def convert(key: str) -> str: camel = re.sub("(.)([A-Z][a-z]+)", r"\1_\2", key) return re.sub("([a-z0-9])([A-Z])", r"\1_\2", camel).lower() return {convert(k): v for k, v in d.items()}
6f12faf003a80bc050fde26770788cbaffb00122
72,781
def to_multiregion(region): """Convert a single region or multiple region specification into multiregion list. If a single region (chrom, start, end), returns [(chrom, start, end)] otherwise returns multiregion. """ assert isinstance(region, (list, tuple)), region if isinstance(region[0], (list, tuple)): return region else: assert len(region) == 3 return [tuple(region)]
8d9a41e7d9e16bd1bc8553f9be38b5152ce8c7de
72,788
def extract(ts): """ Retrieve lists of C, T, D from taskset ts """ C = [] T = [] D = [] for i in range(len(ts)): C.append(ts[i].C) T.append(ts[i].T) D.append(ts[i].D) return C, T, D
d87c675fe150c8d1c7e8db32559283a7090121d8
72,790
from typing import Dict from typing import Tuple def get_line_found_and_hit(dict: Dict[int, int]) -> Tuple[int, int]: """Return the count for entries (found) and entries with an execution count greater than zero (hit) in a dict (linenumber -> execution count) as a list (found, hit)""" found = len(dict) hit = sum(1 for count in dict.values() if count > 0) return (found, hit)
4cf39b34dd11c3e702337c9b9d7f9f2ae7612ebb
72,791
import torch def preprocessing(num_ways, num_shots, num_queries, batch_size, device): """ prepare for train and evaluation :param num_ways: number of classes for each few-shot task :param num_shots: number of samples for each class in few-shot task :param num_queries: number of queries for each class in few-shot task :param batch_size: how many tasks per batch :param device: the gpu device that holds all data :return: number of samples in support set number of total samples (support and query set) mask for edges connect query nodes mask for unlabeled data (for semi-supervised setting) """ # set size of support set, query set and total number of data in single task num_supports = num_ways * num_shots num_samples = num_supports + num_queries * num_ways # set edge mask (to distinguish support and query edges) support_edge_mask = torch.zeros(batch_size, num_samples, num_samples).to(device) support_edge_mask[:, :num_supports, :num_supports] = 1 query_edge_mask = 1 - support_edge_mask evaluation_mask = torch.ones(batch_size, num_samples, num_samples).to(device) return num_supports, num_samples, query_edge_mask, evaluation_mask
86802320714009b3c4a244dd71ca902e274bbf7b
72,792
def location_to_index(location, spacing, shape): """Convert a location to an index. Parameters ---------- location: tuple of float or None Location of source in m. If None is passed at a certain location of the tuple then the source is broadcast along the full extent of that axis. For example a source of `(0.1, 0.2, 0.1)` is a point source in 3D at the point x=10cm, y=20cm, z=10cm. A source of `(0.1, None, 0.1)` is a line source in 3D at x=10cm, z=10cm extending the full length of y. spacing : float Spacing of the grid in meters. The grid is assumed to be isotropic, all dimensions use the same spacing. shape : tuple of int Shape of the grid. This constrains the valid indices allowed. Returns ------- tuple of int or slice Location of source in grid. Where source is broadcast along the whole axis a slice is used. """ index = tuple(int(loc // spacing) if loc is not None else None for loc in location) # Ensure index is positive index = tuple(max(0, ind) if ind is not None else None for ind in index) # Ensure index is less than shape index = tuple(min(s-1, ind) if ind is not None else None for s, ind in zip(shape, index)) index = tuple(ind if ind is not None else slice(None) for ind in index) return index
457e4575761d4999fc2fcd90caccfd8b8207f78d
72,800
def get_fractions(setting_fractions_df, location): """ Get the fraction of people with contacts in each setting of household (H), school (S), or work (W). Args: setting_fractions_df (pandas DataFrame) : a dataframe location (str) : name of the location Returns: dict: A dictionary of fractions of people with contacts in each setting for the location. """ fractions = dict.fromkeys(['H','S','W','R'],1.) d = setting_fractions_df[setting_fractions_df.location == location] fractions['H'] = d.NhN.values[0] fractions['S'] = d.NsN.values[0] fractions['W'] = d.NwN.values[0] return fractions
efa6fbc55405c647b83f43f959b6b3c56754d819
72,801
def oncogenes_count(driver_dataframe): """Function to count number of oncogenes from final driver gene dataframe.""" oncogene = driver_dataframe["driver_role"] == "Oncogene" df_oncogene = driver_dataframe[oncogene][[ "gene", "driver_role"]].drop_duplicates().reset_index(drop=True) return len(df_oncogene.index)
e734b4d0f85b149ccddd2dc3bb11af7869d53fa7
72,803
def get_image_scale(image_size, target_size): """ Calculates the scale of the image to fit the target size. `image_size`: The image size as tuple of (w, h) `target_size`: The target size as tuple of (w, h). :return: The image scale as tuple of (w_scale, h_scale) """ (image_w, image_h) = image_size (target_w, target_h) = target_size scale = (target_w / float(image_w), target_h / float(image_h)) return scale
2a0677754ede840f850b1337d7c14eddbae44d40
72,806
def get_list_as_str(list_of_objs): """ Returns the list as a string. """ return '[' + ' '.join([str(x) for x in list_of_objs]) + ']'
5b747f727d87db2ea4edd3b6aeedd27b25a7b49e
72,808
def assert_utility_signal(library, session, line): """Asserts or deasserts the specified utility bus signal. Corresponds to viAssertUtilSignal function of the VISA library. :param library: the visa library wrapped by ctypes. :param session: Unique logical identifier to a session. :param line: specifies the utility bus signal to assert. (Constants.UTIL_ASSERT*) :return: return value of the library call. :rtype: :class:`pyvisa.constants.StatusCode` """ return library.viAssertUtilSignal(session, line)
cba39190520ed41f94afa7991595f51b3d4401f3
72,813
import copy def build(cfg, registry, args=None): """ Build the module with cfg. Args: cfg (dict): the config of the modules registry(Registry): A registry the module belongs to. Returns: The built module. """ args = copy.deepcopy(cfg) name = args.pop("name") ret = registry.get(name)(**args) return ret
3a662160eed76e11a714090dcaa15367893e90f1
72,816
import warnings def convert_method_3_nb_into_str(method_3_nb): """ Converts method_3_nb into string Parameters ---------- method_3_nb : int Number of method 3 Returns ------- method_3_str : str String of method 3 """ if method_3_nb is None: msg = 'method_3_nb is None. Going to return None.' warnings.warn(msg) return None dict_method_3 = {0: 'food_pro', 1: 'metal', 2: 'rest', 3: 'sports', 4: 'repair'} method_3_str = dict_method_3[method_3_nb] return method_3_str
e364ace46829c2aeac4dc4bb4f31eb6a0d304b41
72,822
import copy def expand_list(list_1d: list) -> list: """Expand 1d list to 2d Parameters ---------- list_1d : list input list Returns ------- list_2d: list output 2d list """ list_2d = copy.deepcopy(list_1d) if not isinstance(list_1d[0], list): list_2d = [list_2d] return list_2d
5c594076650dbc2a50be64cbb5cb55ea2f6d184f
72,826
def _parse_name(name): """Returns a pair namespace, name parsing string like namespace/name. Namespace could be None if there is not backslash in the name. """ if '/' in name: return name.split('/', 1) return None, name
fe6456cfa630d9d5e3475518264f6f1b262f1761
72,829
from typing import Union from pathlib import Path from typing import cast def ensure_path(path: Union[Path, str]) -> Path: """Return path object from `pathlib.Path` or string. While `Path` can be called on strings or `Path` and return a `Path`, it does not behave correctly for mock path instances. This helper function ensures we can support normal usage and mocked paths used for testing. """ if hasattr(path, "open"): return cast(Path, path) return Path(path)
64c679ef37a13f9a1776e4d0b01bc4e246d966ce
72,833
import configparser def read_config(config_file): """Read the config file. Args: config_file (file) : Plugin config file Returns: object: config object """ config = configparser.ConfigParser() config.read(config_file) return config
20d67952dfd6c619f5693996162e2cca984af483
72,834
def spiral_matrix(matrix): """Navigates a 2D array and traverses the edges in a spiral-pattern. Args: matrix; list: a 2D list to traverse. Returns: A string representation of all points traveled in the matrix in the order they were traveled to. """ output = list() rows = len(matrix[0]) columns = len(matrix) # Our iterators for columns and rows respectively. x = 0 y = 0 # Our edge coordinates. edge_x = 0 edge_y = 0 while x < rows and y < columns: # Traverses the top edge of the matrix. for x in range(0 + edge_x, rows): output.append(matrix[y][x]) rows -= 1 # Traverses down the right edge of the matrix. for y in range(1 + edge_y, columns): output.append(matrix[y][x]) columns -= 1 if edge_x < x and edge_y < y: # Traverses along the bottom edge of the matrix. for x in range(rows - 1, -1 + edge_x, -1): output.append(matrix[y][x]) edge_x += 1 # Traverses along the left edge of the matrix. for y in range(columns - 1, 0 + edge_y, -1): output.append(matrix[y][x]) edge_y += 1 else: break """ The instructions seemed to indicate that I should return a string, so I chose to use the generator notation here to perform that function. I chose this vs. a list comprehension since it is a bit more space-efficient. """ output_strings = ' '.join((str(number) for number in output)) return output_strings
013e9e9a8f47ed0d8b5631cb2e912654f85c0897
72,837
import random def _get_random_number(interval): """ Get a random number in the defined interval. """ return random.randrange(2**(interval-1), 2**interval - 1)
f586330e3eba08e5ccc22e31cf8a8a04b20a9aa6
72,838
import json def json_encode(obj): """ Serialize obj to a JSON formatted str """ return json.dumps(obj)
b04774e675971c3c234df9b2e09436cd349707c5
72,839
def scaps_script_generator(calc_param): """ Generate SCAPS simulation input script as a string. """ return "\n".join(["//Script file made by Python", "set quitscript.quitSCAPS", "load allscapssettingsfile {}".format(calc_param['def']), "set errorhandling.overwritefile", "set layer1.mun %f" % calc_param['mu_n_l'], "set layer1.defect1.Ntotal %f" % calc_param['Nt_SnS_l'], "set layer2.chi %f" % calc_param['EA_ZnOS_l'], "set interface1.IFdefect1.Ntotal %f" % calc_param['Nt_i_l'], "action workingpoint.temperature %f" % calc_param['T_l'], "action iv.startv %f" % 0.0, "action iv.stopv %f" % calc_param['V_max'], "action iv.increment %f" % 0.02, "action intensity.T %f" % calc_param['ill_l'], "calculate"])
fc20d8cbf004bdc3585925b018680ecb09de8022
72,842
def all_comics_for_series(series_obj): """ Get all published or announced comics for a series. :param series_obj: :class:`marvelous.Series` instance :return: `list` of :class:`marvelous.Comic` instances """ limit = 100 offset = 0 total = None comics = [] fetches = 0 while total is None or offset < total: print(f'Fetching {limit} comics from {offset} offset, out of {total}') response = series_obj.comics({ 'format': 'comic', 'formatType': 'comic', 'noVariants': True, 'limit': limit, 'offset': offset, 'orderBy': 'issueNumber' }) comics += response.comics total = response.response['data']['total'] offset += limit fetches += 1 # Just a safety break. No comic has more than 1k issues if fetches > 10: break return comics
b45d1e39fe02be7227f25abbe13cce4226300202
72,844
def create_tuple_mapper(input_fn, output_fn): """ Creates a mapping function that receives a tuple (input, output) and uses the two provided functions to return tuple (input_fn(input), output_fn(output)). """ def fun(item): input, output = item return input_fn(input), output_fn(output) return fun
af851dfff9f3f836f7f2e0ff28055041a7294aeb
72,846
def build_youtube_resource(title, description, recording_date, coords=None, location_desc=None, tags=None, category=25, privacy='unlisted', language='en'): """ Build a YouTube video resource as per https://developers.google.com/youtube/v3/docs/videos. :param title: :param description: :param recording_date: :param coords: :param location_desc: :param tags: :param category: Default is 25, 'News & Politics'. :param privacy: public|private|unlisted :param language: 2-letter language code. """ recording_details = { 'recordingDate': recording_date.in_timezone('UTC').to_iso8601_string().replace('+00:00', '.0Z'), } if coords: recording_details['location'] = { 'latitude': coords[0], 'longitude': coords[1], 'altitude': 0.0, } if location_desc: recording_details['locationDescription'] = location_desc return { 'snippet': { 'title': title, 'description': description, 'tags': tags if tags else [], 'categoryId': category, 'defaultLanguage': language, 'defaultAudioLanguage': language, }, 'status': { 'privacyStatus': privacy, }, 'recordingDetails': recording_details, }
35fe25a1f4478e11b1cb1f860d49ff3185c5d86e
72,847
def ix(dot,orb,spin): """ Converts indices to a single index Parameters ---------- dot : int Dot number orb : int Orbital number (0 for p- and 1 for p+) spin : int 0 for spin down, 1 for spin up. Returns ------- int """ return 4*dot+2*orb+spin
e8ce258d243d5b2933a91596c3df4b191ed7edcb
72,861
def add_scale_bar(apx, s, sl, c='y'): """ Adds an aplpy scale bar :param apx: aplpy fig :param s: astropy.units quantity, size (with units) of the scale bar :param sl: string, label for scale bar :param c: string, colour of scalebar :return: """ apx.add_scalebar(s) apx.scalebar.set_label(sl) apx.scalebar.set_color(c) return apx
d109560ce942f1b98777ae182e81b5842731cc03
72,864
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 zipdict(keys, vals): """Creates a dict with keys mapped to the corresponding vals.""" return dict(zip(keys, vals))
15cb1a2c5936f973703ea14126056ff076160f70
72,870
def uh(h): """Convert a hexadecimal string representation of a number to an integer. Example: uh('0xabcdef0') == 0xabcdef0 uh('abcdef0') == 0xabcdef0 """ return int(h.replace('0x', '').replace(' ',''), 16)
4c8bfcbbdae132807fe71c50a9bfc8e6be0651ce
72,871
def generate_prompt(is_continuation): """ calculate and return a string with the prompt to display """ if not is_continuation: return '>>> ' return '... '
6f6be71caa0b1c207a69deead956c6fb12f31c15
72,875
import torch def load_model(fname): """Loads a model on CPU by default.""" savable = torch.load(fname, map_location='cpu') return savable.userdata
54cfb716e80c83139fa4d5c4e6a40b9d74147661
72,878
def step(edge, x): """Return 0.0 if x < edge; otherwise result is 1.0, with x a float scalar or vector.""" return 0.0 if x < edge else 1.0
57f4dc9f3455b7cde342336268377fe06865fae0
72,881
def solveMP(MP, xr, yr, d): """ Get optimal solution and objective value for current master problem """ # optimize MP.update() MP.optimize() MPobj = MP.objVal # get first-stage varibles xrsol_t = {} for u in d.users: for v in d.VMs: for p in d.providers: xrsol_t[u,v,p] = xr[u,v,p].x yrsol_t = {} for u in d.users: for r in d.routers: yrsol_t[u,r] = yr[u,r].x return xrsol_t, yrsol_t, MPobj
fe2d45e7f74609be12b3f2fd0a05eb6bce6beaaa
72,882
import unicodedata def remove_accents(word: str) -> str: """ Return the same word with all accents removed >>> remove_accents('Mongolië') 'Mongolie' """ nfkd_form = unicodedata.normalize('NFKD', word) return u''.join([c for c in nfkd_form if not unicodedata.combining(c)])
4602c40046914ead801496deb1ef805a6abea91e
72,883
def permute(arr, permutation): """ Permute the array: permutation[i] is the new index for the i-th element of arr """ if permutation is None: permutation = range(len(arr)) result = [None] * len(arr) for element, index in zip(arr, permutation): result[index] = element return result
b59efd8f5fdad3ccef48fe8d4920b0d7253e0a45
72,884
def ft_db_close_conn_sqlite(conn): """Close sqlite database connection. """ conn.close() return True
93d3334b78764947a3757417b6b988aae82a6060
72,885
def merge_fields(*fields): """ Provided as a convenience to merge multiple groups of fields. Equivalent to: `fields.update(**other_fields)`. Dictionaries are processed in order and overwrite fields that are already present. Parameters ---------- fields : *args Field dictionaries to merge. Returns ------- dict """ out = {} for flds in fields: out.update(**flds) return out
df2bae5dfe899cc5ca2e761bd807aae9887ea64c
72,889
def find_group_single_candidate(square: tuple, squares: list, grid: list) -> list: """ Checks for a single option a square can have based on no other square in a group having it as an option :param square: A tuple (row, column) coordinate of the square :param squares: A list of squares (tuples) to check the options of :param grid: The sudoku grid as a 3D list :return: A list of options """ if square in squares: squares.remove(square) square_options = set(grid[square[0]][square[1]][1]) for sq in squares: if grid[sq[0]][sq[1]][0] == 0: square_options = square_options - set(grid[sq[0]][sq[1]][1]) else: square_options = square_options - {grid[sq[0]][sq[1]][0]} return list(square_options)
1983720f4540b0bd964a2ba535455ca0510ef369
72,890
def _is_in(obj, lst): """Checks if obj is in lst using referential equality. """ return any(el is obj for el in lst)
c6ee76d82bd77f3f80d86320cdef8ac5a01506b9
72,892
def _check_features(schema1, schema2): """ Get list of features to check based on table schemas Parameters ---------- schema1: table1 schema schema2: table2 schema Returns ------- schema: merged and modified schema check_features: a dictionary of (data type, feature list) to check """ # select useful columns in schema schema1 = schema1[schema1['column'] != 'column not in current table'][['column', 'type', 'include']].rename( columns={'column': 'column_1', 'type': 'type_1', 'include': 'include_1'}) schema2 = schema2[schema2['column'] != 'column not in current table'][['column', 'type', 'include']].rename( columns={'column': 'column_2', 'type': 'type_2', 'include': 'include_2'}) # merge two schemas schema = schema1.merge(schema2, left_on='column_1', right_on='column_2', how='outer') # start to record the errors schema['error'] = '' schema.loc[schema['type_1'] != schema['type_2'], 'error'] = "inconsistent data types" schema.loc[schema['include_1'] == 0, 'error'] = "exclude" schema.loc[schema['include_1'] != schema['include_2'], 'error'] = "inconsistent include" schema.loc[schema['column_1'].isnull(), 'error'] = "column not in table1" schema.loc[schema['column_2'].isnull(), 'error'] = "column not in table2" # classify the features to compare schema_correct_include = schema[(schema['include_1'] == 1) & (schema['error'] == '')].reset_index(drop=True) check_features = {} for dtype in ['key', 'numeric', 'str', 'date']: check_features[dtype] = schema_correct_include[schema_correct_include['type_1'] == dtype]['column_1'].values return schema, check_features
efb50b1b1522f7d378568e9ca8e9fd1d1192bc22
72,895
def parseSingleLink(line): """Parse a single link having the format: src dst [weight] line - non-empty line of the input text that starts from a non-space symbol return [src_str, dst_str, weight_str | None], """ line = line.split(None, 3) # Ending comments are not allowed, but required unweighted link might contain input weight assert len(line) >= 2 and line[0][0].isdigit() and line[1][0].isdigit(), ( 'src and dst must exist and be digits') if len(line) == 2: line.append(None) else: assert line[2][0].isdigit() or line[2][0] == '.', 'Weight should be a float number' return line
32aea6ed5fa6225c9514150f67580162ae11d0c4
72,897