seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
from typing import Callable
from typing import Union
import torch
from typing import Dict
from typing import List
from typing import Tuple
from typing import Set
from typing import Any
def _apply_to_tensors(
fn: Callable, container: Union[torch.Tensor, Dict, List, Tuple, Set]
) -> Any:
"""Recursively apply to... | bigcode/self-oss-instruct-sc2-concepts |
def r10s(factor: float = 1) -> float:
"""
The horizontal screw spacing on the mounting rails
of a 10-inch half rack.
"""
return 236.525 * factor | bigcode/self-oss-instruct-sc2-concepts |
def unknown_labels(dim):
"""
The labels for the "unknown" basis. Just returns an empty list.
Parameters
----------
dim : int
Dimension
Returns
-------
list
"""
return [] | bigcode/self-oss-instruct-sc2-concepts |
import torch
from typing import Sequence
from typing import cast
def project_point_cloud_to_map(
xyz_points: torch.Tensor,
bin_axis: str,
bins: Sequence[float],
map_size: int,
resolution_in_cm: int,
flip_row_col: bool,
):
"""Bins an input point cloud into a map tensor with the bins equalin... | bigcode/self-oss-instruct-sc2-concepts |
def check_sorted(a):
"""Determines if list is sorted."""
for i, val in enumerate(a):
if i > 0 and val < a[i-1]:
return False
return True | bigcode/self-oss-instruct-sc2-concepts |
def extract_properties_values_from_json(data, keys):
"""Extracts properties values from the JSON data.
.. note::
Each of key/value pairs into JSON conventionally referred
to as a "property". More information about this convention follow
`JSON Schema documentation <https://json-schema.o... | bigcode/self-oss-instruct-sc2-concepts |
def tcl_str(string: str = '') -> str:
""" Returns Tcl string surrounded by {}
:param string: Python string.
"""
return ' {' + string + '} ' | bigcode/self-oss-instruct-sc2-concepts |
from datetime import datetime
def create_identifier(hint: str = '') -> str:
"""
Can be used to create unique names for files by exploiting the uniqueness of the current date.
Be aware that if two identifiers are created during the same second they are equal!
Follows the form YYYY_MM_DD__hh_mm_ss.
... | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def sieve(n: int) -> List[int]:
"""
A simple implementation of the http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
:param n: Maximum value to search up to, not included.
:return: List of primes upto but not including n.
"""
all_numbers = [True] * n
for i in ran... | bigcode/self-oss-instruct-sc2-concepts |
def isValidID(id: str) -> bool:
""" Check for valid ID. """
#return len(id) > 0 and '/' not in id # pi might be ""
return id is not None and '/' not in id | bigcode/self-oss-instruct-sc2-concepts |
import math
def vershik_kerov_logan_shepp(n):
"""
Returns asymptotic value of ℓn for large n.
For a permutation σ∈Sn, let ℓ(σ) denote the maximal length of an increasing subsequence in σ.
Define ℓn = (1/n!) * ∑(σ∈Sn) ℓ(σ),
the average value of ℓ(σ) for a σ chosen uniformly at random from Sn.
... | bigcode/self-oss-instruct-sc2-concepts |
def flip_corner(corner: tuple) -> tuple:
"""
Flip a tuple of a variable amount of sides
:param corner: tuple with number of sides
:return: flipped clock-wise tuple
"""
fliped_sides: list[str] = list()
for s in corner:
if s == 'N':
fliped_sides.append('W')
elif s... | bigcode/self-oss-instruct-sc2-concepts |
def format_import(names):
"""Format an import line"""
parts = []
for _, name, asname in names:
if asname is None:
parts.append(name)
else:
parts.append(name + " as " + asname)
line = "import " + ", ".join(parts) + "\n"
return line | bigcode/self-oss-instruct-sc2-concepts |
def count_leading_spaces(string: str) -> int:
"""
Count the number of spaces in a string before any other character.
:param string: input string
:return: number of spaces
"""
return len(string) - len(string.lstrip(" ")) | bigcode/self-oss-instruct-sc2-concepts |
def replace_special_quotes(html_str: str):
"""
replace special quotes with html entities
"""
# special quotes
html_str = html_str.replace('“', '“')
html_str = html_str.replace('”', '”')
html_str = html_str.replace('’', '’')
html_str = html_str.replace('‘', '‘')
... | bigcode/self-oss-instruct-sc2-concepts |
def bash_array(lst):
"""Converts python array [a, b, c] to bash array (a b c)"""
contents = ' '.join(str(x) for x in lst)
return '({:s})'.format(contents) | bigcode/self-oss-instruct-sc2-concepts |
import re
def get_length(s):
""" Determine the length of the string from it's name which is
prepended as:
"foobar%d" % N
"""
x = re.search("[\d]+$", s)
# there can be only one or no match here
n = 0
if x :
n = int(x.group(0))
return n | bigcode/self-oss-instruct-sc2-concepts |
from typing import Optional
import re
def _try_parse_port(port_str: str) -> Optional[int]:
"""Tries to extract the port number from `port_str`."""
if port_str and re.match(r"^[0-9]{1,5}$", port_str):
return int(port_str)
return None | bigcode/self-oss-instruct-sc2-concepts |
def sum(n):
"""
Returns the sum of integers between 1 and `n` (inclusive).
This implementation uses recursion.
"""
if n == 1:
return 1
elif n > 1:
return n + sum(n - 1) | bigcode/self-oss-instruct-sc2-concepts |
from typing import Optional
import re
def read_commit(version_data: str) -> Optional[str]:
"""Parse commit string from version data
@param version_data: Contents of version file
@return: commit, or None if not found
"""
p = re.compile('.*Commit: ([^\n\r]*)', re.DOTALL)
match = p.match(version_... | bigcode/self-oss-instruct-sc2-concepts |
def z2lin(array):
"""dB to linear values (for np.array or single number)"""
return 10 ** (array / 10.) | bigcode/self-oss-instruct-sc2-concepts |
def model_field_attr(model, model_field, attr):
"""
Returns the specified attribute for the specified field on the model class.
"""
fields = dict([(field.name, field) for field in model._meta.fields])
return getattr(fields[model_field], attr) | bigcode/self-oss-instruct-sc2-concepts |
def count_models(block):
"""Count models in structure file block.
:param block: PDBx data block
:type block: [str]
:return: number of models in block
:rtype: int
"""
atom_obj = block.get_object("atom_site")
model_num = []
for i in range(atom_obj.row_count):
tmp = atom_ob... | bigcode/self-oss-instruct-sc2-concepts |
def hex_to_bin(txt: str) -> str:
"""Convert hexadecimal string to binary string.Useful for preprocessing the key and plaintext in different settings."""
return bin(int(txt,16))[2:] | bigcode/self-oss-instruct-sc2-concepts |
def clean_lemma(lemma: str, pos: str) -> str:
"""Cleans whitespace and special symbols
Args:
lemma: Raw token lemma.
pos: Lemma POS.
Returns:
Clean lemma.
"""
out_lemma = lemma.strip().replace(" ", "").replace("_", "").lower()
if pos != "PUNCT":
if out_... | bigcode/self-oss-instruct-sc2-concepts |
def to_byte(val):
"""Cast an int to a byte value."""
return val.to_bytes(1, 'little') | bigcode/self-oss-instruct-sc2-concepts |
from typing import Tuple
import re
def replace_code(
begin_delim: str, end_delim: str, content: str, new_code: str
) -> Tuple[str, int]:
"""Replaces text delimited by `begin_delim` and `end_delim` appearing in `content`, with `new_code`.
Returns new string and number of matches made."""
return re.subn... | bigcode/self-oss-instruct-sc2-concepts |
import requests
def get_root_domains(url, filename):
""" Updates root domain file.
:param url: URL of the root domains list.
:param filename: File name to write the list.
"""
r = requests.get(url)
with open(filename, 'w') as f:
f.write(r.text)
return True | bigcode/self-oss-instruct-sc2-concepts |
def create_hf(geom):
"""Create header and footer for different types of geometries
Args:
geom (str): geometry type, e.g., polygone
"""
if geom == "polygone":
header = """
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
... | bigcode/self-oss-instruct-sc2-concepts |
import math
def string_to_array(s):
"""Convert pipe separated string to array."""
if isinstance(s, str):
out = s.split("|")
elif math.isnan(s):
out = []
else:
raise ValueError("Value must be either string of nan")
return out | bigcode/self-oss-instruct-sc2-concepts |
import math
import hashlib
def adventcoin_mine(salt, zeros, prob=0.99):
"""MD5-hashes salt + counter, increasing counter until hash begins with a given number of 0's in HEX,
or until maximum value is reached
:param salt: string to append before countes
:param zeros: number of zeros to search for
:... | bigcode/self-oss-instruct-sc2-concepts |
def _format_cached_grains(cached_grains):
"""
Returns cached grains with fixed types, like tuples.
"""
if cached_grains.get("osrelease_info"):
osrelease_info = cached_grains["osrelease_info"]
if isinstance(osrelease_info, list):
cached_grains["osrelease_info"] = tuple(osrelea... | bigcode/self-oss-instruct-sc2-concepts |
def unfold_fields(lines):
"""Unfold fields that were split over multiple lines.
Returns:
A list of strings. Each string represents one field (a name/value pair
separated by a colon).
>>> unfold_fields("foo \n bar \n baz \nbiz \nboz ")
['foo bar baz ', 'biz ', 'boz... | bigcode/self-oss-instruct-sc2-concepts |
def analyzer(klass):
"""Return an instance of the CUT with some defaults."""
a = klass(
start_states=["In Progress", ],
commit_states=["Selected", "Created"],
end_states=["Done", ]
)
return a | bigcode/self-oss-instruct-sc2-concepts |
def map_symbols_to_currencies(currencies):
"""
Create dictionary where key is symbol of currency and value is
currency itself
:param list currencies:
List of dictionaries with data about many currencies
:return: Dictionary with symbols and currencies
:rtype: dict
:raises KeyError: ... | bigcode/self-oss-instruct-sc2-concepts |
import yaml
def load_configs(s: str) -> dict:
"""Load config from string."""
return yaml.load(s, Loader=yaml.FullLoader) | bigcode/self-oss-instruct-sc2-concepts |
def extract_text_body(parsed_email):
"""
Extract email message content of type "text/plain" from a parsed email
Parameters
----------
parsed_email: email.message.Message, required
The parsed email as returned by download_email
Returns
-------
string
string conta... | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def demand_satisfied(people_after: List) -> List[bool]:
"""Verifies that each person gets the appropriate number of appointments.
We assume that scheduling occurs over a single week. Thus, people in the
`1x` cohort get one test, people in the `2x` cohort get two tests,
and peo... | bigcode/self-oss-instruct-sc2-concepts |
def progress_to_dict(path: str) -> dict:
"""
Converts a Delphin progress file into a dict.
:param path: path to folder
:return: converted progress dict
"""
file_obj = open(path + '/progress.txt', 'r')
lines = file_obj.readlines()
file_obj.close()
progress_dict = {'simulation_time'... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def round(tensor, decimal_places):
"""
Round floats to the given number of decimal places.
:param tensor: input tensor
:type tensor: torch.Tensor
:param decimal_places: number of decimal places
:types decimal_places: int
:return: rounded tensor
:rtype: torch.Tensor
""... | bigcode/self-oss-instruct-sc2-concepts |
def split_parts(msg):
"""Splits a key=value pair into a tuple."""
index = msg.find("=")
return (msg[:index], msg[index+1:]) | bigcode/self-oss-instruct-sc2-concepts |
import mimetypes
def guess_extension(mime):
"""Shortcut for getting extension to a given mime string.
The parameter mime can be None"""
return mimetypes.guess_extension(type=mime or "") | bigcode/self-oss-instruct-sc2-concepts |
import re
def idify(utext):
"""Make a string ID-friendly (but more unicode-friendly)"""
utext = re.sub(r'[^\w\s-]', '', utext).strip().lower()
utext = re.sub(r'[\s-]+', '-', utext)
if not len(utext):
# Headers must be non-empty
return '_'
return utext | bigcode/self-oss-instruct-sc2-concepts |
def my_func02(num01, num02):
"""
返回两个参数的和
:param num01: 数字1
:param num02: 数字2
:return: 两个数字的和
"""
return num01 + num02 | bigcode/self-oss-instruct-sc2-concepts |
def map_msa_names(df, msa_lookup):
""" Helper function to handle known MSA name changes/inconsistencies
:param df: A pandas dataframe, BLS OEWS data set
:param msa_lookup: a dictionary containing MSA code to peer type lookup
:return df: A pandas dataframe
"""
df['area_title'] = df['area'].map... | bigcode/self-oss-instruct-sc2-concepts |
def legend(is_legend_show=True,
legend_orient="horizontal",
legend_pos="center",
legend_top='top',
legend_selectedmode='multiple',
**kwargs):
""" Legend component.
Legend component shows symbol, color and name of different series.
You can click ... | bigcode/self-oss-instruct-sc2-concepts |
def get_average(numbers):
"""
Args:
numbers (list): A list of floats.
Returns:
float: The average of the floats in numbers list.
"""
total = 0.0
for number in numbers:
total += number
return total/ len(numbers) | bigcode/self-oss-instruct-sc2-concepts |
def set_hidden_measurement_lists_from_Ns_Nv(num_nodes, Ns, Nv, list_bus_id_power_hiding_priority=None, list_bus_id_voltage_hiding_priority=None):
"""
Returns the list of the hidden power bus ids and a list of hidden voltage ids
:param num_nodes: number of buses in the grid
:param Ns: Number ... | bigcode/self-oss-instruct-sc2-concepts |
def denormalize_m11(x):
"""Inverse of normalize_m11."""
return (x + 1) * 127.5 | bigcode/self-oss-instruct-sc2-concepts |
def test_row(dataframe):
"""
test if dataframe contains at least one row
Parameters
----------
dataframe: pandas dataframe
Raises
------
ValueError
If number of row is smaller than 1, raise ValueError
Returns
-------
is_valid: boolean
True if greater than 1... | bigcode/self-oss-instruct-sc2-concepts |
def _get_elem_at_rank(rank, data, n_negative, n_zeros):
"""Find the value in data augmented with n_zeros for the given rank"""
if rank < n_negative:
return data[rank]
if rank - n_negative < n_zeros:
return 0
return data[rank - n_zeros] | bigcode/self-oss-instruct-sc2-concepts |
def pythonize_yang_name(name):
"""
Convert a name like "interface-name" to "InterfaceName" or
"interface" to "Interface
"""
if '-' in name:
py_name = ''
sub_components = name.split('-')
for s in sub_components:
py_name += s.capitalize()
return py_name
... | bigcode/self-oss-instruct-sc2-concepts |
import requests
def get_tv_episode_detail(key, id, season, episode, language="en-US"):
"""
function get_tv_episode_detail
Get the TV episode details by id.
inputs: key - TMDB API key.
id - id of the movie
season - Season of the tv series (INT)
... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def _kl_divergence_q_prior_normal(mu, logvar, per_dim=False):
"""
Returns KL-divergence between the variational posterior
$q_{\phi}(z|x)$ and the isotropic Gaussian prior $p(z)$.
This forms the 'regularization' part of the ELBO.
If the variational posterior is taken to be normal ... | bigcode/self-oss-instruct-sc2-concepts |
def get_blue_green_from_app(app):
"""
Returns the blue_green object if exists and it's color field if exists
>>> get_blue_green_from_app({})
(None, None)
>>> get_blue_green_from_app({'blue_green': None})
(None, None)
>>> get_blue_green_from_app({'blue_green': {}})
(None, None)
>>... | bigcode/self-oss-instruct-sc2-concepts |
def get_last_conv_layer_name(model_keras):
"""
Search for the last convolutional layer
Args:
model_keras: A keras model object
Returns:
Name of the layer (str)
"""
for layer in reversed(model_keras.layers):#loop in reverse order
# Select closest 4D layer to the end of th... | bigcode/self-oss-instruct-sc2-concepts |
def flatten_args(args):
"""
Given a dictionary of arguments, produce a string suitable for inclusion
in a command line, such as "--name1 value1 --name2 value2"
"""
return " ".join(["%s %s" % (name, value)
for name, value in args.iteritems()]) | bigcode/self-oss-instruct-sc2-concepts |
def _decimal_lshift_exact(n, e):
""" Given integers n and e, return n * 10**e if it's an integer, else None.
The computation is designed to avoid computing large powers of 10
unnecessarily.
>>> _decimal_lshift_exact(3, 4)
30000
>>> _decimal_lshift_exact(300, -999999999) # returns None
""... | bigcode/self-oss-instruct-sc2-concepts |
def calculate_polynomial_derivative_term(coefficient, variable, order):
"""Calculates the derivative of the nth order term of a polynomial.
Args:
coefficient (float): The coefficient of the nth order term in the
polynomial
variable (float): float to plug in for the variable in the p... | bigcode/self-oss-instruct-sc2-concepts |
def single_line(line, report_errors=True, joiner='+'):
"""Force a string to be a single line with no carriage returns, and report
a warning if there was more than one line."""
lines = line.strip().splitlines()
if report_errors and len(lines) > 1:
print('multiline result:', lines)
return joiner... | bigcode/self-oss-instruct-sc2-concepts |
import unittest
def combined_suites(*test_suites):
"""Combines several suites into one"""
combined_suite = unittest.TestSuite(test_suites)
return combined_suite | bigcode/self-oss-instruct-sc2-concepts |
import unicodedata
def strip_diacritics_2(input_string: str) -> str:
"""Return a copy of `input_string` without diacritics, such that
strip_diacritics('skříň') == 'skrin'
"""
trans_dict = {char: int(unicodedata.decomposition(char).split()[0],
base=16)
f... | bigcode/self-oss-instruct-sc2-concepts |
def liquidViscosity(T, lVP):
"""
liquidViscosity(T, lVP)
liquidViscosity (centipoise) = 10^(A + B/T + C*T + D*T^2)
Parameters
T, temperature in K
vPP, A=lVP[0], B=lVP[1], C=lVP[2], D=lVP[3]
A, B, C, D and E are regression coefficients
Returns
liquid viscosity... | bigcode/self-oss-instruct-sc2-concepts |
def valid_xml_char_ordinal(c):
"""Filters out certain bytes so that XML files contains valid
characters. XML standard defines a valid character as:
Char ::= #x9 | #xA | #xD | [#x20 - #xD7FF] |
[#xE000 - #xFFFD] | [#x10000 - #x10FFFF]
Args:
c: Character to be checked
Returns:
... | bigcode/self-oss-instruct-sc2-concepts |
def add_vp_vs(df):
"""Calculates the Vp and Vs for a las file
Args:
df (Pandas.DataFrame): input dataframe MUST CONTAIN `DTCO` and `DTSM`
Returns:
pandas.DataFrame: input dataframe with vp and vs calculated
"""
df['Vp'] = (1000000 / df['DTCO']) / 3.281
df['Vs'] = (1000000 / df['... | bigcode/self-oss-instruct-sc2-concepts |
def calculate_simpson_index(set1, set2):
"""Calculates the Simpson index of two sets"""
size_intersection = float(len(set1.intersection(set2)))
size_smaller_set = min(float(len(set1)), float(len(set2)))
return size_intersection / size_smaller_set | bigcode/self-oss-instruct-sc2-concepts |
def return_label(file_path):
"""
Extract label from filename
Inputs:
---------------
file_name: Source of raw wav signal str
Outputs:
---------------
y: target as string
"""
if "silence" in file_path.lower():
y = 'silence'
e... | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def get_sum_of_elements(lst: List) -> int:
"""Sum of list."""
return sum(lst) | bigcode/self-oss-instruct-sc2-concepts |
from typing import Optional
def get_location_id(data: dict) -> Optional[str]:
"""
Returns location_id from a data dictionary, or defaults to None
:param dict data: The event data
:return str|None: A string containing the location id, or None
"""
try:
return data["event"]["data"]["new"]... | bigcode/self-oss-instruct-sc2-concepts |
import re
def get_cell_barcode(record, cell_barcode_pattern):
"""Return the cell barcode in the record name.
Parameters
----------
record : screed record
screed record containing the cell barcode
cell_barcode_pattern: regex pattern
cell barcode pattern to detect in the record name... | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def spooler_pids() -> List[int]:
"""Returns a list of all spooler processes IDs."""
return [] | bigcode/self-oss-instruct-sc2-concepts |
import base64
def encode_file_to_base64(fpath_in, prefix):
""" encode_file_to_base64: gets base64 encoding of file
Args:
fpath_in (str): path to file to encode
prefix (str): file data for encoding (e.g. 'data:image/png;base64,')
Returns: base64 encoding of file
"""
... | bigcode/self-oss-instruct-sc2-concepts |
def le_bytes_to_int(as_bytes: bytes, signed: bool) -> int:
"""Converts a little endian byte array to an integer.
:param as_bytes: A little endian encoded byte array integer.
:param signed: Flag indicating whether integer is signed.
"""
return int.from_bytes(as_bytes, byteorder='little', signed=sig... | bigcode/self-oss-instruct-sc2-concepts |
import string
def base26(x, _alphabet=string.ascii_uppercase):
"""Return positive ``int`` ``x`` as string in bijective base26 notation.
>>> [base26(i) for i in [0, 1, 2, 26, 27, 28, 702, 703, 704]]
['', 'A', 'B', 'Z', 'AA', 'AB', 'ZZ', 'AAA', 'AAB']
>>> base26(344799) # 19 * 26**3 + 16 * 26**2 + 1 ... | bigcode/self-oss-instruct-sc2-concepts |
def pgcd(a, b):
"""Renvoie le Plus Grand Diviseur Communs des entiers ``a`` et ``b``.
Arguments:
a (int) : un nombre entier
b (int) : un nombre entier
"""
if a < 0 or b < 0:
return pgcd(abs(a), abs(b))
if b == 0:
if a == 0:
raise ZeroDivisionError(
... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Dict
from typing import Tuple
from typing import Set
def prepare_senses_index_for_search(senses_dict: Dict[str, Dict[str, Tuple[tuple, Tuple[int, int]]]]) -> \
Dict[str, Set[str]]:
""" Build a search index for a fast selection of sentence candidates, which contain some sense from the Ru... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Sequence
def to_sequence(obj):
"""Convert an object to sequence.
Parameters
----------
obj : `object`
Returns
-------
`collections.Sequence`
Examples
--------
>>> to_sequence(None)
()
>>> to_sequence(1)
(1,)
>>> to_sequence('str')
('str... | bigcode/self-oss-instruct-sc2-concepts |
def select(t, *columns):
""" Select columns from table
>>> t = Symbol('t', 'var * {x: int, y: int, z: int}')
>>> select(t, t.x, t.z)
t[['x', 'z']]
"""
return t[[c._name for c in columns]] | bigcode/self-oss-instruct-sc2-concepts |
from typing import Dict
import pickle
def _from_checkpoint(
fname: str='checkpoint.pkl') -> Dict:
""" Load a checkpoint file """
with open(fname, 'rb') as f:
checkpoint = pickle.load(f)
return checkpoint | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
from typing import Dict
from typing import Any
def _transform_dto_list_to_list_of_dicts(dto_list) -> List[Dict[str, Any]]:
"""
Given a list of DTO objects, this function returns a list of dicts, that can be passed to jsonify function.
"""
return [vars(dto_obj) for dto_obj in dt... | bigcode/self-oss-instruct-sc2-concepts |
def join_rows(rows, joiner=' '):
"""
Given a series of rows, return them as a single row where the inner edge cells are merged. By default joins with a single space character, but you can specify new-line, empty string, or anything else with the 'joiner' kwarg.
"""
rows = list(rows)
fixed_row = rows... | bigcode/self-oss-instruct-sc2-concepts |
def parse_float(val):
"""parses string as float, ignores -- as 0"""
if val == '--':
return 0
return float(val) | bigcode/self-oss-instruct-sc2-concepts |
def running_mean(l, N):
"""From a list of values (N), calculate the running mean with a
window of (l) items. How larger the value l is, the more smooth the graph.
"""
sum = 0
result = list(0 for x in l)
for i in range(0, N):
sum = sum + l[i]
result[i] = sum / (i + 1)
for i ... | bigcode/self-oss-instruct-sc2-concepts |
def get_outbreaks(flowmat, incidence, R0=2.5, asymf=10, attenuate=1.0):
"""
Calculate the probabilities of outbreak for all regions
:param flowmat: Arriving passengers row -> column
:param incidence: fraction of infectious in the populations
:param R0: Basic reproduction number
:param asymf: ho... | bigcode/self-oss-instruct-sc2-concepts |
def bin_to_hex(x):
"""Convert Binary to Hex."""
y = hex(int(x, 2))[2:]
if len(y) < 8:
y = (8 - len(y)) * "0" + y
return y | bigcode/self-oss-instruct-sc2-concepts |
import re
def process_tweets(text):
"""Exclude mentions, urls, and html reference characters in a string using regular expression"""
text = re.sub("(\@|https:\/\/)\S+", "", text) # remove mentions and urls
text = re.sub(r"&[a-z]+;", "", text) # exclude html reference characters
return text | bigcode/self-oss-instruct-sc2-concepts |
def f90bool(s):
"""Convert string repr of Fortran logical to Python logical."""
assert type(s) == str
try:
s_bool = s[1].lower() if s.startswith('.') else s[0].lower()
except IndexError:
raise ValueError('{0} is not a valid logical constant.'.format(s))
if s_bool == 't':
re... | bigcode/self-oss-instruct-sc2-concepts |
from functools import cmp_to_key
def argsort(mylist, comp=None):
"""Returns the indices that sort a list.
Parameters
----------
mylist : list of objects
List to sort.
comp : function, optional
A comparison function used
to compare two objects in the list.
Defaults ... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Optional
import torch
def file2ckpt(path: str, device: Optional[str] = None) -> dict:
"""
Load the ckpt file into a dictionary to restart a past simulation. It is a thin wrapper around torch.load.
Args:
path: A string specifying the location of the ckpt file (required)
... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Sequence
from typing import Sized
def are_none(sequences: Sequence[Sized]) -> bool:
"""
Returns True if all sequences are None.
"""
if not sequences:
return True
return all(s is None for s in sequences) | bigcode/self-oss-instruct-sc2-concepts |
def concat(str_one, str_two):
"""
Returns the concatenation of 2 strings. A string
with null value is considered as an empty string.
"""
if not str_one:
str_one = ""
if not str_two:
str_two = ""
return str_one + str_two | bigcode/self-oss-instruct-sc2-concepts |
from shutil import which
def is_tool(name):
"""Check whether `name` is on PATH and marked as executable."""
# from whichcraft import which
return which(name) is not None | bigcode/self-oss-instruct-sc2-concepts |
import functools
def cached(func):
"""Decorator to cache the result of a function call."""
func.cache = {}
@functools.wraps(func)
def wrapper(*args, **kwargs):
if kwargs:
key = args, frozenset(kwargs.items())
else:
key = args
if key not in func.cache:
... | bigcode/self-oss-instruct-sc2-concepts |
import re
from datetime import datetime
def _get_iso_date(date_string: str) -> str:
""" convert date from the form 1/22/2021 13:28:27 to iso format """
regex = r'\d{1,2}/\d{1,2}/\d{4} \d{1,2}:\d{1,2}:\d{1,2}'
found_list = re.findall(regex, date_string)
if found_list:
date_value = datetime.strp... | bigcode/self-oss-instruct-sc2-concepts |
def remove_erroneous_blocks(blocks, delta_time=2.0, n_blocks=3):
""" Remove sessions with erroneous data due to a NeuroPsy Research App malfunction.
The error causes block data to be duplicated and the values for df1 & df2 multiplied again by 100.
The duplicated blocks are identified by comparing their time... | bigcode/self-oss-instruct-sc2-concepts |
def get_sitemap(app, excludes=("/", "/static/<path:filename>")):
"""Returns a sitemap for the given application.
Args:
app (flask.Flask): Application to be scanned.
excludes (tuple): Tuple of endpoints to be hidden.
Returns:
list: Returns a list containing valid endpoint urls and ... | bigcode/self-oss-instruct-sc2-concepts |
def estimate_infectious_rate_constant(events,
t_start,
t_end,
kernel_integral,
count_events=None):
"""
Returns estimation of infectious rate for given events on... | bigcode/self-oss-instruct-sc2-concepts |
def survey_media(instance, filename):
"""Return an upload path for survey media."""
if not instance.survey.id:
instance.survey.save()
return 'survey/{0}/{1}'.format(instance.survey.id, filename) | bigcode/self-oss-instruct-sc2-concepts |
import requests
def check_main_service_healthcheck(SVC_URL):
""" Check the main service url health. Returns True of False based on HTTP response code"""
try:
r =requests.get(SVC_URL+'/NexTrip')
if r.status_code ==200:
return True
else:
return False
except Ex... | bigcode/self-oss-instruct-sc2-concepts |
from textwrap import dedent
import inspect
def get_func_code(f):
"""Get the code of function f without extra indents"""
return dedent(inspect.getsource(f)) | bigcode/self-oss-instruct-sc2-concepts |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.