content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def knapsack_dp(val, wt, wt_cap):
"""0-1 Knapsack Problem by bottom-up dynamic programming.
Time complexity: O(nC), where
- n is the number of items, and
- C is the weight capacity.
Space complexity: O(nC).
"""
n = len(wt)
# Create tabular T of n x (wt_cap+1).
T = [[None] * (... | e8e0231dfff6a3f63f2650677cc86aa0193c05a4 | 101,423 |
def split_s3_path(s3_path):
"""Get a bucket name and object path from an 's3 path'.
An S3 path is one in which the object path is appended to the bucket name.
For example: my-music-bucket/path/to/file.mp3
S3 paths may also begin with the character sequence "S3://" to disambiguate
it from a local pa... | 209d69c66d9d795393007ffc46431874ffc56885 | 101,427 |
def get_files_from_response(response):
"""Returns a list of files from Slack API response
:param response: Slack API JSON response
:return: List of files
"""
return response.get('files', []) | f25bd83f1984f9bdd99ed8fb61dbb5889e0108fc | 101,428 |
import torch
from typing import Optional
def sentence_pattern(sent: torch.Tensor, pad_mask: Optional[torch.Tensor] = None):
"""
If sentence is
[[1, 2, 3, 2, 4, 5, 2],
[1, 2, 3, 4, 5, 0, 0]]
pattern will be
[[[1, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 1, 0, 0, 1],
[0, 0, ... | 2195b9976ace05981a2a36ad0284e2effd063b98 | 101,429 |
def read_file(filename: str):
"""
Read file and return content
:param filename: Filename to read (string)
:returns: file contents (string)
"""
with open(filename, "r") as file_object:
file_contents = file_object.read()
return file_contents | cce0b9f5478edb138239996b9496e04f7040905f | 101,430 |
def mouse_on_button(scaled_mouse, button_pos, button_size):
"""
Indique si le pointeur de la souris est sur le bouton.
Parameters
----------
scaled_mouse : int * int
Position du pointeur de la souris mise à l'échelle
button_pos : int * int
Position du bouton
button_size : in... | 136a16f4cbd323d51723353e517c4db61c0171a8 | 101,433 |
import pathlib
def get_basename(path: str) -> str:
"""Extract basename from given path ``path``."""
return pathlib.Path(path).name.replace('.py', '').replace('test_', '') | 96428bfa919d1fe21d690e141477773dbd221a76 | 101,436 |
from typing import Tuple
def get_tuples(val01: int, val02: int) -> Tuple[int, int]:
""" Constructs a tuple out of integers. """
return (val01, val02) | d1569786ec9a884baf1c8d8f34b591fe321fa631 | 101,437 |
def getWords(filename, length=None):
"""
Returns all the words of a given length from the given global dictionary file
"""
with open(filename) as f:
l = []
for words in f:
word = words.strip().lower()
if (length is None) or (length is not None and len(word) =... | 99092e3281cc8a4ce8588155ad6607288e82f162 | 101,438 |
from typing import List
from typing import Optional
from typing import Dict
def convert_sequences_to_polygons(sequences: List, height: Optional[int] = None, width: Optional[int] = None) -> Dict:
"""
Converts a list of polygons, encoded as a list of dictionaries of into a list of nd.arrays
of coordinates.
... | fb6203ebdee42cb2d59aef0bdda47224031a01a2 | 101,443 |
def broadcast(op, xs, ys):
"""Perform a binary operation `op` on elements of `xs` and `ys`. If `xs` or
`ys` has length 1, then it is repeated sufficiently many times to match the
length of the other.
Args:
op (function): Binary operation.
xs (sequence): First sequence.
ys (seque... | 59fb072f407b412029d14b553540350b1ac61bf0 | 101,444 |
def bellman_ford(g, src):
"""
Compute shortest-path distances from src to reachable vertices of g.
Graph g can be undirected or directed, but must be weighted (can be
negative) such that e.element() returns a numeric weight for each edge e.
If there is a negative-weight cycle, there is no unique sh... | 610a6777b88d322b916eec3fc09ff84e950f955c | 101,448 |
def get_high_score(empty_squares, scores):
"""
Returns high score for get_best_move function
"""
max_score = float("-inf")
for coord in empty_squares:
if scores[coord[0]][coord[1]] >= max_score:
max_score = scores[coord[0]][coord[1]]
return max_score | 53f0f3231b695bd516cfdab054e60984b301a700 | 101,449 |
from datetime import datetime
def get_years(months=0, refer=None):
"""
获取基准时月份增量的年月
:param:
* months: (int) 月份增量,正数为往后年月,整数为往前年月
* refer: (datetime obj) datetime 对象,或者有 month 和 year 属性的实例,默认为当前时间
:return:
* result: (string) 年月字符串
举例如下::
print('--- get_years demo ... | 1f9f1f45e124fb253c35843215408dca0b29b916 | 101,452 |
def get_types_distribution(articles):
"""
:param articles: PyMongo collection of articles
:return: Dictionary with article types as keys, and number of articles of
type as value
"""
cursor = articles.aggregate(
[{"$group": {"_id": "$doc_type", "count": {"$sum": 1}}}]
)
result = ... | a2ef3de905637feabdd44133239a4b49f1dbca34 | 101,453 |
from typing import Iterator
import warnings
def _read_next_tag(fp: Iterator[str]) -> bytes:
"""Read the next tag from the tag file.
Attempts to read the next item from the iterator (usually a text file) `fp`
for use as the printable final 18 bytes of a block tag. bootloader_hd
prints the last 18 bytes of al... | c57ebd60de8baa17b0615c9b6c31300433bf5118 | 101,459 |
import math
import random
def get_learning_rate(low, high):
""" Return LogUniform(low, high) learning rate. """
lr = math.exp(random.uniform(math.log(low), math.log(high)))
return lr | 19acb6f69fda438055c74ee6ae38872002833d76 | 101,460 |
import re
def normalize_font_style_declaration(value):
"""Make first part of font style declaration lowercase (case insensitive).
Lowercase first part of declaration. Only the font name is case sensitive.
The font name is at the end of the declaration and can be 'recognized'
by being preceded by a si... | 4ef81e6cf9c5d074ccc6378e2c60b1f3cb47fb80 | 101,465 |
def tomatrix(coeffs):
"""Form the quadratic form matrix (see equations 11 and 12 in paper)
"""
matrix = {}
for a in range(4):
matrix[a] = {}
for b in range(4):
matrix[a][b] = {}
c1 = 0.429043; c2 = 0.511664 ;
c3 = 0.743125 ; c4 = 0.886227 ; c5 = 0.247708 ;
for ... | 007e0e8e2ff10dc4a74c07b09cd48624a2e67f81 | 101,466 |
def submit_gcp_connector_sync_action(api, configuration, api_version, api_exception, gcp_connector_id):
""" Submits a synchronize action of a GCP connector.
:param api The Deep Security API exports.
:param configuration The configuration object to pass to the API client.
:param api_versi... | ac69abf5e01c889e1a8e233a5a3be396ce7c8776 | 101,468 |
def GetFullyQualifiedScopePrefix(scope):
"""Gets the fully qualified scope prefix.
Args:
scope: the Definition for the scope from which the type must be accessed.
Returns:
the fully qualified scope prefix string.
"""
scope_stack = scope.GetParentScopeStack() + [scope]
return '.'.join([s.name for s... | 3105dfc562a312296cfcd927a997c195aa580d82 | 101,470 |
def _toVersionTuple(versionString):
"""Split a version string like "10.5.0.2345" into a tuple (10, 5, 0, 2345).
"""
return tuple((int(part) if part.isdigit() else part)
for part in versionString.split(".")) | 6eba8bcca4dfeca386c6e4b65eb15d9fc7f2a054 | 101,473 |
import torch
def stack_as_batch(tensor: torch.Tensor, n_repeats=1, dim=0) -> torch.Tensor:
"""Inserts new dim dimension, and stacks tensor n times along that dimension"""
res = tensor.unsqueeze(dim)
repeats = [1] * res.ndim
repeats[dim] = n_repeats # repeat across target dimension
res = res.repeat(*repeats)
ret... | 3d65487dd23f38a74dec5d667dced427c3637bcd | 101,474 |
def split_path(path):
"""
Normalise GCSFS path string into bucket and key.
"""
if path.startswith('gs://'):
path = path[5:]
path = path.rstrip('/').lstrip('/')
if '/' not in path:
return path, ""
else:
return path.split('/', 1) | d4f1881b9d280f9a5bca003e69b017bf2f408e54 | 101,477 |
from datetime import datetime
def day_of_year(year:int,
month:int,
day:int)->int:
"""
Calculate day of year from a date
"""
doy = datetime(year, month, day).timetuple().tm_yday
return doy | adad28c69ee045ea139ab3e66c627aaa7cd5e37b | 101,480 |
import torch
def neigh_diff_standard(bmus: torch.Tensor, positions: torch.Tensor) -> torch.Tensor:
"""
Positional difference function.
Computes index difference between Best Matching Units (`bmus`) and `positions`, where `positions`
are indices of elements inside the SOM grid.
Parameters
---... | a32470cb8b7ae439d745334cbea4699abb98377c | 101,488 |
def underscore_filter(s):
"""Change spaces to underscores and make lowercase
"""
return "_".join(s.lower().split(' ')) | 18a08b375991dbf7e25bf345c1d70cef7faeaf5f | 101,495 |
def get_pr_list(script, project_key, repo_slug, state="OPEN", target_branch=None):
"""
Gets the list of PRs
:param script: a TestScript instance
:type script: TestScript
:param project_key: The project key
:type project_key: str
:param repo_slug: The repo slug
:type repo_slug: str
:p... | 5932dbc1957384c1739756a9e78c0777084ce930 | 101,497 |
def file_matches(s, l):
"""
:param s: filename
:param l: list of filepaths
:return: list of matching filepaths
"""
return list(filter(lambda x: x.endswith(s), l)) | 105a02001a9cfb3736cd53594e9d776cec4d813e | 101,499 |
from typing import Any
def check_is_editing_something(match: Any) -> bool:
"""Checks if an editing match is actually going to do editing. It is
possible for an edit regex to match without doing any editing because each
editing field is optional. For example, 'edit issue "BOTS-13"' would pass
but would... | 10b009417fb2945a7db5a2756fea8c6472b31f4d | 101,500 |
def calibrate_2band(instr1, instr2, airmass1, airmass2, coeff1, coeff2,
zero_key='zero', color_key='color', extinct_key='extinction'):
"""
This solves the set of equations:
i_0 = i + A_i + C_i(i-z) + k_i X
z_0 = z + A_z + C_z(z-i) + k_z X
where i_0 and z_0 are the instrumental magnit... | df3d586646098b0c723032406a5ffbea8df11eb9 | 101,504 |
import json
def json_to_jsonlines(json_file):
"""Naive Implentation for json to jsonlines.
Args:
json_file: A string, the file name of the json file.
Returns:
The input json file as new line delimited json.
"""
with open(json_file) as f:
data = json.load(f)
return '\n'.join([json.dumps(d) for... | f9f664f3539a29e4337d396964057aea032b1b96 | 101,510 |
def feuler(f, t, y, dt):
"""
Forward-Euler simplest possible ODE solver - 1 step.
:param f: function defining ODE dy/dt = f(t,y), two arguments
:param t: time
:param y: solution at t
:param dt: step size
:return: approximation of y at t+dt.
"""
return y + dt * f(t, y) | 6172855218859935a6adf58baa7cb94b4e7cd201 | 101,516 |
def _query_set_limit(query: str, limit: int) -> str:
"""
Add limit to given query. If the query has limit, changes it.
Args:
query: the original query
limit: new limit value, if the value is negative return the original query.
Returns: query with limit parameters
"""
if limit < 0... | e91bf2e69ea849c1da16f69b5afb5db9272e1f77 | 101,529 |
import hashlib
def get_hash_string(enc_model):
"""
Encode model name using md5 hashing.
Parameters
----------
enc_model: str
Returns
-------
str:
return encoded model name
"""
md5str = hashlib.md5(enc_model)
return md5str | 31c794043dfa8ecc4f3ea3f44567249f48179587 | 101,531 |
def unique(dataset, n_threads, return_counts=False):
""" Find unique values in dataset.
Args:
dataset (z5py.Dataset)
n_threads (int): number of threads
return_counts (bool): return counts of unique values (default: False)
"""
dtype = dataset.dtype
if return_counts:
... | ef0720c1582f451c71c5f2aaea34671387e99282 | 101,533 |
import random
def rabinMiller(num: int) -> bool:
"""Rabin-Miller primality test
Uses the `Rabin-Miller`_ primality test to check if a given number is prime.
Args:
num: Number to check if prime.
Returns:
True if num is prime, False otherwise.
Note:
* The Rabin-Miller pr... | 99bd54a171e4cfd5ce1de79c29f3bf9d8e292c9f | 101,534 |
def flatten(xs):
"""
Flatten any recursive list or tuple into a single list.
For instance:
- `flatten(x) => [x]`
- `flatten([x]) => [x]`
- `flatten([x, [y], [[z]]]) => `[x, y, z]`
"""
if isinstance(xs, (list, tuple)):
return [y for ys in [flatten(x) for x in xs] for y in ys]
return [xs] | f405fe2af3dcc970afea1cf3d18e6ec348544d84 | 101,536 |
def getOffsetLength(filename, line_number, line_count):
"""
Calculates the field offset and length based on line number and count.
"""
offset = 0
length = 0
with open(filename, 'r') as f:
for line in f:
if line_number > 1:
offset += len(line)
line_number -= 1
elif line_count ... | b69a10cd08b6aaf33f6cd2c036bd427dc1b48d7d | 101,541 |
import json
def update_error_message(chart_data_json_str, acq_state, hat_selection,
active_channels):
"""
A callback function to display error messages.
Args:
chart_data_json_str (str): A string representation of a JSON object
containing the current chart data... | 640c1cf8ecfdb082174b99c4384267df1cc39fda | 101,542 |
def select_points_in_frustum(points_2d, x1, y1, x2, y2):
"""
Select points in a 2D frustum parametrized by x1, y1, x2, y2 in image coordinates
:param points_2d: point cloud projected into 2D
:param points_3d: point cloud
:param x1: left bound
:param y1: upper bound
... | 40d8b31d59ae539a64e69c76f1f0ac99fcaf10f5 | 101,545 |
import functools
import traceback
def print_exc(function):
"""
A decorator that wraps the passed in function and prints any exceptions.
"""
@functools.wraps(function)
def wrapper(*args, **kwargs):
try:
return function(*args, **kwargs)
except Exception:
trace... | 51f08aa4e8448686b3f11c8ecb651d4f61b81d1f | 101,546 |
def perfect_square_binary_search(n: int) -> bool:
"""
Check if a number is perfect square using binary search.
Time complexity : O(Log(n))
Space complexity: O(1)
>>> perfect_square_binary_search(9)
True
>>> perfect_square_binary_search(16)
True
>>> perfect_square_binary_search(1)
... | 0bd73c991499be94160a5972c0b5233ae811bc72 | 101,549 |
def cleanup_list(l):
"""Fixes a list so that comma separated items are put as individual items.
So that "--reviewers joe@c,john@c --reviewers joa@c" results in
options.reviewers == sorted(['joe@c', 'john@c', 'joa@c']).
"""
items = sum((i.split(',') for i in l), [])
stripped_items = (i.strip() for i in item... | 299067c1783eee411bd09e8db61e2826ff87415f | 101,550 |
from typing import List
def find_all(substring: str, string: str) -> List[int]:
"""
Find all occurrences of substring in string
"""
tmp = string
offset = 0
occurrences = []
while tmp.find(substring) != -1:
occurrences.append(tmp.find(substring) + offset)
offset += tmp.f... | df9ce297448df522beed8cf218a1d0f2bb03c4b6 | 101,552 |
def from_maybe(default, maybe_val):
"""Takes a maybe_value and a default,
if the maybe_value is nothing returns the default,
else returns the value."""
try:
return maybe_val.value
except ValueError:
return default | 803671a411b05c79ad5f3e7764ebffdcaeb0511c | 101,555 |
def find_biomass_reaction(
model, biomass_string=["Biomass", "BIOMASS", "biomass"]
):
"""
Identifies the biomass reaction(s) in a metabolic model.
Parameters
----------
model : cobra.Model
Metabolic model.
biomass_string : str or list
String denoting at least a part of the n... | bbc9232462fb3850be1208e324ab147aa14be086 | 101,557 |
def find_carriers(rules, inner_color):
"""Return a list of bag colors that contain the bag of the given inner color"""
valid_bags = []
for outer, inners in rules.items():
inners_list = [i[1] for i in inners]
if inner_color in inners_list:
valid_bags.append(outer)
return ... | 3a65444d89e1b9088afb262c9e7fac3d5448714e | 101,558 |
def syntax_error_transformer(lines):
"""Transformer that throws SyntaxError if 'syntaxerror' is in the code."""
for line in lines:
pos = line.find('syntaxerror')
if pos >= 0:
e = SyntaxError('input contains "syntaxerror"')
e.text = line
e.offset = pos + 1
... | ca197906bd9a509627d1b2bb66c7b8aafaa42cb0 | 101,559 |
import hashlib
def hasher(string, size=8):
"""Simple function to generate a SHA1 hash of a string.
Parameters:
- string : string or bytes
The string to be hashed.
- size : int
Size of the output hash string.
Returns:
- h : string
Hash string tr... | a591ae9da62acd7b958b4fd407a7f31bcda90db1 | 101,563 |
def residuals(X, y, beta):
"""Calculate the residuals of a linear regression
Arguments
---------
X: np.array
Design matrix of shape (N, 2), as created by ``~ctapipe.fitting.design_matrix``
y: np.array
y values
beta: np.array
Parameter vector of the linear regression
... | 8a9c91f23d7e870e41dde314bc9e03ff194e4ed7 | 101,564 |
def searchForm(
buttonText="",
span=2,
inlineHelpText=False,
blockHelpText=False,
focusedInputText=False,
htmlId=False):
"""
*Generate a search-form - TBS style*
**Key Arguments:**
- ``buttonText`` -- the button text
- ``span`` -- column span
... | 5a980390e5742bb31fa280750b3d52f485f632b8 | 101,565 |
def exec_script(scriptpath, stdout=None, stderr=None, mock=False):
""" This function must return a command line executable as a string.
Parameters
----------
scriptpath: str
Path to the script to be executed
stdout: str
Path to file to which stdout is to be piped
... | 30e9ee1947572102b5afc5481a24a86b7ece2fc3 | 101,571 |
def _2str(s):
"""Convert s to a string. Return '.' if s is None or an empty string."""
return '.' if s is None or str(s) == '' else str(s) | f2a8f016fc6d2528019c0c99c7f22435e1c029f0 | 101,573 |
def read_file_to_string(filename):
"""
Given a filename, opens the file and returns the contents as a string.
"""
f = open(filename, 'r')
file_str = ""
for line in f:
file_str = "{0}{1}".format(file_str, line)
f.close()
return file_str | b49fb0146bc35f880564090bca22820f99162d3c | 101,579 |
from functools import reduce
def count_leaf_nodes(node):
"""Count the number of leaf nodes in a tree of nested dictionaries."""
if not isinstance(node, dict):
return 1
else:
return reduce(lambda x, y: x + y,
[count_leaf_nodes(node) for node in node.values()], 0) | 8716363896cdc54b25a98ce50abdb8f0096a1f94 | 101,583 |
def count_idf(questions):
"""
统计逆文档频率idf
:param questions: list, 输入语料, 字级别的例子:[['我', '爱', '你'], ['爱', '护', '士']]
:return: dict, 返回逆文档频率, 形式:{'我':1, '爱':2}
"""
idf_char = {}
for question in questions:
question_set = set(question) # 在句子中,重复的只计数一次
for char in question_set:
... | bf54ea7437af318645e552524cd8de34a6d2456d | 101,587 |
import torch
def compute_accuracy(output, target):
"""
Calculates the classification accuracy.
:param target: Tensor of correct labels of size [batch_size, numClasses]
:param output: Tensor of model predictions.
It should have the same dimensions as target
:return: prediction accuracy... | 18edcad92bf681e3edd9a625991a1e4bd813a585 | 101,589 |
def words_to_substitute(match):
"""Ask the user for the words to substitute to placeholders"""
words = list()
for _, name in match:
article = 'an' if name[0].lower() in 'aeiou' else 'a'
words.append(input(f'Give me {article} {name}: '))
return words | 5fba5a4243666f9cb6ce07a2e23cc11d946e165a | 101,590 |
def _join_package_name(ns, name):
"""
Returns a app-name in the 'namespace/name' format.
"""
return "%s/%s" % (ns, name) | d48cdeba7906ecc4829a1b6fb2986ddea47a7bd6 | 101,592 |
def get_first_major_location(data):
"""Returns the best location in the article to start at when an article is entered"""
length_sum = 0
for segment in data['text_segments']:
length_sum+=len(segment[2])
if(length_sum>1000):
return segment[1]
return 1000 | c8c4d1cad579b4bf8d6df7dec7a3fc35558be04f | 101,593 |
def check_if_variable_used(methodNode, name):
"""Check if a variable with the given name is assigned in the given method"""
for assignment in methodNode.find_all('assignment'):
# if assignment has name node on the left side, compare the name of the variable with the given name
if assignment.tar... | a56869d678af428fb4b216441f384144c78431c6 | 101,598 |
def diff_set(before, after, create_replaced=True):
"""Compare sets to get additions, removals and replacements
Return 3 sets:
added -- objects present in second set, but not present in first set
removed -- objects present in first set, but not present in second set
replaced -- objects that have the... | f61fab8c964c768c57f574061c5e0226de9f2771 | 101,600 |
def file_name(n: int, koncnica: str) -> str:
"""Vrne niz z imenom datoteke za n-ti EGMO s podano končnico."""
return f"egmo{n}.{koncnica}" | 1caf942c40c6a26feabb0050f16b08ddd121216e | 101,601 |
import math
def error_probability_to_qv(error_probability, cap=93):
"""
Convert an error probability to a phred-scaled QV.
"""
if error_probability==0:
return cap
else:
return min(cap, int(round(-10*math.log10(error_probability)))) | 71f0b178f5348f4757e562b1c9ba94eafd179999 | 101,603 |
def make_fuel_mat_str(values):
"""Make a string for fuel material cards in MCNP format.
This function takes burnup material inventory data from the main 'values'
dictionary and makes fuel material cards as a string in MCNP format.
Arguments:
values (dict)[-]: Main dictionary storing processed ... | ec6d71525ca1127ddd72e9714f3a7f01c343dd92 | 101,605 |
def multiple_help_text(item):
"""Return help text for option with multiple=True."""
return f" Use the option multiple times to specify more than one {item} [multiple]" | 8d0591451231af16892cf54cf5863958abb16767 | 101,607 |
def get_categorized_testlist(alltests, ucat):
""" Sort the master test list into categories. """
testcases = dict()
for category in ucat:
testcases[category] = list(filter(lambda x: category in x['category'], alltests))
return(testcases) | d94a0a65e36fdf52f24873e6b44c0f9ab93b4838 | 101,609 |
import pickle
def unpickle(file):
"""
Unpickles datafile
"""
with open(file, 'rb') as f:
data_dict= pickle.load(f, encoding="bytes")
return data_dict | 7bdf27d9d423d0dde07cbf493b39e008053b851f | 101,612 |
def _safe_recv(sock, count):
"""
Wraps sock.recv() handling short reads.
:param sock: a socket to recv() from
:param count: the number of bytes to ask for
:return: a byte string with those bytes
"""
result = sock.recv(count)
bytes_read = len(result)
if 0 < bytes_read < count:
... | 890c13bc27e7b0b14c51fd40dd253e51809b6de3 | 101,613 |
def remove_typedefs(signature: str) -> str:
"""
Strips typedef info from a function signature
:param signature:
function signature
:return:
string that can be used to construct function calls with the same
variable names and ordering as in the function signature
"""
# r... | 7aaf66f6a5e5e8047b61a61b0e6e7f195600695c | 101,616 |
def interpolateRecallPoints(recallPoints):
"""
Get a list of interpolated precision and recall. I.e., transforms the list
of recall points in a list of recall points with 11 points.
Does't change the recallPoints list.
param recallPoints: a list of recall points in pairs (precision, recall),
t... | 4fa212d5ecadf0d1e83fd6cbd905c9aaf3cdd77b | 101,618 |
def to_user_facing_code(code):
"""Returns a user-facing code given a raw code (e.g., abcdefghij)."""
return '{}-{}-{}'.format(code[:3], code[3:6], code[6:]) | efa31e4c991a493cfe1c2f470e33262cd3bb5b51 | 101,621 |
def digit_sum(num: int) -> int:
"""Calculate the sum of a number's digits."""
total = 0
while num:
total, num = total + num % 10, num // 10
return total | bb4658e0406b3324fedafb31ff44c557e05fcbb0 | 101,624 |
import hashlib
def valid_proof(last_proof, proof, last_hash, difficulty):
"""
Validates the Proof
:param last_proof: <int> Previous Proof
:param proof: <int> Current Proof
:param last_hash: <str> The hash of the Previous Block
:return: <bool> True if correct, False if not.
"""
guess = f'{last_proof}{proof}{... | 3667e7171a65f088974f954de37c0b6e11048412 | 101,627 |
def convert_bc_stage_text(bc_stage: str) -> str:
"""
function that converts bc stage.
:param bc_stage: the string name for business cases that it kept in the master
:return: standard/shorter string name
"""
if bc_stage == "Strategic Outline Case":
return "SOBC"
elif bc_stage == "Out... | fab9950d9c7df01f9731aecf6cae7ca4621c35a7 | 101,630 |
def ref_tuple_to_str(key, val):
"""Tuple like ('a', 'b') to string like 'a:b'."""
return '%s:%s' % (key, val) | cdb8d713583e4c467f5bf2df5b2568a7f079901a | 101,632 |
def has_token_in_position(node, token, pos):
"""Has the node the specified token in specified position
(indexed from 0)?
"""
tokens = list(node.get_tokens())
return tokens[pos].spelling == token | 63b0eb049cdd9f1881b40fc7acd9991910aa0381 | 101,637 |
import random
def sample_gamma(alpha, beta):
"""
Sample gamma variate for small alpha, using
transformation from Marsaglia&Tsang method
http://www.hongliangjie.com/2012/12/19/how-to-generate-gamma-random-variables/
"""
x = random.gammavariate(alpha + 1.0, beta)
return x * po... | 59012b46308634483f1034e7ba51a06f8a9e2cf0 | 101,644 |
def update_path(dct, path, update):
"""
Update a dict structure (e.g. JSON), using a path to specify what value to update.
The `path` specifies a hierarchy of (string) dictionary keys to traverse, separated by periods.
Suffixing a key with `[]` indicates the value of that key is an list, and should be ... | 5eab915b4fdc5b316b35d427aa999c3d763de116 | 101,646 |
def format_path_nodes(urls):
"""
Takes the content response from a neo4j REST API paths call (URLs to paths)
and returns a list of just the node ID's
"""
nodeIds = []
for url in urls:
nodeIds.append(url.split("/")[-1])
return nodeIds | cd00cd92b5b5c9e01c62fd6dac242f65924204da | 101,649 |
import torch
def load_to_cpu(filename):
"""Load torch object specifically to CPU"""
return torch.load(filename, map_location=lambda storage, loc: storage) | 9fcd1634cc2e838a33f4d6366f5220b6670853ed | 101,653 |
from typing import List
def get_object_structure(obj: dict) -> List[str]:
"""
Traverse through object structure and compose a list of property keys including nested one.
This list reflects object's structure with list of all obj property key
paths. In case if object is nested inside array we assume th... | 2be1faff3901a217e0f74f3fc9a08244b6ad68c1 | 101,656 |
import collections
def calculate_hints(guess: str, secret: str) -> tuple[int, ...]:
"""Compare a guess against a secret word and calculate a hint on how close the
guess word is to the secret word.
The hint will be comprised of the following:
- 2 - the guess <char> is in the secret word and in the... | 3187c98618ab7cbc94843e52c02f742ef995907f | 101,660 |
def has_data(group, dataset_name):
"""Check whether HDF5 group contains a non-empty dataset with given name.
Parameters
----------
group : :class:`h5py.Group` object
HDF5 group to query
dataset_name : string
Name of HDF5 dataset to query
Returns
-------
has_data : {True... | 705f3ca52a3591368292065009b112a7661f8975 | 101,666 |
from typing import Tuple
def _convert_twos_complement(obj: int) -> Tuple[int, str]:
""" Converts a negative integer to a twos complement binary string to the nearest octet
Args:
obj: Negative integer
Returns:
The required length in octets of the binary two's complement representation and
... | d88326976b78689004955daa6bcb98cbc0588934 | 101,667 |
def removeGame(gtitle: str) -> str:
"""Return a query to remove a given game from the database."""
return (f"DELETE FROM game "
f"WHERE title='{gtitle}';"
) | 589096681b70232cbd199f7b2f5bd4685418888d | 101,671 |
import torch
import math
def geometric_transform(pose_tensor,
similarity=False,
nonlinear=True,
as_matrix=False):
"""Converts pose tensor into an affine or similarity transform.
Args:
pose_tensor: [..., 6] tensor.
similarity ... | f31187a518129316450e10a760fdf18faac0b47b | 101,672 |
def noop(value, param=None):
"""A noop filter that always return its first argument and does nothing with
its second (optional) one.
Useful for testing out whitespace in filter arguments (see #19882)."""
return value | babd4941efdff8fa67df07a5dd3d86da210b91c2 | 101,677 |
def _theta(a, b):
"""Returns 1 if a >= b, 0 otherwise."""
return int(a >= b) | 2dd02cb2e7a316c6a3d851a5e476fe7bb89657d9 | 101,680 |
import math
def saturation_vapour_pressure(t):
"""
:param t: temperature [C]
:return: saturation vapour pressure
"""
return 0.6108 * math.exp((17.27 * t)/(t + 237.3)) | b628294d634a2b5741b1d0ac24afbd6ef7980fb4 | 101,681 |
def calcOutputLen(outputFormat, article_len, wrd):
"""calc length of the summary. wrd is the user-specified output length or ratio"""
if outputFormat == "word_count":
return int(wrd)
else:
return article_len * float(wrd) | 28b53afe4541169df5d72e5d1be57412454232b2 | 101,683 |
def convertToDateAndTime(seconds):
"""
Returns a string with hours, minutes and seconds
"""
hours=seconds//3600
minutes=(seconds%3600)//60
seconds=(seconds%60)
return str(hours)+" hrs, "+str(minutes)+" min, "+str(seconds)+" seconds" | 2ac418ec61fee7081f62a02ab9984121f43d7912 | 101,694 |
def GetForwardingArgs(local_port, remote_port, host_ip, port_forward):
"""Prepare the forwarding arguments to execute for devices that connect with
the host via ssh.
Args:
local_port: Port on the host.
remote_port: Port on the remote device.
host_ip: ip of the host.
port_forward: Direction of the... | dd82440b001c78624439b1d9cefc5c6c918aaf87 | 101,701 |
def constant_features(X, frac_constant_values = 0.90):
"""
Identifies features that have a large fraction of constant values.
Parameters
----------
X : pandas dataframe
A data set where each row is an observation and each column a feature.
frac_constant_values: float, ... | d27b4c5eabc2fe676c76217c2faba13765b6b742 | 101,702 |
def check_nans(df, verbose=True):
""" checks for NANs in a dataframe """
nans = df[df.isnull().any(axis=1)]
num = nans.shape[0]
print('{} nan rows'.format(num))
if verbose:
print('nan values are:')
print(nans.head())
return nans | 6159650235a9e4f578d22b38ec11066c3f5d7275 | 101,704 |
from typing import Any
def create_mapping(key: str, value: Any):
"""
Creates a mapping of a given key and value.
Parameters
----------
key : str
The key for the mapping.
value : Any
The value for the mapping.
Returns
-------
dict
A dictionary containing th... | c3b923ef2261a35d3e97db0ed25ae43961c6e54e | 101,705 |
from typing import List
from typing import Dict
def _gen_confirm(msg: str) -> List[Dict]:
""" For generating a confirmation prompt. """
return [
{
'type': 'confirm',
'message': msg,
'name': 'confirmation'
}
] | 400379ade3f3385407ba499f97dbe5b2172c42aa | 101,708 |
def polynomial(x, coef, b=0):
"""polynomial = aX² + bX + c + b"""
return coef[0] * x ** 2 + coef[1] * x + coef[2] + b | 21788e85831fcf1449cd8a31e43d2f92a160dcd8 | 101,715 |
def getEndJoints(jnt):
"""
Recurse through children and return all joints that have no joint children.
Args:
jnt (PyNode): A joint node
"""
result = []
children = jnt.listRelatives(children=True, typ='joint')
if not children:
result.append(jnt)
else:
for child in... | 7d24cdef7b9d8b4e31eda2a83ec52c022a91774e | 101,717 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.