content stringlengths 39 9.28k | sha1 stringlengths 40 40 | id int64 8 710k |
|---|---|---|
def productory(matrix_list):
"""
Multiplies from lest to right the matrices in the list matrix_list.
Arguments
----------
matrix_list : list of numpy.ndarray
List of matrices to be multiplied.
Returns
----------
M : numpy.ndarray
Product of the matrices in matrix_list.
... | f2f15f1e68329c7988a04ff4d25ed339a1277957 | 414,514 |
def writeDictCfg(dct, cfgname):
"""
Write out a config file from a dictionary.
- Entries: 'key=value\n'
:param dct: Dictionary to be written as a config file.
:param cfgname: Filename or path/to/filename for config file.
:return: Config filename or path/to/filename
"""
cfg_out = open(cfg... | 05135322f0759637db71681a39ca4cbf6948fd4f | 308,624 |
from textwrap import dedent
def trim(text):
"""Like textwrap.dedent, but also eliminate leading and trailing
lines if they are whitespace or empty.
This is useful for writing code as triple-quoted multi-line
strings.
"""
lines = text.split('\n')
if len(lines) > 0:
if len(lines... | 0c1bc710b6bf1e9bb7b42d990942423c8ebf7cf9 | 594,126 |
def generate_div(i):
"""
Generate a div with the style-<i> class.
eg.
>>> generate_div(0)
"<div class="box style-0"></div>
"""
return '<div class="box style-' + str(i) + '"></div>' | 1984414e1350f2ad036f4f4c6b42ef90deabfb5d | 554,195 |
import re
def remove_url(text):
"""
Supprime les URLs
:param text: texte à transformer
:return: texte transformé
"""
return re.sub(r'http\S+', '', text) | d0f3716808863d5e868da1efc4a7bb16ffa47ac1 | 705,155 |
from typing import Any
from typing import Optional
def _guess_crs_str(crs_spec: Any)->Optional[str]:
"""
Returns a string representation of the crs spec.
Returns `None` if it does not understand the spec.
"""
if isinstance(crs_spec, str):
return crs_spec
if hasattr(crs_spec, 'to_epsg')... | 11328ea9d1cc955faa63c37a64d115e8252b0c57 | 686,799 |
def none_formatter(error):
"""
Formatter that does nothing, no escaping HTML, nothin'
"""
return error | a08468a71060cf6f629c6f8b9b9e0c1dabc5f60d | 660,102 |
def egg_drop(n: int, k: int) -> int:
"""
What is the minimum number of trials we need to drop eggs to determine which floors of a building are safe for
dropping eggs, given n eggs and k floors?
:param n: number of eggs
:param k: number of floors
:return: the minimum number of trials
>>> egg... | c12426c93bedb721393b5ef4e165c834d018784e | 73,384 |
import requests
import re
def extract_conceptnet(phrase):
"""Access ConceptNet API and read relational triples as well as their weight and simple example"""
url_head = 'http://api.conceptnet.io/c/en/' # access ConceptNet API
raw_json = requests.get(url_head + phrase).json()
edges = raw_json['edges']
... | 0a8bdc41b1ed8a5f403804eb27a01f7a5d5c2380 | 551,419 |
from typing import Union
def get_error_message(traceback: str) -> Union[str, None]:
"""Extracts the error message from the traceback.
If no error message is found, will return None.
Here's an example:
input:
Traceback (most recent call last):
File "example_code.py", line 2, in <module>
... | bb1ccbb55e15a9670efbb4ddc71b22a35cfd9b17 | 683,887 |
import re
def get_unique_name_from_tag(image_uri):
"""
Return the unique from the image tag.
:param image_uri: ECR image URI
:return: unique name
"""
return re.sub('[^A-Za-z0-9]+', '', image_uri) | e963c292c0e41c0d4db2b2a59d962ee51ab3874c | 208,574 |
def _enforce_shape(points):
"""Ensure that datapoints are in a shape of (2, N)."""
if points.shape[0] != 2:
return points.T
return points | b23a9afd4bc4bfa0f09a2377b723d0b36d08fe51 | 188,587 |
def parseLineForExpression(line):
"""Return parsed SPDX expression if tag found in line, or None otherwise."""
p = line.partition("SPDX-License-Identifier:")
if p[2] == "":
return None
# strip away trailing comment marks and whitespace, if any
expression = p[2].strip()
expression = expre... | 654cd788f92971f25caf3b4c1cae90d534333ed7 | 236,412 |
import hashlib
def hash_bytes(data: bytes):
"""Compute the same hash on bytes as git would (e.g. via git hash-object).
The hash is the sha1 digest, but with a header added to the bytes first:
the word "blob", followed by a space, followed by the content length,
followed by a zero byte.
"""
ass... | 6a5054ba3393e81d2c35a014fa8c2665fda9517e | 198,523 |
def add_suffix_to_parameter_set(parameters, suffix, divider='__'):
"""
Adds a suffix ('__suffix') to the keys of a dictionary of MyTardis
parameters. Returns a copy of the dict with suffixes on keys.
(eg to prevent name clashes with identical parameters at the
Run Experiment level)
"""
s... | 39c184a6d836270da873b4c2e8c33e9a1d29f073 | 686,867 |
def wpm(typed, elapsed):
"""Return the words-per-minute (WPM) of the TYPED string."""
assert elapsed > 0, 'Elapsed time must be positive'
# BEGIN PROBLEM 4
return len(typed) / 5 * 60 / elapsed
# END PROBLEM 4 | 9b131376e0bd4b1f3eb826bdf61dd46534fed452 | 255,077 |
from typing import Optional
import pkg_resources
def get_installed_model_version(name: str) -> Optional[str]:
"""
Return the version of an installed package
"""
try:
return pkg_resources.get_distribution(name).version
except pkg_resources.DistributionNotFound:
return None | ecfa4c092aed284ee1cd66f08b610f5d5c8fab20 | 145,062 |
def split_into_groups(s, length=3):
"""splits given string into groups of length"""
if length < 0:
raise TypeError('split length must be >= 0')
s = ''.join(reversed(s))
groups = [s[i:i + length] for i in range(0, len(s), length)]
return [''.join(reversed(g)) for g in reversed(groups)] | 7ac764d65c3f6e7e3240433ea22a8a97ac8da014 | 419,377 |
def get_sequence(center_idx, half_len, sample_rate, max_num_frames):
"""
Sample frames among the corresponding clip.
Args:
center_idx (int): center frame idx for current clip
half_len (int): half of the clip length
sample_rate (int): sampling rate for sampling frames inside of the c... | e0622d4f2eea08a572c8ff6d332744f94729ab6d | 495,492 |
def format_file(path, tool):
"""Format file with clang-format and return True."""
tool("-i", path)
return True | f18e74c25b68f60ae1e468a88ec0a4301b5be506 | 101,751 |
import re
def preprocess_title(text):
"""Pre-process an episode title string by removing unnecessary quotations, brackets, and whitespaces."""
text = re.sub('[\(\[].*?[\)\]]', '', text) # remove brackets
text = re.sub(' +', ' ', text) # remove multiple whitespaces
text = text.strip().strip('\"').str... | 2cb1a8fdbda3a3f87bf98d1fde10cdd23c344063 | 396,929 |
def clear_sesam_attributes(sesam_object: dict):
"""
Return same dict but without properties starting with "_"
:param sesam_object: input object from Sesam
:return: object cleared from Sesam properties
"""
return {k: v for k, v in sesam_object.items() if not k.startswith('_')} | 9dc1c59cacb29b34d1f650803ad44d2febc7d940 | 621,242 |
import torch
def remove_first_sv(emb, first_sv):
"""
Projects out the first singular value (first_sv) from the embedding (emb).
Inputs:
emb: torch Tensor shape (glove_dim)
first_sv: torch Tensor shape (glove_dim)
Returns:
new emb: torch Tensor shape (glove_dim)
"""
# Calcul... | 92eed8657e9e57348efb3603e678dd9ffcd7cddb | 328,865 |
def last_slash_check(a_path):
"""Check if the path provided has an ending slash. If it does, remove
it and return a revised path. If not, do nothing.
"""
if a_path[-1] == '/':
new_path = a_path[:-1]
else:
new_path = a_path
return new_path | 8c0ed34b214f4137ceb72f4c9915e9151e5292b5 | 276,159 |
def export_sheet(ss, sheet_id, export_format, export_path, sheet_name):
"""
Exports a sheet, given export filetype and location. Allows export format 'csv', 'pdf', or 'xlsx'.
:param ss: initialized smartsheet client instance
:param sheet_id: int, required; sheet id
:param export_... | 76b49fa0904140571eb84526f6021448db54dea9 | 24,924 |
def resolve_cardinality(class_property_name, class_property_attributes, class_definition):
"""Resolve class property cardinality from yaml definition"""
if class_property_name in class_definition.get('required', []):
min_count = '1'
elif class_property_name in class_definition.get('heritable_require... | fed27e5c326842f5895f98e3f5e9fb5852444b07 | 54,153 |
def scan_uv_parsing(inp, uv_alpha_univariate, uv_fold_change, uv_decision_tree, uv_paired_samples, uv_correction, uv_labelsize_vulcano, uv_figsize_vulcano, uv_label_full_vulcano):
"""
Initialize univariate analysis.
Initialization function for univariate analysis.
inp : dict
Method dictionary.... | f217acea354f91c141b3845f5234e9b27f3ec4e0 | 183,241 |
from typing import Sequence
from typing import Optional
def split_round_robin(values: Sequence, num_procs: Optional[int]) -> Sequence[Sequence]:
"""
Split values into a `num_procs` sequences.
```python
split_round_robin(range(10), 3) == [[0, 3, 6, 9], [1, 4, 7], [2, 5, 8]]
```
"""
if num_... | 4bfbd5861a4555140b64a872404f0b6702029bd9 | 254,813 |
def get_std_dev(total_size: int, comm_size: int) -> float:
"""
In community generation, larger communities should have a smaller standard
deviation (representing tighter-knit communities). This generates a std dev
based on the ratio of the number of nodes in this community to the number
of nodes in ... | cb0ddaedee57eb98df337cd3a23e16d648f4a389 | 307,415 |
from typing import Tuple
def extgcd(a: int, b: int) -> Tuple[int, int, int]:
"""a * x + b * y = gcd(a, b)
See:
https://qiita.com/drken/items/b97ff231e43bce50199a
https://www.youtube.com/watch?v=hY2FicqnAcc
O(gcd(a, b))
"""
if b == 0:
return (a, 1, 0)
g, x, y = extgcd(b, a %... | 5aa89cd563685ea95b84d94bfbeb7df247fa705d | 529,014 |
def epsilon(n):
"""
Compute Jacobi symbol (5/n).
"""
if n % 5 in [1, 4]:
return 1
elif n % 5 in [2, 3]:
return -1
else:
return 0 | 5c335cd59cbbe8a130763f1ebac2887afaac3e48 | 61,649 |
import requests
def http_get(url, api_uri, token, **params):
"""
Helper function to perform an http get, with optional parameters
:param url: The url of the endpoint
:param api_url: The URI of the specific api
:param token: The access token
:param params: kwargs for optional parameter to the ... | d902b9475677d3350f55032516cd0ab112092998 | 533,802 |
def dict_reverse(dictionary):
"""
Reverse a dictionary. If values are not unique, only one will be used. Which one is not specified
Args:
dictionary (dict): dict to reverse
Returns:
reversed (dict): reversed dictionary
"""
return {v: k for k, v in dictionary.items()} | 056340e45218f8c1aeb3682bff918b83bf6779f4 | 290,305 |
def dfs(i, j, mat, visited):
"""
Applies Depth first search.
Args:
i (int): The row index of the src element
j (int): The column index of the src element
mat (List[List[int]]): The input matrix
visited (List[List[bool]]): The visited matrx
"""
if visited[i][j]:
... | ba99534759da7f5ead9862318a959c3aae1619a6 | 266,495 |
import importlib
def import_class_from_string(class_string):
"""
Import (and return) a class from its name
Arguments keywords:
class_string -- name of class to import
"""
module_name, class_name = class_string.rsplit('.', 1)
module = importlib.import_module(module_name)
return getattr... | f852c29d320ea3b00742dc0077c2318f0384e181 | 533,661 |
import re
def getIndsPropString(wkwdata):
"""Get the string for the property containing the indices of train, validation and test data"""
allAttributes = dir(wkwdata)
r = re.compile('^data_.*_inds$')
return list(filter(r.match, allAttributes)) | c3e4b95c4f1a5c17cf14c730d79a002eb768d91b | 370,897 |
def parse_errata_checksum(data):
""" Parse the errata checksum and return the bz2 checksum
"""
for line in data.splitlines():
if line.endswith('errata.latest.xml.bz2'):
return line.split()[0] | d3de13d48b495793a7d7c82f1b8656332bf5ea39 | 359,950 |
def _strip_whitespace(text_content: str) -> str:
"""Return text_content with leading and trailing whitespace removed
"""
output_content: str = str(text_content)
if text_content is not None and len(text_content) > 0:
output_content = text_content.strip()
return output_content | 6dda9623013f9ec7289e1098f49d8f991fbe2079 | 616,055 |
def identity(x):
"""Identity activation function. Input equals output.
Args:
x (ndarray): weighted sum of inputs.
"""
return x | 86f6b926244b517023d34b76dbef10b4ae5dcfce | 674,846 |
def to_lowercase(text: str) -> str:
"""
Returns the given text with all characters in lowercase.
:param text: The text to be converted to lowercase. (String)
:return: The given text with all characters in lowercase. (String)
"""
text = text.lower()
return text | 79ddb531bac0a4f6d19045ffe5bd2a01656545ed | 419,690 |
def field_names(model):
"""Return a set of all field names for a model."""
return {field.name for field in model._meta.get_fields()} | 0e89e793c07a567a1c016c304fa652bf621f06ac | 136,141 |
def read_define(filename, define):
""" Read the value of a #define from a file. filename is the name of the
file. define is the name of the #define. None is returned if there was no
such #define.
"""
f = open(filename)
for l in f:
wl = l.split()
if len(wl) >= 3 and wl[0] == ... | 0b696cb9f20b68bb708633b8ef5b92afb6c90a27 | 334,945 |
def single_high_initializer(low_genome='LOW', high_genome='HIGH'):
"""Generate a population that contains two types of genomes:
all of the population will be 'LOW' except for one, which will
be 'HIGH'."""
first = True
def create():
nonlocal first
if first:
first = False
... | 1d11f405f715e2e4fecd85ca5fdf4def00cefdf9 | 456,509 |
def dist(x, y, S):
"""
Mahalanobis distance:
d(x,y) = \\sqrt( (x-y)^T*S^-1*(x-y) )
where S^-1 = diag(1/s_i^2 for s_i in std)
Input must be torch.Tensor((1,N)) for x,y,S
"""
d = ((x-y).pow(2)/S).sum(1).sqrt()
return d | 676171a62ca828adbc140177c497c15124084817 | 52,190 |
from typing import Any
import logging
def search(model: dict[str, Any], search_keys: list[str]) -> list:
"""
Search an AaC model structure by key(s).
Searches a dict for the contents given a set of keys. Search returns a list of
the entries in the model that correspond to those keys. This search wil... | 574522c8c6a94e231ce819271d3db807bbb3bed3 | 392,553 |
def describe(data_matrix):
"""Get the shape of a sparse matrix and its average nnz."""
return 'Instances: %3d ; Features: %d with an avg of %d per instance' % \
(data_matrix.shape[0], data_matrix.shape[1],
data_matrix.getnnz() / data_matrix.shape[0]) | 98cd820dd9c2728a5ba1a59693ca480cb3c88f13 | 111,256 |
import random
def happens(prob):
""" Trigger a random event to happen
Arguments:
prob {float} -- chances to return true
Returns:
[bool] -- if the random event happens
"""
chance = random.uniform(0,1)
return chance <= prob | ca4f36317ede9e8d6fc9f7e50a41c876433631be | 560,668 |
def rescale(var, dt):
"""
Rescale variable to fit dt, based on quantities library
:param var: Variable to rescale
:param dt: Time steps
:return: Rescaled integer
"""
return (var.rescale(dt.units) / dt).magnitude.astype(int).item() | c7dffa2c0ac6b622716e2be3fbb7a926efad9404 | 185,038 |
def filter_instances_by_family(instances, family_name=None):
"""Yield instances whose 'familyName' custom parameter is
equal to 'family_name'.
"""
return (i for i in instances if i.familyName == family_name) | 3294c3f3dd0648defd1593688a87019a28b5adcd | 345,526 |
def from_datastore(entity):
"""Translates Datastore results into the format expected by the
application.
Datastore typically returns:
[Entity{key: (kind, id), prop: val, ...}]
This returns:
[ name, street, city, state, zip, open_hr, close_hr, phone, drink, rating, website ]
where n... | 24d274a1261aedeff976ee89c913c1ca73fa42d5 | 115,319 |
def _strip_unsafe_kubernetes_special_chars(string: str) -> str:
"""
Kubernetes only supports lowercase alphanumeric characters, "-" and "." in
the pod name.
However, there are special rules about how "-" and "." can be used so let's
only keep
alphanumeric chars see here for detail:
https://... | f5a0e0f61aec408acfc4eee1745053e36a483a6a | 99,410 |
import torch
def kld_loss(mu, logvar, mean_reduction=True):
""" First it computes the KLD over each datapoint in the batch as a sum over all latent dims.
It returns the mean KLD over the batch size.
The KLD is computed in comparison to a multivariate Gaussian with zero mean and identity covarianc... | 9ce92de5d34a385bb095a6182da8ec09577ca42c | 440,842 |
from datetime import datetime
def format_bitmex_api_timestamp(timestamp: datetime) -> str:
"""Format BitMEX API timestamp."""
return timestamp.replace(tzinfo=None).isoformat() | fa657ca06a03921b07f69d6104389bc5daf5d782 | 461,550 |
def get_position_by_substring(tofind, list):
"""
Get index where `tofind` is a substring of the entry of `list`
:param tofind: string to find in each element of `list`
:param list: list to search through
:return: index in `list` where `tofind` is found as a substring
"""
for i, e in enumera... | 8836fe6cbb1279d21320c6048c45d36746aafc8a | 666,778 |
def get_combined_params(*models):
"""
Returns the combine parameter list of all the models given as input.
"""
params = []
for model in models:
params.extend(list(model.parameters()))
return params | 907beb6a48e7abfdb75cdb19ff5f5e166c62b612 | 360,654 |
def drop_irrelevant_features(df):
"""
Drop irrelevant columns from features set
:param data_df: features_data
:return: a dataframe of relevant features
"""
cols_to_exclude = ['index', 'level_0', 'id']
df = df.drop(cols_to_exclude, axis=1)
return df | e5652dde05504843c88d117d23c2ea42e8e25ba8 | 544,366 |
def KGtoLB(mkg):
"""
Convertie une masse en kg vers lb
note: 1 kg = 2.20462 lb
:param mkg: masse [kg]
:return mlb: masse [lb]
"""
mlb = mkg * 2.20462
return mlb | 05ecbe4fb668b6c52da9c43243145cabc61699a2 | 573,043 |
def bounding_box(rects):
"""
Get a new Rect which circumscribes all the rects.
:param list rects
:return bounding Rect
:rtype Rect
"""
top = float('inf')
left = float('inf')
bottom = 0
right = 0
for rect in rects:
top_left, bottom_right = rect
top = min(top,... | 9102db8bd9d34929ed1f9eb2c70c90ea00272632 | 465,958 |
def valid_line(line: str) -> bool:
"""
行バリデーション
Parameters
----------
line: str
行テキスト
Returns
-------
valid: bool
validであるフラグ
"""
lstriped = line.lstrip()
if len(lstriped) == 0:
return False
if lstriped[0] == '#':
return False
if l... | 569b34f80a77b765304ddb19fd9699c2e3909f99 | 529,304 |
def check_wide_data_for_blank_choices(choice_col, wide_data):
"""
Checks `wide_data` for null values in the choice column, and raises a
helpful ValueError if null values are found.
Parameters
----------
choice_col : str.
Denotes the column in `wide_data` that is used to record each
... | a9564026133dea68f17ee9b099feec409828707a | 651,028 |
from typing import Optional
def flatten_dict(
d: dict,
s: str = '',
exc: Optional[list] = None
) -> dict:
"""Reformat a multi-layer dictionary into a flat one.
:param d: Input dict.
:param s: Prefix to be added to keys.
:param exc: List of keys to exclude from the resulting di... | 28a0c80954bfa2d0f24ec5b408edbfe24e928c7a | 304,974 |
import re
def norm_freqs(data, expression, count_name=str, normalize=True, analyze=True):
"""Get frequencies (normalized = optional) of a regex pattern in a Series with one or more strings.
Args:
data (DataFrame): a dataframe with texts to extract frequencies from.
expression (re.compile): a... | e497ad1db53b3b366a5f03f507f8cc1c34b9b213 | 185,480 |
import importlib
def get_module(modulename):
"""Returns a module object for given Python module name using `importlib.import_module`."""
return importlib.import_module(modulename) | cfb55e25784a64fe516d2310ae38f7b846030021 | 291,593 |
def _create_default_branch_id(repo_url: str, default_branch_ref_id: str) -> str:
"""
Return a unique node id for a repo's defaultBranchId using the given repo_url and default_branch_ref_id.
This ensures that default branches for each GitHub repo are unique nodes in the graph.
"""
return f"{repo_url}... | 323d88f3e50343281952d701a18981f57055da04 | 234,528 |
def get_conv_output_shape_flattened(input_shape, structure):
"""
Input_shape: (Channels, Height, Width) of input image
structure: List containing tuple (out_channels, kernel_size, stride, padding) per conv layer
"""
def get_layer_output(input, layer_structure):
# See shape calculatio... | e9355ef4728b0adde40b89d853728fb9a2efdc04 | 259,512 |
def remove_node(G, node):
"""
Wrapper around networkx.classes.graph.Graph.remove_node to return a dict mapping an incident node to its edge attributes
"""
rv = {}
for edge in G.edges(node, data=True):
u = edge[0]
v = edge[1]
edge_attr = edge[2]
t = None
if u =... | 14404c6af08e4e82b3dcd755d6fee49c1f1ea3c9 | 477,149 |
import pkgutil
def is_installed(package):
"""Check if a python package (Kipoi plugin) is installed
Args:
package (str): package/plugin name
Returns:
True if package/plugin is installed
"""
return pkgutil.find_loader(package) is not None | 11329b5d826d390af96956fa9cbf04bb4baf359e | 548,128 |
import random
import string
def generate_verification_code() -> str:
"""Generate a random 6-digit code
Returns:
str: a 6-digit code in string format .e.g '654874'
"""
return "".join(random.choices(string.digits + string.digits, k=6)) | 4b6a6891e73c93cd92a5d1fc6098ca6faa5dcd5b | 573,883 |
import torch
def create_eye_batch(batch_size, eye_size):
"""Creates a batch of identity matrices of shape Bx3x3
"""
return torch.eye(eye_size).view(
1, eye_size, eye_size).expand(batch_size, -1, -1) | ae1171af3f13e4be03ddada62481f0dcd9c6b202 | 571,041 |
import io
def read_file(path):
"""Returns all the lines of a file at path as a List"""
file_lines = []
with io.open(path, mode="rt", encoding="utf-8") as the_file:
file_lines = the_file.readlines()
return file_lines | 8e220e0b90ded168a1d1d8d37b7451b7796b1ed5 | 699,612 |
import requests
def get_recognitions(mem_skip, api_key):
"""This function triggers the GET RECOGNITIONS API.
https://api.highground.com/#api-Recognition-GetRecognition
Keyword Arguments:
mem_skip -- tracks member records to skip for looping through all records
api_key... | 08a73c10cec7173f2f60dc9ef61190747431fc2e | 178,672 |
async def read_exactly(stream, count):
"""Read the specified number of bytes from stream. Keep trying until we
either get the desired amount, or we hit EOF.
"""
s = b''
while count > 0:
n = await stream.receive_some(count)
if n == b'':
raise EOFError
count = coun... | afc0786ac0ec89313762d5294069716a1d07f167 | 558,967 |
def maxi(a,b):
""" Maximal value
>>> maxi(3,4)
4
"""
if a > b:
return a
return b | 9270324dc5025f39c0c463fcfae9d99fa9b1a5e1 | 553,060 |
def CreateSafeUserEmailForTaskName(user_email):
"""Tasks have naming rules that exclude '@' and '.'.
Task names must match: ^[a-zA-Z0-9_-]{1,500}$
Args:
user_email: String user email of the task owner.
Returns:
String with unacceptable chars swapped.
"""
return user_email.replace('@', '-AT-').rep... | 5d43d366447970a24cbbfdb092c83334b18a7cf5 | 415,433 |
import hashlib
def calculahash(cadena):
"""Devuelve el hash SHA256 de una cadena dada como entrada
:param cadena: texto de entrada para calcular su hash
:return: el hash calculado con SHA256
"""
return hashlib.sha256(cadena.encode()).hexdigest() | 6b2e04c00b13471e470ba52ab6c5e500b84c15c3 | 643,494 |
def bisection(f, a, b, TOL, N):
"""To find a solution to f(x) = 0
Finds the solution to f(x) = 0 given the continuous function f on the interval [a, b], where
f(a) and f(b) have opposite signs.
Args:
f: a function to be evaluated (can be a lambda or def).
a: the lower bound in the giv... | fa2971cdd62623d68739b4a8b9ea5ca2965efa3b | 464,260 |
def _RGB2sRGB(RGB):
"""
Convert the 24-bits Adobe RGB color to the standard RGB color defined
in Web Content Accessibility Guidelines (WCAG) 2.0
see https://www.w3.org/TR/2008/REC-WCAG20-20081211/#relativeluminancedef for more references
:param RGB: The input RGB color or colors shape== ... x 3 (R,... | c2c5c25d64cc7b0cb9b004846b72aecada7c5d85 | 700,755 |
def le(h):
"""
Little-endian, takes a 16b number and returns an array arrange in little
endian or [low_byte, high_byte].
"""
h &= 0xFFFF # make sure it is 16 bits
return [h & 0xFF, h >> 8] | ea5a0b0f49f43f43456b9afbb04fff9b2fd866c4 | 415,550 |
def get_fontext_synonyms(fontext):
"""
Return a list of file extensions extensions that are synonyms for
the given file extension *fileext*.
"""
return {'ttf': ('ttf', 'otf'),
'otf': ('ttf', 'otf'),
'afm': ('afm',)}[fontext] | 8dd131392ba98bfd4f90d1ba3d275ed7048ad35a | 299,486 |
def verify_splits(splits, keyfunc):
""" Verifies that the splits of each transaction sum to 0
Args:
splits (dict): return value of group_transactions()
keyfunc (func): function that returns the transaction amount
Returns:
(bool): true on success
Examples:
>>> from operat... | 9d30da42e5366f60fb09e9cdca8a2726ced7ba19 | 552,683 |
def normalize_json_fields(result_list):
"""
Makes sure that each json contains the same fields.
Adds them with None as value if any field is missing.
"""
found_keys = set()
for item in result_list:
found_keys.update(item.keys())
for item in result_list:
for key in f... | a0498db7929ba0663c2da57663986ff8ab52b8de | 240,186 |
import collections
def attrize(container_name=None, **dct):
"""Given a dict, return a named tuple where the values are accessible as
named attributes. A collection name can be given as an optional
parameter.
Examples
--------
>>> foo = attrize(**{'a': 1, 'b': 2})
>>> foo.a
1
"""
... | 3b61159922e1e6773be46feef28aacf9f0256aa9 | 482,069 |
import json
def get_filepaths(sets):
"""
Extracts the file paths from the provided .json file and returns, the content of
the .json file as a dictionary as well as a potential error message.
"""
# Reading in the json file with the settings
try:
with open(sets, "r") as read_file:
... | 5fdf13cd8184159b73c403b5b00d2dd803367f23 | 422,160 |
import yaml
def load_conf(conf_path):
"""Load a yaml encoded conf file."""
try:
with open(conf_path) as f:
y = yaml.load(f, Loader=yaml.CLoader)
return y or {}
except Exception as e:
raise ValueError('Invalid or nonexistent config filename') | 651afd19fbf28fc35c3827f3651b8d26ff5f8ab4 | 523,623 |
def vector_product(vec1, vec2, do_alignment=True):
"""
Computes the dot product of two vectors.
Parameters
----------
vec1, vec2 : ProbabilityVector
Returns
-------
product_scalar : float
"""
if do_alignment:
series1, series2 = vec1.series.align(vec2.series)
else:
... | 60cc45e863ef8d7afc6f0d12b87018fe8689f18f | 532,180 |
def byte_compare(stream_a, stream_b):
"""Byte compare two files (early out on first difference).
Returns:
(bool, int): offset of first mismatch or 0 if equal
"""
bufsize = 16 * 1024
equal = True
ofs = 0
while True:
b1 = stream_a.read(bufsize)
b2 = stream_b.read(bufsi... | 59adfe50fefdb79edd082a35437018d4b954ec75 | 1,218 |
def linepoint(t, x0, y0, x1, y1):
"""Returns coordinates for point at t on the line.
Calculates the coordinates of x and y for a point
at t on a straight line.
The t parameter is a number between 0.0 and 1.0,
x0 and y0 define the starting point of the line,
x1 and y1 the ending point of the l... | 4296a5133daacd210886ca6e40e926ba98dc409f | 408,315 |
def calc_cov(samples):
"""
Calculates covariance matrix as described in paper.
Args:
samples (list of np.matrix) - a list of sample-matrices
Returns:
np.matrix - the covariance matrix
>>> s1 = np.matrix([[1, 0], [0, 1]])
>>> s2 = np.matrix([[2, 0], [0, 2]])
>>> calc_cov([s... | ae9da378620c081099c6e3e79ebd7f332607b696 | 203,294 |
from pathlib import Path
def fixture_sample_file() -> Path:
"""Return a sample file."""
return Path(__file__).parent.joinpath("sample.txt") | 765dbf2283f2f21c705ce9a8eac1728f4cbed7ea | 100,744 |
import hashlib
def generate_token(login: str, auth_salt: str) -> str:
"""Generate token based on login and hash salt."""
encoded_key = (login + auth_salt).encode('utf-8')
token = hashlib.sha512(encoded_key).hexdigest()
return token | eca8901c16f511077ca85c19f8f0cb54e46a9e25 | 551,688 |
def get_port(device):
""" Get the port, as string, of a device """
return str(device.port) | 2c68a38dc12c981718d50d44be16b0ca5d317c23 | 94,945 |
def _get_model_features(model_pipe):
"""Get features from a `civis.ml.ModelPipeline`
"""
model_features = []
target_cols = model_pipe.train_result_.metadata['data']['target_columns']
for feat in model_pipe.train_result_.metadata['data']['column_names_read']:
if feat not in target_cols:
... | b39fe53effc1d2873ceac02450d6022e06702337 | 461,534 |
def format_flux_mode_indices(atom_idxs):
""" Formates the atom indices into a string that is used
to define the fluxional (torsional) modes of a
molecular species for Monte Carlo calculations in MESS.
:param atom_idxs: idxs of atoms involved in fluxional mode
:type atom_idxs: list(i... | 01f62f092247a293334b09803755037f34648a6b | 189,660 |
def to_var(log_std):
"""Returns the variance given the log standard deviation."""
return log_std.exp().pow(2) | 841dd6aae46ae37c9c71f002e7a70c2ebd8e531b | 201,296 |
import math
def calculate_temp_NTC(raw_val):
"""
Converts the raw value read from the NTC temperature sensor
module into degrees celsius.
"""
voltage = raw_val * 5 / 1023
resistance = (5 * 10000 / voltage) - 10000
temp = ((3.354016 * (10**-3)) + (2.569850 * (10**-4)) *
math.l... | 500d4e9073b5d50c96b74e549fdd91cce364e09d | 536,298 |
def get_fuel_needed(mass: int) -> int:
"""Calculate fuel needed to launch mass."""
return mass // 3 - 2 | ed4139ed2e57fce478e3eb3d94ba55f3b20bbf25 | 413,572 |
def wild2regex(string):
"""Convert a Unix wildcard glob into a regular expression"""
return string.replace('.','\.').replace('*','.*').replace('?','.').replace('!','^') | c30360076fde573b3865143b761579e2c7466877 | 63,904 |
import re
def sanitized_name(name, wid):
"""Clean an action name and change it to
proper format. It replaces all the unwanted
characters with `_`.
Args:
name (str): The crude action name.
Returns:
str: The sanitized action name.
"""
return "popper_{}_{}".format(
r... | 82937a39db4de08b0bb7b0304333119c02dcc293 | 321,483 |
import math
def get_product_factors(n):
""" get product factors of n
"""
if n <= 0 or not isinstance(n, int):
return []
else:
product_factors = []
for i in range(1, math.ceil(math.sqrt(n)) + 1):
if n % i == 0:
product_factors.append(i)
... | ed9f577d367fc9492fcd7d3a47d956d2dc892f77 | 521,856 |
def n_subsystems(request):
"""Number of qubits or modes."""
return request.param | 28ed56cc26e4bfa1d607bf415b3a7611eb030a27 | 31,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.