content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def hex_to_rgb(value):
"""Converts colour from hex triplet into rgb tuple.
value (str): colour as hex triplet
"""
value = value.lstrip('#')
lv = len(value)
return tuple(int(value[i:i+lv//3], 16) for i in range(0, lv, lv//3)) | 77f8141f055403cd84564820f0d826425e8500f8 | 639,359 |
def true_stress(tech_stress, tech_strain):
"""
Calculate the true stress data from technical data
Parameters
----------
tech_stress : array-like float
stress data from tensile experiments
tech_strain : list of float
strain data from tensile experiments
Returns
-------
... | 327c4912f4c5c8bbda9cd229c2eed8dd3e9bb798 | 639,364 |
import hashlib
def hash_string(strdata: str) -> str:
"""Hash a string
:param strdata: string data to hash
:return: hexdigest
"""
return hashlib.sha1(strdata.encode('utf8')).hexdigest() | 29d25ebe6993d3c8ac7c236cf020a4fc83aff61a | 639,366 |
def reciprocal_overlap(astart, aend, bstart, bend):
"""
Calculates reciprocal overlap of two ranges
:param `astart`: First range's start position
:type `astart`: int
:param `aend`: First range's end position
:type `aend`: int
:param `bstart`: Second range's start position
:type `bstart`... | 886afbba383a9a3c037b84df0ee30c1d01cc4131 | 639,371 |
import itertools
def combine_dictionaries(dictionaries):
"""Combine a list of non-overlapping dictionaries into one.
Args:
dictionaries (list): List of dictionaries.
Returns:
dict: The combined dictionary.
Examples:
>>> combine_dictionaries([{"a": 1}, {"b": 2}])
{'a... | f61535e51f8c8af5dd98adb526b8b428a6a17425 | 639,372 |
def tree_similarity_ratio(ted, t1, t2):
"""
Return the similarity ratio from 0 to 1 between two trees given their edit distance
`ratio` idea from [DiffLib](https://fossies.org/dox/Python-3.5.1/difflib_8py_source.html)
"""
# print(ted)
# import networkx as nx
# empty_tree = nx.DiGraph()
... | 5ed52f83aaafeaa64e9597ed628cf83c8fd9a454 | 639,373 |
def is_number(s):
"""
This function checks if given input is a float and returns True if so, and False if it is not.
:param s: input
:return: Boolean.
"""
try:
float(s)
return True
except ValueError:
return False | 652656c88719a886a1230dc514fd11d650deab04 | 639,376 |
from bs4 import BeautifulSoup
def soupify(html, vars=[]):
"""
Convert html string to beautiful soup
"""
return BeautifulSoup(html.format(vars), "html.parser") | 3018bb41bf59dc356d8d987b29ec01420b86a662 | 639,383 |
import array
def _prepare_for_sound(mls):
"""
Re-scale the MLS so that is a proper array of bytes. This allows us to use
it with an audio device. We assume 16-bit precision.
"""
new_mls = []
int_max = 2**15 - 2
for sample in mls:
if sample == 0:
# Min UInt16
... | fb90c3e4f1b9b2aa7dd36bd2310a48540495f048 | 639,384 |
import logging
def get_logging_level(level: str) -> int:
"""Get the logging level as a logging module constant.
:param level: `str` The log level to get.
:returns: The log level, defaults to `INFO`
"""
return getattr(logging, level.upper(), logging.INFO) | 06c64fc904c8269e7bb65cf9ec403f747eb8861d | 639,387 |
def get_model_name(step):
"""
Return filename of model snapshot by step
:param step: global step of model
:type step: int
:return: model snapshot file name
:rtype: str
"""
return 'network-snapshot-{:06d}.pth'.format(step) | 1517e3104bf5cae654f5d6350a177a1d16f8ac13 | 639,395 |
import hashlib
def sha256(s):
"""Return SHA256 digest of the string `s`."""
return hashlib.sha256(s).digest() | a27a485bebe0b14f7e70f5f6f665b03d1ea43069 | 639,399 |
def build_path(package_name: str) -> str:
"""Build path from java package name."""
return package_name.replace(".", "/") | 7ef955bf28cd60a3350420cab1160c15c46cee09 | 639,400 |
def extList(l, item):
"""Add 'item' to list 'l', return index of 'item'"""
l.append(item)
return len(l)-1 | da384911802053d67ef5b8409ad97917ced36049 | 639,401 |
def parse_branch_ref(filename):
"""Given a filename of a .git/HEAD file return ref path.
In particular, if git is in detached head state, this will
return None. If git is in attached head, it will return
the branch reference. E.g. if on 'master', the HEAD will
contain 'ref: refs/heads/master' so 'refs/heads/... | e7a9df3e72460b4bc3ac7f97fd6f830cda309b22 | 639,402 |
from typing import Dict
def calculateHandlen(hand: Dict[str, int]) -> int:
"""Calculate hand length
Args:
hand:
Returns:
int: the length (number of letters) in the current hand.
"""
return sum(hand.values()) | 830d95ed3379e74f561bd0de6f70ff69d2b9271f | 639,403 |
def normalize_url(url: str) -> str:
"""Normalize URL
Arguments:
url {str} -- A URL
Returns:
str -- A normalized URL
"""
# remove string after "?" to comply with Pydantic AnyHttpUrl validation
# e.g. http:/example.com/test.js?foo=bar to http://example.com/test.js
splitted = ... | 86131ea4afc377748b8d280f2486f7abfa0e19f4 | 639,412 |
import math
def calculate_tail_correction(num_particles, box_length, cutoff):
"""
The tail correction associated with using a cutoff radius.
Computes the tail correction based on a cutoff radius used in the LJ energy calculation in reduced units.
Parameters
----------
num_particles :... | 5b1571bd032c38a4a506e24fffcad448152f19c1 | 639,414 |
def get_surt_association_script(surt, sheet):
"""Creates the beanshell script for a SURT->Sheet association."""
return "appCtx.getBean(\"sheetOverlaysManager\").addSurtAssociation(\"%s\", \"%s\" );" % (surt, sheet) | a1ff769144714b4d00e6855f3220838895eee08f | 639,419 |
def get_citation_links(session, profile_url):
"""
From the given url to Google scholar page, extract all absolute links to
paper citations.
Args:
session (HTMLSession)
profile_url (str): a url to a person's Google Scholar page.
Returns:
list: list of absolute URLs to paper ci... | 38d040217db7b95c35a614011bbd2286c315991a | 639,424 |
from operator import add
def element_wise(list1, list2):
"""
Perform element wise sum between two lists.
"""
return list(map(add, list1, list2)) | cac2b99227701461f0a9f02f30195129fec69208 | 639,429 |
import torch
def sum_rightmost(value: torch.Tensor, dim: int):
"""Sum out ``dim`` many rightmost dimensions of a given tensor.
Args:
value: A tensor of ``.dim()`` at least ``dim``.
dim: The number of rightmost dims to sum out.
"""
if dim == 0:
return value
required_shape =... | 9214bc18e08cd08efa946ec84740c283901e06f5 | 639,431 |
from pathlib import Path
from typing import Optional
def load_latest_model(model_folder: Path) -> Optional[Path]:
"""Finds the latest model inside the folder where
all the models are saved
Args:
model_folder (Path): folder containing the models
Returns:
Path: file path of the most re... | 62818ca57b6e2e4ae97890c30eca1e21b6fd0d45 | 639,432 |
def Mgap(d, Cij):
"""
returns the resonator gap between the lid and resonator to provide the necessary capacitance:
given the capacitance and resonator diameter
equation 13
"""
return 0.695*d*d/(100*Cij-2.61*d) | 41338166b855ede68b9a02c83703809cdbe08cd1 | 639,433 |
def load_events(filename, energy_thr = 0.01, nof_events = -1):
"""
load photon events from a text file (W,E,X,Y,Z,WX,WY,WZ), remove events with energy below threshold
:param filename: file name to load events from
:param energy_thr: energy threshold, events with energy below threshold will be thrown out... | 817b65af714f40be30c173bcfd3f1dc80f32ac6a | 639,434 |
def bytes_to_hex(bytes_str):
"""Convert a byte string to it's hex string representation"""
return ''.join(["%02X " % ord(x) for x in bytes_str]).strip() | d4d8cca6483bb8859efb1fe5163a1b5c3d8339c8 | 639,435 |
def prefix(values, content):
"""
Discover start and separate from content.
Will raise ValueError if none of the starts match.
"""
for value in values:
if content.startswith(value):
break
else:
raise ValueError('invalid starts')
content = content[len(value):... | 54efd93d5611b40683d382c640e20a6b43c08827 | 639,439 |
def add_inputs(input_1: float, input_2: float, *extra) -> float:
"""
adds 2 or more numbers together
:param input_1: first number
:type input_1: float
:param input_2: second number
:type input_2: float
:return: all the inputs added together
:rtype: float
"""
... | a28e92787f51a2b4525562dcfb74ffd9a3c61d3b | 639,442 |
def applianceSystemStoragePath(config):
"""
Returns the path to the internal appliance persistent storage.
"""
return config['storage.system.path'] | 2af2ec4ccd4a9999b00370c0cf251c293053a6eb | 639,446 |
import math
def DistanceBetweenCoordinates(lat1, lon1, lat2, lon2):
"""Distance between two coordinate pairs (in km)
Based on:
http://cyberpython.wordpress.com/2010/03/31/python-calculate-the-distance-between-2-points-given-their-coordinates/
"""
lat1_r = math.radians(lat1)
lat2_r = math.radians(lat2)
l... | c808b03ccfad3e7b16a42bd58118159da00f1c8e | 639,447 |
import json
def read_result(outfile):
""" Reads the result of an experiment """
return json.load(open(outfile, "rb")) | 1fd7f75db7b5580f3064ff213e616ebd6c4428cd | 639,450 |
def directory_structure(tmpdir):
"""Create a directory structure like this:
root
_____|___________________
| | | |
repo Main.java epic.py other_repo
________|________ ______|_________
... | 601d630c2a6251ae88c5d86abd3320e0aa07e336 | 639,451 |
from typing import List
from typing import Union
from typing import Tuple
def linear_search(arr: List[Union[int, float, str]], ele: Union[int, float, str]) -> Union[Tuple[bool, int], Tuple[bool, None]]:
"""Linear search algorithm
Args:
arr (List[Union[int,float,str]]): array list to search
el... | 857648c19cd0438c381bb63e3a08209e0aee8de5 | 639,454 |
def _calculate_total_mass_(elemental_array):
"""
Sums the total weight from all the element dictionaries in the elemental_array after each weight has been added (after _add_ideal_atomic_weights_())
:param elemental_array: an array of dictionaries containing information about the elements in the system
... | 1c02c9ecbd09e7a3e74c7207dc435ee4e9ebbcf7 | 639,455 |
def _cleave(
sequence,
sites,
missed_cleavages,
min_length,
max_length,
semi,
clip_nterm_met,
):
"""Digest a protein sequence into its constituent peptides.
Parameters
----------
sequence : str
A protein sequence to digest.
sites : list of int
The cleavag... | 10660bf01ba6ca2fa012b7dbef86031fad1352c4 | 639,456 |
def find_link_href(links: list, rel: str) -> str:
"""Extract link href by rel for linkdto instances."""
return next(l for l in links if l.rel == rel).href | 952d4d9c81c40a5ae31b0f4881e0d46cd9b7f869 | 639,457 |
def _no_spaces(string, replace_with='_'):
"""
Remove whitespace from a string, replacing chunks of whitespace with a
particular character combination (replace_with, default is underscore)
"""
return replace_with.join(string.split()) | 3b37de82d840b1057c5d9ad716a32b9fdeddcd12 | 639,464 |
from typing import Dict
from typing import Any
def __get_cumulative_cases_count(data_json: Dict[str, Any]) -> int:
"""
Returns the cumulative number of cases stored in the given data point.
"""
try:
return data_json["cumCasesByPublishDate"]
except KeyError:
return 0 | 4e6ceef73880fe3430c92bc5a43deef545b01985 | 639,479 |
def get_copy(o, copy):
"""Returns copy of object."""
if copy:
return copy(o)
else:
return o | 613ea1f268bad62418970360dd966653aefe2688 | 639,495 |
from typing import Dict
from typing import Tuple
def calc_nsplits(chunk_idx_to_shape: Dict[Tuple[int], Tuple[int]]) -> Tuple[Tuple[int]]:
"""
Calculate a tiled entity's nsplits.
Parameters
----------
chunk_idx_to_shape : Dict type, {chunk_idx: chunk_shape}
Returns
-------
nsplits
... | ac241f1dc6616830c9bebf0ac0638e6d0fa6ce71 | 639,498 |
import typing
def IndentList(num_spaces: int, strings: typing.List[str]) -> typing.List[str]:
"""Indent each string in a list of strings by a number of spaces.
Args:
num_spaces: The number of spacces to indent by. Must be greater than or
equal to zero.
strings: The list of strings to indent.
... | 277e212089cd17f1950239c42557e27918ccac2a | 639,501 |
def overlapped_slices(bbox1, bbox2):
"""Slices of bbox1 and bbox2 that overlap
Parameters
----------
bbox1: `~scarlet.bbox.Box`
bbox2: `~scarlet.bbox.Box`
Returns
-------
slices: tuple of slices
The slice of an array bounded by `bbox1` and
the slice of an array bounded ... | b76ed091489b154db145d7f35f13bb90baedd840 | 639,502 |
def format_list(list1, fmt = '%16s', delimiter = ","):
"""
format list of numbers to string.
delimiter defaults = ','
"""
string1 = delimiter.join(fmt % h for h in list1) + '\n'
return string1 | 65a341b59f27867c7da069314b37dbd2cd95fa1b | 639,512 |
from typing import List
def piecewise_volume_conversion(
ul: float, sequence: List[List[float]]) -> float:
"""
Takes a volume in microliters and a sequence representing a piecewise
function for the slope and y-intercept of a ul/mm function, where each
sub-list in the sequence contains:
... | 87dc40bd9d09e95081ab6ed49ea550a8e9b59c9e | 639,514 |
from typing import Any
def add_price_in_dollars(row: Any) -> float:
"""
Calculate the price in dollars by converting the value of the 'priceInCents` to dollars.
Args:
row: The pandas row to be analysed
Raises:
N/A
Returns:
dollars: The price in dollars, calculated from the... | 296b0be078f3f084d0dc48f7c51c703662776035 | 639,515 |
import math
def square_image_shape_from_1d(filters):
"""
Make 1d tensor as square as possible. If the length is a prime, the worst case, it will remain 1d.
Assumes and retains first dimension as batches.
"""
height = int(math.sqrt(filters))
while height > 1:
width_remainder = filters % height
if ... | a39f20e8859dbd22172b4cddc2b59c5a0240b4db | 639,519 |
def filter_per_split(dataset, train=True):
""" Filter samples depending on their split """
return dataset['is_train'] if train else ~dataset['is_train'] | ef68d7bdec9b062027bff0405d4de259dfda64d0 | 639,522 |
def has_dependencies(node, dag):
"""Checks if the node has dependencies."""
for downstream_nodes in dag.values():
if node in downstream_nodes:
return True
return False | 51e31ab6ba283901caeaea7cf1e158b31e3670c2 | 639,523 |
def static_vars(**kwargs):
"""
Custom decorator to allow declaration of static variables like this:\n
@static_var(variable = 0)\n
def foo(parameters):\n
foo.variable += 1
"""
def decorate(func):
for k in kwargs:
setattr(func, k, kwargs[k])
return func
retu... | 4d7b3c7e8be75bc094007885fca40a6ad74dfe84 | 639,530 |
import re
def realname(module_name):
"""
Return the real name of a module. The real name of a modules
is in lower snake_case.
Transform a CamelCase name into snake_case name.
"""
reg_first = re.compile(r'(.)([A-Z][a-z]+)')
reg_all = re.compile(r'([a-z0-9])([A-Z])')
s1 = reg_first.sub(r... | 33982291832b0ab30237003c80c9b0a4e2aede68 | 639,533 |
def is_callback(func):
"""Check if function is callback."""
return "_pyhap_callback" in getattr(func, "__dict__", {}) | dc74cbb3ba12f836227564ded39fa23102219142 | 639,536 |
def has_points(user, points):
"""Returns True if the user has more than the specified points."""
return user.get_profile().points() >= points | 2907a3dd31ff36adc1010d91c9bcab5db0f1b987 | 639,537 |
def get_fig_size(ratio=None, scale=None):
"""Get size of figure given a ratio and a scale.
Parameters
----------
ratio: float
Something like 16:9 or 4:3
scale: float
A multiplicative factor to ccale the original figure keeping its ratio"""
ratio = 4 / 3.0 if ratio is None else r... | 3ae801bda79702ae095b8ec098ef9c966cf59837 | 639,538 |
def is_article_link(wikilink):
"""Return True is wikilink is an article link.
Parameters
----------
wikilink : str
Wikilink to be tested
Returns
-------
result : bool
True is wikilink is an article link
Examples
--------
>>> is_article_link('[[Danmark]]')
T... | c862c3d9655ac60d97cb4a7b0e102fa7bc3ee9e8 | 639,540 |
def timeToSeconds(d: int = 0, h: int = 0, m: int = 0, s: float = 0.0) -> float:
""" Return 'seconds' representation of a given time as defined by days, hours,
minutes and seconds.
Args:
d: number of days to add to returned seconds.
h: number of hours to add to returned seconds.
m: n... | 45a5abde77512c14241d48407aacc1569603e35a | 639,544 |
def dicts_are_consistent(d1: dict, d2: dict) -> bool:
"""
checks if all items whose keys are in (d1 and d2) are equal.
returns bool.
"""
return all(d1[k] == d2[k] for k in set(d1).intersection(set(d2))) | 645a4901e71a8273109aafec1cb6559e8fa779e8 | 639,546 |
def get_number_line(selected_file: str) -> int:
""" Return a int with the number line from sentences.txt """
with open(selected_file) as f:
return sum(1 for line in f) | 21da131ab2c8a176a86b6d098fea657f9f9e4779 | 639,547 |
def read_input(path: str):
"""
Read game board file from path.
Return list of str.
"""
with open(path, mode='r', encoding='utf-8') as data:
content = data.readlines()
for i in range(len(content)):
content[i] = content[i].strip()
return content | 2183619dd542762cf62dc7557319614df0341de1 | 639,554 |
def _GetProcStatusPath(pid):
"""Returns the path for a PID's proc status file.
@type pid: int
@param pid: Process ID
@rtype: string
"""
return "/proc/%d/status" % pid | ba1c6d322b15fcb62594b3f2ad7ff18a30ac1bbd | 639,555 |
import torch
def gaussian_radius(det_size, min_overlap=0.5):
"""Get radius of gaussian.
Args:
det_size (tuple[torch.Tensor]): Size of the detection result.
min_overlap (float): Gaussian_overlap. Defaults to 0.5.
Returns:
torch.Tensor: Computed radius.
"""
height, width = ... | 590a8c1b6c5c31b905d7d253da09664a54625676 | 639,562 |
def action_of(origin: str, destination: str) -> int:
"""Finds which action was taken from origin to destination.
If the states origin and destination are separated by one action, it returns
the numeric value of the action taken (0 = up, 1 = right, 2 = down, 3 = left).
It returns -1 if they are separate... | 57a720f348c23dc521dba5dd1602deb424256882 | 639,564 |
def title(name):
""" Write title keyword"""
return [f'*TITLE\n{name:s}\n'] | f9ff12bd0ff64373b7ebf21887b59a1cc3519d0f | 639,566 |
def get_resource_requests_from_networktab(networktab):
"""
Parse `networktab` to extract only `ResourceSendRequest` information.
"""
events = networktab['traceEvents']
network_events = []
for event in events:
if event['name'] == 'ResourceSendRequest':
network_events.append(ev... | 97e50596fbdd057878f2febfc49f3f7d81faa9f1 | 639,569 |
def Vdiode(Icell, Vcell, Rs):
"""
Calculate Vdiode from current, voltage and series resistance.
:param Icell: cell current [A]
:param Vcell: cell voltage [V]
:param Rs: cell series resistance [:math:`\Omega`]
:return: diode voltage [V]
"""
return Vcell + Icell * Rs | 45f9f7c02be6172c5ed4e36cb804a0199347ef99 | 639,571 |
from functools import reduce
import operator
def product(iterable):
"""
Returns the product of an iterable
If the list is empty, returns 1
"""
product = reduce(operator.mul, iterable, 1)
return product | 20fe35cb8b306b199fc0b85b061511ffcaae0c1a | 639,572 |
def nested_value(d, keys):
"""Access an element in nested dictioary `d` with path given by list of `keys`"""
for k in keys:
d = d[k]
return d | 0e42b078a4450422e08530ddb67066400d198b2d | 639,573 |
def to_hex(payload):
"""
Converts an int or long to hex but removes the "0x" at the start.
@rtype: str
@return: A string representing the number in hex without "0x".
"""
return hex(payload)[2:] | 08b28e4e2364fc3578a69c85478300a0549bccfb | 639,575 |
def GetRank(text, header):
"""
Get the rank under header.
Possible Headers: Tournament results, Match results
"""
headerStart = text.find(header)
found = text.find("Yomi AI", headerStart)
if found == -1:
raise Exception("MAJOR PARSING ERROR. Yomi AI text not found.")
en... | 159db975b9225ea25914ff2a39ca6d92757d5a5f | 639,576 |
def dump(file_path, yaml, objyaml):
"""Write the value of objyaml into file path."""
def start_end_lines(input_str):
"""Return formatted string"""
return "---\n{0}---\n".format(input_str)
with open(file_path, 'w') as target_yaml_file:
yaml.dump(objyaml, target_yaml_file, transform=st... | d2efea826a9d65117d8541b70e353ae91f28de4b | 639,578 |
import time
def timestamp_datetime(value):
"""
transfer unix time to formatted timestamp.
Args:
value (int): unix time.
Returns:
str: formatted time.
"""
time_format = '%Y-%m-%dT%H:%M:%S%z'
time_struct = time.localtime(value)
return time.strftime(time_format, time_str... | 8caaaf180682f9ece0703cdbe47945e26e63331b | 639,579 |
def adt_object_to_element_name(adt_object):
"""Returns XML element name for the given adt_object"""
objtype = adt_object.objtype
return f'{objtype.xmlnamespace.name}:{objtype.xmlname}' | 9b2c9490268ad5dd9ea387255d60d9440e1beff1 | 639,581 |
def max_discharge_rule(mod, s, tmp):
"""
**Constraint Name**: Stor_Max_Discharge_Constraint
**Enforced Over**: STOR_OPR_TMPS
Storage discharging power can't exceed available capacity.
"""
return mod.Stor_Discharge_MW[s, tmp] \
<= mod.Capacity_MW[s, mod.period[tmp]] \
* mod.Avail... | 0de0429758ce79d8bb49a1a2daf6181c031a2aee | 639,584 |
def add_eprint_to_bib(bib, eprint):
"""
Insert the eprint information in a given bibtex string
Parameters
----------
bib: str
The bibtex string without the arxiv number
eprint: str
The arxiv number
Returns
-------
bib: str
The bibtex ... | 703f011199a7d3730b8056cae8bb0cfafab6d1d2 | 639,588 |
def get_throw_descriptions(get_nb_floor_objects, initial_state, current_state):
"""
Get all 'throw' descriptions from the current state (if any).
Parameters
----------
get_nb_floor_objects: function
Function that gets the number of objects thrown on the floor of the current state compared to... | 81d89ccfcab034469be59ca1dd8c7bb6346b69af | 639,589 |
def _merge(listA, listB):
""" Merges two list of objects removing
repetitions.
"""
listA = [x.id for x in listA]
listB = [x.id for x in listB]
listA.extend(listB)
set_ = set(listA)
return list(set_) | 0d9a6f377855cae22388768effca23dda68ac5b3 | 639,590 |
def relu_backward(z, a_grad):
"""relu反向
:param z: shape[Out]
:param a_grad: shape[Out]
:return: shape[Out]
"""
return a_grad * (z > 0) | f9ec500feff6bb9360610c4297e61b6f0a521e24 | 639,595 |
import random
def randpop(seq):
""" removes and returns a random item from the sequence """
return seq.pop(random.randrange(len(seq))) | 7f4743ae672126f64940b5cec3a6d62bc149ecee | 639,597 |
import threading
def startWithCallback(process, onExit):
"""
Call process.start(), and then calls the function onExit when the
subprocess completes.
onExit is a callable object, will receive process as parameter.
"""
def runInThread(process, onExit):
process.join()
onExit(proc... | ca174aa1cc3b642cf520a8d404643d09ad41e97e | 639,598 |
from typing import Iterable
def read_nested_dict_value(nested_dict, nested_keys: Iterable, default_value=None, error_on_miss=False):
"""
Read a value from a series of nested dictionaries, such as returned by ruamel.yaml
:param nested_dict: The nested dictionaries (configuration map) to read from
:par... | 3ee4524ec5495b8936e3f6027a128544737e9d0e | 639,602 |
import re
def update_max_version(src, key, new_max_version, category):
"""
Examples
========
>>> src = '''
... sklearn:
... ...
... models:
... minimum: "0.0.0"
... maximum: "0.0.0"
... xgboost:
... ...
... autologging:
... minimum: "1.1.1"
.... | 4e2bc7f430f7ad2cce70dea18b27def00a496764 | 639,606 |
def c2k(c: float, r: int = 2) -> float:
"""Celsius to Kelvin."""
return round(c + 273.15, r) | c30c9af6d641da0167277af86608e5db0a0c20de | 639,608 |
def drop_duplicates(data):
"""Drop duplicate rows in a DataFrame."""
return data.drop_duplicates() | 9fd92cec19326ec584c8186e4fb6ccdce05fd24a | 639,609 |
def fixIoU(bb1, bb2):
"""
Calculate the fix Intersection over Union (IoU) of two bounding boxes.
fixiou = intersection_area / min(bb1_area, bb2_area)
Parameters
----------
bb1 : set
Keys: ('x1', 'y1', 'x2', 'y2')
The (x1, y1) position is at the top left corner,
the ... | 769e245a622c36550ca3fbc90896566c4a85eb61 | 639,611 |
import pickle
def load_pickle(parent_dir):
"""
Accepts a parent directory Path object
which can contain only one pickled file with a .pkl extension
Finds the file, loads it, and returns it
"""
# print(parent_dir)
filepath = list(parent_dir.glob('*.pkl'))[0]
with open(str(filepath), 'rb... | e9aba6608d945ad01894a1af24601af3d9e664e0 | 639,613 |
def date_to_epoch(date):
"""Convert a datetime stamp to epoch time."""
epoch_time = date.strftime('%s')
return int(epoch_time) | 088c3d28e5badda315908b735eaa15daf5cf559d | 639,615 |
def ParseAction(messages, action):
"""Converts an action string to the corresponding enum value.
Options are: 'allow' or 'deny', otherwise None will be returned.
Args:
messages: apitools.base.protorpclite.messages, the proto messages class for
this API version for firewall.
action: str, the action... | e13285d2a7873ecbdd7fcf7756e31d9653b7a5d1 | 639,617 |
import torch
def pad_charts(charts, padding_value=-100):
"""Pad a list of variable-length charts with `padding_value`."""
batch_size = len(charts)
max_len = max(chart.shape[0] for chart in charts)
padded_charts = torch.full(
(batch_size, max_len, max_len),
padding_value,
dtype=... | 349c7bd0b60a8a84bdea3abbbc7adff62a5d683f | 639,619 |
def array_to_string(array):
"""Turns a array into a string separated by §."""
string = ''
for s in array:
string += '§' + s
return string[1:] | 57d5f32c6cd24f8cb9dc1d184cc3e8933261727c | 639,620 |
from typing import Dict
def _filter_frequency(ngrams: Dict[str, int], min_freq: int) -> Dict[str, int]:
"""
Filter a ngram list for ngrams with a minimum frequency.
:param ngrams:
:param min_freq:
:return:
"""
output = {}
for (ngram, freq) in ngrams.items():
if freq >= min_fre... | 99582e66a201066808fc1ce525b10e7404023456 | 639,625 |
def convert_postag(pos):
"""Convert NLTK POS tags to SentiWordNet's POS tags."""
if pos in ['VB', 'VBD', 'VBG', 'VBN', 'VBP', 'VBZ']:
return 'v'
elif pos in ['JJ', 'JJR', 'JJS']:
return 'a'
elif pos in ['RB', 'RBR', 'RBS']:
return 'r'
elif pos in ['NNS', 'NN', 'NNP', 'NNPS']:... | c1d3c2e154ca6e98c19c3f398dd0aa689db535d2 | 639,627 |
def get_hierarchical_net_pos(net):
""" Get x,y positions for plotting hierarchical graph.
For example:
.. plot::
:include-source:
>>> import graphy
>>> G = graphy.graphgen.gen_hierarchical_net(5, 2)
>>> pos = graphy.graphgen.get_hierarchical_net_pos(G)
>>> graphy.p... | 1d7f2319403b958c942745865580df06e712c4e5 | 639,632 |
from typing import OrderedDict
def ordered_dict(iterable):
"""Create an OrderedDict from an iterable of (key, value) tuples.
"""
ordict = OrderedDict()
for key, value in iterable:
ordict[key] = value
return ordict | 696776a778877049ec41de7193162013699fa5e3 | 639,633 |
def pick_third_largest_num(sequence: list[int]) -> int:
"""数列から3番目に大きい整数を取得する
Args:
sequence (list): 整数のリスト
Returns:
(int): 3番目に大きい整数
"""
return sorted(sequence)[-3] | 3d21863a41af4acd2e50fe2999519a3a165a2941 | 639,636 |
def build_gnab_feature_id(gene_label, genomic_build):
"""
Creates a GNAB v2 feature identifier that will be used to fetch data to be rendered in SeqPeek.
For more information on GNAB feature IDs, please see:
bq_data_access/data_types/gnab.py
bq_data_accvess/v2/gnab_data.py
Params:
gene... | b9b6f8f4acb791c7478a621baef8997db503eb71 | 639,637 |
def domains_to_samples(domains, sample_column='contig_id', target_column=None):
"""
Group Domain DataFrame into a list of DataFrames and list of output states based on given sample_id column
:param domains: Domain DataFrame with multiple sequences (samples), each marked by a unique ID in the sample_column
... | 6114ffa4294d3a722e44e05b6164392def542867 | 639,639 |
def EncodePrivate(sk):
"""
Encode a private key into bytes (exactly 32 bytes for both
do255e and do255s).
"""
return bytes(sk) | 4763eb9bedf0b5d802b3ed3cd9441941c4567710 | 639,641 |
import re
def get_prefixlength(ip):
"""Returns the length of the network prefix, in bits."""
regex = r'(\d+)[.](\d+)[.](\d+)[.](\d+)[/](\d+)'
if not re.findall(regex, ip):
return ip
p = re.split(regex, ip)
return int(p[5]) | 6ac8e0c827175e13e8adb30010c93be46a35b49f | 639,647 |
from typing import Dict
import pathlib
import json
def load_git_info(input_path=None) -> Dict[str, str]:
"""
Load previously saved output of git_info from a json file.
Args:
input_path: Input path to json file. If None, the default will be
bclustering/git_info.json
Returns:
... | fcfba69430e91b36fb0e4f8047d2e3e673645729 | 639,648 |
def OutputGraphViz(scenario, final_tasks, output):
"""Outputs the build dependency graph covered by this scenario.
Args:
scenario: The generated scenario.
final_tasks: The final tasks used to generate the scenario.
output: A file-like output stream to receive the dot file.
Graph interpretations:
... | 2138632a92a2513adf4b78b913f83a8e85077681 | 639,654 |
def Linear(score, score_min, score_max, val_start, val_end):
"""Computes a value as a linear function of a score within given bounds.
This computes the linear growth/decay of a value based on a given score.
Roughly speaking:
ret = val_start + C * (score - score_min)
where
C = (val_end - val_start) /... | 8f39ba6b5d81b46c382b05c1d74d71926a775013 | 639,657 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.