content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import itertools
def vertex_color_qubo(G, colors):
"""Return the QUBO with ground states corresponding to a vertex coloring.
If `V` is the set of nodes, `E` is the set of edges and `C` is the set of
colors the resulting qubo will have:
* :math:`|V|*|C|` variables/nodes
* :math:`|V|*|C|*(|C| - 1)... | 2e672d8a816d05aa9067cadc738c91d86be7ecbd | 632,060 |
import torch
def correct(output, target, tokens):
"""Computes the number of correct predictions.
Args:
output (torch.tensor): output of the model
target (torch.tensor): masked labels
tokens (int): vocabulary size
Returns:
int: number of correct predictions
"""
wit... | 48dc9021720212048d7903c81229a529a122d9e1 | 632,065 |
def parse_event_description(in_event):
"""Find and make nice the gig description from a single event from bar 303 website
Args:
in_event (scrapy.http.response.html.HtmlResponse): The html response for the single event from bar 303 website
Returns:
str: Event Description, maybe an e... | 3a15bc3a3aa272c8ff6e06c8dec09f02bfcfcb87 | 632,066 |
import random
def random_order(ugraph):
"""
returns a list of random node order
"""
nodes = ugraph.keys()
random.shuffle(nodes)
return nodes | 781ac99331ad2f76292ccaeb5017bd859719ca52 | 632,068 |
import torch
def is_autocast_enabled() -> bool:
"""Similar to torch.is_autocast_enabled, but compatible with torch 1.5.1"""
if hasattr(torch, "is_autocast_enabled"):
return torch.is_autocast_enabled()
return False | a998dbf371840ea3cce00536d309ea32620344a2 | 632,069 |
def _split_input_slice(input_shape, num_split):
"""Get input slice from the input shape.
Parameters
----------
input_shape : tuple
The input shape of the net.
num_split : int
The number of split we want to have.
Returns
-------
slices : list of slice
The split ... | 60e72838a6cc2c4d0701a4c106997e81c41a8028 | 632,071 |
def get_DIB_data(Dataset):
"""Function that modifies a pytorch dataset so that the target contains the example index."""
class DIBData(Dataset):
def __getitem__(self, index):
img, target = super().__getitem__(index)
return img, (target, index) # append the index
return DIB... | 6b094f88cf2233cf669c4fa4156994132d6b2394 | 632,073 |
from datetime import datetime
def datetime_to_iso(timestamp):
"""Parse a datatime string and returns a datetime in iso format.
@param timestamp: timestamp string
@return: ISO datetime
"""
return datetime.strptime(timestamp, "%Y-%m-%d %H:%M:%S").isoformat() | dee6c931605250033e12f406109b4fbf3b65acf6 | 632,075 |
def is_good_response(response):
"""Helper method to check if boto3 call was a success."""
code = response["ResponseMetadata"]['HTTPStatusCode']
# get response code 201 on EFS creation
return 200 <= code < 300 | 4501439f140fed4576dff8f84fcf038aa552f781 | 632,076 |
def vips_image_new_from_array(cls, array, scale = 1, offset = 0):
"""Create a new image from an array.
The array argument can be a 1D array to create a height == 1 image, or a 2D
array to make a 2D image. Use scale and offset to set the scale factor,
handy for integer convolutions.
"""
# we ac... | 6c9b74e4d899b9b488d7f5ea331e0b6ec26aa409 | 632,079 |
def svc_ids(svc):
"""
Returns the account ID and service ID of a given service.
"""
return svc['accountId'], svc['id'] | 80fc584a69279187b76c4a3366b36f70289636e0 | 632,080 |
def split_train_test_val(X, y, threshold=0.1): # Tested [N]
"""
Creates and compiles a fully-connected feed forward neural network model using Keras
Args:
X (DataFrame):
y (ndarray): Labels
threshold (float): The proportion to split the data
Returns:
Xval (Dat... | 1a12592a54ba62dbd3bd0b1478bf9dc79dd20284 | 632,085 |
import torch
def soft_step(x, temperature):
"""Differentiable relaxation of the Heaviside step function."""
return torch.sigmoid(x / temperature) | 672db4208cc50474e225e0dcc7d53393af4fc47a | 632,088 |
def pmul(p, n):
"""Return the multiple of the given probabilty."""
return 1.0 - (1.0 - p) ** n | a8424efe5476e900a56d2aa6cc9fc510e3e29030 | 632,090 |
def is_medium_truck(df):
"""Return if vehicle is a medium truck, per NHTSA convention."""
yr = df['YEAR']
body = df['BODY_TYP']
return ((yr.between(1975, 1981) & body.isin([53, 54, 56])) |
(yr.between(1982, 1990) & body.isin([70, 71, 75, 78])) |
((1991 <= yr) & body.isin([60, 61... | 64c08fe1774846a94a31d77d2aa1ced87b96b4c5 | 632,091 |
from typing import Optional
from typing import Any
def make_create_json(
summary: str,
project_key: str,
type_name: str,
description: Optional[str],
assignee: Optional[str],
priority_name: Optional[str],
labels: Optional[str],
due_date: Optional[str],
) -> Any:
"""Makes a JSON stri... | 6071e90f6d18de8766d492abd72723bc91aa61a3 | 632,094 |
def normalize_pixel_values(pixels):
""" Normalize pixel values to be in the range [0, 1] """
pixels = pixels.astype("float32")
pixels /= 255.0
return pixels | e8d4a621e6c411251e41eeac2cfc82989895affd | 632,096 |
def clean_meta_data(meta_data_frame):
"""
Clean the meta data we have. Remove an unnamed column, rename some other columns, drop some columns
:param meta_data_frame: pd dataframe
:return: cleaned pd dataframe
"""
meta = meta_data_frame.loc[:, ~meta_data_frame.columns.str.contains("^Unnamed")]
... | fb61391e99067b02471310fb6c629204fd436739 | 632,097 |
def to_iamc_layout(df):
"""Transform *df* to a standard IAMC layout.
The returned object has:
- Any (Multi)Index levels reset as columns.
- Lower-case column names 'region', 'variable', 'subannual', and 'unit'.
- If not present in *df*, the value 'Year' in the 'subannual' column.
Parameters
... | aaa64e3b3f4139881955675a88e9f93af02453ea | 632,101 |
def multi_match_aware_interval(k, delta, i, s, pi, li):
"""
Function returning the interval of relevant substrings to lookup using the
multi-match-aware substring selection scheme described in the paper.
Args:
k (int): Levenshtein distance threshold.
delta (int): Signed length differenc... | 096b3650df7c7f73e8d5644395c66ff36b40072e | 632,103 |
def delete_files_template(get_s3_client_func, get_bucket_func, delete_keys_func, key_list, s3_bucket):
"""
Curried template function for deleting files from an S3 bucket
:param get_s3_client_func: A function that returns an S3 client
:param get_bucket_func: A function that returns an object representi... | d766fd1fb12b044f3436da0846f3802a6ad521c1 | 632,104 |
def hashable(raw):
"""If `raw` contains nested lists, convert them to tuples
>>> hashable(('a', 'b', 'c'))
('a', 'b', 'c')
>>> hashable(('a', ['b', 'c'], 'd'))
('a', ('b', 'c'), 'd')
"""
result = tuple(hashable(itm) if isinstance(itm, list) else itm
for itm in raw)
r... | 9d66280ccc739d16fbae3a07c61b51cff19439ea | 632,108 |
import torch
def get_float_encoding(
token: str, embedding_size: int, vmax: float = 1.0
) -> torch.Tensor:
"""Convert a token representing a float into a _fixed_ embedding vector.
NOTE: This can be used for *any* range of numbers > 0.
Args:
token (str): A token representing a float. NOTE: Nee... | 0bc9414ba80663d5d05c3a55077cae78a25d21eb | 632,109 |
def catch_erroneous_destination(destination):
"""
Catch instructions that are not valid and throw an error.
"""
error_msg = "Available instructions are: 'any', or '#', where '#' "\
"is an integer."
if destination not in ["any"]:
try:
integer_destination = int(destination)... | acd76e5487dfab294b70a0f2ead8266ca2130e52 | 632,112 |
def paragraphs(linelist):
"""
Break a list of lines at blank lines into a list of line-lists.
"""
plist = []
newlinelist = []
for line in linelist:
line = line.strip()
if line:
newlinelist.append(line)
elif newlinelist:
plist.append(newlinelist)
... | 681633b1e03c0adb1619d919c47f30108d5684a8 | 632,125 |
def friendly_number(number, base=1000, decimals=0, suffix='',
powers=['', 'k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y']):
"""
Format a number as friendly text, using common suffixes.
>>> friendly_number(102)
'102'
>>> friendly_number(10240)
'10k'
>>> friendly_number(12341234, ... | b29797dc747791853001fb32a387c184b3b9a138 | 632,126 |
from typing import List
def list_truncated_nums(n: int) -> List[int]:
"""
Returns a list of all left and right truncated numbers of n
>>> list_truncated_nums(927628)
[927628, 27628, 92762, 7628, 9276, 628, 927, 28, 92, 8, 9]
>>> list_truncated_nums(467)
[467, 67, 46, 7, 4]
>>> list_truncat... | ec349e55e60e3164373702d2d020a9cd791ec039 | 632,128 |
def judge_checksum(content: bytes) -> bool:
"""
Judge if the checksum is right or not.
:param content: the content of segment
:return: A bool
"""
even_sum = 0x0
odd_sum = 0x0
for i in range(len(content)):
b = content[i]
if i % 2:
odd_sum += b
odd... | aec6fc15a213639de432b58ae9ac2e7abb5d92ee | 632,134 |
from functools import reduce
def factors(n, ordered=True):
"""Get factors of a number in a list.
Parameters:
n (int): The number that you want to get the factors of.
ordered (bool): Whether you want the output to be ordered from smallest to largest. Setting this value to false will marginally increas... | 5927699ae291cbbea3aad20aba9fd423a17e245c | 632,141 |
import re
def regex_password(password):
"""
Regex
Password includes at least one digit, one uppercase letter, one lowercase letter, and one special character.
"""
# The {8,} means "at least 8".
# print(re.match(r"^(?=.*[\d])(?=.*[A-Z])(?=.*[a-z])(?=.*[@#$%^&*?!+-_=])[\w\d@#$]{8,}", password))
... | b7593fcaa5b75d8ed154e0930cdfc0b4d09b7247 | 632,142 |
def px2hc(xpx, ypx, dx, dy, xc, yc, sz):
"""
Given positions in pixel coordinates (x = [0->nx-1]; y = [0->ny-1]),
determine the HC x and y coordinates in arcseconds.
- xpx, ypx = pixel coordinates of AR positions
- dx, dy = arcsec/px
- xc, yc = FOV center in arcsec from solar disk center
- x... | 0ef0cea5e31757069cdc5a4af9b93778ef881efd | 632,144 |
def get_hyperparams(tree_type, dataset):
"""
Input
tree_type: str, Tree-ensemble type.
dataset: str, dataset.
Return
- Dict of selected hyperparameters for the inputs.
"""
lgb = {}
lgb['adult'] = {'n_estimators': 100, 'num_leaves': 31, 'max_depth': -1}
lgb['bank_mark... | dc311006f33a18089681f4f835d62fadd388444f | 632,146 |
import logging
def get_birthday(soup):
"""
Utility function to get the Birthday of an actor from his wikipedia page.
:param soup: Beautiful Soup object
:return: String containing the actor's birth date in yyyy-mm-dd format.
"""
logging.info("getBirthday called.")
# Isolate the info box ta... | 22c0efbfcbea85dabbdfae619b6f7ac28e46fe82 | 632,148 |
import math
def _2d_rotate(position, angle_degrees):
"""rotate a 2d vector around an angle (in degrees)"""
radians = math.radians(angle_degrees)
# take the negative of the angle because the orientation circle works clockwise in this world
cos = math.cos(-radians)
sin = math.sin(-radians)
x, y ... | cd031deef2ed1be59ffa03214055ede3277d7912 | 632,154 |
import itertools
def product_no_consecutives(iterables, repeat=2):
""" Returns Cartesian product of input iterable excluding those contaning
equal consecutives elements.
See: `itertools.product`
"""
def has_no_equal_consecutives(sequence):
it, it_shifted = itertools.tee(sequence)
next... | e8fa05f8dfff07ccc9abc708ba6cd625a516bb68 | 632,155 |
def is_scoped_package(name):
"""
Return True if name contains a namespace.
For example::
>>> is_scoped_package('@angular')
True
>>> is_scoped_package('some@angular')
False
>>> is_scoped_package('linq')
False
>>> is_scoped_package('%40angular')
True
"""
return name.st... | 22d54aaf967f8556686a023f296f70d38a864496 | 632,161 |
def quotify(text: str) -> str:
"""
Turn a string into a discord quote.
:param text: Text to put into quote
:return: Discord quote
"""
return "> " + text.replace("\n", "\n> ") | afb856ad81190ac15279dbffb1d1b24413645366 | 632,162 |
def AddRepositoryTags(prefix='', rid=True, date=True, revision=True,
wrap=False):
"""Add repository tagging into the output.
Args:
prefix: comment delimiter, if needed, to appear before tags
rid: bool; True includes the revision Id: repository tag.
date: bool; True includes the Da... | 59057ebaad1f2807bb186c0010fbc8f5828988f2 | 632,163 |
import json
def load_json(filename):
""" load external json file """
with open(filename) as data_file:
json_data = json.load(data_file)
return json_data | 9557ed533588606a4e66a1fc110a09e728cb4d4b | 632,164 |
import math
def euclid(onsets, pulses):
"""returns a list of ones and zeros for a give euclidean rhythm
>>> euclid(3,8)
[1, 0, 0, 1, 0, 0, 1, 0]
"""
slope = float(onsets) / float(pulses)
result = []
previous = None
for i in range(pulses):
current = int(math.floor(float(i) * sl... | ac06108bc86f57c8a0b381f813fa03aecf3ea752 | 632,168 |
def class_to_dict(inst, ignore_list=[], attr_prefix=''):
""" Writes state of class instance as a dict
Includes both attributes and properties (i.e. those methods labeled with @property)
Note: because this capture properties, it should be viewed as a snapshot of instance state
:param inst: insta... | 1c3e1f752028240f67188d47499a0557b0351a82 | 632,169 |
def generate_id(text):
"""Deterministically generates an ID from a given text.
NOT guaranteed to be unique, but the alternative was to
either drop some data for not having IDs, or
generating uniquely on the fly: which is hard to do on
a batch system.
A negative integer is returned to avoid... | cec5c398dbc3fc3ee12fb9d2d8af6081bd91165f | 632,170 |
import re
def hasMainFunc( filename ):
"""
Returns True if file contains something that looks like a main() or
main( int argc, char argv ) function.
"""
main_regex = re.compile('.*main(.*argc.*argv).*')
f = open(filename)
for line in f.readlines():
if main_regex.search( line ):
... | 0c80895b7fbaadfc772a724c687f2f5e68b22677 | 632,173 |
import requests
import time
def get_from_bgg(api_url, parameters):
"""Successively attempts to get data from BGG given an API"""
response = requests.get(api_url, params=parameters)
# Retry if return codes indicate "too many requests"
while response.status_code == 202 or response.status_code == 429:
... | 361c4e29aecfd8a70da7ec75924400b44a519b04 | 632,174 |
import re
import itertools
def extract_param_list(params, prefix=''):
"""Extract a list-of-dicts based on parameters containing AWS style list.
MetricData.member.1.MetricName=buffers
MetricData.member.1.Unit=Bytes
MetricData.member.1.Value=231434333
MetricData.member.2.MetricName=buffers2
Met... | f84a4db4592c9609074996df7b1bd33adbf5e1e1 | 632,175 |
def is_palindrome(num):
""" Returns true if a number is a palindrome """
reverse, forward = 0, num
while (num > 0):
reverse = reverse*10 + num%10
num /= 10
return forward == reverse | e1e3eb23a3bd83d8978c68468b633dc2daca370c | 632,176 |
def privilege_check(user, *required_privileges):
"""Tests if the user has one of the required_privileges to view the
requested component.
"""
for perm in required_privileges:
if user.has_property(perm):
return True
return False | 18fe8837a9152991b2ef8974c19303677349ee8c | 632,177 |
def pages_endash(record):
""" Convert pages to use an html en dash
"""
try:
# Convert to list of page numbers
pages = [p.strip() for p in record['pages'].split('-')
if p.strip()]
record['pages'] = '–'.join(pages)
except KeyError:
pass
return reco... | 873efb473df3f2222b94d1ed51c830125226e879 | 632,178 |
import requests
def status_crawler(LEETCODE_SESSION: str, question_name: str) -> bool:
"""Check if question solved
Args:
LEETCODE_SESSION (str): User's LeetCode session.
question_name (str): LeetCode question name.
Returns:
bool: Solved or not.
"""
cookies = {"LEETCODE_SE... | 0cad01ba7331680628da089c33cc9dccf37d3815 | 632,181 |
def add_special_tokens(tokenizer):
""" Returns GPT2 tokenizer after adding separator and padding tokens """
#tokenizer = GPT2Tokenizer.from_pretrained('gpt2')
special_tokens = {'bos_token':'<|startoftext|>','eos_token':'<|endoftext|>', 'pad_token':'<|pad|>','sep_token':'<|summarize|>'}
num_add_toks = tokenizer.add_... | df424fb3ef9e4db5f66f12a81dcb9974376cfa75 | 632,192 |
from typing import Sequence
def sub_seq(s1: Sequence, s2: Sequence) -> bool:
"""
Checks if sequence s1 is subsequence of s2,
:param s1: First sequence.
:type s1: Sequence
:param s2: Second sequence.
:type s2: Sequence
:return: True if s1 is subsequence of s2.
:rtype: bool
"""
... | 4bb5c7eb8b680129fd3f419479d22ec787bea6ed | 632,193 |
def drop_null_rows(df):
"""Drop all rows containing null values"""
return df.dropna().reset_index(drop=True) | c7bb10b89b9fddd0f526443368214b3d8da278ef | 632,196 |
def get_error_name(error):
"""Return canonical error name as string.
For builtin errors like ValueError or Exception, will return the bare
name, like ValueError or Exception.
For all other exceptions, will return modulename.errorname, such as
arbpackage.mod.myerror
Args:
error: Except... | de57d629ba53d453ab3066c3f4024df42efef11e | 632,197 |
import re
def get_host(email: str) -> str:
""" Get host from email
Arguments:
email (str): email to get host from
Returns:
str
"""
try:
host = re.findall(r"@(.*)$", email)[0]
if "." not in host:
host = "invalid"
except IndexError:... | 4f50704247118d19584c1b4b58ef4f8c085a86e3 | 632,198 |
def is_s3_path(path: str) -> bool:
"""Returns True if the path points to a S3 bucket, False otherwise."""
return path.startswith("s3://") | e559486b24e357ce27931456763848e9b7505b1f | 632,199 |
def slug_is_available(slug, job_category_model, job_category=None):
"""
Determine whether the given slug is available for use and not a duplicate
"""
JobCategory = job_category_model
siblings = JobCategory.objects.all()
if job_category:
siblings = siblings.exclude(id=job_category.id)
... | 20d8014dc8a6574bc0253eae7f22ddb42edb2998 | 632,200 |
def st_fleet_details(fleet, user):
"""
Details of a sitetracker fleet.
"""
return {'fleet': fleet, 'user': user} | cb66b728b18de0bb26fce6fb7321e9f3638b3b60 | 632,201 |
import json
def parse_env(environment_string: str) -> str:
"""
Parses an environment string as passed from the command line and ensures that it is a JSON
object with the appropriate structure (i.e. a map of strings to strings)
Args:
environment_string
JSON string denoting a mapping of env... | 3fc588c23007a3df7b1f52e3ed23efdd970437f1 | 632,203 |
def toint(number):
"""
Helper to return rounded int for a float or just the int it self.
"""
if isinstance(number, float):
number = round(number, 0)
return int(number) | 23f07ba85a5a674330c006187c7d6f01aa94716b | 632,205 |
def get_asset_url(release, quiet=False):
"""
get the assets url from the release information
:return: the assets_url
"""
return release["assets_url"] | 38815dce5158c4980e57a4cf7aa7a386e371e57f | 632,206 |
import torch
def make_pad_mask(seq_lens):
"""Make mask for padding.
Args:
seq_lens (IntTensor): `[B]`
Returns:
mask (IntTensor): `[B, T]`
"""
bs = seq_lens.size(0)
max_time = seq_lens.max()
seq_range = torch.arange(0, max_time, dtype=torch.int32, device=seq_lens.device)
... | 10f264cf9578d1ef18d7073aad589a9b5ed575e8 | 632,209 |
def _data_range(data: str) -> bool:
""" Checks if a string data are a numbers in range. """
return True if data.find('-') != -1 else False | 16ba9bade3ec711c59e33f0410d6b48eda4963e6 | 632,212 |
from typing import Any
from typing import Tuple
import operator
def _ensure_index_tuple(x: Any) -> Tuple[int, ...]:
"""Convert x to a tuple of indices."""
try:
return (operator.index(x),)
except TypeError:
return tuple(map(operator.index, x)) | 3c328971d7110f826f377aee008f85027caa28f8 | 632,213 |
import string
def clean_punctuation(texts):
"""Remove punctuation from strings"""
cleaned_tokens = [[word.strip(string.punctuation) for word in sentence] for sentence in texts]
return cleaned_tokens | 06f76dd62ae047b5379b9047f737673bc52c63e8 | 632,216 |
def common_chars(seq, k):
""" Returns the set of characters that appear more than k times in
the input string, along with their number of occurrences.
Example:
>>> common_chars("cat in a hat", 2)
{("a", 3), (" ", 3)}
"""
chars = set()
for i in range(len(seq)):
if seq.count(seq[... | 9a2fc7cfae84ae06abc54526e6a9b020ba238367 | 632,218 |
def extract_data_key(returned_data):
"""
Build and return dict containing measurement 'name', description ('text')
and unit of measurement.
"""
return {i["name"]: {"text": i["$"], "units": i["units"]} for i in returned_data["SiteRep"]["Wx"]["Param"]} | 7c9ba5e1d4f0c6f416f5f1f370ea52bc68b3e1cf | 632,220 |
def _gen_index_list_to_fifty_mbyte_increment(file_buffer_list):
"""Create a list of indexes marking the ~50 MByte increments of cumulative size
of the file_buffers provided by the streamlit.file_uploader
Parameters
----------
file_buffer_list : ``list``
list of file_buffers (derived from io... | 35ed1ce2dfe81e216d87b66b77f078386b8404a4 | 632,221 |
def get(execution_id, client):
"""Request a execution with certain ID."""
return client.get_execution(str(execution_id)) | 723cfef7b67be2e3307ec4f7313e2381446ac1df | 632,223 |
def push_stream(cache, user_id, stream):
"""
Push a stream onto the stream stack in cache.
:param cache: werkzeug BasicCache-like object
:param user_id: id of user, used as key in cache
:param stream: stream object to push onto stack
:return: True on successful update,
False if fa... | ff2213edf1f0ee65edd73e4318eb6bc9a64700d7 | 632,228 |
from typing import Tuple
import re
def format_header(header: str) -> Tuple[str, int, str]:
"""Calculates the level of the header, removes leading and trailing whitespaces and creates the markdown-link.
:param header: header line from the markdown file
:return: a tuple consisting of the cleaned header, th... | 7dc52247d4c9702d03f402634ef615a359084373 | 632,231 |
def load_features_list(input_path):
"""
Reads in a file of distinct feature names line-by-line and returns
these features as a list. Each feature name in the file must occur
on a separate line.
Parameters
----------
input_path : str
Path to the features file. Each feature in the inp... | df36db1f537d407d2769f70dc4e143542fccb363 | 632,232 |
def all_bases_valid(seq):
"""Confirm that the sequence contains only bases"""
valid_bases = ['a', 'A', 'c', 'C', 'g', 'G', 't', 'T', 'N']
for base in seq:
if base not in valid_bases:
return False
return True | ff04072d7280d1f09e11d6c0f5537861a5cb38e7 | 632,234 |
import six
def to_float(x):
"""Convert an object to a float, unless it is None
Examples:
>>> print(to_float(12.3))
12.3
>>> print(to_float('12.3'))
12.3
>>> print(to_float(None))
None
"""
if isinstance(x, six.string_types) and x.lower() == 'none':
x = None
retu... | 4ac05529e0eb733c3d0901896e87e9f6a5fd4915 | 632,239 |
import functools
def len_gen(gen):
"""return length of a generator.
built-in len() does not work on generators.
Note: like iterators, generators can only iter once, so after running
len_gen() on it, you can't iter over it again.
"""
return functools.reduce(lambda x, y: x + 1, gen, 0) | 85633117872a3df2d2baa6ea0bbdd80ea8b69a22 | 632,241 |
def matrix_transpose(matrix: list) -> list:
"""
Compute the transpose of a matrix
"""
transpose: list = []
for row in range(len(matrix[1])):
column = []
for col in range(len(matrix)):
column.append(matrix[col][row])
transpose.append(column)
return transpose | bd6b3c6befb3efb488ad5f4ec33d181042e35574 | 632,242 |
import time
def my_decorator(fn):
"""my_decorator is a custom decorator that wraps any function
and prints on stdout the time for execution.
"""
def wrapper_function(*args, **kwargs):
start_time = time.time()
# invoking the wrapped function and getting the return value
value =... | a4f09253d4230403a69e05dc50435c3469701a51 | 632,244 |
def strtobool (val, yesvals = ["yes", "y"], novals = ["no", "n"]):
"""Convert a string representation of truth to true (1) or false (0).
Raises ValueError if 'val' is anything else."""
val = val.lower()
if val in yesvals:
return 1
elif val in novals:
return 0
else:
raise ... | a273f56761f9fd675668408f629051ea11cf8a42 | 632,245 |
def title_is_in_row(title_search_string, title_row):
"""Returns true if the target title in the passed row."""
return title_search_string.lower() in title_row.lower() | baf5e0e57cc90907b5d8d8ee44435245ee58eacd | 632,247 |
from typing import Iterable
def _is_iterable(value):
"""
Check whether the value is an iterable (excludes strings).
*value* is the value to check,
Returns whether *value* is a iterable (:class:`bool`).
"""
return isinstance(value, Iterable) and not isinstance(value, (str, bytes)) | 45b3bbfb142738e132d47d649fe7340e16480fea | 632,250 |
import tarfile
def scan_gz(filepath):
""" Scan a .tar.gz file. """
return tarfile.open(filepath, 'r:gz').getnames() | 547dc0a5e0301f1a198823a4ca6c770efa8f2309 | 632,251 |
def printAngle(angle, shift, molecule, alchemicalTransformation):
"""Generate angle line
Parameters
----------
angle : Angle Object
Angle Object
shift : int
Shift produced by structural dummy atoms
molecule : molecule object
Molecule object
alchemicalTransformation :... | 0e4d20acce1a7f8abbd2efee07d319df2955a814 | 632,252 |
def label_case(snake_case):
"""Specialized helper function to replace underscore with spaces and capitalize first letter of string, but keep WMR and WMQ capitalized
Args:
snake_case (str): String written in snake case to be reformatted.
Returns:
str: The reformatted string.
... | 54bce935de444c1fdc99ce22dc3809f5cd38e0d4 | 632,253 |
def ComptonRotationAngle(azimuth):
"""Reference frame rotation so that MuellerMatrixCompton holds
Args:
azimuth(num): scattering azimuth (degree)
Returns:
angle: rotation of the axes in degrees
"""
# First component axis perpendicular to the scattering plane
return azimuth - 90 | 522b9b5acb8b6d83f09a88c456b4cd0dc8318ce8 | 632,258 |
def get_user_pool_domain(prefix, region):
"""Return a user pool domain name based on the prefix received and region.
Args:
prefix (str): The domain prefix for the domain
region (str): The region in which the pool resides
"""
return '%s.auth.%s.amazoncognito.com' % (prefix, region) | c43cb15bb960281f6ffbe5a4823471191ac01b2f | 632,260 |
def is_vcf_chrom_header(line):
"""
Returns ``True`` if ``line`` is a VCF chrom-definition header line, ``False`` otherwise.
:param line: line from VCF file
:return: ``bool``
"""
if line.startswith('##contig='):
return True
else:
return False | 7b519b73a8bd978595c859bb19fb5b6f6f6b3849 | 632,263 |
def get_top_users_and_orgs(user_data_df, top_repos_df):
"""Gets the top 25 Github Users and top 25 Organizations.
Note: Top 25 Users are determined based on total followers.
Top 25 Organizations are determined based on total stars
for all of an organizations repos.
Parameters
-----... | 285885028d35574475c9bbf0a0d2c6f98feadcb0 | 632,264 |
def check_dtype(**kwds):
""" Check a dtype for h5py special type "hint" information. Only one
keyword may be given.
vlen = dtype
If the dtype represents an HDF5 vlen, returns the Python base class.
Currently only builting string vlens (str) are supported. Returns
None if the dtype... | 5cc43f94209c9a2ed4c31cbc1c5cf432725dfeb8 | 632,268 |
from typing import Callable
from typing import Tuple
def recurse_tsv(contents: str, fnc: Callable, delim: str = "\t") -> Tuple[str, bool]:
"""Recurse with a callback function in TSV contents.
Just visit each line and look at values only.
Args:
contents:
TSV/CSV contents string
... | ecf7072bdcd1f8679c8046c4cf641e2e91a31686 | 632,269 |
def Step(v, threshold=0, act_value=1, inact_value=0):
"""
Step function where the threshold,
activated and inactivated value can be defined.
"""
return act_value if v > threshold else inact_value | e4b90c902a89e1bdab47ec761e704a2cae2789dc | 632,270 |
def _format_result(counts, cl_reg_index, cl_reg_nbits):
"""Format the result bit string.
This formats the result bit strings such that spaces are inserted
at register divisions.
Args:
counts (dict): dictionary of counts e.g. {'1111': 1000, '0000':5}
cl_reg_index (list): starting bit in... | 7dffaa93f8e84ac1ebf26a90e859a92c059102f2 | 632,272 |
def one_is_not_none(*args) -> bool:
"""
Return True if exactly one arg is not None.
"""
return sum([arg is not None for arg in args]) == 1 | 2d5d462516c44c1347be0a2b08f5d5ead1a68884 | 632,273 |
def calculate(action, a, b):
"""
Calculate the result of the action and the two numbers.
"""
print(f'{action}ing a = {a} and b = {b}')
if action == 'add':
return a + b
elif action == 'subtract':
return a - b
elif action == 'multiply':
return a * b
elif action =... | f6f8f24fbc7df462d6fefc5793c3e26956c5f1e0 | 632,274 |
from typing import Iterable
def any_not_none(iterable: Iterable) -> bool:
"""
Verify if any of the elements of the iterable is not None.
The default behaviour of the builtin any function checks the value
with `if element` and causes the values like zero (0) to be
treated as Falsy values. This func... | 5b93147db9f78eaa8d2b9e9060e6a5283c2ff201 | 632,281 |
def average_overlap(similarity_fn, samples, *ignore_params):
"""Returns the arithmetic mean of each candidate sentence in the samples
Args:
similarity_fn (function): similarity function used to compute the overlap
samples (list of lists): tokenized version of the translated sentences
*i... | f5bbe73ae1f4400378612f6670782f3751906240 | 632,283 |
def to_primitive(rho, rhou, rhov, ener, gamma=1.4):
"""Converts conservative variables to primitive variables rho, u, v, and p."""
u = rhou / rho
v = rhov / rho
p = (gamma - 1.0) * (ener - 0.5 * rho * (u**2 + v**2))
return rho, u, v, p | f45ffb914b69bb57d817a5b2a541299ea15fa666 | 632,284 |
import torch
def torch_eye(n, m=None, out=None):
"""
Like `torch.eye()`, but works with cuda tensors.
"""
if m is None:
m = n
try:
return torch.eye(n, m, out=out)
except TypeError:
# Only catch errors due to torch.eye() not being available for cuda tensors.
modu... | 9ba8ca767ea4bc60dee5ed3b35d4eb82afca609b | 632,288 |
def calculations_rain_module(basin, rain_intensity, timestep):
"""
Calculates the volume of rain falling on a basin during 1 timestep.
:param basin: Basin in which the rain is falling
:param rain_intensity: amount of rain falling per hour [mm/hour]
:param timestep: amount of seconds per timestep
... | ed894972f08024bf3913ec3f933fbb07b95b4fca | 632,292 |
def linear10(value):
"""Convert dB value to linear units (power-like)."""
return 10 ** (value / 10) | fbc4c70c0dd3628ca854fa90bb2056076579d846 | 632,293 |
from pathlib import Path
def _set_dir_iol(dir_in, dir_out, dir_log=None):
""" Set directory name for input, output, and logs.
"""
dir_in = Path(dir_in)
dir_out = Path(dir_out)
if dir_log is None:
dir_log = dir_out.parent
else:
dir_log = Path(dir_log)
return dir_in, dir_out,... | 0404443da3f58342e065a169c5c8f39aeea59754 | 632,294 |
import hashlib
def encode_password(string):
"""
Encodes a password using SHA-256 algorithm.
"""
# Converts the string into bytes
encoded_string = string.encode()
# Create the SHA-256 object
result = hashlib.sha256(encoded_string)
# Get the hexadecimal format of the encoded data
hex... | 33b982d17e59933dbc63711f213c7d72a85b22b0 | 632,296 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.