content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def get_time_string(time, up_24=True, include_seconds=False): """Get a human friendly representation of `time`. :param time_value: time value. :param up_24: True to use 24 hours time format. :param include_seconds: True to include seconds value in result. :return: string time formatted like `13:...
7829c8992d8f27c1b0ae1feb93c777cdd182fa56
601,533
def evaluate(exp, curr_count): """ Safely evaluates the mathematical expression in the message. Parameters ========== - exp: :class:`str` Expression to be verified - curr_count: :class:`int` The current count Returns ======= [ - :class:`int`: Evaluation result...
4a6fbc7d6ae657321b9566bea101dcefaab674c8
601,536
def pre_text(string, lang=None): """ Encapsulate a string inside a Markdown <pre> container """ s = "```{}```" if lang is not None: s = s.format(lang+"\n{}") return s.format(string.rstrip().strip("\n").replace("\t", ""))
dac87253c7a1d8d9fc298069c5cac665d38214c0
601,542
def has_secondary_role(query, role): """ Checks if member has 'role' in the secondary_roles :param query: member.secondary_role query :param role: role to be checked :return: True if member has role """ count = query.filter(short_name=role).count() return count > 0
88c2fa8832280738dc0bfbf32ec97e6b97832d7e
601,543
def memory_setting(label): """ Parse user-supplied memory setting. Converts strings into floats, representing a number of bytes. Supports the following notations. - raw integers: 1, 1000, 1000000000 - scientific notation: 1, 1e3, 1e9 - "common" notation: 1, 1K, 1G Suffixes suppor...
07076583847b676e1993f8ff5158fe48aa3b8765
601,545
def adder(num1: int, num2: int) -> int: """ Adds two integers together :param num1: the first int to add :param num2: the second int to add :return: the sum of num1 and num2 """ return num1 + num2
7b17dc555fcefb77ed5e1c12941b10a08cae9a72
601,552
def remove_zero_width_space_chars(string): """Removes Zero Width Characters (\\u200b, \\u200c, \\u200d, \\uFEFF) from a string and return a new one.""" str = [] for char in string: ch = char.encode('ascii', 'backslashreplace') if ch not in [b'\\u200b', b'\\u200c', b'\\u200d', b'\\uFEFF']: ...
1764ff544ac31bbaa4b1d8a3474942116ab92c52
601,554
def _get_baseline(p): """Helper to extract baseline from params""" if p.baseline == 'individual': baseline = (p.bmin, p.bmax) else: baseline = p.baseline return baseline
fca69ce901aaced68b8ed8a766e28d2c11e1528d
601,557
import math def computeErrors(predictedRDD, actualRDD): """ Compute the RMSE and MAE between predicted and actual RDD Args: predictedRDD: predicted ratings for each movie and each user where each entry is in the form (UserID, MovieID, Rating) actualRDD: actual ratings whe...
7e966d5ce3167a265c3fdf7cc6d11c33756ce8e0
601,558
def _compression_value_conversion(value): """ PNG compression values are within range [0, 9]. This value must be mapped to a [0-100] interval. """ try: if int(value) < 0 or int(value) > 100: raise RuntimeError("Quality argument must be of between 0 and 100.") return 0 if ...
8deda0aff0851bd8dbc7c827a9107f881e52f546
601,562
def convert_ms_to_frames(sample_length, framerate): """Convert sample length in milleconds to number of frames.""" return int(framerate * (sample_length/1000.0))
86fb1f0531bc89351b70a3f7cd5345408ed98c59
601,565
import re def is_email(email: str, only: bool = False) -> bool: """ check whether a string is a valid email address :param email: the string to be checked :param only: indicate whether to allow mailto: at the beginning :return: True if a valid email, False otherwise """ if type(email) is n...
36a4bfb46c197817e8effbd31c006c8b58651671
601,566
def update_appliance_location_nepk( self, ne_pk: str, wx: int, wy: int, latitude: float, longitude: float, ) -> bool: """Update appliance location graphical information by Network Primary Key (nePk) .. list-table:: :header-rows: 1 * - Swagger Section - Met...
085c9a52725028bec5c09620705a3a4d673924c3
601,567
import math import torch def generate_A(alpha): """ Generate the autoregressive coefficients from the model parameters. """ alpha = alpha.tanh() / math.sqrt(2) chunks = torch.chunk(alpha, alpha.size()[-1], -1) # size: [T, P, 1] A_x_left = (chunks[0] * math.cos(-math.pi / 4) - ...
440bf10eda13af7b58286c5702dc78a2c1b40f57
601,587
def average(nums): """Find mean of a list of numbers.""" return sum(nums) / len(nums)
30b1689663d80657c1530cfcd10f6b5dcfdf2de9
601,588
def get_raw_xml(active_zip_archive, file_of_interest): """ For a file of interest in an active zip archive, returns the raw xml as a string. """ with active_zip_archive.open(file_of_interest, 'r') as file: raw_xml = file.read() zip_path = active_zip_archive.filename return (...
1af46f755662be730a9aa018fea0f15b5a19f441
601,591
def _rel_create_dict(relationships): """ Convert a set of :class:`.Relationship` objects into a dictionary of :class:`.Relationship` lists, keyed by type. :param relationships: :return: """ d = {} for relationship in relationships: key = type(relationship).__name__ d.setdefa...
963bbd108a130ab164e0a57bdede06a97f937a51
601,593
def iterate_games(fn): """Return an iterator over the text of each individual game in file `fn'. All extra whitespace is removed within and at the end of lines, and lines which are whitespace only are dropped, creating a 'canonical' representation of the text. """ return iter(filter(lambda x: x....
901cd8c715842cba1426c2efba876b74dbc1c48b
601,596
import gzip def gzopen(filename,mode='r'): """ Open file or gzip file """ if filename.endswith('.gz'): file = gzip.open(filename, mode) else: file = open(filename, mode) return file
829c4ab7539739e94f0b7d822060a964a6dbec5a
601,599
def create_fields_payload(action=None, fields=None): """Creates a payload for all given fields. The action can be "field" or "omit" :param action: The action for the request, should be "fields" or "omit", defaults to None :type action: str, optional :param fields: The given fields, defaults to None...
f6fb3f6a5303fe8d704bc6159dab47cd6628ba2b
601,604
def get_neighbors_of(cell): """ Return the neighbors of cell. """ x, y = cell neighbors = [] distance = 1 r = range(0 - distance, 1 + distance) for row in r: for col in r: if not row == col == 0: neighbors.append((x + row, y + col)) return set(ne...
5880ad0ef07e4537da224e13956764008d4109a1
601,605
import json def load_services(file_name="./json/amtrak-trip.json"): """Load a json file with parsed services from an amtrak itinerary.""" with open(file_name) as f: return json.loads(f.read())
e3378086a937b6138248e214af2cc20761eaba2d
601,606
def is_sequence(x): """ Returns whether x is a sequence (tuple, list). :param x: a value to check :returns: (boolean) """ return (not hasattr(x, 'strip') and hasattr(x, '__getitem__') or hasattr(x, '__iter__'))
9f7e08919d7e8378a9472d8bcd4f9537d8e7a051
601,610
def get_filter_config(shape): """Returns a default Conv2D filter config (list) for a given image shape. Args: shape (Tuple[int]): The input (image) shape, e.g. (84,84,3). Returns: List[list]: The Conv2D filter configuration usable as `conv_filters` inside a model config dict. ...
46e60c72e8ed5c6f327209308765f25a53dcffb4
601,612
def decode_integer(value): """ Decode from binary and return the integer value as a string """ return str(int(value, 2))
25d022ae82260e9eae7b139c9273fcde78151b23
601,613
def pad_sentences(sents, pad_id): """ Adding pad_id to sentences in a mini-batch to ensure that all augmented sentences in a mini-batch have the same word length. Args: sents: list(list(int)), a list of a list of word ids pad_id: the word id of the "<pad>" token Return: aug_...
ea77c7359844ed14d430848482d270915fdea393
601,614
def remove_newline(str): """ replace newline with single space """ return str.replace('\n', ' ')
f771c9ca382236d8469a4c76e4dcf632d6b06631
601,619
def obj_in_list(target_list, obj): """ >>> l = [1,2,3,4] >>> obj_in_list(l, 2) True >>> obj_in_list(l, 5) False """ return True if obj in target_list else False
7b59581d98cf174cad8967a4c149984d69fb7487
601,623
def get_padding(size, kernel_size, strides): """ Calculate the padding array for same padding in the Tensorflow fashion.\\ See https://www.tensorflow.org/api_guides/python/nn#Convolution for more. """ if size[0] % strides[0] == 0: pad_h = max(kernel_size[0] - strides[0], 0) else: pad_h = max(kernel_si...
6ba716444bbadfcdea7205911a3c97418ae8d4c2
601,624
import re def validate_email(value): """Validates email address value. :param value: A candidate value for an email address :type value: string | NoneType :return: True if values is a valid email address or None. Otherwise returns False :rtype bool """ return value is None or bool(re.matc...
376ac1a5e3509e07170c264b652a785646d59b95
601,629
import hashlib def sha256(text): """Returns SHA256 of the string `text`.""" return hashlib.sha256(text.encode("utf8")).hexdigest()
2609c5338e59bb34017898ca28e8e60966b7402f
601,631
def create_dictionary(filename): """Return a dictionary with the letter of the alphabet as the key and the name of the flower as the value for each row in flower.txt.""" dict_flowers = {} with open(filename) as flowers: for line in flowers: letter, flower = line.strip().split('...
c77b8b78568bdfd4b064164e8006e07fe304fe53
601,640
from typing import Iterable def create_visualmap_pieces(groups: Iterable[str]) -> list[dict]: """Return tooltip formatter code. Parameters ---------- groups : iterable of str Groups. Returns ------- list of dict Examples -------- >>> create_visualmap_pieces(['travel'...
83681dd6c16f1fb51354727d95936a5b357d7ce9
601,642
from typing import Counter def aggregate_event_cat_act(event_list): """ Return a dictionary-like list of (eventCategory,eventAction) frequency counts. :param event_list: list of event tuples (eventCategory,eventAction) :return: dict-like list of frequencies [((eventCat1,eventAction1) freq_1),((eventCa...
845435ec647a5d5909c60ca34fa884fd5940c515
601,646
def severity_mapping(severity: int) -> int: """ Maps AWS finding severity to demisto severity Args: severity: AWS finding severity Returns: Demisto severity """ if 1 <= severity <= 30: demisto_severity = 1 elif 31 <= severity <= 70: demisto_severity = 2 e...
31d481b13940e5454c0c860ccb6c057f1905d66b
601,651
import re def parse_show_interface_lag(raw_result): """ Parse the 'show interface' command raw output. :param str raw_result: vtysh raw result string. :rtype: dict :return: The parsed result of the show interface command in a \ dictionary of the form: :: { 'lag_...
dffa2a88df465159ff8a4ba3cf802d4dce60469b
601,655
import re def makeFeaClassName(name, existingClassNames=None): """Make a glyph class name which is legal to use in feature text. Ensures the name only includes characters in "A-Za-z0-9._", and isn't already defined. """ name = re.sub(r"[^A-Za-z0-9._]", r"", name) if existingClassNames is None...
05fe6182961dff0ff4065b28a161f280422d67cc
601,658
def _flatten_multi_geoms(geoms, colors): """ Returns Series like geoms and colors, except that any Multi geometries are split into their components and colors are repeated for all component in the same Multi geometry. Maintains 1:1 matching of geometry to color. "Colors" are treated opaquely and s...
bfb9622b8989e26945be5f7978d26279f4ea1880
601,660
def compute_difference(x: int, y: int) -> int: """ Calculates the difference of two integers. Parameters ---------- x First value y Second value Returns ------- Difference of the two provided values. """ return x - y
13926afd3f6319ec637d47d24263bb96916a8f47
601,663
from typing import Dict from typing import List from pathlib import Path import string def load_aligner_phones_lower(aligner_phone_path:str)->Dict[str,List[str]]: """Returns a dict mapping example_id to lowercase phonemes based on the input path to the aligner's phonemes. Args: aligner_phone_path...
17630baf4e3fbf9526bc8ca94a01c77684358bc5
601,667
import torch def to_bbox_in_original_image(bboxes, original_image_size, model_input_size): """Convert bounding box to the one in the original image This function uses an original image size and a model input size to transform bounding box coordinates from the ones in the preprocessed image to the one...
68efff98ed43f5c2007074d5d6bb2207d6c238b0
601,672
def methods_of(obj): """Utility function to get all methods of a object Get all callable methods of an object that don't start with underscore returns a list of tuples of the form (method_name, method). """ result = [] for i in dir(obj): if callable(getattr(obj, i)) and not i.startswith...
2f8b9a302c701760c8fc6b2b7c7e76fc0d65a9b7
601,673
def shiftdialogs(dialogs, offset): """Shifts dialogs ((from, to), txt) by the given amount of offset""" ret = [((a+offset,b+offset), txt) for (a, b), txt in dialogs] return ret
31fabd0ce4e2eb560b74aac6ae7b6843240ed5f2
601,674
def replace_sideFlow(side, currentMods): """ Helper function for erasing current sideFlow Modular units Parameters ------------- side = str, should be "side1" or "side2" currentMods = dictionary, Current Modular Units of bioprocess Returns ------------- currentMods """ # i...
eb09b49d6a38344845972b15aab37d9d5997b9c2
601,683
import unicodedata def run_strip_accents(text): """ From tokenization_bert.py by huggingface/transformers. Strips accents from a piece of text. """ text = unicodedata.normalize("NFD", text) output = [] for char in text: cat = unicodedata.category(char) if cat == "Mn": ...
4aa7d17242bba9ffeed51a85f6c3c8fcaa74d105
601,684
def always_iterable(obj, base_type=(str, bytes)): """ Ensure that the object it is passed is iterable. - If ``obj`` is iterable, return an iterator over its items. - If ``obj`` is not iterable, return a one-item iterable containing ``obj``. - If ``obj`` is ``None``, return an empty iterable. B...
3e09b0fd2feb618754b592ca3bd69d216984a65d
601,685
def _convert_value_safe(value): """Convert `neo` values to a value compatible with `pandas`. Some types and dtypes used with neo are not safe to use with pandas in some or all situations. `quantities.Quantity` don't follow the normal python rule that values with that are equal should have the same...
f02f260882c83ee948107c4f131708d4778904fe
601,689
def get_cutout(image, cutout_size): """Takes an image, and cuts it down to `cutout_size x cutout_size` It only affects the final two dimensions of the array, so you can easily deal with multiple images / multiple channels simply by setting up the array with shape (n_channels, height, width) Inp...
e6d70e395b3b5b032565fa39ee09d1b71bbfb4c8
601,690
def _may_have_subcomponents(o): """ Args: o: an object. Returns: True if the object has a callable component_objects method, otherwise False. """ if hasattr(o, "component_objects"): if hasattr(o.component_objects, "__call__"): return True
993f9629ecee31d5b1fe8eee5cd9820e81a53c8d
601,691
def ent_dims_from_state_dict(state_dict: dict) -> tuple[int, int]: """ From a state dict, return the appropriate values of `ent_hidden_size` and `ent_intermediate_size` which can be used for instantiating the model. """ # We assume that all transformer blocks have same dim. low_dim_key = "encode...
7ed009d9683df7ec98b3c99ab289b3bce438692d
601,701
def filter_data(col, min_value, max_value): """Filter DataFrame by min and max value for a specific column.""" def filter(data): data = data.loc[(data[col] > min_value) & (data[col] < max_value)] return data return filter
ae13f439c78a329bd975a40a055c318820433629
601,702
from typing import Tuple import colorsys def rgb_to_hsv(rgb: Tuple[float, float, float]) -> Tuple[int, int, int]: """Convert RGB tuple (values 0-255) to HSV (degrees, %, %).""" hue, sat, value = colorsys.rgb_to_hsv(rgb[0]/255, rgb[1]/255, rgb[2]/255) return int(hue * 360), int(sat * 100), int(value * 100)
e4cb5174379d86c54f98cfd44393260b51c88d90
601,706
def _order_by(flask_request, query, base_class, allowed_keys, default_key): """ Parses the "order_by" argument from flask_request.args, checks that it is allowed for ordering in `allowed_keys` list and sets the ordering in the `query`. In case "order_by" is not set in flask_request.args, use `defaul...
df7828777ade7df893e82550e64bc6d0692c91a3
601,709
def pointing_tuple2str(dirtuple): """ Convert a direction tuple to a string Inverse of pointing_str2tuple(). Parameters ---------- dirtuple : tuple or None Direction tuple defined as (angle1: float, angle2: float, refsys: str) or None if beamctldirarg was not correct format...
7acf9856701f864d0511e14a2d26d580a1eb9fba
601,717
def _dump_to_pages(dump): """Extract pages from an xml dump. Args: dump: a unicode string Returns: a list of unicode strings """ pos = 0 ret = [] start_tag = u"<page>\n" end_tag = u"</page>\n" while True: start_pos = dump.find(start_tag, pos) if start_pos == -1: break start_...
541aee82d72e32fe9311b76a4132afd7ff6fee96
601,718
def _unpack_symgrp( role, strategy, count, payoff=None, id=None, **_ ): # pylint: disable=invalid-name,redefined-builtin """Unpack a symmetry group""" return id, role, strategy, count, payoff
ba3ad9f71914ad039c3a53b7c3db99e9b6b8a134
601,719
def parse(domain): """ Split domain into queryable parts in reverse. Arguments: domain (str): full domain name Examples: >>> parse('www.google.com') ['.', 'com.', 'google.com.', 'www.google.com.'] """ parts = domain.split('.') parts.extend('.') parts.reverse() ...
2f7fc485e598003fd3cfc96c87b3d7264a3efe9c
601,721
def count_alive_neighbors(grid, x, y): """ Count neighbors that are alive. """ height = len(grid) width = len(grid[0]) alive_count = 0 for i in range(-1, 2): for j in range(-1, 2): neighbor_x = x + i neighbor_y = y + j if i == 0 and j == 0: ...
309f93f76af26fa55a5df6f651826792c2303494
601,724
def zipper(demand, ambient, inlet): """Make the mapping between demand/ambient/inlet temperatures.""" mapping = [] for day_index in range(365): daily_demand = demand[day_index] daily_ambient = ambient[day_index] daily_inlet = inlet[day_index] for hour_index in range(24): ...
5da967d565556989fdb3debab49d3df9b1485b35
601,725
def log2(num): """ Integer-valued logarigthm with base 2. If ``n`` is not a power of 2, the result is rounded to the smallest number. """ pos = 0 for pow_ in [16, 8, 4, 2, 1]: if num >= 2 ** pow_: num //= (2 ** pow_) pos += pow_ return pos
b692d508029505a62e81dd4d8efaa0e21435b007
601,726
def fake_send_message(*args, **kwargs): """Fake sending a message.""" return {"ok": True, "result": {}}
a3a7d9beee3839667d05654aa710b6ce5fac6f7f
601,728
def dropSpans(spans, text): """ Drop from text the blocks identified in :param spans:, possibly nested. """ spans.sort() res = '' offset = 0 for s, e in spans: if offset <= s: # handle nesting if offset < s: res += text[offset:s] offset = e ...
aaa36ebc64f3d99ca831fe764346155d43bb18dc
601,729
def reaumur_to_fahrenheit(reaumur: float, ndigits: int = 2) -> float: """ Convert a given value from reaumur to fahrenheit and round it to 2 decimal places. Reference:- http://www.csgnetwork.com/temp2conv.html >>> reaumur_to_fahrenheit(0) 32.0 >>> reaumur_to_fahrenheit(20.0) 77.0 >>> re...
dfe5c361dd2e6af65414eeb5f1214cb31defcc8f
601,730
from typing import ByteString def has_common_prefix(label: ByteString, other_label: ByteString) -> bool: """ Whether label and other_label have a prefix in common. """ if not label or not other_label: return False return True if label[0] == other_label[0] else False
9ba89d7b94284e3ed14e8a524cbc648df7196547
601,733
import six import types def _get_definition_module(obj): """ Get the name of the module that an object is defined in, or ``None`` if unknown. For classes and functions, this returns the ``__module__`` attribute. For object instances, this returns ``None``, ignoring the ``__module__`` attribu...
3377a30926587664faaa61dc8575e9c166095716
601,734
def _get_var_meta(cr, case_name, var): """ Return the metadata for the variable of the given name in the given case. Parameters ---------- cr : CaseReader The case reader housing the data. case_name : str The case from which the outputs with available metadata is to be returned....
7c16e474b9bbd3b5a83869a342793e35f2b252c1
601,739
import math def get_overall_score(r1_score, bond_score, missing_elements_score, stoich_score, anisotropy_penalty, score_weighting): """ Get the overall score for an optimizer result :param r1_score: :param bond_score: :param missing_elements_score: :param stoich_score: :param anisotropy_pe...
2f8174ed7e08644156d5a5287dcbabba759f3e9a
601,741
def convert_to_binary(df, col): """Converts binary values t and f into 1 and 0 values and nan values into 0.""" df[col] = df[col].replace({"t": 1, "f": 0, "nan": "NaN"}).fillna(0) return df[col]
5fb5493f6ca9bccf1acd36b6d43d93e4febb087b
601,745
def merge_transitions(transitions, existing_transitions): """ Merge two dictionaries of transitions together. :param Dict[int,List[int]] transitions: Some transitions. :param Dict[int,List[int]] existing_transitions: Other transitions. :return Dict[int,List[int]]: The merge of the two par...
c763a6a030cddffcfa01c26f5ed154e37ac4423a
601,748
import math def logsumexp(*vals): """Computes log(sum([exp(v) for v in vals])) in a numerically stable manner. If you only need to sum over two values use logsumexp2. """ shift = max(vals) return shift + math.log(sum((math.exp(v - shift) for v in vals)))
88dc56e12722b38f82d7f82aa82d87bb96ec059d
601,752
def giip(area=40, res_height=20, porosity=0.25, avg_water_saturation=0.4, gas_vol_factor=0.00533): """Returns the estimate for gas initially in place (SCF) given the area (acres), reservoir height (ft), porosity (fraction), average water saturation (fraction), and the gas formation volume factor (RCF/SCF).""" ...
ac9e189eb91c9c000f6d8e20e134451580e50653
601,756
import gzip import bz2 def open_by_suffix(file_name, mode='r'): """Opens file based on suffix.""" # noqa modified from https://stackoverflow.com/questions/18367511/how-do-i-automatically-handle-decompression-when-reading-a-file-in-python file_name = str(file_name) if file_name.endswith('gz'): ...
c13a6b74043300ae01110a4d2da9eaeaad44009e
601,758
def divides(i, j): """Returns true if j divides i""" if j is 0: return False elif i % j: return False else: return True
a4eb4b81d9a7f43a63b14dd34bf4a2c1cd51c901
601,761
def center(bbox): """get the center coord of bbox""" return [(bbox[0]+bbox[2])/2, (bbox[1]+bbox[3])/2]
6ef93528c968804156886d282d18460491a1b9b9
601,762
def zone(location): """Return the timezone field of a location.""" return location[3]
07da495fa65ab4f74dcd57a1bbcaa508f2b9faef
601,763
def domain_slice(lb, ub, lbounds, ubounds): """Create a slice corresponding to the neighbourhood of domain (lb, ub).""" if any(lb >= lbounds): slice_lb = len(lbounds) - (lb >= lbounds)[::-1].argmax() - 1 else: slice_lb = 0 # Entirely below input domain. if any(ub <= ubounds): ...
2aae91d91ca8ec72ef18c51e35f8205ac4b79547
601,765
import functools def validator(func): """Calls the pre_validate and post_validate functions before and after the wrapped function""" @functools.wraps(func) def wrapped(self): self.pre_validate() func(self) self.post_validate() return wrapped
a6fae10d896d11a656365f5f7d8bc1de8e342917
601,767
def extract_json_from_line(line): """Extracts the JSON from a line of JS that we know has a { in it. It's assumed that this line has already had .strip() called on it (i.e. it has no leading or trailing whitespace). """ # The -1 in the slicing operation below removes the trailing semicolon # (...
5235e671e919f37bbeaac98623b79db44d4c1cdc
601,771
import torch def test_vae(model, data_loader): """ Function for testing a model on a dataset. Inputs: model - VAE model to test data_loader - Data Loader for the dataset you want to test on. Outputs: average_bpd - Average BPD average_rec_loss - Average reconstruction lo...
ad15e3b302d8f5c5fe8a80b317f0b5cf669f3a73
601,773
def str_for_latex(string): """ Helper method to convert some strings that are problematic for latex. """ string = string.replace('_', '\\_') string = string.replace('$', '\\$') string = string.replace('&', '\\&') string = string.replace('%', '\\%') string = string.replace('#', '\\#') ...
0c7efbd0fed53fd9212233032f8f2cbb4159b75c
601,774
def geradora_funcao_quadratica(a, b, c): """ Retorna a função f(x) = a * x ** 2 + b * x + c """ return lambda x: a * x ** 2 + b * x + c
f7564d5bcd8b6ec22494a134b95e009eb83a68b5
601,775
from typing import Counter def get_unique_chars(irow, reverse=False): """ Get unique characters in data Helper function ---- reverse: bool Reverses order of the two chars returned """ chars = Counter(irow) if len(chars) > 2: raise Exception("Data is not binary") e...
111c4b78b21704e67ed9ec055c42abed5a971953
601,777
def factorialb(m): #defining this solution as factorialb - factorial option b """Return the factorialb of m.""" ans = 1 for i in range(2, m + 1): ans = ans * i return ans
ce36753fba0152b39a158c4e1c89f86038354d67
601,778
def strrep(text, old, new): """ Replaces all the occurrences of a substring into a new one Parameters ---------- text : str the string where to operate old : str the substring to be replaced new : str the new substring Returns ------- str The new...
e3c0720c819b1b102c21aba03920e41e1591b461
601,779
def get_column_names(cursor, table): """ Finds the column names for a table """ cursor.execute(f"Select * FROM {table} LIMIT 0") return [desc[0] for desc in cursor.description]
ceb8af9e4b402064b8217c6b1d200e3cfdc2b525
601,781
def get_collection_item_names(bpy_collection): """Get names of current items in a blender collection, e.g. object names in bpy.data.objects Args: bpy_collection : a blender iterable, where items are a tuple, and the 1st item element is a name string Returns: list of strings : names of item...
ecd257b86d92900f7a033a0aebf746177df39d61
601,782
def get_longest_string(string_array): """ Return the longest string in a list of strings """ return max(string_array,key=len)
82e97adf9b8bd06ae9f2333a6b1684adc0fcb438
601,783
def rect2math(r): """Convert rectangles to mathematical coordinates.""" return (r.x0,r.y0,r.x1,r.y1)
9eefb2dc1c5a6e783ead82cc9ba88e361a498ab4
601,785
import math def block_to_coords(block, sequence): """Receives block number 1 through 9 and sequence 1 through 9, both read left to right, top to bottom, and returns the y, x coordinates on the puzzle""" # 0 1 2 3 4 5 6 7 8 # - - - - - - - - - # 0 - 0 1 2 0 1 2 0 1 2 # 1 - 3 4 5 3 4 5 3...
1934b6467bdf2635f96ad1d10cfead4cb52fdd25
601,787
def sum_lists(arg1, arg2): """ Return a list that is the element-wise sum of the elements of the two lists of equal size passed as arguments. Lists can be used to represent vectors of numbers as in Linear Algebra. However, as you can test in a python shell, for example, `ipython`, the effect th...
e340624d6f33fda5d02750499ddaf90595016335
601,790
def read_np_archive(archive): """Load Numpy archive file into a dictionary, skipping any values that cannot be loaded. Args: archive: Loaded Numpy archive. Returns: Dictionary with keys and values corresponding to that of the Numpy archive, skipping any values that could not ...
569dc1770bb4352d4a1d3cbcdf3fe0fb3e23f32d
601,791
def profile_upload_path(instance, filename): """file will be uploaded to MEDIA_ROOT / profile / user_<id>_username / <filename>""" return f'profile/{instance.user.id}_{instance.user.username}/{filename}'
6e107639644d6c73bde354219903a5fcf8346c39
601,796
def get_text(score): """Returns a textual representation of the likelihood that a domain is parked, based on the score. """ if score == 0: return 'Unlikely' elif score <= 0.3: return 'Possibly' elif score <= 0.6: return 'Fairly likely' elif score <= 0.85: retu...
d6def93429845e7df31cf395bb472760c2a36019
601,797
def check_for_duplicate_ids(id_map) -> bool: """ Checks for duplicate ids in the map :param id_map: The id_map generated by build_id_dict() :return: True if duplicate non-null id's exist, false otherwise """ used_ids = set() for sheet in id_map.keys(): for row in id_map[sheet].keys()...
82ba822baa0fe090c1df2c95f89394d4f0eb0c72
601,799
from datetime import datetime def get_message_string(user): """ Creates a message with a user and the current time """ now = datetime.now() day_string = now.strftime("%d/%m/%Y") hour_string = now.strftime("%H:%M:%S") message = now.strftime(f"Actualizado por {user} a las {hour_string} del {...
4612b7308ed0a81616367a82c9cde6c9cc6d15ae
601,804
from typing import Sequence import re def _tokenize_for_bleu_eval(code: str) -> Sequence[str]: """Tokenize the input for computing the bleu score. We perform the same tokenizing step as the retrieve and edit dataset. It is the 'def tokenize_for_bleu_eval(code)' function from 'github_eval.py' in the published...
897fd71c10f17d19e8630f92d644d84c058ccf1f
601,807
def _websocket_mask_python(mask, data): """Websocket masking function. `mask` is a `bytes` object of length 4; `data` is a `bytes` object of any length. Returns a `bytes` object of the same length as `data` with the mask applied as specified in section 5.3 of RFC 6455. This pure-python implem...
a0194d25aa2017d83fcc13e67791a5f735ee7fa5
601,810
def hex_to_rgb(hex_color): """Transforms a hexadecimal color string into an rgb-tuple of 0-255 integers""" if len(hex_color) == 4: # Thank you w3c for this convenient shorthand form # (#fb0 is equal to #ffbb00) hex_color = "#" + hex_color[1]*2 + hex_color[2]*2 + hex_color[3]*2 a...
b6ef1a3eb8e509c4042606e09c107b63d04f2ef1
601,818
def _get_course_cohort_settings_representation(cohort_id, is_cohorted): """ Returns a JSON representation of a course cohort settings. """ return { 'id': cohort_id, 'is_cohorted': is_cohorted, }
5f7c8b523801b1ee42d58d6f836f0b7e587d8c29
601,819
def _read_file(filename): """ Read a file and return the bytestring Args: filename: The location of the file Return: The bytestring of the file """ f = open(filename, 'rb') data = f.read() f.close() return data
d30735a80f2eff2c413d5063ce219e28feb773a0
601,820