content stringlengths 39 9.28k | sha1 stringlengths 40 40 | id int64 8 710k |
|---|---|---|
import math
def gcd(*args):
"""
Generalize math.gcd to take more than two inputs.
"""
items = list(args)
while len(items) > 1:
items.append(math.gcd(items.pop(), items.pop()))
return items[0] | c9d139b9a05d68e09ff7b0756167d92a0b1c2211 | 596,641 |
def signature(params, separator='/'):
"""Create a params str signature."""
def _signature(params, sig):
for key in params.keys():
sig.append(key)
if isinstance(params[key], dict):
_signature(params[key], sig)
my_list = list()
_signature(params, my_list)
... | 44470d1e4fed1a357cec888f6ec112e67f60a3a1 | 316,603 |
import json
def get_user_data(user_id, orgs=None, groups=None):
"""Get an example redis user object"""
if groups is None:
groups = [
{
"name": "organization_admin",
"permissions": [
{"name": "all", "code": "all"},
{"n... | 2af1b7daaa2acfd355e3d0535d62fa03ca07a783 | 352,792 |
def filter_number(data, target, number):
"""Filters the given data for the wanted number."""
return [x for x, y in zip(data, target) if y == number] | b2ef61e32e33084e45a3be19e6d39e2207885e78 | 419,997 |
def intersect_line_ray(lineSeg, raySeg):
""" Constructs a line from the start and end points of a given line
segment, and finds the intersection between that line and a ray
constructed from the start and end points of a given ray segment.
If there is no intersection (i.e. the ray goes in the oppo... | 365836039161666eb30d0051916dceb7260f3c19 | 90,062 |
def get_denominator(denominator: float | int) -> int:
"""
If denominator is a float or int, then return the integer value.
If denominator is a float, then round it to the nearest integer. If the
rounded value is 0, then return 1.
Parameters
----------
denominator : Union[float, int]
... | 95ba08743fd9b1a30ed246e39095666dcfc2494c | 326,939 |
def build_edge_topic_prefix(device_id: str, module_id: str) -> str:
"""
Helper function to build the prefix that is common to all topics.
:param str device_id: The device_id for the device or module.
:param str module_id: (optional) The module_id for the module. Set to `None` if build a prefix for a d... | 05fe493967b1064dc21c0f4280297a35102f55a1 | 107,534 |
import torch
def compute_angle(xyz, angle_list):
"""
Compute angles between atoms.
Args:
xyz (torch.Tensor): coordinates of the atoms.
angle_list (torch.LongTensor): directed indices
of sets of three atoms that are all in each
other's neighborhood.
Returns:
... | da689c38f891d582130a880ced7b6f5c9da3d62b | 295,262 |
def create_location_code(channel_obj):
"""
Get the location code given the components and channel number
:param channel_obj: Channel object
:type channel_obj: :class:`~mth5.metadata.Channel`
:return: 2 character location code
:rtype: string
"""
location_code = "{0}{1}".format(
... | bfee90668369d075690e72efc2eadec95c4ed2cf | 320,788 |
def alias(aliases):
"""Decorator for slashcommand aliases that will add the same command but with different names.
Parameters
----------
aliases: List[:class:`str`] | :class:`str`
The alias(es) for the command with wich the command can be invoked with
Usage:
.. code-block::
... | 95c20f61348dc043ced53f4e95fac0fb24ee117f | 641,732 |
from typing import Dict
from typing import Tuple
def extract_base_url_from_spec(spec: Dict) -> Tuple[str, Dict]:
"""Extract the server urls from the spec to be used when generating functions.
Args:
spec: The OpenAPI Spec dictionary to extract the urls from.
Returns:
A tuple of the first ... | ab434db79c5e3e76667668bedcde6af5054c6709 | 148,228 |
def seconds_to_time(seconds):
"""Return a nicely formatted time given the number of seconds."""
m, s = divmod(seconds, 60)
h, m = divmod(m, 60)
d, h = divmod(h, 24)
return "%d days, %02d hours, %02d minutes, %02d seconds" % (d, h, m, s) | bf87da51527af08f60b3425169af1f696ecc9020 | 14,605 |
def elementwise_within_bands(true_val, lower_val, upper_val):
"""Whether ``true_val`` is strictly between ``lower_val`` and ``upper_val``.
Parameters
----------
true_val : float
True value.
lower_val : float
Lower bound.
upper_val : float
Upper bound.
Returns
--... | 90f822eed76339446ec56836d0d80ee58a08219c | 394,180 |
def split(el, n):
"""
Split list of elements in n approx. equal parts for multiprocessing
Parameters
----------
el : list
List of elements to split
n : int
Number of lists to split input up into
Returns
-------
parts : Iterable
List of n lists of parts of th... | 1f4045ade61a3b80fbe0092b1e335bfc870a8d32 | 253,208 |
def name_to_number(name):
"""
Converts a string called name to an integer.
Otherwise, it sends an error message letting you know that
an invalid choice was made.
"""
if name == "rock":
return 0
elif name == "Spock":
return 1
elif name == "paper":
return 2
el... | a38fd44573cb6a5be9fe58a6b1859ae7a3a47849 | 430,845 |
def get_status(dev):
"""Get FPGA status"""
dev.write_raw('PL:ACTIVE?')
r = dev.read_raw()
assert len(r) == 1
return ord(r[0]) - ord('0') | b5ecbc32ff1da632742d6d32694eb63a9ab23bea | 534,109 |
def set_default_attr(obj, name, value):
"""Set the `name` attribute of `obj` to `value` if the attribute does not already exist
Parameters
----------
obj: Object
Object whose `name` attribute will be returned (after setting it to `value`, if necessary)
name: String
Name of the attri... | 651538a814dee5c3af69a99f1a97be0e49734d88 | 657,571 |
def delta(m, n):
"""Kronecker delta"""
if m == n:
val = 1
else:
val = 0
return val | d2586ff41a7f8cd743f061a4235fd31675636f93 | 300,537 |
def find_combos(length: int) -> int:
"""
In the data, there are no gaps of two, only gaps of one or three, between
numbers in the sorted list.
The rules are such that the number of combos are the same regardless
of the specific numbers involved--there are the same number of combos
for [0, 1, 2, ... | 8ff8d5c161508c9d55d24ddbcfa2f67f8e95fc5b | 620,115 |
def prod_cart(in_list_1: list, in_list_2: list) -> list:
"""
Compute the cartesian product of two list
:param in_list_1: the first list to be evaluated
:param in_list_2: the second list to be evaluated
:return: the prodotto cartesiano result as [[x,y],..]
"""
_list = []
for element_1 in ... | 9fdbfc558f5ec3b11c78535b9125e0a1c293035e | 1,727 |
import torch
def select_class(X: torch.Tensor, y: torch.Tensor, k: int):
"""
Select all vector examples from the training set matrix X that correspond to the class k
:param X: a Float matrix of size (N, d), where d is the vector dimension
:param y: a Long vector of class labels
:param k: the class... | 04dc6729da8fb23f44eaca0ed3bfe3a0dfffef77 | 223,560 |
def calc_map_dims(x_size, y_size, mp_size, mp_dpi):
"""
Calculate output map size.
:param x_size: <int or float> Image x dimension
:param y_size: <int or float> Image y dimension
:param mp_size: <int> Percent of image space of which the map will occupy
:param mp_dpi: <int> Map density, as dots ... | 6ba3d1299097b3247c2527a321b1924e58f9ac85 | 587,339 |
def inter_cluster_variance(clusters, graph):
"""
The inter cluster variance, or the within-cluster sum of squares returns for all given clusters
the sum of squared distances of each sample within that cluster to the clusters centroid.
The sum of those squared distances is returned. For distance calculat... | 42bef8a0863baaa64f9dde64bde3b4890b145000 | 518,558 |
def runge_kutta4(t0, dt, tf, x0, f):
"""
Implements the Runge Kutta 4 algorithm for numerically integrating the solution of a system of first order
differential equations.
:param t0: Initial time
:param dt: Fixed time step
:param tf: Final time
:param x0: Initial state; NOTE: must be numpy a... | 2d6445e123e615f70f83b2a215a7706323ac6ffb | 221,849 |
def expand_series(ser, columns):
"""
Helper function to quickly expand a series to a dataframe with according
column axis and every single column being the equal to the given series.
"""
return ser.to_frame(columns[0]).reindex(columns=columns).ffill(axis=1) | e86956f5a32cb44066361846a0e602d53cfb241b | 572,901 |
from typing import Union
import torch
from typing import Any
def squeeze(_list:Union[list, tuple, torch.Tensor, Any], hard=False):
"""If list only has 1 element, returns that element, else returns original
list.
:param hard: If True, then if list/tuple, filters out None, and takes the first
element out even ... | 7c2acb01db65106b8b3cef116b7cd799517e4498 | 487,290 |
def jaccard(set1,set2):
""" Calculates Jaccard coefficient between two sets."""
if(len(set1) == 0 or len(set2) == 0):
return 0
return float(len(set1 & set2)) / len(set1 | set2) | 20dfb2d2c34b0915bd13979b732344176bec7e84 | 430,157 |
def fixed16(code, length):
"""Creates a fixed16 header."""
return "%s %11d\n" % (code, length) | a368eb1056a9d13979e6fd1023cd77740d41d702 | 311,999 |
import json
def parse_json(file_path: str) -> dict:
"""Summary
Load and parse json file
Args:
file_path (str): path of config file
"""
with open(file_path) as file_obj:
return json.load(file_obj) | 9177ee41f174fa9e62e4eb2ddb7726948f7dd116 | 279,889 |
def compare(riddle, attempt):
"""
compare function gets answer for "Bulls&Cows" game
by comparison riddle to attempt
:param riddle: the string consisted of 4 different numeric symbols to be recognised
:param attempt: the string consisted of 4 different numeric symbols as an attempt to recognize the ... | bffce2ae5d0a06a9dcc2c1b685537b48373df0d9 | 533,195 |
def nullHeuristic(state, problem=None):
"""
A heuristic function estimates the cost from the current state to the nearest
goal in the provided SearchProblem. This heuristic is trivial.
"""
return 0 | 34502d37d218cacda6857818c8f51229f48042b5 | 419,360 |
def convert(x,y):
"""
converts a set and a dict into the required "X" format for algX
for instance:
X = {1, 2, 3, 4, 5, 6, 7}
Y = {
'A': [1, 4, 7],
'B': [1, 4],
'C': [4, 5, 7],
'D': [3, 5, 6],
'E': [2, 3, 6, 7],
'F': [2, 7]}
outputs:
{
1: {'A', 'B'},
2: {'E... | 129c6283bd1dd0276df6a3954e032ccf5a2e3221 | 409,505 |
import math
def acos_deg(value):
""" returns acos as angle in degrees """
return math.degrees(math.acos(value) ) | c908ad126caf0be23a2df15446392d0448bbda8a | 241,847 |
import pickle
def load_dt(filename):
"""
加载保存好的决策树
:param filename: 文件名
:return: python dict
"""
# 'b' 表示二进制模式
fr = open(filename, 'rb')
return pickle.load(fr) | c61772d6c8606e45ef323bd8dd30cb0c9e6ebf35 | 11,008 |
import math
def calculate_distance_km_given_pl_abg_nlos(acceptable_PL_ABG_NLOS, radio_frequency, alpha, beta, gamma, sigma):
"""
Calculate distance given Free-space path loss (FSPL)
Formula:
PL_ABG_NLOS (in dB) = 10 * alpha * log(d) + beta + 10 * gamma * log(f) + sigma
distance in meters formula
... | bc8424e8716490e4729417892f54c67ecb1beecc | 502,177 |
def zero_counter(number):
"""Counts the number of consecutive 0's at the end of the number"""
x = 0
while (number >> x) & 1 == 0:
x = x + 1
return x | 598fdc5bfed992f6921151e831c3d71c6ea184cf | 258,911 |
def flatten_dict(d):
"""Flatten a dictionary where values may be other dictionaries
The dictionary returned will have keys created by joining higher- to lower-level keys with dots. e.g. if the original dict d is
{'a': {'x':3, 'y':4}, 'b':{'z':5}, 'c':{} }
then the dict returned will be
{'a.x':3, 'a... | 3efd9a4edacedd22ac42f3b8db16392acd69d70a | 410,689 |
import gzip
def open_file(file_path, mode = 'r'):
"""
Open a file which can be gzipped.
:param file_path:
:param mode:
:return:
"""
if file_path.split(".")[-1] =="gz":
#print "opening gzipped file"
INFILE = gzip.open(file_path, mode+'b')
else:
INFILE = o... | f117344ead1f51397689e5af3c427a109290a884 | 429,670 |
def can_link_to(person, contact, model):
"""
Determines whether or not the specified person can form a social network
link to the specified contact.
:param person: The person wanting to link.
:param contact: The contact to determine link eligibility.
:param model: The model to use.
"""
... | 8250b3d2ff7fb5be2cb47e83caa99c827517ea79 | 689,344 |
def skeletonModuleName(mname):
"""Convert a scoped name string into the corresponding skeleton
module name. e.g. M1.M2.I -> M1__POA.M2.I"""
l = mname.split(".")
l[0] = l[0] + "__POA"
return ".".join(l) | e6c898d11303d7138e14e0fcd061782873c08142 | 356,781 |
def get_variables_for_task(doc, task):
""" Get the variables that a task must record
Args:
doc (:obj:`SedDocument`): SED document
task (:obj:`Task`): task
Returns:
:obj:`list` of :obj:`Variable`: variables that task must record
"""
variables = set()
for data_gen in doc.... | 727db5187c9f9cc19ba8a258a4e01bd270ca470a | 556,834 |
def number_of_sublists(l):
"""
Retorna el numero de sublistas que contiene una lista.
:param l: Lista a calcular
:type l: list
:return: Número de sublistas
:rtype: int
"""
count = 0
for i in l:
if isinstance(i, list):
count = count + 1 + number_of_sublists(i)
... | 185c56b91fd2a34c71fcf0e12fb4401596883e72 | 501,669 |
import six
def Enum(*sequential, **named):
"""
Create an enumeration.
>>> Numbers = Enum('ZERO', 'ONE', 'TWO')
>>> Numbers.ZERO
0
>>> Numbers.ONE
1
Credits http://stackoverflow.com/a/1695250
"""
enums = dict(six.moves.zip(sequential, six.moves.range(len(sequential))), **named... | 1508d2b3b5ea16d9404c23b901cc9e9a52ef2168 | 332,766 |
def list_symbols(client, drawing=None, symbol_file=None, sheet=None):
"""List symbols contained on a drawing.
Args:
client (obj):
creopyson Client
drawing (str, optional):
Drawing name. Defaults: current active drawing.
symbol_file (str, optional):
Sy... | 859c9c3689ef795db5b06ce3ed760ddf5c4d14f2 | 201,126 |
def unhex(x):
"""Ensure hexidecimal strings are converted to decimal form"""
if x == '':
return '0'
elif x.startswith('0x'):
return str(int(x, base=16))
else:
return x | a13c64dc8ae4bded1a2d5f896c83b5fa5bc08bba | 515,170 |
import yaml
def parse_yaml_to_dict(contents):
"""
Parses YAML to a dict.
Parameters
----------
contents : str
The contents of a file with user-defined
configuration settings.
Returns
-------
dict
Configuration settings (one key-value
pair per setting) or... | de97a20c5343ab909351261a3dfafad8590b2f57 | 61,870 |
def net_gains(principal,expected_returns,years,people=1):
"""Calculates the net gain after Irish Capital Gains Tax of a given principal for a given expected_returns over a given period of years"""
cgt_tax_exemption=1270*people #tax free threashold all gains after this are taxed at the cgt_ta_rate
cgt_tax_r... | 623b6c1126ad2486ba94c3b02f1a8ed335fed74b | 648,228 |
def selection_sort(items):
"""Sort given items by finding minimum item, swapping it with first
unsorted item, and repeating until all items are in sorted order.
Running time: O(n**2) As it loops through the whole array for each element
Memory usage: O(1) Sorting is done in place on the array
"""
... | d7396df561adc9805d5e91dcbfa3ddd3e67018a8 | 146,046 |
import functools
import operator
def comb(n: int, k: int) -> int:
"""Compute binomial coefficient n choose k"""
if not 0 <= k <= n:
return 0
k = min(k, n - k)
numerator = functools.reduce(operator.mul, range(n, n - k, -1), 1)
denominator = functools.reduce(operator.mul, range(1, k + 1), 1... | a2bd3ec8dc28b581e271b9420d4dac3cf30a4547 | 423,314 |
import torch
def apply_gains(bayer_images, red_gains, blue_gains):
"""Applies white balance gains to a batch of Bayer images."""
red_gains = red_gains.squeeze(1)
blue_gains= blue_gains.squeeze(1)
bayer_images = bayer_images.permute(0, 2, 3, 1) # Permute the image tensor to BxHxWxC format from BxCxHxW format
... | f8bb037ba247d5c5e3963d16c9a9c4dd3d002b0e | 238,710 |
def get_sha1_or_none(repo, ref):
"""Return string of the ref's commit hash if valid, else None.
:repo: a callable supporting git commands, e.g. repo("status")
:ref: string of the reference to parse
:returns: string of the ref's commit hash if valid, else None.
"""
commit = repo("rev-parse", "-... | d20473120136b5f2410b5210a013451bfa68e250 | 647,336 |
def reached_minimum_node_size(data, min_node_size):
"""
Purpose: Determine if the node contains at most the minimum
number of data points
Input : Data array and minimum node size
Output : True if minimum size has been reached, else False
"""
if len(data) <= min_node_size:
r... | 6240a65f67ad8d98232395f7184c0ff44a24c996 | 410,015 |
def check_sequence_names_present(sequence):
"""
Checks that the names of entities are all present
"""
result = any(map(lambda x: 'name' in x, sequence))
if not result:
return {
'result': False,
'message': "All entries in ssl_sequence must have a name."
}
r... | 3edcf93023f18d5db731712c9e248c1ba24c6834 | 318,413 |
def find_distance(a, b, c):
"""Determine if distance between three ints is equal
assuming unsorted entries"""
int_holder = [a, b, c]
int_holder.sort()
distance_1 = int_holder[1] - int_holder[0]
distance_2 = int_holder[2] - int_holder[1]
if distance_1 == distance_2:
return 'They are... | 3e488b631c248de3069f4167f157022358114852 | 33,879 |
import builtins
def podstrc_vstup(monkeypatch):
"""Podstrčí funkci input daný vstup, tak jako by ho zadal uživatel."""
# Tohle je trochu pokročilá testovací magie.
# Viz pokročilý kurz: https://naucse.python.cz/course/mi-pyt/intro/testing/
vstup = []
def _podstrc(*args):
vstup.extend(args)... | 29d19db389bc87cdd10c1d73361c6025a5eca9e8 | 399,579 |
def proc_to_str(val, entry):
"""Process a value to string"""
return str(val) | 04c01556c1f6673f3935b9880a7eb4e6839badb6 | 572,322 |
def find_nodes(graph, filter_fn):
"""
Find all nodes whose names pass the predicate :filter_fn.
"""
nodes = set()
for node in graph.nodes.values():
if filter_fn(node.name):
nodes.add(node)
return nodes | d4aca7e4582161098677ed44051cf9cd65956b4b | 185,725 |
def parse_file(filename):
"""
Parses file for error messages in logs
Args:
filename
Returns:
error_count: count of error messages in file
error_msgs: list of error messages
"""
# Initialize return vals
error_count = 0
error_msgs = []
with open(filenam... | 855ad9411646961b3afdec14e7b3547af81fae84 | 35,214 |
import unicodedata
def is_control(ch):
"""判断'char'是否是Control or Format"""
if ch == "\t" or ch == "\n" or ch == "\r":
return False
cat = unicodedata.category(ch)
# Cc表示Control Cf表示Format
if cat in ("Cc", "Cf"):
return True
return False | 0fb469bff38a0c677bbcf66eddb27c7a0466622e | 449,927 |
import torch
def loss_bbox_regression(offsets, gt_offsets):
"""
Use sum-squared error as in YOLO.
@Params:
-------
offsets (tensor):
Predicted bbox offsets of shape [M, 4].
gt_offsets (tensor):
GT bbox offsets of shape [M, 4].
@Returns:
-------
loss_bbox_reg (scal... | 0adc65b74a925ff38b3051c2f0cd33d93efd9fcf | 384,141 |
import re
def pascal_case_ify(name):
"""
Uppercase first letter of ``name``, or any letter following an ``_``. In
the latter case, also strips out the ``_``.
=> key_for becomes KeyFor
=> options becomes Options
"""
return re.sub(r'(^|_)\w', lambda m: m.group(0)[-1].upper(), name) | 5b7a47274f7e6e774089ad7618a63dfe7651a4ab | 295,374 |
import random
def _random_value(x = None, min=0, max=10):
"""
(not very eye pleasing ;)
returns a random int between min and max
"""
return random.randint(min,max) | 315300dd21d56885d47448e5b6660a72cffb0bc4 | 678,416 |
def IsVector(paramType):
""" Check if a param type translates to a vector of values """
pType = paramType.lower()
if pType == 'integer' or pType == 'float':
return False
elif pType == 'color' or pType.startswith('float'):
return True
return False | 58a14693ffabc2230eea0b3f6702aa56ffc514ca | 41,857 |
def subprocess_command(exp='xpptut15', run='0260', procname='pixel_status', qname='psnehq',\
dt_sec=60, sources='cspad,opal,epix100,pnccd,princeton,andor') :
"""Returns command like 'proc_control -e xpptut15 -r 0260 -p pixel_status -q psnehq -t 60 -s cspad,pnccd'
"""
if procname == 'p... | 4e9a6665c6fd75470ac118a9630d3f684e9261f6 | 213,655 |
import re
def extractYearMonthDate(url):
"""Assumes url is a string, representing a url with a full date
returns re match object, representing the full date from the url"""
pattern = "\d{4}/\d{2}/\d{2}"
result = re.search(pattern, url)
return result | 4ec18936ab43368aba09e49d1699ab26a4d57e8f | 111,263 |
def norm_ws(s):
"""Normalize whitespace in the given string."""
return ' '.join(s.strip().split()) | 7d9b5e01bd3b310a09ef1205e0ce94da1f0d4a42 | 262,186 |
import json
def _exiftool_json_sidecar(
self,
use_albums_as_keywords=False,
use_persons_as_keywords=False,
keyword_template=None,
description_template=None,
ignore_date_modified=False,
):
""" Return dict of EXIF details for building exiftool JSON sidecar or sending commands to ExifTool.
... | 13d3cfe697d34f1967a1251dce0703adc3d16c59 | 240,367 |
import re
from datetime import datetime
import pytz
def parse_dates(date_string, hour=12):
"""
Extract a pair of dates from a string
Args:
date_string(str): A string containing start and end dates
hour(int): Default hour of the day
Returns:
tuple of datetime: Start and end da... | eb24dd98e405b87cff6224d89450ee6834bebb27 | 159,799 |
def parse_row(row, cols, sheet):
"""
parse a row into a dict
:param int row: row index
:param dict cols: dict of header, column index
:param Sheet sheet: sheet to parse data from
:return: dict of values key'ed by their column name
:rtype: dict[str, str]
"""
vals = {}
for header, ... | 580afc8d38f1ea2ce13fa9ccdc5c75e56860a97c | 668,398 |
def accuracy(reference, test):
"""
Given a list of reference values and a corresponding list of test
values, return the percentage of corresponding values that are
equal. In particular, return the percentage of indices
C{0<i<=len(test)} such that C{test[i] == reference[i]}.
@type reference: C{... | d4729fb115efb3037f677342c9faf3f08c993466 | 288,151 |
def _calculate_payload_size(payload_length):
"""For a given payload, return the bytes needed for the payload.
This is for the entire payload with padding, regardless of which unit it is
stored in.
>>> _calculate_payload_size(0)
8
>>> _calculate_payload_size(8)
8
>>> _calculate_payload_... | 473679c2ddf2a088b037a312777269c6b3535f20 | 452,372 |
import threading
def threaded(call, *args, **kwargs):
"""Execute ``call(*args, **kwargs)`` in a thread"""
thread = threading.Thread(target=call, args=args, kwargs=kwargs)
thread.start()
return thread | 6c16d5bfcf9eb037169d1b4e6958d46e2fc6abe9 | 576,214 |
def parse_response_status(status: str) -> str:
"""Create a message from the response status data
:param status:
Status of the operation.
:return:
Resulting message to be sent to the UI.
"""
message = status
if status == 'SUCCESS':
message = "Face authentication successful... | 7eab8fa4b115d79c014070fd78d7d088011bf226 | 80,931 |
import pathlib
def git_path(repo_root, tail=None):
"""Returns a Path to the .git directory in repo_root
with tail appended (if present) or None if repo_root is not set.
"""
path = None
if repo_root:
path = pathlib.Path(repo_root) / ".git"
if tail is not None:
path = pat... | 6335deadff7613657ea3dcd7e5019bf863aba67d | 667,766 |
import re
def CamelCaseToOutputFriendly(string):
"""Converts camel case text into output friendly text.
Args:
string: The string to convert.
Returns:
The string converted from CamelCase to output friendly text.
Examples:
'camelCase' -> 'camel case'
'CamelCase' -> 'camel case'
'camelTLA'... | a1d726fe68649efe0c0b6cf17e95e55ad4a8183f | 54,813 |
def help_flag_present(argv: list[str], flag_name: str = 'help') -> bool:
"""
Checks if a help flag is present in argv.
:param argv: sys.argv
:param flag_name: the name, which will be prefixed with '-', that is a help flag. The default value is 'help'
:return: if the help flag is present
"""
... | a804ec64702e6173d94c50f024373f67d9893344 | 669,769 |
def slicebyn(obj, n, end=None):
"""
Iterator over n-length slices of obj from the range 0 to end.
end defaults to len(obj).
"""
if end is None:
end = len(obj)
return (obj[i:i+n] for i in range(0, end, n)) | 4a87829826a8d440a99a1815252b25526623ef00 | 95,281 |
def regrid_get_operator_method(operator, method):
"""Return the regridding method of a regridding operator.
:Parameters:
operator: `RegridOperator`
The regridding operator.
method: `str` or `None`
A regridding method. If `None` then ignored. If a `str`
then... | 59b728fc74d89cf3daee34dff668d62a6d1fe5b0 | 638,039 |
def getName(fp, fp_names):
"""Determines the new name of a fingerprint in case
multiple fingerprints with the same name"""
# check if fp already exists. if yes, add a number
if fp in fp_names:
suffix = 2
tmp_name = fp + "_" + str(suffix)
while tmp_name in fp_names:
su... | 446701f56c142bd07e7ae12b796439481feda337 | 151,055 |
def get_least_key(kv):
"""
Given a dictionary, returns the key with minimum value.
:param kv: Dictionary considered.
:return: Key with the minimum value.
"""
min_k = None
min_v = None
for k, v in kv.items():
if min_v is None or v.item() < min_v:
min_k = k
... | 4357754a492ab3f463025d85576f3fe1a03c32e4 | 322,958 |
def char_encode(num: int, is_lower=True) -> str:
"""
Converts an integer to a character string \
with elements from a-z or A-Z.
:num: The integer base 10 to be converted.
:return: The character base 26.
"""
buffer = 97 if is_lower else 65
result = "" if num != 0 else chr(buffer + num % ... | ccf90376d3dd260d8287cbf80df65fb799cc1ce6 | 333,620 |
def clean(s, chars):
"""Clean string s of characters in chars."""
translation_table = dict.fromkeys(map(ord, chars), '_')
return s.translate(translation_table) | da18deb6ba272016a90ff5894f7bb63d2d4e57ee | 283,626 |
def bytestring(s, encoding='utf-8', fallback='iso-8859-1'):
"""Convert a given string into a bytestring."""
if isinstance(s, bytes):
return s
try:
return s.encode(encoding)
except UnicodeError:
return s.encode(fallback) | d73ae1377c770d218585c51db216b21918d5d562 | 122,423 |
def getValue(dataMatrix,x,y):
"""Return the sum of all the numbers in neighborhood."""
return dataMatrix[x-1][y-1]+dataMatrix[x-1][y]+dataMatrix[x-1][y+1]+dataMatrix[x][y-1]+dataMatrix[x][y]+dataMatrix[x][y+1]+dataMatrix[x+1][y-1]+dataMatrix[x+1][y]+dataMatrix[x+1][y+1] | 7b80889bb91e0c9c68aee38f4ea0dddb773c0088 | 270,275 |
from datetime import datetime
def validate_date(date_text):
"""Validates that the date is in ISO 8601 format: YYYY-MM-DD"""
try:
if date_text != datetime.strptime(date_text, "%Y-%m-%d").strftime('%Y-%m-%d'):
return False
return True
except ValueError:
return False | 2d7592edc150b9270403d01c849fd57097111107 | 636,734 |
def filter_low_swh(ds):
"""Remove all records with low significant wave heights."""
return ds['sea_state_30m_significant_wave_height_spectral'] > 1.0 | 93c872885f446c0db87c6b3616b549a677ef5af8 | 676,386 |
from functools import reduce
def compute_product_string(product_string):
"""Takes `product_string` and returns the product of the factors as string.
Arguments:
- `product_string`: string containing product ('<factor>*<factor>*...')
"""
factors = [float(f) for f in product_string.split("*")]
... | ebd2a7e57529dc24960a29b5406634830f30bf83 | 628,380 |
def calc_rso(ra, frac=0.75):
"""
Clear-sky solar radiation.
Parameters
----------
ra : numpy ndarray
Extraterrestrial solar radiation.
frac : float <= 1
Fraction of extraterrestrial solar radiation that
reaches earth on clear-sky days.
"""
s = 'Please enter a fr... | f6cd63ed42a30cb545b43df9991013bf2f0513d2 | 489,602 |
import re
def lit_sub(*args, **kw):
"""Literal-safe version of re.sub. If the string to be operated on is
a literal, return a literal result. All arguments are passed directly to
``re.sub``.
"""
lit = hasattr(args[2], '__html__')
cls = args[2].__class__
result = re.sub(*args, **kw)
i... | 403c93ee341e4b0b2c6b7a7ef91bf55a0726ace0 | 537,149 |
import torch
def init_mask(aux):
"""
Initializes masks of weight to freeze
Parameters
----------
aux: dict
A map from weight name to tuple (W, Z, U, project_fun)
Returns
-------
mask: dict
A map from weight name to tuple (W, mask)
"""
with torch.no_grad():
... | d9131d150a65ed00d4b4ee587fdad210b540652c | 428,466 |
import re
def interpret_cv(cv_index, settings):
"""
Read the cv_index'th CV from settings.cvs, identify its type (distance, angle, dihedral, or differance-of-distances)
and the atom indices the define it (one-indexed) and return these.
This function is designed for use in the umbrella_sampling jobtyp... | 01ef867caf1aa8756182dcab3a0e3bc2261cacc2 | 661,824 |
def add_to_dict_if_not_present(target_dict, target_key, value):
"""Adds the given value to the give dict as the given key
only if the given key is not in the given dict yet.
"""
if target_key in target_dict:
return False
target_dict[target_key] = value
return True | 343b3324a17adb8055680e0226404c8c127e3267 | 375,550 |
def cytoscape_edge(edge):
"""convert edge data into cytoscape format"""
return dict(
id=edge["_id"],
edgeType=edge["edge_type"],
score=edge["score"],
source=edge["_from"],
target=edge["_to"],
) | e435f4aac213795f8fb755b84d765ceda6751493 | 549,272 |
def the_H_function(sorted_citations_list, n=1):
"""from a list of integers [n1, n2 ..] representing publications citations,
return the max list-position which is >= integer
eg
>>> the_H_function([10, 8, 5, 4, 3]) => 4
>>> the_H_function([25, 8, 5, 3, 3]) => 3
>>> the_H_function([1000, 20]) => 2... | 24ad3d85963ef0a9d4531ba552371d7e829f1c2a | 709,949 |
import re
def create_index_search_tag_for_variable(variable_expression):
"""
Creates tag from variable expressions such as 'A%b(i)%c' that
can be used to search the index via the scoper module.
The example 'A%b(i)%c' is translated to a tag 'a%b%c' (lower case).
All array indexing expressions are s... | 7d2e3b5a17e29a29d8fd397316fb2abbb5aa58b1 | 564,053 |
import six
def parse_int(num):
"""
Parse integer from a string.
"""
is_empty = isinstance(num, six.string_types) and len(num) == 0
if is_empty:
return None
try:
return num and int(num)
except ValueError:
pass | d2c61b20d0612602457a375c84a1a26d4cd59ed1 | 472,853 |
import math
def wrap_always(text, width):
"""A simple word-wrap function that wraps text on exactly width characters.
It doesn't split the text in words."""
return '\n'.join([text[width * i:width * (i + 1)] \
for i in range(int(math.ceil(1. * len(text) / width)))]) | f6e5b85007fffc78576c8d5bbe89077400ca96b0 | 654,814 |
import errno
def _maybe_read_file(filename):
"""Read the given file, if it exists.
Args:
filename: A path to a file.
Returns:
A string containing the file contents, or `None` if the file does
not exist.
"""
try:
with open(filename) as infile:
print(infile.read... | c8cb46edaa0af2a0cffda530b3a6d98e8f9ee166 | 256,804 |
def rreplace(s, old, new, occurrence, only_if_not_followed_by=None):
"""replaces occurences of character, counted from last to first, with new
character.
Arguments:
s - string
old - character/string to be replaced
new - character/string to replace old with
occurence - nth occurence up to w... | 8db045d1399697d5bc3bfa7fb3d345019c04cfd8 | 166,087 |
def dict_depth(dic, level=0):
""" Check the depth of a dictionary.
**Parameters**
dic: dict
Instance of dictionary object or its subclass.
level: int | 0
Starting level of the depth counting.
"""
if not isinstance(dic, dict) or not dic:
return level
re... | b036dbdd796c866e4ea5293d2dee6139e15d881c | 264,972 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.