content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def filter_traceback(tb_list): """Given a traceback as a list of strings, looks for common boilerplate and removes it.""" # List of boiler plate pattern to look for, with example before each # The match pattern is just some string that the line needs to contain """ File "asynq/async_task.py", l...
ce883c3d2c9118125b41701b1c981bfa8583011b
658,304
import json def read_json(file_path: str) -> dict: """ Function that reads JSON configuration file and returns data. >>> from snakypy import helpers >>> file = '/tmp/file.json' >>> helpers.files.read_json(file) Args: file_path (str): You must receive the full/absolute file path ...
f2f1f2e5c0b05c12b391fe095fd4c53ebdc4c9a3
658,309
import math def floor(x): """Round x to the nearest whole number smaller than or equal to x.""" return math.floor(x)
8e769a4f74d5256d048421b4010165f40977d597
658,312
import re def words(text): """Get all words from the text.""" return re.findall("[a-z]+", text.lower())
e28f2dd54aabc9d0abe88300e0575cbb8a29e445
658,315
import re def parse_signature(signature): """ Parses one signature :param signature: stanc3 function signature :return: return type, fucntion name and list of function argument types """ rest, return_type = signature.rsplit("=>", 1) function_name, rest = rest.split("(", 1) args = re.fi...
91e451902601e4196ca4e79458f3fb44193210b4
658,316
def rgb(rgb_colors): """ Return a tuple of integers, as used in AWT/Java plots. Parameters ---------- rgb_colors : list Represents a list with three positions that correspond to the percentage red, green and blue colors. Returns ------- tuple Represents a tuple ...
c2e3861c631bf5c64e426e02455758732d70fb8e
658,317
def _triangulate(g, comb_emb): """ Helper function to schnyder method for computing coordinates in the plane to plot a planar graph with no edge crossings. Given a connected graph g with at least 3 vertices and a planar combinatorial embedding comb_emb of g, modify g in place to form a graph whose ...
c8ecd268c4de7d15f7d7a9071d6607c1b3f1943e
658,322
def enabled_disabled(b): """Convert boolean value to 'enabled' or 'disabled'.""" return "enabled" if b else "disabled"
d599aa1711a767c921d3ccd7af9ad18e8430ca4e
658,324
def match_update_from_regex(re_parsing_rules, stmt): """Parse an update statement using regexes. Args: re_parsing_rules (dict): Dictionary containing the rules for parsing statements as values and their effects as keys. stmt (str): String representing a statement Returns: ...
1a5de48c816d2517df962ee5cf7a62a1d52ff0a7
658,325
import requests import json def custom_ws_perm_maker(user_id: str, ws_perms: dict): """ Returns an Adapter for requests_mock that deals with mocking workspace permissions. :param user_id: str - the user id :param ws_perms: dict of permissions, keys are ws ids, values are permission. Example: {...
86837c953dafd6b96f70de79c64ce72b6997e0cc
658,328
def heuristic(point_1, point_2): """Calculates the manhattan distance between points and returns an integer""" x1, y1 = point_1 x2, y2 = point_2 man_dist = abs(x1 - x2) + abs(y1 - y2) return man_dist
275855aa70a15a6ccd600ff5b046fd24a463a389
658,329
def read_whitelist(whitelist_file): """This function reads the white list file and returns the list""" # create an empty dictionary to store the white lists whitelistdict = {} with open(whitelist_file, 'r') as fp: for line in fp: whitelistdict[line.strip()] = True # return the ...
aa416fd866673e1ddf9c5c91d19b11a8fafa6fe5
658,330
def create_count_neighbors_ca1d(width): """ Returns a list with the weights for 'neighbors' and 'center_idx' parameters of evodynamic.connection.cellular_automata.create_conn_matrix_ca1d(...). The weights are responsible to count the number of alive neighbors. Parameters ---------- width : int Neig...
5e1416a39f398bb4858855009c022af0101c1a5f
658,331
import re def isHour(time): """renvoit 1 si l'heure est au bon format pour etre transformé en heure, 0 sinon""" try: assert isinstance(time, str) regex = re.compile(r"[0-9]*:[0-9]*") assert regex.match(time) args = time.split(":") assert len(args) == 2 and isinstance(...
f04b7242e09a4cdc35356298126499b09d22651c
658,333
import base64 def base642str(s: str): """ Convert a base64 to string. :param s: the base64 string :return: a string """ return base64.b64decode(s).decode()
7f5a09206d5f81e348cd5c9b6489b808a5d00894
658,335
import struct def u32(x): """Unpacks a 4-byte string into an integer (little endian)""" return struct.unpack('<I', x)[0]
07c4e353375cac3ef8e4de44d6823aa888affb97
658,337
import http def auth_reject(realm=None): """ Returns a HTTP 401 UNAUTHORIZED response to a user that is being rejected from requesting a resource. Use the realm param to control which realm is provided in the rejection """ auth_header_value = 'Basic' if realm is not None: auth_header_...
1759cb35603196cf7c7030939da8dd236fe563b7
658,340
import hashlib def sha1(text_: str) -> str: """Get SHA1 hash from string in hex form.""" return hashlib.sha1(str(text_).encode("UTF-8")).hexdigest()
5561c35c86821ed4098917c21eb4a5ed7abcac0b
658,345
def get_current_account_id(context): """ Get current account id. @param context: the context of the event @return: current account id """ return context.invoked_function_arn.split(":")[4]
d3f8fce71edf575af7aebd7c75a9cc71f2900f86
658,346
def getShortVersion(version: str) -> str: """ :param version: A Python version. :return: The major and minor part of 'version'. """ return '.'.join(version.split('.')[:2])
ca77869adc2610d48e48eba0c525c1f1589b5c9e
658,347
import math def dip(x0, z0, x1, z1): """ Compute dip between two points: (x0, z0) (x1, z1) Parameters ---------- x0 : float X-coordinate of point 0 x1 : float X-coordinate of point 1 z0 : float Z-coordinate of point 0 z1 : float Z-coordinate of point 1 ...
63d0420b79a708082ceb1117eedc88899886659f
658,350
def solver_problem1(inputs): """ Count the number of increasement from given list """ num_increased = 0 for i in range(1, len(inputs)): if inputs[i] > inputs[i - 1]: num_increased += 1 return num_increased
ab0a82da86ba730934f2a1e572ae4f145fb5e463
658,351
def get_n_grams(text, n): """ Computes the n-grams of a given text :rtype : list :param text: The text provided :param n: The n of n-grams :return: List of all the word's n-grams """ # returning the list of n-grams return [text[i:i+n] for i in range(len(text) - n + 1)]
107c1c36c3b3cd0fa66e012f6af36911a0ed3c66
658,352
def normalize(z): """ Normalize an array. :param z: The array to normalize :type z: array """ return (z - min(z)) / (max(z) - min(z))
2483412c7ce8e11a5d912d1fab678c3e4f6a91aa
658,354
import string def str_to_python_id(val): """Convert a string to a valid python id in a reversible way Arguments: val (str): The value to convert Returns: str: The valid python id """ result = '' for c in val: if c in string.ascii_letters or c == '_': resul...
7fe7f7808b6e106ea9fddabf37393cdc521de920
658,357
def set_generator(filename, index): """ Given a file, returns a set with all the values from the column[index] """ results = set() with open(filename, 'r') as fi: for line in fi: line = line.strip().split() results.add(line[index]) return results
50cd2afab1e57381030c48dfaf53ce64fd7910a3
658,358
def fetch_pipe_elements(pipesystem, ignore_inlets=False, ignore_outlets=False): """Iterates through the PipeSystem and returns a list of all PipeElements Arguments ------------------ pipesystem : PipeSystem The PipeSystem for which the elements should be gathered for ignore_inlets : bool ...
0b6f808108809ced30c101b1c70184107f0e0c9b
658,361
from typing import List def get_requirements(reqs_filename: str) -> List[str]: """Get a package's requirements based on its requirements file.""" try: with open(reqs_filename, "r", encoding="utf-8") as reqs_file: reqs = reqs_file.read().strip().split() return reqs except FileN...
67c1034401dc9394d8ee15b46451d50e4cae7f69
658,363
def adjust_to_1(row): """If total sum larger than 1, remove the differnce from largest value.""" total = sum(row) if total > 1: largest = max(row) replace = row.index(largest) row[replace] = largest - (total-1) return row
90cc4b5c276cc0cc8cc6ed89db684ced81cee4c8
658,364
def _set_default_duty_cycle(duty_cycle: float, type_id: int) -> float: """Set the default max rated temperature for mechanical relays. :param duty_cycle: the current duty cycle. :param type_id: the type ID of the relay with missing defaults. :return: _duty_cycle :rtype: float """ if duty_cy...
a9ae302568b0c857420d2877fdf7c32f4e53f41a
658,365
def _R(T, Cr, n): """ Basic function for calculating relaxation time due to the Raman mechanism. For canonical definition, see fx. DOI: 10.1039/c9cc02421b Input T: temperature for the calculation Cr: Raman pre-factor n: Raman exponent Output tau: relaxation time due to ...
5b7f5547dae4caf0ee1761032a2867a559373cb8
658,368
def partially_tracked(df, track_ratios): """Number of objects tracked between 20 and 80 percent of lifespan.""" del df # unused return track_ratios[(track_ratios >= 0.2) & (track_ratios < 0.8)].count()
aa0e0543f71161183480f251733cf764c10f3d79
658,369
from datetime import datetime def trim_microseconds(dt: datetime) -> datetime: """Trim microseconds from a datetime as per ECMA-262.""" return dt.replace(microsecond=((dt.microsecond // 1000) * 1000))
b560e7edf42401e76667066bfa6f7992bd9b3973
658,370
import torch def temporal_separation_loss(cfg: dict, coords: torch.Tensor) -> torch.Tensor: """ Encourages key-point to have different temporal trajectories. :param cfg: Configuration dictionary :param coords: Key-point coordinates tensor in (N, T, C, 3) :return: The separation loss """ # Tr...
7de1f78311454266ba529e326e0d313a69ffb376
658,371
def rank2int(rank): """Convert a rank/placing string into an integer.""" ret = None try: ret = int(rank.replace(u'.',u'')) except Exception: pass return ret
227edc366f1a675a91efb4919139838ea81f13a2
658,377
def write(path, content): """Write to file.""" with open(path, 'a') as _file: return _file.write(content)
d123d53f4c7c2c389ba39c503501b4e739fc4f7e
658,378
def slice_up_range(n, num_slices, start=0): """ Divides up `range(start,start+n)` into `num_slices` slices. Parameters ---------- n : int The number of (consecutive) indices in the range to be divided. num_slices : int The number of slices to divide the range into. start :...
557f93babcab7bcb84196e0b48d74fbc21e11462
658,381
def normalize_image(x): """ Normalize an image so its values are between 0.0 and 1.0. This is useful for plotting the gradient. """ # Get the min and max values for all pixels in the input. x_min = x.min() x_max = x.max() # Normalize so all values are between 0.0 and 1.0 x_norm = (x...
d1646ad132bd4931299ffa15da03665f99021ebc
658,384
import requests def get_docket(auth_token, docket_number, court_name, client_matter="", cached=True, normalize=True): """ Takes in an authentication token as a string, a docket number as a string, and the court name as a string, and returns the docket data as a dictionary. Optional parameters are...
4f38c1bd791f76e0a0bc6e732dc89f36178745dc
658,389
def format_phone_number(phone): """ Given a phone number as a string of digits (only), format for presentation. Local Libya numbers will look like '+218 (0)xx-xxx-xxxx', and Thuraya numbers will look like '+88216xxxxxxx' (per Elliott, Hipchat, Dec. 30, 2014). You can also use this from a template: ...
a22fdaee76786bff27610a5cf89f872a77004fd0
658,396
def maxim(numar1, numar2): """Funcție ce determină maximul dintre două numere.""" if numar1 > numar2: return numar1 elif numar2 > numar1: return numar2 else: # Numerele sunt egale return numar1
da86e2417a08d45098bc80386d4301e4fbf47ee1
658,397
def df_retrieve(data,cols_vals): """ Retrieves a subset of a dataframe based on equivalence matches Parameters: data (pandas.DataFrame): the dataframe from which a subset is to be created from cols_vals (dict): a dict with the key as the column name and the val as the equivalence val ...
adf45dfe5220a4b9222e216b9fac9fd199b150ba
658,398
def process_nlp_response(get_response): """ This function takes as input an NLP GET response and returns a list of concept codes. Input: get_response - A list of GET responses Output: codes - A list of concept Codes """ keep = ["ICD9CM", "ICD10CM", "RXNORM", "SNOMEDCT_US", "SNOMED", "NCI"]...
0afb8a28664d51fdbed7a670afbac817795901f1
658,401
def mclag_domain_id_valid(domain_id): """Check if the domain id is in acceptable range (between 1 and 4095) """ if domain_id<1 or domain_id>4095: return False return True
2af736ea6116fb83c34ed89dc464d6853a6fc88a
658,402
def package_name_from_url(url): """Parse out Package name from a repo git url""" url_repo_part = url.split('/')[-1] if url_repo_part.endswith('.git'): return url_repo_part[:-4] return url_repo_part
cea90a8928fed1e2380d543b7e118464c3541475
658,403
from pathlib import Path def is_empty_directory(path: Path) -> bool: """ Returns if path is a directory with no content. """ sentinel = object() return path.is_dir() and next(path.iterdir().__iter__(), sentinel) == sentinel
cda66be499f0fd40716226a765bcc5cd8ddfb1a3
658,405
def _StopOps(from_ops, stop_gradient_ops, pending_count): """The set of ops that terminate the gradient computation. This computes the frontier of the forward graph *before* which backprop should stop. Operations in the returned set will not be differentiated. This set is defined as the subset of `from_ops` co...
63693d9ea9b25b124ed258144211585fa7162970
658,409
def merge_dict(a: dict, b: dict) -> dict: """ Merge 2 dictionaries. If the parent and child shares a similar key and the value of that key is a dictionary, the key will be recursively merged. Otherwise, the child value will override the parent value. Parameters ---------- a dict: P...
cc827b5d8cba295b7eeda0723a3ae2a664c296f9
658,415
def spammer_cmd_header(username): """Return formatted text for spammer command header. Args: username (str): DeviantArt username. Returns: str: Formatted text for spammer command header. """ return '\n'.join([ 'REPORT LINK: https://contact.deviantartsupport.com/en?subOption...
86630edf06a24de3e246408ea0eb4a5a73097bae
658,417
def placeholder(_: str): """ Return False. Using this as a command argument annotation will always fail the command. Useful for groups. """ return False
e8e426469c530046211345549407aa6981a336c0
658,418
def sbs_annotation_converter(x: str) -> str: """ Eithers swaps from word -> arrow format for SBS or vice versa. word: (REF)(ALT)(LEFT)(RIGHT) arrow: (LEFT)[(REF)>(ALT)](RIGHT) """ if '>' in x: return x[2]+x[4]+x[0]+x[6] else: return x[2]+'['+x[0]+'>'+x[1]+']'+x[3]
462eb604687354150fb6971ef4d1a633655bd8bb
658,419
def _check_consistency_sizes(list_arrays) : """Check if all arrays in list have the same size Parameters: ----------- list_arrays: list of numpy arrays Return ------ bool: True if all arrays are consistent, False otherwise. """ if len(list_arrays) == 0 : return True re...
400ed2a038069fb4e267d5b52a0310ebd5c81b15
658,422
def validate_probability(p: float, p_str: str) -> float: """Validates that a probability is between 0 and 1 inclusively. Args: p: The value to validate. p_str: What to call the probability in error messages. Returns: The probability p if the probability if valid. Raises: ...
ec805e54db85b0d288973e0e95d7dead870eba65
658,424
def remove_newlines(text): # type: (str) -> str """ Remove newlines. The `name` field serves as a displayable title. We remove newlines and leading and trailing whitespace. We also collapse consecutive spaces to single spaces. :param text: Text for newline removal :return: Single line of t...
06a06d2756099fc45ffc1345bf0bef44cffa9f78
658,426
def get_layer_parents(adjList,lidx): """ Returns parent layer indices for a given layer index. """ return [e[0] for e in adjList if e[1]==lidx]
883f239e0964aae6fb50b0cbee1490fb9df8d7a4
658,427
def extract_bmpstp(filename): """ Extracts Bmpstp from filename. Filenames are often of the form: fort.Bmpstp or: fort.(Bmpstp+myid) """ ii = int(filename.split('fort.')[1].split('+myid')[0]) # Extract from filename # Not true? #if ii >= 100: # print(...
14c97713d23c3bbf522084c5dfa5c06bf0d7cf54
658,442
def intersect_2d(x1, x2): """ Given two arrays [m1, n], [m2,n], returns a [m1, m2] array where each entry is True if those rows match. :param x1: [m1, n] numpy array :param x2: [m2, n] numpy array :return: [m1, m2] bool array of the intersections """ if x1.shape[1] != x2.shape[1]: ...
0be6afa1f0d1cdd9bdf41dde0d938db8e46e308b
658,448
from typing import Any def flags_to_args(flags: dict[str, Any]) -> dict[str, Any]: """ Turn flags dict from docopt into **kwargs-usable dict. '--'-prefix is removed, dashes are turned into underscores and keys are lowercased. When conflicts arise (ie --repo: None vs REPO: "ideaseed"), do a 'or', ...
32c4b13d4814b8da20f84f27c1f0b1675c91e064
658,449
def createFile(name, paramToValue, numberOfCycles=1): """Creates a dictionary storing file information""" File = {'name': name, 'paramToValue': paramToValue, 'numberOfCycles': numberOfCycles} return File
55294fb81152977ff0262c78888fb08986234a0a
658,451
def rol(x, i): """Rotate the bottom 32 bits of x left by i bits.""" return ((x << i) | ((x & 0xffffffff) >> (32 - i))) & 0xffffffff
33ecbe3ed9f0806e14c6abbfb75889e916dfc78b
658,453
import traceback def _formatException(_, ei): """ Format and return the specified exception information as a string. This implementation builds the complete stack trace, combining traceback.format_exception and traceback.format_stack. """ lines = traceback.format_exception(*ei) if ei[2]: ...
ce4b571159eb1b1df45323ceebff684eea054359
658,454
def virial_temp_HB(mass, z): """Virial temperature from halo mass according to Haiman & Bryan (2006ApJ...650....7). z is the redshift. Units are Msun and kelvin. """ return 1800. * (mass/1e6)**(2./3.) * (1.+z)/21
8ce9df3435414491b815f6a1e0f9c8da7d5c6aa1
658,455
import json def GetDataFromFile(filename): """ Retrives JSON formatted data from a file and loads as a Python object. Returns False if the requested file is unreadable. """ try: fileObj = open(filename, 'r') except IOError: return False data = json.load(fileObj) fileObj.close() return data
343566b38772a1054b7eda89d388af38f2cb9bf9
658,456
def is_not_outstanding(invoice): """ Return `True` if the given invoice is paid """ return invoice.status == 'Paid'
03c06180a87ec9eb1d9708010e2cf62a88cad03a
658,457
from pathlib import Path def resolve_path(path: Path, database_yml: Path) -> Path: """Resolve path Parameters ---------- path : `Path` Path. Can be either absolute, relative to current working directory, or relative to `config.yml`. database_yml : `Path` Path to pyannote.d...
0f371334aec7e4c1ac04f8ffdab961094a01a02f
658,463
def get_revision_ids_for_credential(credential): """ For the given credential, return a list of archive credential IDs. """ _range = range(1, credential.revision + 1) ids = [] for i in _range: ids.append("{0}-{1}".format(credential.id, i)) return ids
58b86adce5351c956c056eef17d179989c4172ee
658,467
def inverse_mvr(mean, var): """ Inverse function of the negative binomial fixed-dispersion mean-variance relationship. Vectorized. Parameters ---------- mean, var : float The mean and variance of a NB distribution, respectively. Returns ------- float The dispersion ...
89f83639d5bfb0f7f5f4a7121f747ec2b4f5724e
658,468
def state_from_scratch(args: tuple, kwargs: dict) -> dict: """Create pipeline state from (args, kwargs).""" state = {i: v for i, v in enumerate(args)} state.update(kwargs) return state
26b84c95fcdeae55e903cdfa763bfc59597caedb
658,469
def timestr(seconds): """Return time as string M:SS.""" minutes = seconds // 60 seconds = seconds - (minutes * 60) return f"{minutes}:{seconds:02}"
2f37ade13839170ad48af401fd80ae171a688070
658,470
import torch def zeros_like(input, *args, **kwargs): """ In ``treetensor``, you can use ``zeros_like`` to create a tree of tensors with all zeros like another tree. Example:: >>> import torch >>> import treetensor.torch as ttorch >>> ttorch.zeros_like(torch.randn(2, 3)) # the sa...
13cdc7481cfccab12a2bd5fe20a754442176c447
658,474
def resolve_mro(model, name, predicate): """ Return the list of successively overridden values of attribute ``name`` in mro order on ``model`` that satisfy ``predicate``. Model classes (the ones that appear in the registry) are ignored. """ result = [] for cls in type(model).__mro__: ...
8f98e774e908075b84dc1d1c15f961f3879c17ea
658,477
from typing import Optional from typing import List def _listify(chars: str) -> Optional[List]: """ Converts a string into a list of characters. :param chars: String containing the characters you wish to turn into a list. :return: List of characters. """ return list(chars)
b7b6e2180c41c0f4048ea87011d7667365b2c9e2
658,481
def islower(text): """ Checks if all cased characters in ``text`` are lowercase and there is at least one cased character. Cased characters are defined by the Unicode standard. All alphabetic characters in the ASCII character set are cased. :param text: The string to check :type text...
daae3011c5c4ceb80dda46ec68b905a5bac06f31
658,482
def startswith(s, prefix): """ True if the string starts with the specified prefix. """ return s.startswith(prefix)
656669790d43b90cf2b8a2a15cb4c73b7182d36d
658,484
def _section(section_name, section_data): """Add opening/closing section_name tags to data.""" opening_tag = ['<' + section_name + '>'] closing_tag = ['</' + section_name + '>'] section = None if isinstance(section_data, list): section = opening_tag + section_data + closing_tag elif isi...
2f4b89ad5d8c8b7feff799f215f43f5275c67ada
658,486
def sanitize(name): """ Sanitize the specified ``name`` for use with breathe directives. **Parameters** ``name`` (:class:`python:str`) The name to be sanitized. **Return** :class:`python:str` The input ``name`` sanitized to use with breathe directives (primarily for use ...
3585902680c05bb681df36ba4083525b808e71de
658,489
def obj_get_name(obj): """get_name(obj) return object name.""" return obj.__name__
c13c1a219c7a00552d0c1b1b51fb205337beb95a
658,490
def clock_emoji(time): """ Accepts an hour (in 12 or 24 hour format) and returns the correct clock emoji. Args: time: 12 or 24 hour format time (:00 or :30) Returns: clock: corresponding clock emoji. """ hour_emojis = { "0": "🕛", "1": "🕐", "2": "🕑", ...
4ba4864d6fbdced7413e3233cba35c3a8d45a9f7
658,491
import itertools def count_alive_neighbors(alive_cells: set, coords: tuple) -> int: """return the number of alive neighbors of a given cell""" alive = 0 ranges = ((c-1, c, c+1) for c in coords) for cell in itertools.product(*ranges): if cell in alive_cells: alive += 1 if coords...
a84782f90632f433b2adffe6283ca6909332a680
658,493
def minor(matrix: list[list], row: int, column: int) -> list[list]: """ >>> minor([[1, 2], [3, 4]], 1, 1) [[1]] """ minor = matrix[:row] + matrix[row + 1 :] return [row[:column] + row[column + 1 :] for row in minor]
1261617518e5a1fe8cf247881796e87a29dd3c0a
658,497
def maxpitchamp(amparray): """ Max Pitch Amplitude audio feature: High Predictability rate (86%) :param amparray: array of pitch period amplitudes (floats) :return maxamp: Max pitch period amplitude """ maxamp = 0 if len(amparray) > 0: maxamp = max(amparray) return maxamp
529d2214a1fc708a1126c65c02d87800bd7d9bba
658,503
def get_overlap(a, b): """ Computes the amount of overlap between two intervals. Returns 0 if there is no overlap. The function treats the start and ends of each interval as inclusive, meaning that if a = b = [10, 20], the overlap reported would be 11, not 10. Args: a: Fi...
692892f21169b5d626fe40e6a0700385a181d513
658,508
def _GetResourceMessageClassName(singular_name): """Returns the properly capitalized resource class name.""" resource_name = singular_name.strip() if len(resource_name) > 1: return resource_name[0].upper() + resource_name[1:] return resource_name.capitalize()
19cc9802ed97398120753e36e856fc44d6a3cf6c
658,511
def n_values(obj, keys): """Extract multiple values from `obj` Parameters ---------- obj : dict A grow or data "object" keys : list A list of valid key names Must have at least one element Returns ------- tuple The values for each key in `args` Notes ...
1394b19f0978ae1b15fddc5515325d31bfa36434
658,516
def fibonacci(n): """ fibonacci function Args: n (int): the number for the n numbers of fibonacci Returns: a list of finobacci numbers """ result = [1] # fibonacci number starts from 1 t1 = 1 t2 = 1 if n > 0: for _ in range(n-1): result.append(t2)...
8c0d4089782c1114428cf5f43bf316a673e9f159
658,523
import logging def log_func_decorator(func): """ Decorator to log the execution of a function: its start, end, output and exceptions """ logger = logging.getLogger() def wrapper(*args, **kwargs): logger.info( 'Executing function "{}" (args: {}, kwargs: {})'.format( ...
f812c046612fe5c24fdcc0e4b61a3ce1d9f3bec6
658,525
import struct def int2byte(i): """Encode a positive int (<= 256) into a 8-bit byte. >>> int2byte(1) b'\x01' """ return struct.pack('B', i)
78749aa3c581e7dd944260c05c49c2ae1434abb1
658,526
from typing import List import random def sample_vector(dimensions: int, seed: int) -> List[float]: """Sample normalized vector given length. Parameters: dimensions: int - space size seed: Optional[int] - random seed value Returns: List[float] - normalized random vector of given ...
c1da7b824857e63d8745e1944fc1689c92b7c786
658,527
def add_to_visited_places(x_curr: int, y_curr: int, visited_places: dict) -> dict: """ Visited placs[(x,y)] contains the number of visits that the cell (x,y). This updates the count to the current position (x_curr, y_curr) Args: x_curr: x coordinate of current position y_curr: ...
605d1941ae0f069405ed4b804cf9c25ee3381b9b
658,528
def remove_keys(dict_, seq): """Gracefully remove keys from dict.""" for key in seq: dict_.pop(key, None) return dict_
65a6b8d846081e42db25f5fc056c59723ee3be9c
658,529
def reverse_score(dataset, mask, max_val=5, invalid_response=None): """Reverse scores a set of ordinal data. Args: data: Matrix [items x observations] of measured responses mask: Boolean Vector with True indicating a reverse scored item max_val: (int) maximum value in the Likert (-like...
98df725b23f14f12106bee43a8de88fded2e42df
658,532
def flat_dataset_dicts(dataset_dicts): """ flatten the dataset dicts of detectron2 format original: list of dicts, each dict contains some image-level infos and an "annotations" field for instance-level infos of multiple instances => flat the instance level annotations flat format: ...
52a3ea4449381f83372cb9cd7fb7c2463b6dab10
658,533
import copy def v3_to_v2_package(v3_package): """Converts a v3 package to a v2 package :param v3_package: a v3 package :type v3_package: dict :return: a v2 package :rtype: dict """ package = copy.deepcopy(v3_package) package.pop('minDcosReleaseVersion', None) package['packagingVe...
37a54fba43dc6c92dd51aa50fe5e160fa4ee9fa9
658,535
def multidict_split(bundle_dict): """Split multi dict to retail dict. :param bundle_dict: a buddle of dict :type bundle_dict: a dict of list :return: retails of dict :rtype: list """ retails_list = [dict(zip(bundle_dict, i)) for i in zip(*bundle_dict.values())] return retails_list
1d3c95ef6f2d5a7065f95b4a26d430d10618cb49
658,540
from typing import Any import zlib def compute_hash(*args: Any) -> str: """ Creates a 'version hash' to be used in envoy Discovery Responses. """ data: bytes = repr(args).encode() version_info = ( zlib.adler32(data) & 0xFFFFFFFF ) # same numeric value across all py versions & platform...
0f41694319d173bddacb633b12c72611f37e9eb6
658,543
def get_coordinates(sub_turn): """ Obtain coordinates entered by human user Attributes ---------- sub_turn: str Game's sub turn. Used to prompt user. """ print(sub_turn, 'phase') user_input = input("Please input in following format: xy ") column, row = -1, -1 # Adding this ...
ce1556bc826581c7b3536bf60f21c51dbf8b4ae8
658,544
def flip(str_array: list[str]) -> list[str]: """ Flip a list of strings on a top-left to bottom-right diagonal :param str_array: array as a list of strings :return: array flipped """ return list(reversed(str_array.copy()))
572ca4337da74493f9f3e489e2875ea7f356f16f
658,548
import hashlib def hash_file(filepath): """ Hashes the contents of a file. SHA1 algorithm is used. :param filepath: Path to file to hash. :type filepath: ``str`` :return: Hashed value as a string :rtype: ``str`` """ HASH_BLOCKSIZE = 65536 hasher = hashlib.sha1() with open(fil...
c9a374ec7aa471c3f226431be55770d108145f41
658,560
def make_xz_ground_plane(vertices): """ Given a vertex mesh, translates the mesh such that the lowest coordinate of the mesh lies on the x-z plane. :param vertices: (N, 6890, 3) :return: """ lowest_y = vertices[:, :, 1].min(axis=-1, keepdims=True) vertices[:, :, 1] = vertices[:, :, 1] - ...
e05622420f431882a11cf60f4db28c094cbc0dca
658,561
def make_title(text): """ turn a text string of words into a title by capitalizing each word """ words = text.split() new_words = [] for word in words: new_words.append(word[0].upper()+word[1:]) return ' '.join(new_words)
a00097cc17f44c9e28f5e523d7347ff8ea091186
658,562