content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def eps(machine):
"""Return numeric tolerance for machine"""
return 1e-5 if machine == "x86" else 1e-8 | 95d6d59ab05a757255529b9ca75e727496fa8369 | 668,755 |
def toint(x):
"""Convert x to interger type"""
try: return int(x)
except: return 0 | 2b31eebc52e9b5774b5562b65c27dd3f62171163 | 668,759 |
def _normalize_string_values(field_values):
"""Normalize string values for passed parameters.
Normalizes parameters to ensure that they are consistent across queries where
factors such as case are should not change the output, and therefore not
require additional Telescope queries.
Args:
f... | d475d89f38dc924e631353be1d814c9cd0b6227c | 668,761 |
def cmd(required_params, *, needs_reply=False):
"""Create the internal structure describing a command
:param required_params: A list of parameters that must be included with the command.
:param needs_reply: The message needs to be replied to (and must have a uuid)."""
return required_params, needs_repl... | 0e9bc63ce3547a8b2856de8af8804fbee3f2bb3d | 668,765 |
import torch
def _chop_model(model, remove=1):
"""
Removes the last layer from the model.
"""
model = torch.nn.Sequential(*(list(model.children())[:-remove]))
return model | 73eca910e3068311c97ea76d6e398697d04c6a2e | 668,766 |
import json
def json_response(func):
""" Translates results of 'func' into a JSON response. """
def wrap(*a, **kw):
(code, data) = func(*a, **kw)
json_data = json.dumps(data)
return (code, { 'Content-type': 'application/json',
'Content-Length': len(json_data) },... | 968a2e3cf8ffedbbc96cc9eee45038115dd80e26 | 668,770 |
import networkx
def get_superterms(term, hpo_g):
"""
Get all HPO terms upstream of a query term
"""
if hpo_g.nodes.get(term, None) is not None:
superterms = networkx.descendants(hpo_g, term)
superterms = [s for s in superterms if s is not None]
else:
superterms = []
r... | f966d0f0f56db36a163b59fa68d599723091b573 | 668,771 |
def cohens_d_multiple(xbar1, xbar2, ms_with):
"""
Get the Cohen's-d value for a multiple comparison test.
Parameters
----------
> `xbar1`: the mean of the one of the samples in the test.
> `xbar2`: the mean of another of the samples in the test.
> `ms_with`: the mean-squared variability of the samples
Returns... | 53b04da90a440f4026a20f8e11bccd824412da62 | 668,774 |
def new_capacity_rule(mod, g, p):
"""
New capacity built at project g in period p.
Returns 0 if we can't build capacity at this project in period p.
"""
return (
mod.GenNewBin_Build[g, p] * mod.gen_new_bin_build_size_mw[g]
if (g, p) in mod.GEN_NEW_BIN_VNTS
else 0
) | 6ccd299aef7296124df5554ed5894fc8d03c6e4b | 668,775 |
def find_key(d, nested_key):
"""Attempt to find key in dict, where key may be nested key1.key2..."""
keys = nested_key.split('.')
key = keys[0]
return (d[key] if len(keys) == 1 and key in d else
None if len(keys) == 1 and key not in d else
None if not isinstance(d[key], dict) el... | 1d3ae404a598103968dacdce2706d1fc7f4ac71e | 668,776 |
def box_area(box):
"""the area of a box
Args:
box: (left, top, right, bottom)
"""
left, top, right, bottom = box
return (right-left+1) * (bottom-top+1) | ccc7bc148455896d497cbf1a1d55cf799e1317e1 | 668,777 |
import re
def is_number(num_str):
"""
Determine whether the string can be converted to a number (int and float)
:param num_str:
:return:
"""
if not re.compile(r"^[-+]?[-0-9]\d*\.\d*|[-+]?\.?[0-9]\d*$").match(num_str):
return False
return True | 774d0efce085e2dccc7737848951a36a45461449 | 668,778 |
def _form_c_loop_beg(ctx):
"""Form the loop beginning for C."""
return 'for({index}={lower}; {index}<{upper}, {index}++)'.format(
index=ctx.index, lower=ctx.lower, upper=ctx.upper
) + ' {' | d5ceb045c1c5c6463846a858e488fbc22511364e | 668,779 |
def _find_known(row):
"""Find variant present in known pathogenic databases.
"""
out = []
clinvar_no = set(["unknown", "untested", "non-pathogenic", "probable-non-pathogenic",
"uncertain_significance", "uncertain_significance", "not_provided",
"benign", "likel... | 8b043504a4df27b0928d975d81ee129c6a984c9b | 668,782 |
def _advance_years(dt, years):
""" Advance a datetime object by a given number of years.
"""
return dt.replace(year=dt.year + years) | 00780f2d12edff3531213ccd881d5cbced3d8f2e | 668,783 |
def drop_cols_with_null(df):
"""
Drops all columns with null value.
:param df: Data Frame Object
:return: Data Frame Object
"""
return df.dropna(axis=1) | 86c00d4eaff7c94d4e24183038befcd19a103d1c | 668,784 |
def max_sub_array_sum(array):
"""Implementation of the Kadane's algorithm to solve the maximum sub-array
problem in O(n) time and O(1) space. It finds the maximum contiguous subarray
and print its starting and end index. Here it will return the indexes of the
slices between which there is the maximum hy... | 90e9468093a008a9a8466e77f5500365e74d4d48 | 668,796 |
from typing import Union
from typing import Dict
def nvl_attribute(name: str, obj: Union[None, Dict], default):
"""
Given an name and a value return
the dictionary lookup of the name
if the value is a dictionary.
The default is returned if not
found.
@param name: name to lookup
@param... | cd2b4a383d88caf8d6900199ae352b6ac83303c2 | 668,797 |
def _fk(feature_name, channel, target):
"""Construct a dict key for a feature instance"""
return "{}::{}::{}".format(feature_name, channel, target) | 80ec588fc801210c8d4598359bde6891b73e73da | 668,800 |
import re
def _get_module_doc(module):
"""Get and format the documentation for a module"""
doc = module.__doc__ or ""
# Replace headlines with bold text
doc = re.sub(r"([\w ]+:)\n-+", r"**\1**", doc)
num_hash = min(2, module.__name__.count("."))
return f"{'#' * num_hash} {module.__name__}\n{... | 63583e38bd91f748572b350091b20c5f73da6ffe | 668,803 |
def prod(seq):
# pylint: disable=anomalous-backslash-in-string
"""Product of a sequence of numbers.
Parameters
----------
seq : sequence
A sequence of numbers.
Returns
-------
float or int
Product of numbers.
Notes
-----
This is defined as:
.. math::
... | a9f81b78e90410713f805cb5b2ecae6c0270009c | 668,804 |
def has_source_files( self ):
"""Checks if there are source files added.
:return: bool
"""
return bool(self._source_files) | 2350569b5411aa480e81109a0ce57da768ed51a3 | 668,805 |
import re
def remove_tags(text):
"""Remove html tags from a string"""
clean = re.compile('<.*?>')
return re.sub(clean, '', text) | b5bb38c10c99ec7979b0d740717e60f87cfccb9d | 668,808 |
from typing import List
def build_on_conflict_do_nothing_query(
columns: List[str],
dest_table: str,
temp_table: str,
unique_constraint: str,
dest_schema: str = "data",
) -> str:
"""
Construct sql query to insert data originally from `df` into `dest_schema.dest_table` via the
temporary... | dbeeba72cec7be0a4ee24ad30044b12fec60e27d | 668,809 |
def get_token_segments(labels, word_ids):
"""
Function to extract correctly formatted answers
Input: array of labels (can be predicted labels, or true labels)
Output: array of tuples; (start index of answer, length of answer)
"""
prev_word_id = None
labels_stats = []
for idx, label ... | 81ae667a488d71f71576e29e34a573b9122cd601 | 668,810 |
def _etsz(rn, g, tmean, u2, vpd, es_slope, psy, cn, cd):
"""Standardized Reference ET [mm] (Eq. 1)
Parameters
----------
rn : scalar or array_like of shape(M, )
Net radiation [MJ m-2 d-1 or MJ m-2 h-1].
g : scalar or array_like of shape(M, )
Ground heat flux [MJ m-2 d-1 or MJ m-2 h-... | 440b4917517f6f4291b92525b67560347f486b8b | 668,818 |
import socket
def is_v4(address):
"""Determines if the supplied address is a valid IPv4 address"""
try:
socket.inet_pton(socket.AF_INET, address)
return True
except socket.error:
return False | 5f4eb02e9e7b6d3ccf772a3eaa5df4b727c6e5c5 | 668,822 |
def year_cv_split(X, year_range):
"""Split data by year for cross-validation for time-series data.
Makes data from each year in the year_range a test set per split, with data
from all earlier years being in the train split.
"""
return [
((X["year"] < year).to_numpy(), (X["year"] == year).to... | f5c7348a6589c180281de35bc9893f1de00252f1 | 668,825 |
def is_list_of_valid_elem(value, elem_validator):
""" Is the given value a list whose each element is checked by elem_check to be True?
:param value: The value being checked
:type value: Any
:param elem_validator: The element checker
:type elem_validator: Any -> bool
:return: True if the given v... | 8464aa82835022930d3efe2148e148d457099c63 | 668,826 |
def return_period_earth(energy_mttnt):
"""
Return period of Asteroid/Comet of a given energy (Megatons TNT) in Years.
:param energy_mttnt: Energy in Megatons TNT
:returns: Return period of given energy level in years
:Reference: EarthImpactEffect.pdf, Equation 3*
"""
return 109 * (energy_mt... | e54bc9b79add1c9efef8710fd3d047097aff6180 | 668,827 |
from typing import Iterable
def _table_cell(items: Iterable[str]) -> str:
"""Make a row of table cell."""
return '|' + '|'.join(f" {t} " for t in items) + '|' | 4b489283126900cdd371eb99c4ae3bd114232966 | 668,832 |
def triangle_up_to(*, index=None, value=None):
"""
[NP] Returns all triangle numbers up to the `index`-th member, or until the value exceeds
`value`.
:param index: integer
:param value: integer
:returns: list of integers, with the desired triangle sequence numbers
"""
assert index is no... | 658d4068fc200138c61b3cb3449643de581b14c2 | 668,833 |
def identity(x):
"""Return exactly what was provided."""
return x | ee6152b046b55e2044b67c4afed07ccc7c6cc471 | 668,841 |
def get_widths_balancer(widths, minmax_ratio=0.02):
"""
Given a list of positive numbers, find a linear function, such that when applied to the numbers, the maximum value
remains the same, and the minimum value is minmax_ratio times the maximum value.
:param widths: list of numbers
:param minmax_rat... | e0f929125e513576e8420f005abc351aaceca45b | 668,842 |
def factorials(number: int, iteratively=True) -> int:
"""
Calculates factorials iteratively as well as recursively. Default iteratively. Takes linear time.
Args:
- ``number`` (int): Number for which you want to get a factorial.
- ``iteratively`` (bool): Set this to False you want... | d4af8b05d91b9ac9fba9f852564e8043cf231e40 | 668,845 |
def mean_percentage_error(y_true, y_pred):
"""Compute the mean percentage error (MPE).
Parameters
----------
y_true : array-like, shape (n_samples,)
Ground truth (correct) target values.
y_pred : array-like, shape (n_samples,)
Estimated target values.
Returns
-------
m... | 35206143e42c68d900fc3e692039fb0dd1343032 | 668,847 |
def match_prio_rule(cz, pr: dict) -> bool:
"""Match a priority rule to citizenlab entry"""
for k in ["category_code", "cc", "domain", "url"]:
if pr[k] not in ("*", cz[k]):
return False
return True | 48028308ae6f67242a17041c9d0fc9e6ecd1d306 | 668,848 |
def estimated_bigram_probability(bigram, unigram_dict, bigram_dict):
""" estimate the probability of bigram (= (syll_1,syll_2)) by:
(count (syll_1,syll_2)) / (count syll_1)
"""
# set the count to zero
count = 0
# check if bigram is actually in our dict
if bigram in bigram_dict:
# i... | adf5d3830118da86b4e9a7981bfda4210f47b7f9 | 668,849 |
def monkeypatch_readline(request, monkeypatch, readline_param):
"""Patch readline to return given results."""
def inner(line, begidx, endidx):
if readline_param == "pyrepl":
readline = "pyrepl.readline"
else:
assert readline_param == "readline"
readline = "rea... | eef729f50cf58da47d474a40a64eed647e345127 | 668,851 |
def _is_idempotence_error(status_code, errors, context):
"""
Determines if an idempotence error has occurred based on the status code, errors and context
"""
return status_code == 409 \
and context is not None \
and context.idempotence_key is not None \
and len(errors) == 1 \
... | e7c42c86cfd03a92a679528a17923625b1e268ba | 668,858 |
def format_verify_msg(status):
"""Format validation message in color"""
OK = '\033[92m OK \033[0m'
FAIL = '\033[91mFAIL\033[0m'
if status:
return OK
else:
return FAIL | b20fb9ffd375ee9faac08198997f39f090b89d20 | 668,859 |
import re
def golang_duration_to_seconds(d: str) -> int:
"""
Convert values like "276h41m7s" to number of seconds
"""
add = ""
for c in ["s", "m", "h"]:
if d.endswith(c):
break
add += "0" + c
d += add
hms = [int(x) for x in re.split(r"\D", d)[:-1]]
res = hm... | 37a4cf681ae8e065e417361813cd9a58dcef1436 | 668,863 |
def split_chain(chain):
"""
Split the chain into individual certificates for import into keystore
:param chain:
:return:
"""
certs = []
if not chain:
return certs
lines = chain.split('\n')
cert = []
for line in lines:
cert.append(line + '\n')
if line =... | 4367c29cdd2059d513ef642c61fa761dd8485412 | 668,866 |
def class_labels(column):
"""
Takes in target column and creates list of binary values. 1 (>=0.5) being in the
positive class (toxic), 0 (<0.5) being in the negative class (Not toxic)
"""
class_label = []
for row in column:
if row < 0.5:
class_label.append(0)
else... | 3b94e6fbc918abb50a932550544408acca42843a | 668,867 |
def _slugify(text: str) -> str:
"""Turns the given text into a slugified form."""
return text.replace(" ", "-").replace("_", "-") | 78a034e07215e7964ebf1fc66162942d7b4ae85e | 668,870 |
def deformat_var_key(key: str) -> str:
"""
deformat ${key} to key
:param key: key
:type key: str
:return: deformat key
:rtype: str
"""
return key[2:-1] | a74b0d5d96dbf365da502bd478ee8efb07e7f7cd | 668,871 |
import glob
def _GetSequentialFileName(base_name):
"""Returns the next sequential file name based on |base_name| and the
existing files."""
index = 0
while True:
output_name = '%s_%03d' % (base_name, index)
if not glob.glob(output_name + '.*'):
break
index = index + 1
return output_name | 943583418b2bac1b8a42c61f5f33b0bc4f38f519 | 668,873 |
def normalize(expr):
"""Pass through n-ary expressions, and eliminate empty branches.
Variadic and binary expressions recursively visit all their children.
If all children are eliminated then the parent expression is also
eliminated:
(& [removed] [removed]) => [removed]
If only one child is ... | 299406a05912421d411e5ad5c1ced2ad45e64a4d | 668,874 |
def get_package(config):
"""
Returns the package associated with this device
Args:
config (dictionary): configuration dictionary
Return:
(string) package
Raises:
Nothing
"""
#split the device string with "-" and get the second value
package = config["devi... | 5a13e28eafceaaab018373141108d2f8e75f2a37 | 668,876 |
def stations_by_river(stations):
"""Takes a list of MonitoringStation
objects and maps each station object (value) to its
respective river (key).
"""
station_map = {}
for station in stations:
if station.river in station_map:
station_map[station.river].add(station)
els... | 4972736fadbd6b3c545497f9bcf57d997551557e | 668,888 |
import hashlib
def sha1_hex_file(filepath, max_bytes=None):
"""
Returns the SHA1 of a given filepath in hexadecimal.
Opt-args:
* max_bytes. If given, reads at most max_bytes bytes from the file.
"""
sha1 = hashlib.sha1()
f = open(filepath, 'rb')
try:
if max_bytes:
... | bf2b59eb9774dc5a4eb3c1bee26cebc7a3f84730 | 668,889 |
def load_categories(file_name):
"""
Loads the category index from file. Each category label is
the name of a class specified on a separate line. The entry order
is the index of the class.
"""
labels = []
with open(file_name) as f:
labels = f.read().splitlines()
categories = {}
... | 54bcd375c2e5b9d5d9078d6f0a75b9cebce03702 | 668,891 |
def as_choice(as_list):
"""
Creates a dropdown list of authorization servers
"""
element = "<select name=\"authzsrv\">"
for name in as_list:
element += "<option value=\"%s\">%s</option>" % (name, name)
element += "</select>"
return element | c4e644019449e9342efac2b888067753ff4fb526 | 668,892 |
def mean(num_list):
"""
Calculates the mean of a list of numbers
Parameters
----------
num_list: list (int or float)
Returns
-------
ret: int or float
The mean of the list
Examples
--------
>>> mean([1, 2, 3, 4, 5])
3.0
"""
try:
return sum(nu... | 2920c76d86572d02c9e4015d16b6cc44d86dd548 | 668,894 |
import socket
def _get_socket_constants(prefix):
"""Create a dictionary mapping socket module constants to their names."""
return {getattr(socket, n): n for n in dir(socket) if n.startswith(prefix)} | a468911c1ff743c908d797d650fc4794223ea80b | 668,895 |
def desi_target_from_survey(survey):
""" Return the survey of DESI_TARGET as a function of survey used (cmx, sv1, sv2, sv3, main)."""
if survey == 'special':
# to avoid error, return one of the column, SV2_DESI_TARGET should be full of 0.
return 'SV2_DESI_TARGET'
if survey == 'cmx':
... | 5e6a012088f540bf1c7101f3d8948a8662dbbad0 | 668,897 |
from datetime import datetime
def get_date_file_name(extension):
"""
Format 'now' datetime and create file name
with a given extension like this: 'YYYY_MM_DD hh_mm_ss.ext'
"""
return "{}.{}".format(datetime.now().replace(microsecond=0), extension).replace(":", "_") | a6530230d69ea175d89b262da69666d465b803d2 | 668,900 |
import select
import errno
def eintr_retry_call(func, *args, **kwargs):
"""
Handle interruptions to an interruptible system call.
Run an interruptible system call in a loop and retry if it raises EINTR.
The signal calls that may raise EINTR prior to Python 3.5 are listed in
PEP 0475. Any calls t... | 4186276824fcfda86a798de055c6e2f5b2515b0e | 668,905 |
def unique_fitnesses(population: list) -> int:
""" Calculates the number of unique fitnesses in the population
Args:
population (list): The list of individual candidate solutions
Returns:
int: The number of unique fitnesses in the population
"""
fitnesses = [individual.fitness for ... | c0057c4e2874ca6ea586e999922ebcc633efb225 | 668,907 |
def are_equal_nodes(n1, n2, underspecified=True):
"""Returns True if nodes n1 and n2 have the same predicate and sortinfo. If underspecified,
allow underspecification."""
if underspecified:
if n1.is_less_specific(n2) or n2.is_less_specific(n1):
return True
return n1.pred == n2.pred a... | 5c4246d757cd0abaebe85aa210f2889d0239d625 | 668,911 |
def _do_decoding(s, encoding):
"""A function to decode a bytes string, or return the object as-is."""
try:
return s.decode(encoding)
except UnicodeError:
raise
except (AttributeError, TypeError):
return s | 4bda03779164567078eac6bdfcb750a4cf689205 | 668,916 |
def enum_to_list(enum):
"""Enum to list."""
return [enum_ele.value for enum_ele in enum] | 131ab8f7b623f58008666a942e23b042ebbac898 | 668,919 |
def clean_update_item_string(string):
"""
Removes "(" and ")" parentheses from a string
Args:
string(str): entry
Returns:
str: string with parens removed
"""
return str(string.replace("(", "").replace(")", "")) | 14634fe1232e620837855c2400b40a4dc865f237 | 668,921 |
def ascii_distance(first, second):
"""
returns the positive distance between the ascii values of input characters
assume: inputs are valid single letters
e.g. inputs ("a", "b") should return 1,
inputs ("b", "a") should return 1 too (postive distance)
"""
return abs(ord(first)-ord(second)... | 6c1bd591e13fccf14dd17249f392e03ce59c7126 | 668,922 |
def GenerateFractionSamples(x, w, frac=0.50):
"""
Randomly samples fraction of the events from given features and weight.
Args:
x : panda.DataFrame
dataframe that contains the features for training.
w : panda.DataFrame
dataframe that contains the MC event weight.
... | 361db7c66ee6f93445a25d2d26752837dc4c989b | 668,927 |
from typing import Dict
from typing import List
from typing import Optional
def get_dict_from_cu_inst_result_file(cu_inst_result_file: str) -> Dict[str, List[Dict[str, Optional[str]]]]:
"""Parses the information contained in cu_inst_result_file into a dictionary of dictionaries,
ordered by dependency type and... | a7352e731c3fb05ad0fa13aa1f63bf5325e8a69a | 668,929 |
def wrap(x, m, M):
"""Wraps ``x`` so m <= x <= M; but unlike ``bound()`` which
truncates, ``wrap()`` wraps x around the coordinate system defined by m,M.\n
For example, m = -180, M = 180 (degrees), x = 360 --> returns 0.
Args:
x: a scalar
m: minimum possible value in range
M: max... | eb86baba697a0890ff90e176fffa0e7cd904d0bd | 668,931 |
def _getMenuIndex(values, current, defaultIndex = 1):
"""
Retrieves the menu index corresponding to the current value selected amongst values.
If the value is invalid, returns the defaultIndex.
"""
try:
# Note: menu index is 1-based.
return values.index(current) + 1
except:
... | 8c739892b777102c71f8522a224d5a5e5d387100 | 668,934 |
from zipfile import ZipFile
def extract_shp(path):
"""Return a geopandas-compatible path to the shapefile stored in a zip archive.
If multiple shapefiles are included, return only the first one found.
Parameters
----------
path : Path
Path to zip archive holding shapefile.
Returns
... | 273fb9917c5d5ecedee142e8e252a2376aac59b0 | 668,936 |
import hashlib
def sha1_20(data):
"""Return the first 20 bytes of the given data's SHA-1 hash."""
m = hashlib.sha1()
m.update(data)
return m.digest()[:20] | af7edbfec599cb2204205d905ae1c843794fb8af | 668,937 |
def prod(l):
"""
l: iterable of numbers.
returns: product of all numbers in l
"""
p = 1
for i in l: p *= i
return p | 0575ddd33f67e416ab96c26d9f010756b607261d | 668,941 |
def find_subseq_in_seq(seq, subseq):
"""Return an index of `subseq`uence in the `seq`uence.
Or `-1` if `subseq` is not a subsequence of the `seq`.
The time complexity of the algorithm is O(n*m), where
n, m = len(seq), len(subseq)
from https://stackoverflow.com/questions/425604/best-way-to-determ... | 8200272668a3d97877ccf0c1731bca5d036681bc | 668,946 |
import lzma
import gzip
def get_open_function(path):
"""Choose an open function based on the file's extension."""
if path.endswith('xz'):
return lzma.open
elif path.endswith('gz'):
return gzip.open
return open | 23dc5bcabc86c67c40b7fb190713eb94deb0175a | 668,948 |
def set_weierstrass_eq(*, a=1, b=1):
"""Return equation that defines Weierstrass curve. """
def wei_eq(x, y):
return y ** 2 == x ** 3 + a * x + b
return wei_eq | 0035f39da01c1524a9429a0054d005395770c59c | 668,949 |
def topological_sort(g):
"""
Returns tuple for a directed graph where:
- First element is a boolean that is set to True if graph contains a cycle
- Second element is an array of vertices in topological order if graph has no cycles,
or None otherwise
"""
visited = set()
removed = set... | aba95b8c4008ebd790ae0b2dcce4ca6e5499b182 | 668,952 |
def cutlabel(s, cuts):
"""Cuts a string s using a set of (n, label) cuts.
Returns a list of (sub, label) pairs.
If there was an initial part before the first cut, then it has a label of None.
If there are no cuts, returns s as a single element, with label None.
"""
cuts = sorted(cuts)
# no c... | 2f81a64d24dc0d31ff6671f2cc8459a38e3af51c | 668,956 |
def issequence(obj):
"""returns True if obj is non-string iterable (list, tuple, ect)"""
return getattr(obj, '__iter__', False) | 60f193a0e5230df22dd6ca3348edef37b5942236 | 668,959 |
import inspect
def get_module_path_from_type(py_type) -> str:
"""
Gets full module path + class name by the given class type
Parameters
----------
cls: python type
Class you want to get full module path for
Returns
-------
String representation of full module path like module... | ed9576f56116693c29fcf8caf8b879f45bdd5ef4 | 668,962 |
def rotate_patches_90deg(patches):
"""
Rotate patch dictionary as if original image is rotated by 90-degree
CCW.
"""
def rot_pos(i, j):
"""
Board Coordinates:
i
9 ... 1
------ 1 j
| | ...
------ 9
"""
return (10 - ... | f488cb151b869d740c47464816329e730a12f3f0 | 668,965 |
def one_max(phenome):
"""The bare-bones one-max function."""
return sum(phenome) | 3ffbeddb61f4533c462b3ba736acf2d1396a91c2 | 668,967 |
from typing import List
def parse_multi_command(command: str, commands_out: List[int]) -> dict:
"""
Given a list of commands separated by semicolons (;), this simply separates
the commands into individual ones.
This is useful for workflows that require different commands at different
steps in a w... | 6e0162b7bfcb3f52ef437bd7cb50df1414dbbf09 | 668,968 |
def get_device_mac(run_command_fn, dev_name, netns_name=None):
"""Find device MAC address"""
if netns_name:
command_prefix = "ip netns exec %s " % netns_name
else:
command_prefix = ""
(output, _) = run_command_fn("%scat /sys/class/net/%s/address" %
(comm... | 19f9a745f107ce2f00717d783e20cfcfe25fe19a | 668,971 |
import re
def get_relvaldata_id(file):
"""Returns unique relvaldata ID for a given file."""
run_id = re.search('R\d{9}', file)
run = re.search('_RelVal_([\w\d]*)-v\d__', file)
if not run:
run = re.search('GR_R_\d*_V\d*C?_([\w\d]*)-v\d__', file)
if run_id and run:
return (run_id.gro... | 4c5444ad6c769c49778d572d5d3559c94a2460e5 | 668,972 |
def swapbytes(bytes_in):
"""Swaps a list of bytes to conform with TI's documentation
Example:
input = [0x0f, 0x00]
output = swapbytes(input)
print output
>>> [0x00, 0x0f]
Args:
bytes_in (2 element list): a list of bytes to swap
Returns:
list: The swapped... | 3dae8d6ef2d9caed62510cfe0925cb177ca834cb | 668,973 |
def get_columns(X):
"""
Select columns to work with
:param X: imported training data
:return: all columns, numerical columns, categorical columns
"""
numerical_cols = [col for col in X.columns if X[col].dtype in ['int64', 'float64']]
categorical_cols = [col for col in X.columns if X[col].dt... | 5bc4dd521a811edccb0130c2c069910bdfc1ac02 | 668,974 |
import torch
def quantile_regression_loss(T_theta, Theta, tau_quantiles):
"""Compute quantile regression loss.
Parameters
----------
T_theta: torch.Tensor
Target quantiles of size [batch_size x num_quantiles]
Theta: torch.Tensor
Current quantiles of size [batch_size x num... | 87c91bbb5c45540301a26feef9432b8605b44f5f | 668,975 |
def shellquote(text):
"""Quote a string literal for /bin/sh."""
return "'" + text.replace("'", "'\\''") + "'" | 71162a5d2ff3699068317395936167e29d069808 | 668,988 |
def checkUniqueness(some_list):
"""
Verifies that every entry in a list is unique. If it is not, it returns
non-unique values.
"""
unique_list = dict([(x,[]) for x in some_list]).keys()
repeated_entries = [u for u in unique_list
if len([s for s in some_list if s == u])... | 616b79e378353dc5c70abb246fa55060cc3d5fd3 | 668,990 |
def encode_categorical(df):
"""
Compresses the size of the dataframe by changing column data type to minimum required size
that can accommodate the values. This is done only for categorical columns.
If a numeric column is expected to have very few values, change that to categorical first
and then us... | 52bfb33513bac65c3ec94c72c487080865e7e4c8 | 668,993 |
def extendShape(shape):
"""Add dummy dimensions to make ``shape`` 3D.
:raises NotImplementedError: If ``shape`` is neither 1, 2 or 3D.
:param np.ndarray | list | tuple shape: Shape.
:return: 3D shape.
:rtype: tuple
"""
if len(shape) == 1:
return shape[0], 1, 1
if len(shape) =... | d294241e958f39ee1b6d6b187354a9e652058585 | 668,996 |
def is_on_intersection(intersection, coord):
"""
Determines if coordinates is within intersection
:param intersection: intersection object
:param coord: coordinates to test
:type intersection: Intersection
:type coord: Coordinates
:return: True if the coord is within the intersection. Fals... | c60f0515f7033842ace5d0186f76b90abbc75e57 | 668,998 |
def is_vectorized_oper(dims):
"""Is a vectorized operator."""
return (
isinstance(dims, list) and
isinstance(dims[0], list)
) | 1437731ee61c0236d1d3c98de73d5877a160431b | 669,000 |
def get_set_bits_count(number: int) -> int:
"""
Count the number of set bits in a 32 bit integer
>>> get_set_bits_count(25)
3
>>> get_set_bits_count(37)
3
>>> get_set_bits_count(21)
3
>>> get_set_bits_count(58)
4
>>> get_set_bits_count(0)
0
>>> get_set_bits_count(256)... | 52a93fa843449c363c47259f4e24270a50dad5aa | 669,001 |
def get_img_to_cap_dict(filename):
"""
Opens the file storing image to caption mappings.
Creates a dictionary and adds the mappings as
key-value pairs to it.
Args:
filename: the name of the file storing image to caption mappings
Returns:
img_to_cap_dict: the dictionary storing image to caption mappings
"""
... | f821c3c6cd68e4a420888be99c8877caae1efdc8 | 669,005 |
def encode_state(fs, fluent_map):
""" Convert a FluentState (list of positive fluents and negative fluents) into
an ordered sequence of True/False values.
It is sometimes convenient to encode a problem in terms of the specific
fluents that are True or False in a state, but other times it is easier (or ... | a24a2207914dc77e38a4ec18551c025b2309361a | 669,014 |
def reply(read=20, write=20):
"""Return the kwargs for creating the Reply table."""
return {
'AttributeDefinitions': [
{
'AttributeName': 'Id',
'AttributeType': 'S'
},
{
'AttributeName': 'ReplyDateTime',
... | 61e8a3e90a215e38d180960ba4affc1bcf259261 | 669,015 |
def escape(line):
"""Escapes special LaTeX characters by prefixing them with backslash"""
for char in '#$%&_}{':
line = [column.replace(char, '\\'+char) for column in line]
return line | 7a5e1c5a0bfe126e1231f916a873ed69213e4109 | 669,022 |
from pathlib import Path
def get_script_path(script_name: str):
"""
Retrieves script path where name is matching {{script_name}}.
"""
p = Path(__file__).parents[1]
script_path = str(Path(p, "assets/scripts", script_name))
return script_path | 95ac410b677f0799425bfc9fc91890d17c02cd5c | 669,026 |
def remove_suffixes(text: str, suffixes:list) -> str:
"""Removes pre-defined suffixes from a given text string.
Arguments:
text: Text string where suffixes should be removed
suffixes: List of strings that should be removed from the end of the text
Returns:
text: Text string with re... | f2436cf470361d3a90373046ff0df32477d6cb9e | 669,028 |
def run_and_return_first_line(run_lambda, command):
"""Runs command using run_lambda and returns first line if output is not empty"""
rc, out, _ = run_lambda(command)
if rc != 0:
return None
return out.split("\n")[0] | 53754cea0ff023a6b318e7064471b9eb3910c548 | 669,029 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.