content stringlengths 39 9.28k | sha1 stringlengths 40 40 | id int64 8 710k |
|---|---|---|
from typing import Union
from typing import List
def str_to_list(text: Union[str, None]) -> Union[List, None]:
"""Split string by comma and return list"""
return text.split(",") if isinstance(text, str) else text | a032383dea16c6594893dcd7f1507a73657958ac | 224,361 |
def extract_version(package_name):
"""
Extracts the version from the package_name.
The version is defined as one of the following:
-3245s
-ab434
-1.1-343s
-2.3-4
-134-minimal-24
but not:
-ab-13
-ab-ab
-m14-m16
The leading "-" is discarded.
Example:
>>> ... | d0f5686f9b9e81654a6c9a8004c6c549fb49ac62 | 264,427 |
def resize_halo_datasets(halos_dset, new_size, write_halo_props_cont, dtype):
"""
Resizes the halo datasets
Parameters
-----------
halos_dset: dictionary, required
new_size: scalar integer, required
write_halo_props_cont: boolean, required
Controls if the individual halo properti... | a5461a776a0991eda04fc5d0e1d2a2a14e6e1f5f | 24,780 |
def bind_ack(data):
"""
Ensure the data is a bind ack and that the
"""
# packet type == bind ack (12)?
if data[2] != b"\x0c":
return False
# ack result == acceptance?
if data[36:38] != b"\x00\x00":
return False
return True | 0ce51d3b9611cca24116815d282bd2b3df2e43d0 | 363,284 |
def get_invite_account_id(event):
"""Return account id for invite account events."""
return event["detail"]["requestParameters"]["target"]["id"] | 9eb49305920d7cdd7cd61005592a4569404be770 | 136,295 |
import re
def _quantity_to_bytes(quantity):
"""Return a quantity with a unit converted into a number of bytes.
Examples:
>>> quantity_to_bytes('42Gi')
45097156608
>>> quantity_to_bytes('100M')
100000000
>>> quantity_to_bytes('1024')
1024
Args:
quantity (str): a quantity, ... | 2ddfc61bf02772110e5b0e675b415285319f6747 | 453,571 |
from typing import List
def get_stuff_class_ids(num_thing_stuff_classes: int,
thing_class_ids: List[int],
void_label: int) -> List[int]:
"""Computes stuff_class_ids.
The stuff_class_ids are computed from the num_thing_stuff_classes, the
thing_class_ids and the vo... | 89e1ffa143d70c03d49cfab1603bdd85af2533be | 185,074 |
import math
def calc_angle_between_two_locs(lon1_deg, lat1_deg, lon2_deg, lat2_deg):
"""
This function reads in two coordinates (in degrees) on the surface of a
sphere and calculates the angle (in degrees) between them.
"""
# Import modules ...
# Convert to radians ...
lon1_rad = math.ra... | 1ffa72e64696fc800de3fbf93bfb01a13ce14d22 | 60,709 |
def apply_first(seq):
"""Call the first item in a sequence with the remaining
sequence as positional arguments."""
f, *args = seq
return f(*args) | 0f7353b66ea677e4b4090dc2824556952daaa7c9 | 658,980 |
def path(service):
""" Return path — or route pattern — for the given REST service. """
return '/-/{0}'.format(service.lower()) | 8f5386ee6c0b43c0692920ac91182c03b9429ea3 | 308,881 |
import re
def re_find(s, r, pos=0, endpos=9223372036854775807):
"""
Returns the match of the first occurrence of the regular expression
`r` in string (or byte-sequence) `s`. This is essentially a wrapper
for `re.finditer()` to avoid a try-catch StopIteration block.
If `r` cannot be found, `None` w... | cb726156d009956e20576757cad24fe8a6fa9279 | 513,510 |
def count_object(network, class_ids, scores, bounding_boxes, object_label, threshold=0.75):
"""
Counts objects of a given type that are predicted by the network.
:param network: object detection network
:type network: mx.gluon.nn.Block
:param class_ids: predicted object class indexes (e.g. 123)
... | 31dd31319a6d579d98929ec9a57892a560b058f3 | 626,060 |
def get_attr_resolver(obj_type, model_attr):
"""
In order to support field renaming via `ORMField.model_attr`,
we need to define resolver functions for each field.
:param SQLAlchemyObjectType obj_type:
:param str model_attr: the name of the SQLAlchemy attribute
:rtype: Callable
"""
retu... | 23376addb0b5a3ab600e251e512f9174a27a66b6 | 650,766 |
def impedance(vp, rho):
"""
Compute acoustic impedance.
"""
return vp * rho | 6be115c3d92b394a5b98cbf502d2bc753522a8a6 | 67,309 |
def make_matrix(num_rows, num_columns, entry_fn):
"""
creates a num_rows * num_columns matrix whose (i,j) entry is an entry_fn
"""
return [[entry_fn(i, j) for j in range(num_columns)] for i in range(num_rows)] | a1dccfe0d5d62bb58c956d56e691d1898e275134 | 184,441 |
def partial_fittable_instance(obj, name=None, **kwargs):
"""Asserts that obj has a partial_fit, and instantiates it with **kwargs if obj is given as a type"""
if name is None:
if isinstance(obj, type):
name = obj.__name__
else:
name = type(obj).__name__
assert hasatt... | 2dc94bccd3dca4710ca1ee0d732fe9f98485a46c | 339,615 |
def map_file_to_plot_id(file_path: str, season_id: str, seasons: list) -> str:
"""Find the plot that is associated with the file
Arguments:
file_path: the path to the file
season_id: the ID of the season associated with the file
seasons: the list of seasons
Return:
Returns th... | 7f5d955ee130835724a1f56ae66252fa264bde29 | 289,683 |
import json
def from_json(value):
""" Decodes a JSON string into an object.
:param str value: String to decode
:returns: Decoded JSON object
"""
return json.loads(value) | 8ab44eb73063fce49dbcc5f1ad51768f27620a41 | 645,349 |
def computechangesetcopies(ctx):
"""return the copies data for a changeset
The copies data are returned as a pair of dictionnary (p1copies, p2copies).
Each dictionnary are in the form: `{newname: oldname}`
"""
p1copies = {}
p2copies = {}
p1 = ctx.p1()
p2 = ctx.p2()
narrowmatch = ct... | c1e0cd4df1fff9bea2d5184fe7dab78fc37695ee | 385,052 |
def get_id(id_):
"""Allow specifying old or new style IDs and convert old style to new style IDs
Old style: 123-the-slug
New style: 123 or the-slug-123
"""
if isinstance(id_, int):
return id_
elif "-" in id_:
front = id_.split("-", 1)[0]
if front.isdigit():
... | 1d895bd7d96b52e3772c4a34a5630ffc9a06b7d2 | 523,296 |
def binomial_coefficient(n, r):
"""
Find binomial coefficient using pascals triangle.
>>> binomial_coefficient(10, 5)
252
"""
C = [0 for i in range(r + 1)]
# nc0 = 1
C[0] = 1
for i in range(1, n + 1):
# to compute current row from previous row.
j = min(i, r)
... | 6a3e88cf757535b03c59a6e482e0b432adaec0db | 121,923 |
def find_subsequence(iterable, predicate):
"""
find the subsequence in iterable which predicted return true
for example:
>>> find_subsequence([1, 10, 2, 3, 5, 8, 9], lambda x: x in [1, 0, 2, 3, 4, 5, 8, 9])
[[1], [2, 3, 5, 8, 9]]
>>> find_subsequence([1, 10, 2, 3, 5, 8, 9], lambda x: x not i... | 784e509b742643fbee1a32226da1d0fb9ec3bd21 | 144,379 |
def fmt_option_key(key, value):
"""Format a single keyword option."""
if value is None:
return ""
return f"{key}={value}" | 271519544ac6b10840898782bb74904e03a16197 | 317,480 |
def get_case_form_ids(couch_case):
"""Get the set of form ids that touched the given couch case object"""
form_ids = set(couch_case.xform_ids)
for action in couch_case.actions:
if action.xform_id:
form_ids.add(action.xform_id)
return form_ids | f3e5822f5be0822808719fa184fdc263ceb73d62 | 182,662 |
import re
def youtube_url_validator(url):
"""
## youtube_url_validator
Validates & extracts Youtube video ID from URL.
Parameters:
url (string): inputs URL.
**Returns:** A valid Youtube video string ID.
"""
youtube_regex = (
r"(?:http:|https:)*?\/\/(?:www\.|)(?:youtube\... | ff2779844ed1cb74125cac285e197ef23bfb8f11 | 240,079 |
def is_prime(nb: int) -> bool:
"""Check if a number is a prime number or not
:param nb: the number to check
:return: True if prime, False otherwise
"""
# even numbers are not prime
if nb % 2 == 0 and nb > 2:
return False
# checking all numbers up to the square root of the number
... | 4368fd20eadd4d773d5f5af06f8717ef633d48b8 | 698,329 |
def _is_public(name: str) -> bool:
"""Return true if the name is not private, i.e. is public.
:param name: name of an attribute
"""
return not name.startswith('_') | 280bd1636ad3a08d51c95165ac15e7a6e75b745b | 320,336 |
def count_parameters(model, tunable_only: bool = True) -> int:
""" Count the number of parameters in the given model.
Parameters
----------
model : torch.nn.Module
PyTorch model (deep network)
tunable_only : bool, optional
Count only tunable network parameters
References
--... | ef825fab61760d7d5e5778f6c85c33fddf4db5d5 | 431,880 |
def transform_optional(node, **kwargs):
"""Sets the optional flag.
"""
return "optional" | 229ad2e6911c714b17bbfe295a964b3438b7f377 | 243,848 |
import math
def sum_digits_factorial(n):
"""
Compute sum of factorials of each digit in the number n
"""
sum_fact = 0
while n > 0:
sum_fact += math.factorial(n % 10)
n //= 10
return sum_fact | 994878df3e8337c482f46f0ae6a7419f4454bf04 | 436,746 |
def remove_non_latin(input_string, also_keep=None):
"""Remove non-Latin characters.
`also_keep` should be a list which will add chars (e.g. punctuation)
that will not be filtered.
"""
if also_keep:
also_keep += [' ']
else:
also_keep = [' ']
latin_chars = 'ABCDEFGHIJKLMNOPQRST... | d29d3928e128fba5d6a773a11746fe6fc6b0b7a2 | 310,589 |
def is_valid_directed_joint_degree(in_degrees, out_degrees, nkk):
""" Checks whether the given directed joint degree input is realizable
Parameters
----------
in_degrees : list of integers
in degree sequence contains the in degrees of nodes.
out_degrees : list of integers
out degre... | c144816f286894e6e4df9adb107d02be630576f2 | 104,367 |
def get_gb_acc_id(year, case_index):
"""
Returns global accident id for GB, year and index of accident.
GB ids will be in form 2200700000001234
2 at the beginning means it is from Great Britain
2007 means the year
1234 means the case ID as in original data
"""
try:
acc_id = 2000... | a4e919866018635c7de0a8a3b66b8e3a16c61fc5 | 177,509 |
def get_source_url(j):
"""
return URL for source file for the latest version
return "" in errors
"""
v = j["info"]["version"]
rs = j["releases"][v]
for r in rs:
if r["packagetype"] == "sdist":
return r["url"]
return "" | c9a44fe7829a908772611d60884b402ef9452e67 | 155,657 |
import logging
def remediate_iam_policy(sa_iam_policy, sa_resource_name, risky_roles):
"""Remove risky IAM roles from the service account IAM policy.
Args:
sa_iam_policy ([dict]): The IAM policy attached to the sa_resource_name.
sa_resource_name ([str]): The GCP service account full resource ... | f5de29116a4f25dd49c2a8b48a64e44b9cdb9794 | 606,338 |
def create_mapping(dict_times):
"""
If times are not integers, transform them into integers.
:param dict_times: Dict where keys are times.
:return: A mapping which is a dictionary maps from current names of time stamps to integers (by their index)
"""
keys = list(dict_times.keys())
mapping =... | 75893a6419b61d86bc0d4d0693bbc1b25f111a75 | 32,512 |
from typing import Union
from typing import Callable
import torch
def get_activation(fn: Union[Callable, str]):
"""Get a PyTorch activation function, specified either directly or as a string.
This function simplifies allowing users to specify activation functions by name.
If a function is provided, it is s... | af66502925599653e7f7c577c7754e0323ee93d7 | 125,441 |
def rain(walls):
"""
walls is a list of non-negative integers.
Return: Integer indicating total amount of rainwater retained.
Assume that the ends of the list (before index 0 and after index
walls[-1]) are not walls, meaning they will not retain water.
If the list is empty return 0.
"""
... | e26b22f09823f4a09b8f209780152ed739bf78bd | 635,099 |
def _ensureListOfLists(iterable):
"""
Given an iterable, make sure it is at least a 2D array (i.e. list of lists):
>>> _ensureListOfLists([[1, 2], [3, 4], [5, 6]])
[[1, 2], [3, 4], [5, 6]]
>>> _ensureListOfLists([1, 2])
[[1, 2]]
>>> _ensureListOfLists(1)
[[1]... | 7600d2d1bdbe20addf86a39d3d20dc8ab30586c0 | 365,711 |
import torch
import math
def compute_particle_xyz_from_internal(particle_1_xyz,
particle_2_xyz,
particle_3_xyz,
bond, angle, dihedral):
""" Compute the Cartesian coordinate of a particle based on i... | 9a3b59d5c29a0c8ac9c5f498925698b8ab29bd16 | 572,388 |
from pathlib import Path
def new_name_if_exists(file: Path):
"""Make a new filename that avoids name collisions.
example: filename(xx).ext where xx is incremented until
unused filename is created.
Args:
file (Path): proposed unique filename.
Returns:
Path... | 89f639e2a5ef12941c8d50b8a4313f71cf1dbe94 | 357,979 |
import math
def calc_overlap(params):
"""
Function to calculate the number of pixels requires in overlap, based on chunk_size and overlap percentage,
if provided in the config file
:param params: (dict) Parameters found in the yaml config file.
:return: (int) number of pixel required for overlap
... | f6dd348cf2299100d30e12c1ebf71c84d5f80183 | 278,512 |
def number_of_short_term_peaks(n, t, t_st):
"""
Estimate the number of peaks in a specified period.
Parameters
----------
n : int
Number of peaks in analyzed timeseries.
t : float
Length of time of analyzed timeseries.
t_st: float
Short-term period for which to estim... | 4118409bd4d330e68f41bf1e51d3940478a7f76e | 365,943 |
def onBoard(top, left=0):
"""Simplifies a lot of logic to tell if the coords are within the board"""
return 0 <= top <= 9 and 0 <= left <= 9 | 2b2007ae2e3acdbb9c04c3df1397cffce97c6717 | 10,247 |
import torch
def haschildren(obj):
"""Check if the object has children
Arguments:
obj {object} -- the object to check
Returns:
bool -- True if the object has children
"""
ommit_type = [torch.nn.parameter.Parameter, torch.Tensor]
if type(obj) in ommit_type:
return Fals... | 03ef8ef009565a437a99beed4f1f6076ac6ffa1a | 604,067 |
def addon(options):
"""
This function constructs a command line invocation that needs to be passed for invoking for a sub workflow.
Only a certain subset of options are propogated to the sub workflow invocations if passed.
"""
cmd_line_args = ""
if options.recurse_mode:
cmd_line_args +=... | 41e556f2d34d71cb09f0f7db4b5a3aa2b99a9a11 | 295,044 |
import struct
import pickle
async def read_and_unserialize_socket_msg(reader):
"""
Read and unserialize the message bytestream received from ScrubCam.
Parameters
----------
reader : asyncio.StreamReader
A reader object that provides APIs to read data from the IO
stream
Return... | 7d549c847d98897d65caeb0b720b07b2580bb6d9 | 405,271 |
from typing import List
def linvectors_list(
pitches: List,
) -> List:
"""Returns the linvectors of a list of MIDI pitches.
"""
result = []
first_linvector = [pitches[0]]
result.append(first_linvector)
for pitch in pitches[1:]:
next_linvector = []
for element in result[-1... | ee92d979427f55b161517422ecee79d5c633b834 | 200,002 |
import torch
def my_l1(x, x_recon):
"""Calculate l1 loss
Parameters
----------
x : torch.cuda.FloatTensor or torch.FloatTensor
Input data
x_recon : torch.cuda.FloatTensor or torch.FloatTensor
Reconstructed input
Returns
-------
torch.cuda.FloatTensor or torch.FloatTen... | a7736bd2d4160546176520a6adbd1c218dc5cc14 | 689,723 |
def time_to_seconds(timestring):
"""
Transform (D-)HH:MM:SS time format to seconds.
Parameters
----------
timestring: str or None
Time in format (D-)HH:MM:SS
Returns
-------
Seconds that correspond to (D-)HH:MM:SS
"""
if timestring is None:
timestring = "00:00:0... | 60ba0e0a78e4eff1ae443923da7b22fccc695576 | 456,439 |
def read_column_tagged_file(filename: str, tag_col: int = -1):
"""Reads column tagged (CONLL) style file (tab separated and token per line)
tag_col is the column number to use as tag of the token (defualts to the last in line)
return format :
[ ['token', 'TAG'], ['token', 'TAG2'],... ]
"""
data ... | 3143548e3df1258b743faa65ccf4bb727846f5e4 | 190,537 |
from typing import List
from typing import Any
from typing import Iterable
def as_list(item_or_sequence) -> List[Any]:
"""Turns an arbitrary sequence or a single item into a list. In case of
a single item, the list contains this element as its sole item."""
if isinstance(item_or_sequence, Iterable):
... | 2edf2d9adb03c0efb16e59a507a918149fdae524 | 39,727 |
import random
def random_class_ids(lower, upper):
"""
Get two random integers that are not equal.
Note: In some cases (such as there being only one sample of a class) there may be an endless loop here. This
will only happen on fairly exotic datasets though. May have to address in future.
:param lo... | dcb351efbf772f2408213b362b9a5af4bfabc8cb | 651,651 |
def vector_subtract(u, v):
"""returns the difference (vector) of vectors u and v"""
return (u[0]-v[0], u[1]-v[1], u[2]-v[2]) | 034c07a1e459725744112b51933c2c0c73c60f68 | 663,204 |
def head_table(rule):
"""Table name of the head of a rule"""
return rule.head.table | aaf0bc25382ad0192de8c826a3cbfc5da4535b27 | 333,011 |
def callMultiF(f,n,cache):
"""
Try to get n unique results by calling f() multiple times
>>> import random
>>> random.seed(0)
>>> callMultiF(lambda : random.randint(0,10), 9, set())
[9, 8, 4, 2, 5, 3, 6, 10]
>>> random.seed(0)
>>> callMultiF(lambda : random.randint(0,10), 9, set([8,9,10]... | ce38fe79c311c60753432b2606216bdd47c8db41 | 535,727 |
def prep_sub_id(sub_id_input):
"""Processes subscription ID
Args:
sub_id_input: raw subscription id
Returns:
Processed subscription id
"""
if not isinstance(sub_id_input, str):
return ""
if len(sub_id_input) == 0:
return ""
return "{" + sub_id_input.strip... | 719693c2a11d1e8611fceec80b34b07a157e91ad | 676,067 |
def read_file(filename: str) -> str:
"""Reads contents of given file"""
with open(filename, "r") as content_file:
return content_file.read() | b2989f88849ac9f77a38435b8bdba497d7d9699a | 296,628 |
def blocks_table_m() -> dict[int, int]:
"""The table is the number of blocks for the correction level M.
Returns:
dict[int, int]: Dictionary of the form {version: number of blocks}
"""
table = {
1: 1, 2: 1, 3: 1, 4: 2, 5: 2, 6: 4, 7: 4, 8: 4, 9: 5, 10: 5, 11: 5,
12: 8, 13: 9, 14... | a964fc403146bf8078659c898226f8b86bb230fd | 348,041 |
def validate_move(move, turn, board):
"""
Determine if the next move is valid for the current player
:param move:
:param turn:
:param board:
:return: boolean flag for if the move is valid as well as the current gamestate dictionary
"""
if turn == 1:
piece = 'X'
else:
... | b3117e72a8377aaceb5ee8c887a272bcb15ea553 | 690,518 |
import uuid
def generate_dtids(registry: str, number: int) -> list:
"""
Generate a list of DTIDs.
Args:
number: The number of generated DTIDs.
registry: Base URL of the DTID registry.
Returns:
List of DTIDs
"""
dtids = []
for _ in range(number):
dtids.append(r... | 3efcc7dd8ab4bd6edd4b3256c7e973df8f15e7fc | 108,357 |
def photon_generation(wave_len, energy):
"""Determine number of photons in a bundle
Parameters
----------
wave_len : float
Wavelength associated with a particular bundle
energy : float
Energy in a bundle
Returns
-------
nphoton : float
Number of photons in a... | c0b1aa263ec81e16b37314b9506b0a2456aa8dfa | 580,082 |
import pkg_resources
def get_config(package=__name__, externals=None, api_version=None):
"""Returns a string containing the configuration information for the given ``package`` name.
By default, it returns the configuration of this package.
This function can be reused by other packages.
If these packages have... | 8d8c95ea4b10cc29bcd7831d2dbdc8f7ad05ff89 | 533,928 |
from typing import List
def _add_docstring_to_top_level_func(line: str, docstring: str) -> str:
"""
Add docstring to the top-level function line string.
Parameters
----------
line : str
Target function line string.
e.g., `def sample_func(a: int) -> None:`
docstring : str
... | e4fcee2a5ac3bae9508174315884aea128dabf93 | 620,490 |
def format_time_filter(start, stop, field):
"""Formats a time filter for a given endpoint type.
Args:
start (str): An ISO date string, e.g. 2020-04-20.
stop (str): An ISO date string, e.g. 2021-04-20.
field (str): The time field to filter by.
"""
start_date = start.split('-')
... | 6c21bb1ff6f90002d0f7f50d2c82fd081db89213 | 676,601 |
def make_good_url(url=None, addition="/"):
"""Appends addition to url, ensuring the right number of slashes
exist and the path doesn't get clobbered.
>>> make_good_url('http://www.server.com/anywhere', 'else')
'http://www.server.com/anywhere/else'
>>> make_good_url('http://test.com/', '/somewhere/o... | bc22f403d6e3c999f2b5cf6c9bbaf57e53e67e0b | 541,037 |
def all_true (seq) :
"""Returns True if all elements of `seq` are true,
otherwise returns first non-true element.
"""
for e in seq :
if not e :
return e
else :
return True | 26ad964d3c9f53aec547e29e703bf97c8e646219 | 422,976 |
import torch
def binary_accuracy(preds, y):
"""
Returns accuracy per batch, i.e. if you get 8/10 right, this returns 0.8, NOT 8
"""
rounded_preds = torch.round(torch.sigmoid(preds))
correct = (rounded_preds == y).float() #convert into float for division
acc = correct.sum() / len(correct)
... | 8d3cc42eec8b9fa2f6b2a905bb840abe9e7e5252 | 531,209 |
def _generate_spaxel_list(spectrum):
"""
Generates a list wuth tuples, each one addressing the (x,y)
coordinates of a spaxel in a 3-D spectrum cube.
Parameters
----------
spectrum : :class:`specutils.spectrum.Spectrum1D`
The spectrum that stores the cube in its 'flux' attribute.
Re... | 9d4b5339f18022607f349c326dc83e319a690a26 | 8,488 |
def query_mission(id):
"""
Build the Query for a single mission
"""
query = f'''
{{
mission(id:"{id}") {{
id
name
manufacturers
description
website
}}
}}
'''
return query | 60d0fdf2bbea4307b901e6b2f3917a5dda7aa7a4 | 589,654 |
from datetime import datetime
def timestamp_ddmmyyyyhhmmss_to_ntp(timestamp_str):
"""
Converts a timestamp string, in the DD Mon YYYY HH:MM:SS format, to NTP time.
:param timestamp_str: a timestamp string in the format DD Mon YYYY HH:MM:SS
:return: Time (float64) in seconds from epoch 01-01-1900.
... | bf2239de21973ae537cee94022e9d2781f7cbd52 | 681,251 |
def wgan_d_loss(scores_real, scores_fake):
"""
Input:
- scores_real: Tensor of shape (N,) giving scores for real samples
- scores_fake: Tensor of shape (N,) giving scores for fake samples
Output:
- loss: Tensor of shape (,) giving WGAN discriminator loss
"""
return scores_fake.mean() - scores_real.mean... | df305b008f6e0e92e917c7f1705cf11e4d78c9f6 | 556,409 |
def _extract_variants(address, variants_str):
"""Return the variants (if any) represented by the given variants_str.
:returns: The variants or else `None` if there are none.
:rtype: tuple of tuples (key, value) strings
"""
def entries():
for entry in variants_str.split(','):
key, _, value = entry.p... | 1644b10ec44e04b565b5b2a1bd67062e57750873 | 505,618 |
def extended_gcd(a, b):
"""Find the solution of ax + by = gcd(x, y), returns (x, y, gcd(x, y))"""
if b == 0:
return 1, 0, a
x, y, gcd = extended_gcd(b, a % b)
return y, x - (a // b) * y, gcd | f3dbc95e3b13d89079916948bf76ddba5184d6c6 | 185,565 |
def _slice_datetime_repr_prefix(obj_repr):
"""Takes a default "datetime", "date", or "timedelta" repr and
returns it with the module prefix sliced-off::
>>> _slice_datetime_repr_prefix('datetime.date(2020, 12, 25)')
'date(2020, 12, 25)'
"""
# The following implementation (using "startsw... | fa4778ab00caa1996041ad650baecb7b0db47b3b | 419,868 |
def is_permutation(a: int, b: int) -> bool:
"""Returns boolean if a and b are permutations of each other."""
s_a, s_b = str(a), str(b)
if set(s_a) != set(s_b):
return False
if len(s_a) != len(s_b):
return False
return sorted(list(s_a)) == sorted(list(s_b)) | e3fa9e013f5794ec44d739282d98f72b8b601ed2 | 679,808 |
def comb(N,P):
"""
Calculates the combinations of the integers [0,N-1] taken P at a time.
The output is a list of lists of integers where the inner lists are
the different combinations. Each combination is sorted in ascending
order.
"""
def rloop(n,p,combs,comb):
if p:
fo... | b3d6e1e2556ae951a0951c485a691cdb51095070 | 336,583 |
from datetime import datetime
def _parse_publishing_date(string):
"""
Parses the publishing date string and returns the publishing date
as datetime.
Input example (without quotes): "Wed, 09 Nov 2016 17:11:56 +0100"
"""
return datetime.strptime(string,"%a, %d %b %Y %H:%M:%S +0100") | e0ddc6da2a8acb90cceb4649f0d8491531408fcb | 689,821 |
import textwrap
def _dedent_under_first_line(text: str) -> str:
"""
Apply textwrap.dedent ignoring the first line.
"""
lines = text.splitlines()
other_lines = "\n".join(lines[1:])
if other_lines:
return f"{lines[0]}\n{textwrap.dedent(other_lines)}"
return text | 4abe7db2f67455d3d6453218022c144317936476 | 273,761 |
from typing import List
def erase_overlap_intervals(intervals: List[List[int]]):
"""
a variant for LeetCode 435
Given a list of intervals, remove minimal intervals to make the rest of the intervals non-overlapping.
注意:剩余列表中允许打乱原列表的顺序。如果要求保持原顺序,则需要在排序前先记录index。
Examples:
1. intervals: [[1, ... | 8ff2bdf43bff7ce5ff6c90f40474557b79f26acc | 204,869 |
def get_file_extension(filename: str) -> str:
"""
Finds the extension of a file given its full name.
:param filename: Complete filename.
:return: The extension file type of the file.
"""
return filename.split('.')[-1] | 740b4345e73d8b7b94a15b2aa2ab338fa4feeab5 | 483,020 |
def collect_solution_pool(m, T, n_hat_prime, a_hat_prime):
"""
This function collect the result (list of repaired nodes and arcs) for all feasible solutions in the solution pool
Parameters
----------
m : gurobi.Model
The object containing the solved optimization problem.
T : int
... | 5eaf9bede69c4c29e412c0311eab74ce1a8bf812 | 492,157 |
def calcPv(r, freq, periods, value):
"""
Parameters
----------
r:
discount rate;
the expected rate of return if every coupon payment was
invested at a fixed interest rate until the bond matures
freq:
frequency
periods:
periods to maturity
value:
future ... | f4ee0a34051a66b46f0d1652ea2c5f3d4d3aae1c | 442,563 |
def get_data_science_bookmarks(bookmarks):
"""Function to select the top level data science folder of bookmarks.
Returns the first element of bookmarks where 'Data Science' is one of the keys.
"""
for item in bookmarks:
if type(item) is dict:
if 'Data Science' in item.keys():... | ae8eb873e4775c030e67c49dd693fc9ee1fb902e | 649,983 |
import getpass
def get_user(prompt=None):
"""
Prompts the user for his login name, defaulting to the USER environment
variable. Returns a string containing the username.
May throw an exception if EOF is given by the user.
:type prompt: str|None
:param prompt: The user prompt or the default o... | fc392cfacc931ee915bb218a80e5db46245f2a1f | 11,108 |
def parse_lookup_table(lookupfile):
"""Parse the lookup table that contains AB genotypes."""
ab_geno = {}
with open(lookupfile, 'r') as l:
for line in l:
tmp = line.strip().split(',')
snp = tmp[0]
# add the line to ab_geno
ab_geno[snp] = tmp
return... | 693b4b11a24b1e57fdfb863c84339bedf6e95883 | 500,325 |
def to_http_url(list):
"""convert [hostname, port] to a http url"""
str = ''
str = "http://%s:%s" % (list[0], list[1])
return str | 021ecc3a32b1646b0dbe0ecf150d91b55d323523 | 518,223 |
def get_instance_ids(instances):
"""
Returns a list of instance ids extract from the output of get_instances()
"""
return [i["Instances"][0]["InstanceId"] for i in instances] | 69720ddf16ccbbee1bb44a780d793ea8b5af60cf | 375,174 |
def _Backward3a_T_Ps(P, s):
"""Backward equation for region 3a, T=f(P,s)
Parameters
----------
P : float
Pressure [MPa]
s : float
Specific entropy [kJ/kgK]
Returns
-------
T : float
Temperature [K]
References
----------
IAPWS, Revised Supplementary ... | cb0b9b55106cf771e95505c00043e5772faaef40 | 2,748 |
import re
def re_find(txt: str, regexp: str, i: int = 0) -> str:
"""Utility: search string txt for a regexp and return i-th group
(i.e. parenthesis) if match succeds. Default is whole match."""
match = re.search(regexp, txt)
if match:
return match.group(i)
return '' | 9bc087852a4fffb226505813304db2c4f0617c13 | 379,370 |
def _backslashreplace_backport(ex):
"""Replace byte sequences that failed to decode with character escapes.
Does the same thing as errors="backslashreplace" from Python 3. Python 2
lacks this functionality out of the box, so we need to backport it.
Parameters
----------
ex: UnicodeDecodeError... | f1100d986e3fabd169bf2e0a387621c900e2428c | 540,957 |
import requests
import re
def collect_metrics(website, pattern=None):
"""Retrieve metrics (response time, status code) from a given website.
Optionally, search for a regex pattern. Then publish to a Kafka topic.
Arguments:
website (str): URL of website to collect metrics from
pattern (st... | 35206802c9af165b7154db3a38207a2d6b438e83 | 145,538 |
def descale(data, data_max, data_min):
"""Reverse normalization
Args:
data (np.array): Normalized data
data_max (float): max value before normalization
data_min (float): min value before normalization
Returns:
[np.array]: Reverse-Normalized data
"""
data_descaled = ... | e078dc5eb9613a9106dd2210f467011525dcb646 | 98,977 |
def should_skip_build(metadata_tuples):
"""Takes the output of render_recipe as input and evaluates if this
recipe's build should be skipped."""
return all(m[0].skip() for m in metadata_tuples) | 0c4c54349bbea32733e9b0459fdfab9466dfdba8 | 604,147 |
def determine_scaling_factor(money_endowment: int) -> float:
"""
Compute the scaling factor based on the money amount.
:param money_endowment: the endowment of money for the agent
:return: the scaling factor
"""
scaling_factor = 10.0 ** (len(str(money_endowment)) - 1)
return scaling_factor | fed7d4598ee771ac857917010301df2d3722a0cb | 254,697 |
def fitAlgorithm(classifier, trainingData, trainingTarget):
"""
Fits a given classifier / pipeline
"""
#train the model
return classifier.fit(trainingData, trainingTarget) | ddc6a7b2f5c42e07e212c2a48fd1d35b1c77dab2 | 71,473 |
def wien(t):
"""The peak wavelength of a blackbody. Input in Kelvins, output in nm"""
return 2.9e6 / t | b40e6d295a373536d93268d8f7ea90c7b97b824a | 469,814 |
def makeSafeXML( someString:str ) -> str:
"""
Replaces special characters in a string to make it for XML.
"""
return someString.replace('&','&').replace('"','"').replace('<','<').replace('>','>') | 44b526c5e9e66cef747024f8eddd12cc4fc06cf5 | 496,319 |
def as_formatted_lines(lines):
"""
Return a text formatted for use in a Debian control file with proper
continuation for multilines.
"""
if not lines:
return ''
formatted = []
for line in lines:
stripped = line.strip()
if stripped:
formatted.append(' ' + l... | ba313e3041a971d3756ab7811ffdc23f31bfe8b1 | 419,325 |
def get_obj_in_list(obj_name, obj_list):
"""
Gets an object out of a list (obj_list) whos name matches obj_name.
"""
for o in obj_list:
if o.name == obj_name:
return o
print("Unable to find object by the name of %s in list:\n%s" %
(obj_name, map(lambda o: o.name, obj_li... | 42c575087e2148722a48a9735558bbf5ba30ddf7 | 556,257 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.