content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def explode_locations(k):
"""Expands the given key ``k``. ``k``s of the form ``'1--3'`` or
``'1,2,3'`` are both expanded into the list ``['1', '2', '3']``.
Can deal with any combination, e.g. ``'1--3,6,9--11,a'`` results in::
['1', '2', '3', '6', '9', '10', '11', 'a']
Always returns a list, e... | f0af9ed9792d48111887ea5bdba256b9d9d8805e | 631,017 |
def _psd_mp_helper(ooi_hyd_data_obj, win, L, overlap, avg_method, interpolate, scale):
"""
Helper function for compute_psd_welch_mp
"""
ooi_hyd_data_obj.compute_psd_welch(win, L, overlap, avg_method, interpolate, scale)
return ooi_hyd_data_obj.psd | f191de119fd359471c532be334746881a4c0efb4 | 631,019 |
def mk_part_uri(uri, idx):
""" Appends fragment part to the uri recording index of the part
"""
return '{}#part={:d}'.format(uri, idx) | ca802c5e7dcbb5b2c0214f90b121b7dc827d4a29 | 631,024 |
def formatter(type):
"""Format floating point numbers in scientific notation
(integers use normal integer formatting)."""
if type == int:
return "%d"
elif type == float:
return "%.3e" | 072a60d9f2e1d8eb609eb3aa1fd5d11d31c64658 | 631,029 |
def linear_y(t0, t_step, slope, y0):
"""
A function to generate y values that satisfied to linear relationship with independent value t_list, slope, and start point of y
Parameters:
-----------
t0: t0, with dependent variable as startpoint_y
t_step: step of t
slope: slope
y0: startpoint... | bbaf3e86c2bd040cafacc600f19b4ab7449e2778 | 631,030 |
def complexAdd(complex1, complex2):
"""This method is used to add 2 complex numbers
Arguments:
complex1 {tuple} -- tuple of 2 representing the real and imaginary part
complex2 {tuple} -- tuple of 2 representing the real and imaginary part
Returns:
tuple -- tuple... | 01653bd5d05baaadca8f3a9b452d199421c237ee | 631,034 |
import torch
def collect(input, index, padding_idx=0):
"""
Perform a batched index select where index is given for each example
Args:
input: tensor of shape (B, T_1, dim_2, dim_3, ...)
index: tensor of shape (B, T_2)
Return:
tensor of shape (B, T_2, dim_2, dim_3, ...)
"""
... | 6121fc76b99e2f23b307d72da3ea3c2e752b72c0 | 631,035 |
import torch
def ndc_to_camera_space(Xn, P):
"""Transform point(s) from normalised device coordinates to camera space.
Args:
Xn (torch.Tensor): homogeneous point(s) in normalised device coordinates.
P (torch.Tensor): projection matrix.
Returns:
Xc (torch.Tensor): homogeneous poin... | 40e731bb349ed5248bf22993107c76245e4e0767 | 631,039 |
import time
def should_refresh(tok):
"""Returns True if the token must be refreshed because it expires soon."""
return time.time() > tok.expiry - 60 | 83e506cb7236813927fd8b5c29715e7f8a681ed3 | 631,040 |
def strip_quotes(s):
"""Trim white space and, if necessary, quote characters from s."""
s = s.strip()
# Strip quotation mark characters from quoted strings.
if len(s) >= 3 and s[0] == '"' and s[-1] == '"':
s = s[1:-1]
return s | 03effc4939b405f84b21feb2e67c5077cb46eee9 | 631,043 |
def set_lifecycle_events_enabled(enabled: bool) -> dict:
"""Controls whether page will emit lifecycle events.
Parameters
----------
enabled: bool
If true, starts emitting lifecycle events.
**Experimental**
"""
return {"method": "Page.setLifecycleEventsEnabled", "params": {"enab... | f9e2ca6972be192a0348c8b8c6b8ce395bf5f17f | 631,045 |
from typing import Tuple
import re
def parse_dice_string(dice_string: str) -> Tuple[int, int]:
"""parses formatted string to a dice roll, e.g. "2D6" for rolling two
six-sided dice.
Args:
dice_string: formatted string for roll.
Returns:
tuple of the count and sides for the roll.
... | dd594325ac3fdd60bff7e700ce7c723b7048373c | 631,048 |
def _get_county_variants(county: str) -> list:
"""
Given a county, returns a list of the possible variants of the county name.
Args:
county: A string literal that represents the county name.
Returns:
A list of the possible variants of the county name.
"""
county = county.replac... | b61356fc1845907c3b761dbdaed607ba965f531a | 631,054 |
def sniff_appendix_id_type(paragraphs):
"""
Detect whether an appendix follows the section paragraph indentation
scheme (a-1-i-A-1-i) or the appendix scheme (1-a)
The sniffer should return 'section', 'appendix', or None.
"""
for graph in paragraphs[:10]:
if graph.text.startswith('(a)'):... | 99fe8ec3b8c007fb5228060c92721a8b35e0fd9d | 631,057 |
def obj_func(xl, arg):
"""Wraps a spreadsheet computation as a Python function."""
# Copy argument values to input range
xl.Range('Inputs').Value = [(float(x), ) for x in arg]
# Calculate after changing the inputs
xl.Calculate()
# Return the value of the output cell
result = xl.Range("Outp... | a1d8b2f3384449fcef0b0f88b21946692c7270f7 | 631,058 |
def is_tree(character):
""" A tree character is defined as "#" """
return character == "#" | fc84c97bb77a8d1f2211e400abdf910c0761152d | 631,059 |
def testset_single(paths, rgen):
"""
Returns a test set where each test corresponds to a single probing path.
This function is reproducible: iteration proceeds through the probing-path dictionary
in sorted order, and a random shuffle is applied before returning.
"""
testset = list()
for src... | a61e9dd7153863162980f6390ee3183c5e0b4568 | 631,061 |
import getpass
def input_api_key() -> str:
"""Get the Meaki dashboard API key from the user's input.
-> Return the API key (string) with the leading & trailing whitespace
removed if the key is not a blank value.
"""
input_message = "Enter your Meraki's dashboard API Key: "
api_key = getpass.... | 69bbe71fac22ed3628adb12344a06c865a5a8340 | 631,062 |
import pkg_resources
def dump_env() -> list[str]:
"""
Get all packages and versions from the current environment.
conda list is slow, use pkg_resources instead
this might miss dev overrides
"""
return sorted(str(pkg) for pkg in pkg_resources.working_set) | 793ecbc3de6a0dbefb591a9376f22a644d60866c | 631,063 |
def body(expr):
"""Gets the body of a parsed lambda (represented as 2-tuples)"""
assert type(expr) == tuple
return expr[1] | 40f51184c9d48be56c91291f645113d3b3485b7f | 631,064 |
def key2param(key):
"""Converts key names into parameter names.
For example, converting "max-results" -> "max_results"
Args:
key: string, the method key name.
Returns:
A safe method name based on the key name.
"""
result = []
key = list(key)
if not key[0].isalpha():
result.append('x')
f... | 064c2800c94767da7a499d3a842808fac9641947 | 631,065 |
from typing import Sequence
def timestamp_to_ms(groups: Sequence[str]):
"""
Convert groups from :data:`pysubs2.time.TIMESTAMP` match to milliseconds.
Example:
>>> timestamp_to_ms(TIMESTAMP.match("0:00:00.42").groups())
420
"""
h, m, s, frac = map(int, groups)
ms = fra... | 2928a0b14876e3b14ad8056bafbab5d540ead686 | 631,067 |
def box_sz(b):
""" Returns the box size"""
return ((b[:, 2]-b[:, 0]) * (b[:, 3]-b[:, 1])) | 5a38db0bcf11b5b31b42bf261e2cd09a07c4188c | 631,069 |
from typing import Dict
from typing import List
from typing import Any
def get_value(dictionary: Dict) -> List[Any]:
"""Return a list of values in a given dictionary."""
return list(dictionary.values()) | 956b2e23055657c2dda1a54c840ea548acdebdfd | 631,071 |
import random
def split_test_from_training_data(network, ratio=0.1):
"""
Splits a given network into two networks with disjoint edges randomly.
"""
test_edges = random.sample(list(network.edges()), int(len(network.edges()) * ratio))
training_network = network.copy()
training_network.remove_edg... | 589c2b4f8c56941bca70a7342e5a47a41e23ce86 | 631,072 |
def invert_dictionary(aDict):
"""Transforms a dict so that keys become values and values become keys"""
return {v: k for k, v in aDict.items()} | a4ec169b2f8d0857d4b22191c8823b17a03fc954 | 631,073 |
def expectation_value(state, operator):
"""
Calculates the expectation value of a superoperator for a quantum state.
Parameters
----------
state: np.ndarray
Vectorised density matrix of a quantum state.
operator: list of np.array
Quantum superoperator.
"""
return sum((s... | e9b8d89a47649209c1263956facd3bb043a052ad | 631,074 |
def find_block_from_timestamp(
w3,
timestamp: int,
low: int = 0,
high: int = 0,
search_range: int = 150_000,
accuracy_range_seconds: int = 180):
"""
A basic algorithm to find a block number from a timestamp.
Args:
w3: web3 instance
timestamp: Target block timestamp
... | 1d819e1494afa6b4d45d8864c576461f5dda6deb | 631,078 |
def percentile(N, P):
"""
Find the percentile of a list of values
@parameter N - A list of values. N must be sorted.
@parameter P - A float value from 0.0 to 1.0
@return - The percentile of the values.
"""
if len(N)==0:
return 0.0
n = int(round(P * len(N) + 0.5))
return N[n-... | 4ef0e9baad1f008e28b821ee7c65177d50e5b8fd | 631,082 |
def problem1(individual):
"""
Implements the first test problem ("bi-objetive Sphere Model").
Variables = 2
Objetives = 2
f(x) = (x'x, (x - a)'(x - a))' with a = (0, 1)' and a, x element of R^2.
Bounds [0, 1]
@author Cesar Revelo
"""
a = [0,1]
f1 = (individual[0] ** 2) + (... | 8a0683de94051a752b4168da90fa63aca6c5493a | 631,083 |
def get_team(teams, team_input):
"""
Returns desired Team from Teams
:type teams: Teams
:type team_input: string
:rtype: Team
"""
for team in teams:
if team_input.lower() in team.name.lower():
return team | 2e3affdd9bd555f4f49939913f0287a3971672e5 | 631,085 |
from typing import List
def _parse_online_cpus_string(raw_string) -> List[int]:
"""
Parses string returned by /sys/devices/system/cpu/online
and returns a list of online cores
"""
parsed_cpus_info = []
for nr in raw_string.split(','):
if '-' not in nr:
parsed_cpus_info.appe... | d0932b855a6211cab6ef032d4ade8661fd23e3ee | 631,086 |
def mimebundle_to_html(bundle):
"""
Converts a MIME bundle into HTML.
"""
if isinstance(bundle, tuple):
data, metadata = bundle
else:
data = bundle
html = data.get('text/html', '')
if 'application/javascript' in data:
js = data['application/javascript']
html +... | 4d32f50a241d2b64952bb4849ddbe52cb55d94a5 | 631,087 |
def wrapM(monad):
"""
Takes a monad and wraps it so that any attribute that is not
in the monad is automaticall forwarded to the monad value.
Complexity: O(1)
params:
monad: the monad to wrap
returns: the proxy object
"""
class Proxy():
"""The monad proxy object"""
... | f97fc22a43ab588c0ae9519a9baaee6ce5406a5a | 631,092 |
import importlib
def get_runner_constructor(suite_tag):
""" Returns the function to run for the test runner.
Args:
suite_tag: A str, locates the test runner for an API.
Returns:
A function to run the tests.
"""
module_name = "api_tests." + suite_tag.lower()
module = importlib.import_module(modul... | d9295bc5a19c3031941e7865fc285a33b2c1ec4a | 631,094 |
def set_or_check_min(x, min_x, var_name):
""" If x is None, set its value to min_x; also check that it is at least min_x.
:param int|float x: the value to check
:param int|float min_x: minimum required value for x
:param str var_name: name of the variable (for error logging)
:return: set/checked val... | aac0290c50a8e4b5145222c415e4a18289101070 | 631,097 |
from pathlib import Path
def batch(action, card_dir: Path, max_backup: int = 1):
"""Performs an `action` repeatedly across a given `region` and
`card_slot`.
Before using this function, ensure all parameters are valid.
Args:
action (function): the function to run in batch
card_dir (Pa... | 0b933da7ca35361c491ee2a24faca214dc74e863 | 631,098 |
def numberOfUniqueTranscripts(transcripts):
""" Given a list of transcripts, return the number of unique names.
"""
names = set()
for t in transcripts:
if t not in names:
names.add(t)
return len(names) | fddde42abaf87dd684ccf17c4a3a9f3326ed8bd8 | 631,104 |
def _break(bitstring,groupsize):
"""
Break a binary string into groups of groupsize digits.
For example, _break('1100001111',4) returns '11 0000 1111'
:param bitstring: The ASCII binary string to break into groups
:param groupsize: The number of bits to group together in each group
:return: A st... | 1cf511e6ef8b33dc24c3f577b6a73267bf7fb76a | 631,106 |
from pathlib import Path
def _is_file_exists(path: str) -> bool:
"""Whether the path is a file.
Args:
path: The file path.
Returns:
True if the path is a file, otherwise returns False.
"""
return Path(path).is_file() | 1b10c9c5f6b08367d20906ed82c924ed12df6587 | 631,109 |
def get_alternated_ys(ys_count, low, high):
"""
A helper function generating y-positions for x-axis annotations, useful when some annotations positioned along the
x axis are too crowded.
:param ys_count: integer from 1 to 3.
:param low: lower bound of the area designated for annotations
:param h... | e606ef555ff29285d4b7b77076939e66b8997856 | 631,116 |
def height2rate(height_of_rainfall, duration):
"""
calculate the specific rain flow rate in [l/(s*ha)]
if 2 array-like parameters are give, a element-wise calculation will be made.
So the length of the array must be the same.
Args:
height_of_rainfall (float | np.ndarray | pd.Series): height... | 6a5b8c0eca91abdbed7d85cc031b3d3ff61aae9a | 631,117 |
import math
def round_up(number, precision=10.0):
"""Round a number up to the given precision.
Precision = 1.0 means 12345.6 gets rounded to 12346,
precision = 10.0 means 12345.6 gets rounded to 12350,
precision = 100.0 means 12345.6 gets rounded to 12400,
and so on.
"""
return math.ceil(number / precision... | bdb4151fdd1db5b3f64d5623770ed531ef36a9ac | 631,118 |
import math
def is_NaN(value):
"""
check value is nan or not
:param value:
:return: bool
"""
if isinstance(value, float):
return math.isnan(value)
else:
return value != value | 03eb4876ba9aabc7150a5d7f57f2d59c1b8aa879 | 631,119 |
def wordCount(wordListDF):
"""Creates a DataFrame with word counts.
Args:
wordListDF (DataFrame of str): A DataFrame consisting of one string column called 'word'.
Returns:
DataFrame of (str, int): A DataFrame containing 'word' and 'count' columns.
"""
return (wordListDF.group... | 8f4e546588a4a0c66955eebe0fab619acdf71a7e | 631,120 |
from typing import Pattern
from typing import Tuple
import re
def parse_vector(s: str, *, num_re: Pattern = re.compile(r"[\d.-]+")) -> Tuple[float, ...]:
"""Convert a vector string into a tuple."""
return tuple(map(float, num_re.findall(s))) | 9221798ef280f9d82f3282071ea16affa441f3d6 | 631,121 |
def param_name(p):
"""Extract parameter name from attributes.
Examples
--------
- ``fix_x`` -> ``x``
- ``error_x`` -> ``x``
- ``limit_x`` -> ``x``
"""
prefix = ["limit_", "error_", "fix_"]
for prf in prefix:
if p.startswith(prf):
i = len(prf)
return ... | 4d012bfec5412c6fef06146ae9c56b2cf860f7b9 | 631,126 |
def get_datafile_save_path(direc):
"""
get_datafile_save_path(direc)
Returns directory path amended with data file subdirectory.
Required args:
- direc (Path): directory path
Returns:
- direc (Path): amended directory path
"""
direc = direc.joinpath("data_files")
... | 46e55a22791c9894d0dd5ceabb29ec34e8f5e117 | 631,127 |
from typing import List
def is_valid_rule_one(character_count_range: List[int], character: str, password: str) -> bool:
"""
Return True if a password is abides to its asscoiated policy else return False
The policy is represented as follows: [1-3] a --> the character a should occur at least 1 time and at m... | f58ae7040d757f1cefd26cfef2d39977f33d6c10 | 631,131 |
def sanitize_name(name: str) -> str:
"""Make a name safe for use as a keyspace name."""
# For now just change dashes to underscores. Fix this more in the future
return name.replace("-", "_") | 70f373141f04d861e9dbe106f83951ada96f1c09 | 631,134 |
def dna_to_rna(seq):
"""
Converts DNA sequences to RNA sequences.
"""
rs = []
for s in seq:
if s == 'T':
rs.append('U')
else:
rs.append(s)
return "".join(rs) | 8d51dc102e7c7b5693a8f3d3daccef89ce65d2ba | 631,137 |
def problem_5_5(a, b):
""" Write a function to determine the number of bits required to convert
integer A to integer B.
Input: 31, 14
Output: 2
Solution: compute (a XOR b) and produce the number of 1 bits in the result.
"""
def num_set_bits(n):
count = 0
while n != 0:
... | 09c6c63af7d69f868867d43783a96f28676ce452 | 631,138 |
def is_aa_by_target_atoms(res):
"""Tell if a Residue object is AA
Args:
res: a Bio.PDB.Residue object representing the residue.
Return:
Bool. Wheather or not the residue is AA.
"""
target_atoms = ["N", "CA", "C", "O"]
for atom in target_atoms:
try:
res[atom]
... | f108e464e08ad82420fbef605d2f0135cfbd271b | 631,141 |
def extract_tags(lexicon):
"""Extract the set of all tags that are used in a lexicon.
The input lexicon should be a dict:
- lexicon = {wordform: {annotation: set(possible tags)}}
"""
tags = set()
for annotations in list(lexicon.values()):
tags.update(*list(annotations.values()))
r... | a9d86a5ade41210be35614515eaa9917b432e38a | 631,143 |
def get_index_lm(l, m):
"""
return the index of an array ordered as
[l=0 m=0, l=1 m=-1, l=1 m=0, l=1 m=1, ....]
"""
return (l+1)**2 -1 -l + m | 3b6cbbf6e5aedda39d5786af58d4403df8d33582 | 631,148 |
def has_overflow(grad_norm):
"""
Detect inf and NaN in grad_norm.
"""
if grad_norm == float('inf') or grad_norm != grad_norm:
return True
return False | 81d02f6a7240cb3d6591ad16da315220291ffd75 | 631,149 |
def mac_to_oid(mac):
"""
Converts a MAC address to an OID string
"""
return '.'.join([ str(int(x,16)) for x in mac.split(':') ]) | 823f68a1708a2d4db6184b3aedc003f9f8fe79fe | 631,150 |
def stuhlinger_velocity(total_efficiency, t_m, specific_mass):
"""Stuhlinger velocity, a characteristic velocity for electric propulsion missions.
The Stuhlinger velocity is a characteristic velocity for electric propulsion missions,
and is used in calculation of optimal specific impulse. It is defined as:... | 7fb20accb5e404a6845794b4c7b41e1de8514694 | 631,153 |
def real_part_of_complex_image(image_complex):
""" Returns a matrix of only the real parts of the elements of the input matrix """
return image_complex.real | 7cc869826ac7a463c48b2e67865ee9df5ceab2e6 | 631,154 |
def is_solution(cnf, assignment):
"""Test whether the given assignment is a solution to the CNF.
assignment is a dictionary from variable names to truth values.
It is not required that all variables in the CNF are assigned.
"""
for clause in cnf:
satisfied = False
for lit in clause... | 74c83fc8c0089261d3afa344ea9ee7e62e850621 | 631,156 |
import random
def weighted_choice(choices):
"""
Provides a weighted version of random.choice
:param choices: A dictionary of choices, with the choice as the key and weight the value
:type choices: list of tuple of (str, int)
"""
total = sum(weight for choice, weight in choices)
rand = ran... | b95c046fb009414f3b16bb78652169d0c7bdae84 | 631,159 |
def calculate_crashes_by_location(df):
"""
Calculates total number of crashes that occurred at each unique lat/lng pair and
generates a comma-separated string of the dates that crashes occurred at that location
Inputs:
- a dataframe where each row represents one unique crash incident
Outpu... | 355928578bf87b7c3f381813f162f1023587faa5 | 631,162 |
def get_loopbacks(yaml):
"""Return a list of all loopbacks."""
ret = []
if "loopbacks" in yaml:
for ifname, _iface in yaml["loopbacks"].items():
ret.append(ifname)
return ret | 9651f264f80a0bfee66b012c8998c467eedecb0b | 631,172 |
def mara_db_alias() -> str:
"""The database alias for mara internal data"""
return 'mara' | a06f1a08508382f10c96ddf97ec024b75f255f8f | 631,174 |
def prod_boiler(info):
"""
Boiler plate text for On-Demand Info for products breakdown
:param info: values to insert into the boiler plate
:param info: dict
:return: formatted string
"""
boiler = ('\n==========================================\n'
' {title}\n'
'===... | 848106e7f78dcad5e55b376c319d222c39f17725 | 631,181 |
def _unpad_img(padded_img, window_size, subdivisions):
"""
Undo what's done in the `_pad_img` function.
Image is an np array of shape (x, y, nb_channels).
"""
aug = int(round(window_size * (1 - 1.0/subdivisions)))
ret = padded_img[
aug:-aug,
aug:-aug,
:
]
# gc.col... | e5f58a2cb7faca8ad77b27ff26a1659138395785 | 631,187 |
def _conv_edges(x, y, fx, fy, sx, sy, n_in, n_out, g=1):
"""Number of edges in convolution."""
nx = (x - fx) / sx + 1
ny = (y - fy) / sy + 1
return (fx * fy * nx * ny * n_in * n_out) / g | 9178607c81c65a216360afd488bc87e93223a1a3 | 631,193 |
def return_group1(code_check):
"""
Input : L/G/R 6 character
Return : First digits of barcode
"""
if code_check == 'LLLLLL':
return 0
elif code_check == 'LLGLGG':
return 1
elif code_check == 'LLGGLG':
return 2
elif code_check == 'LLGGGL':
return 3
elif... | 08a8ab972566c330691a3ce2252158f19b1436ff | 631,194 |
def fdtfile2fieldstring(fdtfile):
"""Make a string of field definitions separated by % (percent sign)
reading from a fdtfile or just take the string and bring into shape:
e.g. 1,AA,20,A,NC,NN%1,F4,4,F,NU,DT=E(UNIXTIME)
:param fdtfile: fdtfile or field string
:return: tuple (number of fields... | dc292c7c0f7d5e8c6c14c5b108dfd28bad13a640 | 631,195 |
import json
def retrieve_history(dataset):
"""
Retrieve history_json field from NetCDF dataset, if it exists
Parameters
----------
dataset : netCDF4.Dataset
NetCDF Dataset representing a single granule
Returns
-------
dict
history_json field
"""
if 'history_js... | 4ff170ce4b34f4264df4eeacc0cf8feccf2bbc8b | 631,197 |
def get_traces_as_tokens(traces_df, col_ref="Activity"):
"""
Groups activities executions into traces
as a string of tokens
Ex:
Activity | Timestamp
-----------------------
START | 2019-09-01
A | 2019-09-01
B ... | d31194821fcbf19184b321f8a1fe0d44b5b67c28 | 631,198 |
def str_to_disp(s):
"""Convert a string to a user-friendly, displayable string by replacing
underscores with spaces and trimming outer whitespace.
Args:
s: String to make displayable.
Returns:
New, converted string.
"""
return s.replace("_", " ").strip() | 9e677a960c7eb4c1b94871c6d29e440266e54866 | 631,199 |
def to_currency(cents: int) -> str:
"""Convert a given number of cent into a string formated dollar format
Parameters
----------
cents : int
Number of cents that needs to be converted
Returns
-------
str
Formated dollar amount
"""
return f"${cents / 100:.2f}" | 086505884da17470c1d003acea23c44d6a1b605c | 631,202 |
def sum_of_self_exponential(numbers):
"""
Sums each digit raised to the power of itself
Ex: sum_of_self_exponential([2, 3, 4]) = 2^2 + 3^3 + 4^4 = 287
"""
return sum(pow(number, number) for number in numbers) | b27b88aa7a86786c9df37f4b851fb1806c6e4ba7 | 631,204 |
def subset_spike_time_by_channel(spike_time_labels, channel_id):
"""Subset spike times by specific channel ID
Args:
spike_time_labels: A numpy array of shape (n_spikes, 2), each row is [time, channel_id]
channel_id: int, channel_id
Return:
a subset of spike_time_labels from a pa... | 5f1b665cca9d30a3194199304797c68036b66499 | 631,208 |
from datetime import datetime
def check_date_time(
y: int, mon: int, d: int, h: int = 0, minute: int = 0, sec: int = 0
) -> bool:
"""Checks if the provided date and time is valid."""
try:
datetime(y, mon, d, h, minute, sec)
except ValueError:
return False
return True | 6b268a968e446a849aa873887c6804e5c248ae53 | 631,211 |
def square(x):
"""Return the square of `x`.
Parameters
----------
x : int or float
The input number.
Returns
-------
x2 : same type as `x`
The square of the input value.
Examples
--------
>>> square(5)
25
"""
return x ** 2 | 5cd099fc07253bd5b7fcef153288ffb2fcff3d1c | 631,214 |
def build_cluster_info(config):
"""
Construct our cluster settings. Dumps global settings config to each cluster
settings, however, does not overwrite local cluster settings. Cluster config
takes precedence over global. Use global config for generic info to be
applied by default.
Note:
... | 02dec2a6ec659c0a579fbc77b5a9677fff9a6871 | 631,216 |
def get_lhc_sequence_filename_and_bv(beam: int, accel: str = 'lhc'):
""" Return the default sequence filename, the sequence name and the bv-flag
for the given beam.
Args:
beam (int): beam to use.
accel (str): accelerator name ('lhc' or 'hllhc').
"""
as_built = '_as-built' if accel.l... | 1e4a9fec3efd4b59db012422175ed0b416c4729b | 631,218 |
def fatorial(a, show=False):
"""
Calcula o fatorial do valor
param: a: valor a ser calculado
param: show: (bool opcional) mostra o calculo
return: resultado no fatorial
"""
f = 1
for i in range(a, 0, -1):
f *= i
if show:
if i == 1:
... | 69f44431996fbc52014169360d2adeb7220bb454 | 631,219 |
def key2struct(jsonkey:str):
"""
string key of type my_key --> MyKey
"""
parts = jsonkey.split('_')
ret = ""
for w in parts:
ret += w.capitalize()
return ret | f21721787a30b80578976a8dc74473198d991147 | 631,222 |
def calc_dihedral(v1, v2, v3, v4):
"""Calculate dihedral angle method.
Calculate the dihedral angle between 4 vectors
representing 4 connected points. The angle is in
]-pi, pi].
:param v1, v2, v3, v4: the four points that define the dihedral angle
:type v1, v2, v3, v4: L{Vector}
"""
ab... | d4a8af56fd25df51e443b1bf25c870b1aff6ae9e | 631,225 |
def nodes_cut_fully(graph, dest):
"""
Return the nodes divided up fully into separate partitions.
Order is established by BFS.
"""
return [[v["id"]] for v in graph.bfsiter(dest)] | f7d5609ea13327e75fb41c9d03e631c9fd69fb83 | 631,228 |
def encode_literal_num(n: int, size: int) -> bytes:
"""Send numbers as literal string in decimal
`size`: target length of the byte str
example: 123 -> ["0","0",... , "1","2","3"]
"""
s = str(n)
s = "0" * (size - len(s)) + s
# prevent overflow
assert s[0] == "0"
return s.encode("utf-8... | 09067cfad4b7304893241bf88beb50ceceb57055 | 631,232 |
def centerstring(string,width):
""" Pad a string to a specific width """
return " "*((width-len(string))/2)+string | c0698d5d52f65ec38e666e8c1652b65db1263129 | 631,234 |
def calculate_dc_dT_CTM(temp):
"""
Seabird eq: dc/dT = 0.1 * (1 + 0.006 * [temperature - 20])
"""
dc_dT = 0.1 * (1 + 0.006 * (temp - 20))
return dc_dT | 045f1c69958f3200a813f26cf05fb18eca9384b1 | 631,238 |
def get_default_semantics(n_dim):
"""
Generate default semantics for n_dim dimensions.
Parameters
----------
n_dim : int
Number of dimensions. Indicating the number of variables of the model.
Returns
-------
semantics: dict
Generated model description.
"""
sem... | 14cac3982b146712480cd698478fb94dfb9006e1 | 631,239 |
def slice_to_list(s):
"""
Converts a slice object to a list of indices
"""
step = s.step or 1
start = s.start
stop = s.stop
return [x for x in range(start,stop,step)] | 9091c43dfc91877cf486ea9a45d862b72ad99416 | 631,245 |
def stoi(n):
"""String to integer. Handles negative values."""
return int(str(n).replace("-", "")) * -1 if "-" in n else int(n) | 4af8b859114ff7955017bbd787898f1d53556bc2 | 631,246 |
def default_iid_function(sample):
"""
The default function for turning a Bgen sample into a
two-part :attr:`pysnptools.distreader.DistReader.iid`.
If the Bgen sample contains a single comma, we split on the comma to
create the iid.
Otherwise, the iid will be ('0',sample)
>>> default_iid_fun... | 881e0ab7ebb3702353ae602a23c753a9196100de | 631,251 |
def vis_params_rgb(bands=['R', 'G', 'B'], minVal=0, maxVal=3000, gamma=1.4, opacity=None):
"""
Returns visual parameters for a RGB visualization
:param bands: list of RGB bandnames, defaults to ['R', 'G', 'B']
:param minVal: value to map to RGB value 0, defaults to 0
:param maxVal: value to map to R... | 7f86e7c22c7dced82a0b11a5033e9d18e2d47e93 | 631,261 |
def nonzero(matrix, row):
"""
usage:
>>> from scipy.sparse import csr_matrix
>>> m = csr_matrix([[1, 0, 2], [3, 0, 0]])
>>> print nonzero(m, 0)
set([0, 2])
>>> print nonzero(m, 1)
set([0])
"""
return set(matrix[row].indices) | 197308cf9ed83124565444a5ac97dae14d805cb8 | 631,263 |
import math
def qubits_needed(number_of_sides):
"""
The number of qubits needed for a die of n faces.
"""
return int(math.ceil(math.log(number_of_sides, 2))) | 09f4c9dbc8a732097209943f0d19f22a006cd181 | 631,265 |
def asURN(epsg):
""" convert EPSG code to OGC URN CRS ``urn:ogc:def:crs:epsg::<code>``
notation """
return "urn:ogc:def:crs:epsg::%d" % int(epsg) | a7de7b3526e8feb163479f1cf3dcb57ed3f9a03e | 631,268 |
import string
import random
def random_string(
length: int, characters: str = string.ascii_letters + string.digits
) -> str:
"""
Generates a random string of a given length from a given character set.
Args:
length: The length of the string to generate.
characters: A string containing ... | 5ebcb226dc4e03d09544fd0d6d09eee755db7cea | 631,271 |
from pathlib import Path
def get_config_dir() -> Path:
"""Returns the path to the config dir"""
return Path(__file__).resolve().parent.parent / 'config' | 4f1ea474da52c6c5d10c87bc5dedfbaf0a4441c4 | 631,280 |
def merge(user, default):
"""Merges a user configuration with the default one.
Merges two dictionaries, replacing default values
of similar matching keys from user.
Parameters:
user (dict):
A user defined dictionary
default (dict):
Returns:
A new merged diction... | d55eb703b441c04b11c497e496197560acb094aa | 631,282 |
def main(event: dict, context: dict) -> dict:
"""
Simple lambda handler to echo back responses
:param event: A JSON-formatted document that contains data for a Lambda function to process.
:param context: Provides methods and properties that provide information about the invocation,
function, and ru... | 9600e58e9212c6c3294b81629923fdc361d84d30 | 631,283 |
def tuple_scale(tup: tuple, factor) -> tuple:
"""Return the tuple with each entry scaled by a factor and rounded."""
return tuple(round(i * factor, 5) for i in tup) | 08b9267eafa2f18a849297d5d0b436de08ca80c1 | 631,285 |
def first_word(sentence):
"""Return first word of a string."""
try:
return sentence.split(' ', 1)[0]
except:
return None | c7938a06b7f6ae4169b622863ed8285e173f34a0 | 631,286 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.