content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
from pathlib import Path
import yaml
def loadConfigDict(configNames: tuple):
# pathLib syntax for windows, max, linux compatibility, see https://realpython.com/python-pathlib/ for an intro
"""
Generic function to load and open yaml config files
:param configNames: Tuple containing names of config fil... | 1bbee88e3ff5df7f26f1502eb34d72a33d01b348 | 655,434 |
def is_comment(string):
"""
Find out if line is a comment or line of code
:param string: line to analyze
:return: True if line is a comment
"""
chars = list(string)
if len(chars) <= 0:
return True
if chars[0] == "#":
return True
else:
return False | 2a6c761130bf608d7363334d95257d8d73332680 | 655,440 |
import zipfile
def un_zip(zip_file, uzip_folder=None):
"""Uncompression .zip file
Args:
zip_files: str, zip_file should be file path;
uzip_folder: str, uncompression files name.
Return:
uzip_folder: str, uncompression files name.
"""
assert zip_file[-4:]==".zip", '`zip... | 770b981aa7cc4576eaeee5d5e15b5912ea3c057a | 655,441 |
def extract_brackets(line):
"""Splits a scroll 'call line' into identifier + suffix."""
ident, _, enil = line[1:].partition("(")
thing, _, _, = enil.rpartition(")")
return ident, thing | 47b35a331ecf01c2772d6289f1ac8171f655573c | 655,442 |
def input_output01(input):
"""
Expects a list of lists as input,
outputs each sublist in a line comma delimited.
"""
return '\n'.join(','.join(map(str,sl)) for sl in input) | 9f433f33b741e8039239ad12b5bda5cfebdad1d9 | 655,446 |
def _str_to_bytes(value: str) -> bytes:
"""Convert ``str`` to bytes"""
return value.encode("utf-8") | 50f7065188c30aeec321eac9e14d880537b66119 | 655,453 |
import torch
def ordinal_accuracy(logits, levels, device='cpu', tolerance=0, reduction='mean'):
"""Computes the accuracy with a tolerance for ordinal error.
Parameters
----------
logits : torch.tensor, shape(num_examples, num_classes-1)
Outputs of the CONDOR layer.
levels : torch.tensor,... | 0c02598013044b4beefc28ddd8908edc64fe5423 | 655,455 |
def rho_top_liq(x_aver_top_mass, rho_lc_x_aver_top, rho_hc_x_aver_top):
"""
Calculates the destiny of liquid at top of column.
Parameters
----------
x_aver_top_mass : float
The average mass concentration at top of column, [kg/kg]
rho_lc_x_aver_top : float
The destiny of low-boill... | df34b2831f578b913187d92edc54751d8e49fcb8 | 655,460 |
def euclidian_distance(ptA, ptB):
"""
Returns the shortest path distance between the two Points
"""
if (ptA.X != ptB.X or ptA.Y != ptB.Y):
return ( (ptA.X - ptB.X)**2 + (ptA.Y - ptB.Y)**2 ) ** (1/2)
return 0.0 | e698fd2964116fd7462a3efe276217712f53cf17 | 655,462 |
def make_binder_pair( h1, h2 ):
"""Returns a binder pair from the two hits
A pair has the form:
( binder1, binder2, orientation1, orientation2 )
Where the binders are pssm names typically and the orientation describes
the strand the pssm binds to (true for positive strand).
"""
b1... | f498d326329c880bdcf26d2786b63b28656d4ab4 | 655,463 |
from typing import Union
from typing import List
def get_corresponding(
value_or_matrix: Union[int, List[List[int]]], row: int, col: int
) -> int:
"""If `value_or_matrix` is a matrix, extract the value in cell specified by
`row` and `col`. If `value_or_matrix` is a scalar, just return it.
"""
if i... | bf838089464f48d2cb12a63e78a9fa0695a6303c | 655,465 |
import torch
def convert_frequencies_to_mels(f: torch.Tensor) -> torch.Tensor:
"""
Convert f hertz to m mels
https://en.wikipedia.org/wiki/Mel_scale#Formula
"""
return 2595.0 * torch.log10(1.0 + f / 700.0) | 05529939f23a53c3ff65e137ce89757ef5203417 | 655,466 |
def strip_line_nums(line):
"""
Strip line numbers from the start of a line.
"""
# Find the end of a number at the start of the line, if there is one.
pos = 0
line = line.strip()
for c in line:
if (not c.isdigit()):
# Don't delete numeric labels.
if (c == ':')... | 62c3460e49f1cf7bb7b0245369068e95521e53bf | 655,475 |
def total_count(expression):
"""
Compute total count library size.
:param expression: Expression count matrix with genes as rows and samples as columns
:return: integer total count library size per sample
"""
return expression.sum(axis=0) | 51374fca9d9d13066900402f5a8f34149569e2a3 | 655,477 |
def filename_dist(dist):
""" Return the filename of a distribution. """
if hasattr(dist, 'to_filename'):
return dist.to_filename()
else:
return dist | 3791f8b03b254108a2a97bc725fd2802187367bd | 655,482 |
def calcul_max(l: list) -> int:
""" returns the sum of the 2 highest elements of l """
_l = list(l)
max1 = max(_l)
_l.remove(max1)
max2 = max(_l)
return max1 + max2 | f62b53959e118ac5466edbdb04100e42c4f40bff | 655,485 |
def _s2_st_to_uv(component: float) -> float:
"""
Convert S2 ST to UV.
This is done using the quadratic projection that is used by default for S2. The C++ and Java S2
libraries use a different definition of the ST cell-space, but the end result in IJ is the same.
The below uses the C++ ST definition... | a78fa1ac89f74b3aa9bfc0585d10f440e6392391 | 655,486 |
def delegate(connection, identity_token, whitelist=None):
"""Returns authentication token and cookies from given X-MSTR-
IdentityToken.
Args:
connection: MicroStrategy REST API connection object
identity_token: Identity token
whitelist: list of errors for which we skip printing erro... | e0d3e8f7f08945e7da6f162564452f5c1d974027 | 655,490 |
def confirm_name(message, name, force=False):
"""Ask the user to confirm the name.
Parameters
----------
message: str
The message to be printed.
name: str
The string that the user must enter.
force: bool
Override confirmation and return True. Default: False.
Returns... | 1acc14ed5d5226eb638446299489aa1c3ed0b36e | 655,491 |
def parse_encode_biosample(data):
"""Parse a python dictionary containing
ENCODE's biosample metadata into a dictionary
with select biosample metadata
:param data: python dictionary containing ENCODE' biosample metadata
:type s: dict
:return: dictionary with parsed ENCODE's biosample meta... | 3438fd4f1d38ff8e654c6b69036682ee6dc6c053 | 655,493 |
import json
import hashlib
def hash_dict(nested_dict):
""" Returns hash of nested dict, given that all keys are strings
"""
dict_string = json.dumps(nested_dict, sort_keys=True)
md5_hash = hashlib.md5(dict_string.encode()).hexdigest()
return md5_hash | 5f518698154b351ca38b8027f047b4a1153f2c83 | 655,496 |
from typing import Union
def milimeter_mercury_to_bars(mm_hg: float, unit: str) -> Union[float, str]:
"""
This function converts mmHg to bar
Wikipedia reference: https://en.wikipedia.org/wiki/Bar_(unit)
Wikipedia reference: https://en.wikipedia.org/wiki/Millimetre_of_mercury
>>> milimeter_mercury... | 71fc982cbaf0f43d493c9a20dcedb609b9009ecd | 655,498 |
def print_exptree(root):
"""
Print out an expression tree object via recursion.
Args:
root: expression tree (object type)
"""
# Empty tree
if root is None:
return 0
# Leaf node
if root.left is None and root.right is None:
return print(f'-- leaf: {root.data}'... | f95dbf1523b2222f72af40268edd8366dc5a2d43 | 655,500 |
import click
def valid_band(ctx, param, value):
""" Check image band validity (band >= 1)"""
try:
band = int(value)
assert band >= 1
except:
raise click.BadParameter('Band must be integer above 1')
return band | 9a95277c8ef6122a8f25bd712f11a8155e7ae0fb | 655,504 |
import socket
def get_node_ip_address(address="8.8.8.8:53"):
"""Determine the IP address of the local node.
Args:
address (str): The IP address and port of any known live service on the
network you care about.
Returns:
The IP address of the current node.
"""
ip_address, port = address.split(... | 039fdb773f1b392669d45bd98a87005e4a463f39 | 655,505 |
from typing import Sequence
from typing import List
def indexify(sequence: Sequence, index_source: Sequence) -> List:
"""For the given `sequence`, get the index of each item in the `index_source`"""
return [index_source.index(item) for item in sequence] | f06e44ba43a12433390475166f4b30ca32bcf1f3 | 655,509 |
def _decayed_value_in_linear(x, max_value, padding_center, decay_rate):
"""
decay from max value to min value with static linear decay rate.
"""
x_value = max_value - abs(padding_center - x) * decay_rate
if x_value < 0:
x_value = 1
return x_value | faae3ebf1eb98758aa798f02c644c8d8370d9216 | 655,510 |
import json
def read_json_file(path: str):
"""Read a json file into a dict."""
with open(path, 'r') as f:
data = json.load(f)
return data | ad266f43de9d7dcec214dd2e17326052f2b185fe | 655,512 |
import string
import random
def generate_session_id(size=32, chars=string.ascii_letters+string.digits):
"""
Generate session id - 32 length string
with ascii letters and digits
"""
return ''.join(random.choices(chars, k=size)) | 4e306e2214bf759054c46a9bd90c461bc3930062 | 655,514 |
def get_chars(path_to_vocab):
"""
Return the list of all characters found in the vocabulary.
"""
chars = set()
with open(path_to_vocab) as f:
for line in f:
chars.update(line.rstrip())
return chars | b8422548a42b63e2d27ad81d2904739d027e1d73 | 655,516 |
def fill_nan(df,list):
"""
Fill nan values with either mean or mode
Parameters
----------
df : dataframe
dataframe used for checking and filling nan values
list: list
list of columns to be checked
Returns
-------
df : dataframe
modified dataframe with no nan... | 5f07eb835c4e20b08e98d319b4749694ad81474f | 655,518 |
def cidade_pais(cidade: str, pais: str) -> str:
"""
-> Devolve o nome da cidade e do seu país formatados
de forma elegante.
:param cidade: O nome da cidade.
:param pais: O nome do país.
:return: Retorna a string -> 'Cidade, País'
"""
return f'{cidade}, {pais}'.title() | bf6412dcff2d27be910ebeda9442384442bd50e3 | 655,520 |
def create_envs(service_component_name, *envs):
"""Merge all environment variables maps
Creates a complete environment variables map that is to be used for creating
the container.
Args:
-----
envs: Arbitrary list of dicts where each dict is of the structure:
{
<environment... | b53e81a2368da1bc8991a63b66173ccf1acb31f0 | 655,523 |
def get_underline(string):
"""
Return an underline string of the same length as `str`.
"""
return "="*len(string) + "\n" | f8cd102447c0788af5c1385d8e01018d6f3eb71a | 655,529 |
def width_multiplier_op(filters: int,
width_multiplier: float,
min_depth: int = 8) -> int:
"""Determine the number of channels given width multiplier"""
return max(int(filters * width_multiplier), min_depth) | 872fff290eba98c4272ec74416bbf6b52462bed2 | 655,531 |
def get_status(runs):
"""Get the most recent status of workflow for the current PR.
Parameters
----------
runs : list
List of comment objects sorted by the time of creation in decreasing order.
Returns
-------
status : string
The most recent status of workflow.
Can ... | 081d5fb6e8218edcbf25adb9f8b1eeb2d2add1a1 | 655,532 |
from typing import Tuple
from typing import Dict
def parse_options_header(value: str) -> Tuple[str, Dict[str, str]]:
"""Like werkzeug.http.parse_options_header(), but ignores the options."""
return value.partition(';')[0].strip(), {} | 1f50d4328061d763c712422a130dc0877a688388 | 655,533 |
def backdoor_examples(xs, backdoor, eps):
"""
Inject a backdoor into training examples with norm epsilon.
"""
return xs + backdoor * eps | 86cb1c986f7ae78b88789bd613b41567d766f10f | 655,534 |
from pathlib import Path
import re
def normalise_nci_symlinks(input_path: Path) -> Path:
"""
If it's an NCI lustre path, always use the symlink (`/g/data`) rather than specific drives (eg. `/g/data2`).
>>> normalise_nci_symlinks(Path('/g/data2/v10/some/dataset.tar')).as_posix()
'/g/data/v10/some/data... | 9dde3bfc5750ac9bd50680a6ab50b3db9699dd09 | 655,538 |
def calc_mean(values):
"""Calculates the mean of a list of numbers."""
values_sum = 0
for value in values:
values_sum += value
return values_sum / len(values) | 4db43d762ecc99d75c42e87992935d7f9c9a9feb | 655,540 |
from datetime import datetime
def datetime_serializer(obj):
"""Convert a datetime object to its string representation for JSON serialization.
:param obj: datetime
"""
if isinstance(obj, datetime):
return obj.isoformat() | cbdb7e8d68d2f2485243db24f4083946635ab469 | 655,542 |
def compute_turbulence_intensity(mean_col, std_col):
"""
Compute turbulence intensity
Args:
mean_col(:obj:`array`): array containing the wind speed mean data; units of m/s
std_col(:obj:`array`): array containing the wind speed standard deviation data; units of m/s
Returns:
:ob... | fc22720b98351006ab09580e2b0155ac76131deb | 655,543 |
def set_pairing_bit_on_device_type(pairing_bit: bool, device_type: int):
"""
Shifts the pairing bit (True = 1, False = 0) 7 bits to the left and adds
the device type
"""
return (pairing_bit << 7) + device_type | 83d5f88c24103ef3086bc1f28e3335e132b053a1 | 655,550 |
def bits2str(inp):
"""
Convert a list of bits into a string. If the number of bits is not a
multiple of 8, the last group of bits will be padded with zeros.
"""
bs = [1<<i for i in range(8)]
return ''.join(chr(sum(bv if bit else 0 for bv,bit in zip(bs, inp[i:i+8]))) for i in range(0, len(inp), ... | 0babfa6786be16ce78e17affa1086a76739375d2 | 655,553 |
import random
def Ui(lo, hi):
"""Uniformly distributed integer, inclusive limits."""
return random.randint(lo, hi) | f2cd9020ff8297367c387cd14b27cf50e75bb59f | 655,555 |
def get_xpath_for_date_of_available_time_element(day_index: int) -> str:
"""
The element showing date of the available time is found in the div having the xpath:
'/html/body/div[4]/div[2]/div/div[5]/div/div[2]/div[3]/div[N]/span'
^
where N ... | 81a3cd1a88c47cfd2cb1b815354ce4a6d2f9dca8 | 655,557 |
def applyOrderDic(order, aDic):
""" Apply order to aList.
An order of the form ["a","b","c"] means that the first element
should be aDic["a"], and so on.
"""
if order==[]:
return aDic.value()
else:
return map(lambda v:aDic[v], order) | 4850830bfdb9b1ad49885f783b65aa796e79d4a7 | 655,559 |
def _get_set_env_var_command(name, value):
"""Return command to set environment variable on device."""
return ['--env={n}={v}'.format(n=name, v=value)] | af01a35130b1b6e93fe4fc2b1de438108c6f0e08 | 655,561 |
def make_dict(table, key_col):
"""
Given a 2D table (list of lists) and a column index key_col,
return a dictionary whose keys are entries of specified column
and whose values are lists consisting of the remaining row entries
"""
table_dict = {}
for key in table:
table... | b52481a7e930857f62b9572a021dff83fbda5ef2 | 655,562 |
from typing import Any
import json
def serialize_json(obj: Any) -> str:
"""Serialize an object to JSON, removing quotes for special strings."""
return json.dumps(obj).replace('"____', "").replace('____"', "") | a9eb1b7aadf05d1b6f588b3d1a260363010eb875 | 655,564 |
import re
def get_index(part):
"""
check if the part is, e.g [123]
return 123 or None
"""
index = None
match = re.match(r'\[(\d+)\]', part)
if match:
index = int(match.group(1))
return index | 0e554f5f2fdbd4ee2d950401158b334e14ca0b99 | 655,565 |
def _vars_dir_for_saved_model(
saved_model_path # type: str
):
# type: (str) -> str
"""
Args:
saved_model_path: Root directory of a SavedModel on disk
Returns the location of the directory where the indicated SavedModel will
store its variables checkpoint.
"""
return saved_model_path + "/va... | 231072db4b519f66b5722e175ea45ea814c3de56 | 655,567 |
from typing import Set
from typing import Callable
from typing import Any
from typing import Dict
def dict_by(keys: Set[str], f: Callable[[str], Any]) -> Dict[str, Any]:
"""Returns a dictionary with keys equal to the supplied keyset. Each value is
the result of applying f to a key in keys.
"""
return {k: f(k... | d60ba87a0bc3912ea77e1b70a73c301f6813ecb7 | 655,568 |
def toX(x, y=None):
"""
This function is used to load value on Plottable.View
:param x: Float value
:return: x
"""
return x | 32ff94906aaebf3305b4eb0ad4110838e2d38a08 | 655,569 |
from pathlib import Path
def remove_root(file_path: str) -> str:
"""Remove the first directory of a path"""
full_path = Path(file_path)
relative_path = Path(*full_path.parts[1:])
return str(relative_path) | 95dc0f948810f5a50a5c707a499d91c7c2045a4c | 655,575 |
import torch
def swish(x):
"""
Simple implementation of Swish activation function
https://arxiv.org/pdf/1710.05941.pdf
"""
return x * torch.sigmoid(x) | 68d3936d06c2cd8fda47df2bbc5d4d7b83aa3b06 | 655,577 |
from pathlib import Path
def get_definitions(base_directory_path):
"""
For given directory return all *_definition.py files in it and its subdirectories.
"""
return Path(base_directory_path).glob('**/*_definition.py') | 08c63b778112f7d1ec2de806e6c94334b00f943f | 655,579 |
def overplot_lines(ax, linelabels, lineloc):
"""
Overplots emission lines on an already existing plot with axes
Input:
ax: matplolib axis
linelabels: list of latex formatted names for the lines
lineloc: list of wavelengths of the lines (most likely in Ang)
Output:
ax2: re... | d82f24ad9366defafc11e2d3ac7739659dcf1a04 | 655,583 |
import re
def remove_chars(text, chars, replace_with=None):
"""
Removes chars from text or replaces them with the input.
Also removes any extra whitespaces which might have been
introduced.
: param text : text upon which the processing is done
: param chars : chars to search fo... | 074581e6ce3a45440d7822d1018ad19e0d98be2a | 655,590 |
def myreadlines(self):
"""Read and return the list of all logical lines using readline."""
lines = []
while True:
line = self.readline()
if not line:
return lines
else:
lines.append(line) | ca0693ef7073588883e7537a3b588cd4b07b3597 | 655,592 |
def common_superclass_wnid(group_name):
"""
Get WordNet IDs of common superclasses.
Args:
group_name (str): Name of group
Returns:
superclass_wnid (list): List of WordNet IDs of superclasses
"""
common_groups = {
# ancestor_wnid = 'n0000425... | 3a8eab12790f761a382dbfda2443818a578822f9 | 655,593 |
def suma_serie(n: int) -> int:
"""Suma los elementos de la serie E_i = i^3 + 5, desde 1 hasta n.
:param n: número de elementos de la serie
:n type: int
:return: suma de los elementos de la serie
:rtype: int
"""
if n == 1:
return 6
else:
return (n ** 3 + 5) + suma_ser... | a876e7c274f7f390da3575733944a10a8a17bf8c | 655,594 |
def NonsfiLoaderArch(target):
"""Returns the arch for the nonsfi_loader"""
arch_map = { 'arm32' : 'arm',
'x8632' : 'x86-32',
'mips32' : 'mips32',
}
return arch_map[target] | 39d5ebc6839e57d2c052d702b052418a262d8edf | 655,595 |
def tree_unflatten(flat):
"""Nest depth-1 tree to nested tree
{'a.b.c': x} -> {'a': {'b': {'c': x}}} """
def recursion(k, v, out):
k, *rest = k.split('.', 1)
if rest:
recursion(rest[0], v, out.setdefault(k, {}))
else:
out[k] = v
d = {}
for k, ... | db66f3cf55e7f6d1ec247d4643226188bc793a6d | 655,596 |
def linear_derivative(z):
"""Linear activation function derivative"""
return 1 | 9e8dd4cdbb54d0ddfa90a375a4b539706db9d0e9 | 655,602 |
def _season_overflow(season, moved_year, now):
"""Pushes illegal seasons ints into the next/previous year."""
if season > 4:
while season > 4:
if moved_year is None:
moved_year = now.year + 1
else:
moved_year += 1
season -= 5
elif ... | 086b3a54700cc0aa447499ffedf33a58e32173c7 | 655,604 |
def get_slope(vector_one, vector_two):
"""Get the slope of a line specified by two vectors"""
return(vector_two[1] - vector_one[1])/(vector_two[0] - vector_one[0]) | 2d20b5fe0fe3734fb66b0b2fc7a3a7aee2811694 | 655,605 |
import itertools
def find_anagrams(word, dictionary):
"""Find all anagrams for a word.
This function only runs as fast as the test for
membership in the 'dictionary' container. It will
be slow if the dictionary is a list and fast if
it's a set.
Args:
word: String of the target word.
... | a7b7f32e673858124ef2ab63284387fdc1d077d2 | 655,608 |
def count_on_screen(screen, wanted):
"""Count occurrences of wanted on the screen."""
return list(screen.values()).count(wanted) | 49a0fc0773139e3279de5b19d0e26bcfb1e722a5 | 655,609 |
def googlenet_params(model_name):
""" Map VGGNet model name to parameter coefficients. """
params_dict = {
# Coefficients: aux_logits, transform_input, blocks, image_size
"googlenet": (True, True, None, 224),
}
return params_dict[model_name] | e7a3320b1dbc118569e12ec736c7faa4843d3338 | 655,612 |
import hashlib
def make_merkle(blob_name: str) -> str:
"""Creates a "merkle" by hashing the blob_name to get a unique value.
"""
m = hashlib.sha256()
m.update(blob_name.encode("utf-8"))
return m.hexdigest() | 1f61b235746e8ae34fe1e0b24e6d141d99517b64 | 655,615 |
def _get_query_parameters(module_params):
"""Builds query parameter.
:return: dict
:example: {"$filter": Name eq 'template name'}
"""
system_query_param = module_params.get("system_query_options")
query_param = {}
if system_query_param:
query_param = dict([("$" + k, v) for k, v in s... | 42f98957b3de2661f36a15fd768a6c10b1a62615 | 655,618 |
def pipes(stream, *transformers):
"""Pipe several transformers end to end."""
for transformer in transformers:
stream = stream.pipe(transformer)
return stream | 93e0ae105e03500d9cb912f900384457910eea72 | 655,619 |
def pad_sentence_batch(sentence_batch, pad_int):
"""Pad char seq with <PAD> so that each char sequence of a batch has the same length"""
max_seq = max([len(seq) for seq in sentence_batch])
padded_batch=[]
for seq in sentence_batch:
temp=[]
for char in seq:
temp.append(char)
... | 80466026bb0d422984c6eff40c62f65be16b51fa | 655,625 |
def moveIntToBoolList(i):
"""
Convert an integer in the range [0, 7] to a list of 3 boolean values, corresponding to the binary representation
:param i: The integer
:return: The list of 3 boolean values
"""
# not using loops or append because this is faster, and this method only needs to work fo... | c150231abc31db538caa8df583c0389aadc38ce9 | 655,629 |
def as_text(value):
"""Returns the string representation of given value
Arguments:
value {any} -- Value to get the string representation for
Returns:
stringified text {String} -- String representation of given value
"""
return "" if value is None else str(value) | bf44d8dfb5878f8ff35239fe22b5c5558a6312f9 | 655,635 |
import random
def gen_mac(last_octet=None):
"""Generate a random MAC address that is in the qemu OUI space and that
has the given last octet.
"""
return "52:54:00:%02x:%02x:%02x" % (
random.randint(0x00, 0xFF),
random.randint(0x00, 0xFF),
last_octet,
) | 66ebfc64ebd2851e0cefab3a5cab2c60a4943ec5 | 655,639 |
def user_privileges(connection):
"""Get the list of privileges for the authenticated user.
The response includes the name, ID, and description of each
privilege and specifies which projects the privileges are valid for.
Args:
connection: MicroStrategy REST API connection object
Returns:
... | 74cc492f0d56714c7e3ccb7cb0822b22a9344a94 | 655,642 |
def combine_first_last_name(df):
"""
Combine first and last name if df has those columns.
"""
if 'first_name' in df.columns and 'last_name' in df.columns:
df['full_name'] = df['first_name'] + ' ' + df['last_name']
df.drop(['first_name', 'last_name'], axis=1, inplace=True)
return df | ae10f70b86c485e0ed65cbdb44036f03b485250a | 655,644 |
def min_if_exist(n1, n2):
"""
Returns the minimum between two numbers, or the only defined number
(in case the other is `None`) or `None` if none of the numbers are defined.
"""
if n1 is None and n2 is None:
return None
elif n1 is None:
return n2
elif n2 is None:
retu... | e50092db053254c6b4f0d1ae284b0d49b21a392b | 655,646 |
import hashlib
def generate_identifier(metadata: str) -> str:
"""Generate a (hopefully) unique identifier."""
obj = hashlib.md5(metadata.encode())
dig = obj.hexdigest()
return str(int(dig[:6], 16)) | bdd9f7bf0323f28d78bfbb1072a0b31189091fff | 655,647 |
import re
def check_global_attr_against_regex(ds, attr, regex):
"""
Returns 0 if attribute `attr` not found, 1 if found but doesn't match
and 2 if found and matches `regex`.
:param ds: netCDF4 Dataset object
:param attr: global attribute name [string]
:regex: a regular expression definition [... | 66ada65616c8e6bb713a4e17dfa5298a2f332ae9 | 655,651 |
def ordinal(n, combine=False):
"""
Return the ordinal of the number n.
If combine then return the number concatenated with the ordinal
"""
number_string = str(n) if combine else ""
special_cases = {1: "st", 2: "nd", 3: "rd"}
if not 10 <= n % 100 <= 20 and n % 10 in special_cases:
re... | 9c2ceaff2f1f9b7d1d0ac3ff4951a65c9c4afae6 | 655,654 |
def npieces(request):
"""Number of collocation pieces."""
return request.param | c98349245b5d846ff45e295e70898a2b36429efc | 655,655 |
def apply_op(input_layer, operation, *op_args, **op_kwargs):
"""Applies the given operation to this before without adding any summaries.
Args:
input_layer: The input layer for this op.
operation: An operation that takes a tensor and the supplied args.
*op_args: Extra arguments for operation.
**op_k... | 9c1b47180772689ea2bc5316b35765823b6ea2e8 | 655,657 |
def extract_job_fields(tags):
"""Extracts common job's metric fields from TaskResultSummary.
Args:
tags (list of str): list of 'key:value' strings.
"""
tags_dict = {}
for tag in tags:
try:
key, value = tag.split(':', 1)
tags_dict[key] = value
except ValueError:
pass
spec_name... | 0ce1884061673156c33ff6f2d4b990b80ddf459e | 655,661 |
def replace_string(text, replacements=None, whitespace=True):
"""A wrapper around str.replace where replacements is a dictionary:
original_string -> replacement_string
whitespace=True surounds the replacement with whitespaces.
"""
if not replacements:
return text
for ori, rpl in repl... | b1dae4d846c8b589ace8496dd73d7a2d4a2efc7b | 655,662 |
def get_domain(url: str, /) -> str:
"""Get domain from an url"""
return url.split('//')[-1].split('/')[0].split('?')[0] | 5e05257585346fa257b2f481aa8d04c32943ae65 | 655,666 |
def rectangles_intersect(rect1, rect2):
"""Returns True if two rectangles intersect."""
return all([(rect1[1][i] >= rect2[0][i]) and
(rect2[1][i] >= rect1[0][i]) for i in range(2)]) | 2428a4caead68340093933f443d27fb8afc0de43 | 655,668 |
from typing import Any
def typename(o: Any) -> str:
"""Return the full name (including module) of the type of o.
>>> typename(5)
'int'
>>> typename('text')
'str'
>>> typename(np.array([1]))
'numpy.ndarray'
"""
# https://stackoverflow.com/a/2020083
name: str = o.__class__.__qualname__
module =... | 19f983b68fd294e1614bef26c21d7c795796467a | 655,671 |
def null_count(df):
"""
Check a dataframe for nulls and return the number of missing values
"""
# Example Input (df = pd.DataFrame):
# > | column 0 | column 1 | column 2 |
# > | ----------- | ----------- | ----------- |
# > | NaN | 9 | 10 |
# > | 4 ... | ce7628f74d532b4c93ddb73ea55becd6f9c0d316 | 655,673 |
def round(addr: int, align: int, up: bool = False) -> int:
"""Round an address up or down based on an alignment.
Args:
addr: the address
align: the alignment value
up: Whether to round up or not
Returns:
The aligned address
"""
if addr % align == 0:
return ... | 0b77bd25d66a5522fb3dd568cc6f6ce0fedbd59c | 655,677 |
def is_group(message) -> bool:
"""Whether message was sent at a group."""
# See "type" at https://core.telegram.org/bots/api#chat.
return 'group' in message.chat.type | 38b719acadb132243b98af0bb95b7e33c47320a2 | 655,678 |
def is_not_excluded_type(file, exclude_types):
"""Return False if file type excluded, else True"""
if exclude_types:
for exclude_type in exclude_types:
if file.lower().endswith(exclude_type.lower()):
return False
return True | 6b4392c9662b55d211207a98b16c3c846558215d | 655,680 |
from functools import wraps
def consumer(func):
"""A decorator, advances func to its first yield point when called.
"""
@wraps(func)
def wrapper(*args, **kw):
gen = func(*args, **kw)
gen.next()
return gen
return wrapper | 331fe56003c14bf9ad89664e74ae92723f797d56 | 655,684 |
def excel_to_python(command_string):
"""
Returns the python equivalent of many excel formula names
"""
d = {
'SUM' : 'np.sum',
'AVERAGE' : 'np.mean',
'MAX' : 'np.max',
'MIN' : 'np.min',
'MEDIAN' : 'np.median',
'MODE' :... | e60d16f871a9d145306e365b28655687e1421c46 | 655,688 |
def get_end_pos(cls, start_pos, dimensions, left=False, up=False):
"""
calculate the end position if were to build an array of items
:param cls: Type
:param start_pos: (int, int)
:param dimensions: (int, int)
:param left: bool: default builds rightward
:param up: bool: default builds downwar... | a03b45f7137e835a8709da933a7a7e4f509f8569 | 655,690 |
def find_out_of_order_packet_indices(packet_ns):
"""
Return indices of packets which have apparently arrived out-of-order.
Specifically: return indices of any packet number which was less than the
previous packet number. For example, for the list of packet numbers:
0, 1, 2, 3, 5, 4, 6, 7.
re... | 67401aba9e62d999368027dc5479c4f4932dafc4 | 655,691 |
import base64
def base64_encode(s):
"""Encode a URL-safe string.
:type s: six.text_type
:rtype: six.text_type
"""
# urlsafe_b64encode() returns six.binary_type so need to convert to
# six.text_type, might as well do it before stripping.
return base64.urlsafe_b64encode(s).decode('utf-8').... | e63ce1c901c1f8822807a2da2d69544ec75e4fd5 | 655,695 |
def resultIsSuccess(res):
"""
JSON-decoded stake pool responses have a common base structure that enables
a universal success check.
Args:
res (dict): The freshly-decoded-from-JSON response.
Returns:
bool: True if result fields indicate success.
"""
try:
return res[... | 760c7e2ab210b6c972392e4b32eae6402f9759bc | 655,696 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.