content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import time
def is_in_last_days(stamp, n):
"""
Check whether the timestamp was created in the last n days.
I guess the 'right' way to do this would be by using timedelta
from the datetime module, but this felt 'ok' to me.
"""
return stamp - time.time() < n * (24 * 60 * 60) | 5b77328f81107b917481216a9fafd644cf9f353e | 669,121 |
from typing import Any
from typing import Union
from typing import Tuple
import operator
def _ensure_index(x: Any) -> Union[int, Tuple[int, ...]]:
"""Ensure x is either an index or a tuple of indices."""
try:
return operator.index(x)
except TypeError:
return tuple(map(operator.index, x)) | d47b62855d1cae40959412b6f509e6f76fefefc7 | 669,122 |
import subprocess
def distribution_name():
"""
Get the LSB release distribution name, e.g. "xenial" on Ubuntu 16.04
"""
return subprocess.check_output("lsb_release -c -s", shell=True).strip().decode("utf-8") | f2c38d49b85142286a546d1d955393cd05bbddca | 669,123 |
import random
def generate_distracting_answer_dump(question_type, top_answers_split):
"""
Use other type top 3 answer to replace
"""
question_types = top_answers_split.keys()
target_q_type = ''
while not target_q_type:
random_q_type = random.choice(question_types)
if random_q_t... | 5c5b663619264c0a07cd267b21577a71aefb9861 | 669,124 |
def line_pad(linestr, padding=''):
"""
:param linestr: multiple line string with `\n` as line separator.
:param padding: left padding string to add before each line.
It could also be a callable object that returns a string.
This is useful when creating dynamic padding.
:return: multiple line s... | 418e71d9511ef0250fe1e473e7a45b7c0f161b0b | 669,125 |
def mat_var(data, struc, field):
"""Get the 'field' from the 'struc' in the 'data' imported from Matlab"""
return data[struc][field].item() | 96533de8006f1d1760b5235a01bda7a22790033f | 669,126 |
def _cols_if_none(X, self_cols):
"""Since numerous transformers in the preprocessing
and feature selection modules take ``cols`` arguments
(which could end up as ``None`` via the ``validate_is_pd``
method), this will return the columns that should be used.
Parameters
----------
X : Pandas ... | e33d36d8b32cc891115ac6fe18d2779b391a9d05 | 669,127 |
def get_slice(config):
"""Get 2D slice defining crop operation appropriate for given configuration"""
nw, nh = config.raw_tile_width, config.raw_tile_height
ow, oh = config.overlap_x, config.overlap_y
w_start, h_start = ow // 2, oh // 2
w_stop, h_stop = w_start + nw, h_start + nh
return [slice(h... | 51c6ad01ffae3bf9f7c75ad58c5e742db2c06e54 | 669,128 |
def torch_to_numpy(t):
"""
torch tensor to numpy array
:param t: the torch tensor
:return: numpy array
"""
return t.numpy() | 793232ee73d11fb1d0e3503d907f0290fc09ebb9 | 669,129 |
import os
import shutil
def prepare_calc_directory(mol_path, T, dir_name=None):
"""Copy pdb file into the directory with the same name. If such directory
doesn't exist it will try to create it.
Parameters
----------
mol_path : string
Path to solute
T : float
A calculation tem... | 922169e15fdd61355377a37d81c3b3df9d802230 | 669,130 |
def str2floatTrap(someStr):
"""
Checks if there is either a starting '(' or an ending ')' around the input string and returns a string without them.
:param someStr: input string
:return:
"""
tempStr = someStr
if tempStr.startswith('('):
tempStr = tempStr[1:]
if tempStr.endswi... | fe5a0661e2874ff9c1bab290163ba18361e0e0a7 | 669,131 |
import mimetypes
def get_url_type(url):
"""
Tries to guess whether an URL points to an image.
"""
link_type, link_encoding = mimetypes.guess_type(url)
if link_type is None:
return "link"
return "image" if link_type.startswith("image/") else "link" | e938f4852e7fbc329f14b00d53edae488fbbb043 | 669,132 |
def gen_target_cfg_items(target_cfg):
"""
Convert target_cfg to list of target configs
"""
if isinstance(target_cfg, list):
# list of templates defined for this target
return target_cfg
elif isinstance(target_cfg, dict):
# only one template defined for this target
ret... | 5ccf6198b44a800061a961d5decfba4701f7ac34 | 669,133 |
def pivot_ct(df, index, columns, sort=True, min_obs=0):
"""Fast count table."""
ct = df.pivot_table(
index=index,
columns=columns,
aggfunc='size',
fill_value=0,
)
# sort
if sort:
ct = ct.loc[ct.sum(1).sort_values(ascending=False).index]
ct = ct[ct... | 303a5f2e31810f891b78bbf047a24a710c9b57ed | 669,136 |
def intersection(l1, l2):
"""Return intersection of two lists as a new list::
>>> intersection([1, 2, 3], [2, 3, 4])
[2, 3]
>>> intersection([1, 2, 3], [1, 2, 3, 4])
[1, 2, 3]
>>> intersection([1, 2, 3], [3, 4])
[3]
>>> intersection([1, 2, 3], [4, 5, 6])
... | 98948fe600c1c1dd52d942d875efbb9d1dfdd46a | 669,138 |
import subprocess
def run_cmd(cmd_line):
""" Run command in system shell """
return subprocess.call(cmd_line, shell=True) | 12ec2fd49188b9009cbb8d4b5b88eecd2c6c6bac | 669,139 |
def bytes_to_nibbles(data):
"""
Utility function to take a list of bytes (8 bit values) and turn it into
a list of nibbles (4 bit values)
:param data: a list of 8 bit values that will be converted
:type data: list
:return: a list of 4 bit values
:rtype: list
.. versionadded:: 1.16.0
... | 66e22ac3984e860c2bfdb789eda7890da3c7d1d9 | 669,140 |
def _equiv_topology(top_1, top_2):
"""Compare topologies using string reps of atoms and bonds"""
for (b1, b2) in zip(top_1.bonds(), top_2.bonds()):
if str(b1) != str(b2):
return False
for (a1, a2) in zip(top_1.atoms(), top_2.atoms()):
if str(a1) != str(a2):
return Fa... | efa70e346874745f119377542cf572d48a852504 | 669,141 |
import re
def ProcessGitHubLinks(markup, github):
"""Replaces the GitHub local links by the external variants."""
markup = re.sub(
r'#(\d+)',
r'[#\1](https://github.com/%s/issues/\1)' % github,
markup)
markup = re.sub(
r'\[(.+?)\]\((wiki/.+?)\)',
r'[\1](https://github.com/%s/\2)' %... | 88284abc8fc76f4b24dd1d5040b0156e4eef0cf7 | 669,142 |
def fmt_text(text):
""" convert characters that aren't printable to hex format
"""
PRINTABLE_CHAR = set(
list(range(ord(' '), ord('~') + 1)) + [ord('\r'), ord('\n')])
newtext = ("\\x{:02X}".format(
c) if c not in PRINTABLE_CHAR else chr(c) for c in text)
textlines = "\r\n".join(l.str... | 0efc068cac4831f273caae768eed049583b9a9ee | 669,143 |
def get_grasp_polygon_lines_from_polygon(polygon):
""" For use with matplotlib Line2D and draw_grasp()
y, x order!
really a polygon format rectangle [[yx], [yx], [yx], [yx]]
"""
num_bboxes = 4
x_current = [[] for k in range(num_bboxes)]
y_current = [[] for k in range(num_bboxes)]
y_idx... | fd2747427d001e35d77d64b1cda88c34667226e2 | 669,145 |
def getSubsetSize(data, bad_list=None, limit=10, testfrac=0.05):
"""Returns a dictionary of lists with structure:
dict['valid'] - valid classes being used in dataset
dict['learnsize'] - # of images being added to learnset
dict['testsize'] - # of images being added to testset
dict['short'] - classes ... | aaba9efa9c631a72a2e69e46dd808773bb1a26fa | 669,146 |
import os
def deleteFiles(src):
"""
parameter:- folder path with files
This will delete files from folder
"""
for file in src:
os.remove(file)
print("--------deleted files-------")
return None | c10c37fa5811b6f73bfdc429674b3899ab548259 | 669,148 |
def prod_client(prod_client):
"""
Production client so tests can send request to service production endpoint
"""
client = prod_client()
response = client.get('/get')
assert response.status_code == 200
return client | 0c00482e06ca63bb730b46b90f6fa770e417bdec | 669,149 |
def transpose(df):
"""Transpose df, set 'Date' as index, and strip columns."""
df = df.T.reset_index().rename(columns={"index" : "Date"})
return df.set_index("Date") | 0f7fa255880c4e89117ada7471e19dbbdf3037e4 | 669,150 |
import requests
def get_EQ_USGS_API(Params):
"""
This function inputs the required details for pulling API's from USGS using requests library. Parameters are taken through {params_diction}
"""
baseurl = 'https://earthquake.usgs.gov/fdsnws/event/1/query?'
params_diction={}
params_dict... | f52afdc449f7de14c363409fddd5c07905689ad0 | 669,152 |
def siamese_target(elements_0, elements_1, get_classes=lambda x: x[1]):
"""Creates the contrastive loss target vector for the given image pairs. A target of 0 is assigned when both images
in a pair are *similar* (have the same class), 1 otherwise.
Args:
elements_0: normal batch of the first elements ... | f5465025bda25cc6fc1a91288ff5a48078c7f5f6 | 669,155 |
import os
def read_from_text_file(directory: str, filename: str):
"""Reads in dictionaries and lists from text file"""
list_from_file = []
dictionaryFromFile = {}
if not os.path.exists(directory + filename):
with open(directory + filename, "w") as filehandle:
pass
print(f"Ope... | e0aba985d914482a318b53b0b6edadfc3a473d36 | 669,156 |
def _fix_precision(val: float, precision) -> int:
"""Convert floating point numbers to (implicitly) fixed point integers.
Circuit parameters can be floats but we also need to use them as
dictionary keys. We secretly use these fixed-precision integers.
"""
return int(val * precision) | 3d7b9ad585df051941e60a4c2038e327528d207f | 669,158 |
def adjustEdges(height, width, point):
"""
This handles the edge cases if the box's bounds are outside the image range based on current pixel.
:param height: Height of the image.
:param width: Width of the image.
:param point: The current point.
:return:
"""
newPoint = [point[0], point[1... | ff8007279b69f952d2694d52d752db45288acc9d | 669,159 |
import uuid
def get_uuid():
"""Return a new UUID in String format.
:returns: String
"""
return str(uuid.uuid4()) | 93c95468a6a39078158ca2a51b98d18b04bec944 | 669,160 |
def _create_key_words_for_cluster(model, terms, clusters_amount):
"""Returns array of clusters each with 30 most important words"""
order_centroids = model.cluster_centers_.argsort()[:, ::-1]
res = []
for i in range(clusters_amount):
arr = []
for ind in order_centroids[i, :30]:
... | 08f57050bc1af9d8dc2c764759c208a37942851b | 669,161 |
def unique_label(operator):
"""Function for generating short name for operator from it's address. It takes first 6 and last 4 symbols and
combines it. """
return operator[:6] + operator[-4:] | 57b845de8af7c0c75479a6151dbe0e7f24898db5 | 669,162 |
def bad_echo(value):
"""
Badly implemented echo method.
:param value:
:return:
>>> bad_echo(5)
5
"""
return 0 | a4149015dc5a0e8a6bd6050cb73a80f713a30ded | 669,163 |
import re
def sphinx_escape(value):
""" Escapes SphinxQL search expressions. """
if not isinstance(value, str):
return value
value = re.sub(r"([=<>()|!@~&/^$\-\'\"\\])", r'\\\\\\\1', value)
value = re.sub(r'\b(SENTENCE|PARAGRAPH)\b', r'\\\\\\\1', value)
return value | 12107cd3fac889f15d008a4a7be46ae17e774529 | 669,164 |
def twitter_url(screen_name, no_rt, start, end):
"""Form url to access tweets via Twitter's search page.
Params
-------
screen_name : str
no_rt : bool
start : datetime-onj
end : datetime-obj
Returns
-------
{string} search url for twitter
"""
url1 = 'https://twitter... | 8f847a42abacea81bf3d87ca8b77c1008584ab26 | 669,165 |
from functools import reduce
def product(fracs):
"""doc"""
t = reduce(lambda x, y: x * y, fracs)
return t.numerator, t.denominator | 53f08cbd06f29363a9d79e24e6bc35892abed924 | 669,166 |
def human_join(iterable, delim=', ', *, final='and'):
"""Joins an iterable in a human-readable way.
The items are joined such that the last two items will be joined with a
different delimiter than the rest.
"""
seq = tuple(iterable)
if not seq:
return ''
return f"{delim.join(seq[:-... | be464110d26e7faeb9bbe5ac404ab5c3722cef0b | 669,167 |
import base64
def s2b(s: str) -> bytes:
"""b64 string to bytes."""
return base64.b64decode(s) | d6e5bd6418f551fee207aaf2ed0c9e14b1b9c6cc | 669,168 |
def elapsedTime(seconds, suffixes=['y','w','d','h','m','s'], add_s=False, separator=' '):
"""
Takes an amount of seconds and turns it into a human-readable amount of time.
"""
# the formatted time string to be returned
time = []
# the pieces of time to iterate over (days, hours, minutes, etc)
... | 1f8892225b7afbd59ae54d7c9f761d2fb69824b6 | 669,169 |
from typing import Union
def constant_schedule(value: Union[float, int]):
"""Constructs a constant schedule.
Args:
value: value to be held constant throughout.
Returns:
schedule: A function that maps step counts to values.
"""
return lambda count: value | 14fc340a21b3b0deb008368a332ae28ab93162e2 | 669,170 |
def getDisplayName(name,suffix="Process"):
""" comvert a camel-case name to an all lower case underscore
separated name.
"""
if name.endswith(suffix) and suffix:
name = name[:-len(suffix)]
out = name[0]
for i in range(1,len(name)):
if name[i].isupper() and not name[i-1].isupp... | df3a9feca01f9efd64c8980f801e58610d56ab68 | 669,171 |
def auth_headers():
"""
Headers to set when authenticating against the API's.
"""
headers = {
'Content-Type': 'application/json',
'Accept': 'application/json',
}
return headers | 80923f8ec5006346d4dbbaf40d70997bc2a27aea | 669,172 |
def parse_lon_lat(grid, lon, lat):
""" Parse lat and lon parameters """
if lat is None:
lat = grid.axes['lat']['data'][0]
if lon is None:
lon = grid.axes['lon']['data'][0]
return lon, lat | 1f0280170c8d2c633c2615a0423d6b671d0dd0f0 | 669,173 |
def get_unique(frame, column_name):
"""
Helper function to get unique count for column
"""
return frame[column_name].value_counts().compute() | 5a32b53897658a6ba4b0aebabc1670c6460c16b8 | 669,174 |
def get_column_by_cum(df):
"""Return ."""
return list(df.columns[df.columns.str.endswith('cum')]) | a0e56d9850e2555879a969e5d8de46e7e9ad0d03 | 669,175 |
def get_parlabel(pid):
"""Return label for a list of parameter ids
Parameter:
pid - list of parameter ids"""
master = ['log $M_b$', '$a_b$', 'log $M_d$', '$a_d$', '$b_d$', '$V_h$', '$R_h$', '$\phi$', '$q_x$', '$q_y$', '$q_z$', '$a_{1,-1}$', '$a_{1,0}$', '$a_{1,1}$', '$a_{2,-2}$', '$a_{2,-1}$', '$a_... | 606e157e124445474c3db992e53a59f2d321be17 | 669,176 |
def get_properties(dataset, property_offsets=None):
"""
Extract properties and return values in a dictionary:
{
'properties':
{
'datetime': time,
'odc:creation_datetime': creation_time,
...
}
}
"""
props = dict()
props['datetime'] = dataset.center_ti... | b525a6eb950a1763f1eb591e9b47d18ce3305cb9 | 669,177 |
def new_position(pos, vel):
"""Calculates the new position od the moons"""
for i in range(4):
for j in range(3):
pos[i][j] += vel[i][j]
return pos | 3203025d166bdb9fb060d7019a17d27c70ec4d98 | 669,178 |
def get_enduse_regs(
enduse,
fuels_disagg):
"""
Get a specific enduse for all regions
Arguments
---------
enduse : str
Enduse to sum
fuels_disagg : list
Fuels per disaggregated regions
Returns
-------
fuels_enduse : dict
Fuels of an enduse fo... | 17a3468fc795cfa0221cb3efca34246f6ff40f2f | 669,179 |
import random
def next_unused_name_in_group(grp, length):
""" Gives a name that isn't used in a Group.
Generates a name of the desired length that is not a Dataset or
Group in the given group. Note, if length is not large enough and
`grp` is full enough, there may be no available names meaning that
... | 302c55264655ef5d5c011462527ea88565dedebe | 669,180 |
def pluralize(count, singular, plural):
"""Return singular or plural based on count"""
if count == 1:
return singular
else:
return plural | cf9ead8a58728b59ecf485542aa6c9afd399b311 | 669,181 |
import os
def load_environment_value(config_key) -> str:
"""Obtain a environmental variable."""
tmp_val = os.getenv(config_key, None)
if tmp_val is None:
raise Exception("Environment Variable {} not found!".format(config_key))
return tmp_val | d6404ecbb2535adc21f524fb3223b9d1a328df68 | 669,182 |
def to_name(value):
"""
Replace all underscores with space, and only take first path when with relationship
So first_name becomes first name
And company.name becomes company
"""
return value.split('.')[0].replace('_', ' ') | c2c22031aecdffb30501ee4d96cfa4516f8202a9 | 669,183 |
def derivative_expr(printer, ast):
"""Prints expression "expr'"."""
expr_str = printer.ast_to_string(ast["expr"])
return f"{expr_str}'" | 8b91f20adc6f2f2ddc1857913d607adf243a834a | 669,184 |
import six
def elide(string, max_length, ellipsis="...", position=1.0):
"""
Elides characters to reduce a string to a maximum length.
Replaces elided characters with an ellipsis.
>>> string = "Hello, world. This is a test."
>>> elide(string, 24)
'Hello, world. This i...'
>>> e... | f32662a49990d32fc53df0abad623d5bed890b76 | 669,185 |
def convert_to_hex(input_string: str):
"""Convert input_string into string of hexadecimal values."""
return " ".join([hex(ord(ch))[2:] for ch in input_string]) | d31be0492960c5fc6a49ecacdd3981f3d71fce14 | 669,186 |
import warnings
def _full_project_name(self, project):
"""Deduce the full project name."""
if project.startswith(('openSUSE', 'SUSE')):
return project
if 'Factory' in project or 'openSUSE' in project:
return 'openSUSE:%s' % project
if 'SLE' in project:
return 'SUSE:%s' % proj... | 6f5a783cca51768c3150d8af28699ca30b9194ab | 669,187 |
def 取整(value):
"""
调用格式: 〈整数型〉 取整 (双精度小数型 欲取整的小数) - 系统核心支持库->算术运算
英文名称:int
返回一个小数的整数部分。本命令与“绝对取整”命令不相同之处为:
如果给定小数为负数,则本命令返回小于或等于该小数的第一个负整数,而“绝对取整”命令则会返回大于或等于该小数的第一个负整数。例如,本命令将 -7.8 转换成 -8,而“绝对取整”命令将 -7.8 转换成 -7。本命令为初级命令。
参数<1>的名称为“欲取整的小数”,类型为“双精度小数型(double)”。
操作系统需求: Windows、Linux
"... | 98b0dee070d644bf57b7ad22dd08339ae426daec | 669,188 |
import os
def get_path(rootpath, wantedpath):
"""Return path to wantedpath relative to rootpath."""
return os.path.join(
os.path.dirname(rootpath),
wantedpath
) | f5a5c734b9e98ff56303d75793875c75cb2f2aa9 | 669,189 |
import math
def risk_level_allocation(station, first_der, second_der):
"""Assign flood risk level to the given station"""
risk_levels = 0
# Risk allocation criteria!
relative_water_level = station.relative_water_level()
if isinstance(relative_water_level, float) and relative_water_level >= 0:
... | 9a67f7e534d4b4b23d723078ea03b5ef51b77e95 | 669,190 |
import platform
import subprocess
def ping(host: str) -> bool:
"""
Returns True if host (str) responds to a ping request.
Remember that a host may not respond to a ping (ICMP) request even if the host name is valid.
:param host: IP or hostname
:type host: str
:returns: True if host responds t... | e10910da450aff77bc13a0117ec1a9925090945b | 669,191 |
import json
def _convert_result(result): # pragma: no cover
"""Translate SOAP result entries into dicts."""
translation = {
'RGE_RUC': 'rnc',
'RGE_NOMBRE': 'name',
'NOMBRE_COMERCIAL': 'commercial_name',
'CATEGORIA': 'category',
'REGIMEN_PAGOS': 'payment_regime',
... | fb41815a01e05809aa7d89815e21366ab55d6524 | 669,193 |
def color565(r, g, b):
"""Return RGB565 color value.
Args:
r (int): Red value.
g (int): Green value.
b (int): Blue value.
"""
return (r & 0xf8) << 8 | (g & 0xfc) << 3 | b >> 3 | 0e281026ca113ca120565ee5b77a849914d47bf8 | 669,195 |
def convert_uint32_to_array(value):
""" Convert a number into an array of 4 bytes (LSB). """
return [
(value >> 0 & 0xFF),
(value >> 8 & 0xFF),
(value >> 16 & 0xFF),
(value >> 24 & 0xFF)
] | e578cb3958511339c3df155d599fe00ee5c24f9d | 669,197 |
def solve(v):
""" Sum big numbers and get first digits. """
# no gmp support, pruning table
# int32 support: trunc digits
t = (
37107, #2875339021027,
46376, #9376774900097,
74324, #9861995247410,
91942, #2133635741615,
23067, #5882075393461,
89261, #67069... | aac5928db0281c11174ac7ea94c96e0f0742236f | 669,198 |
def read_data(filename):
""" read the cities data ffrom txt file and store them as a list of tuples of (x, y) """
cities = []
with open(filename) as f:
lines = f.readlines()
n = int(lines[0].split()[0])
for line in lines[1:]:
cities.append((float(line.split()[0]), float(l... | 177760b787b216d6d95a7436c4b4248d88f000cd | 669,199 |
import functools
def Factorial(x):
"""Computes the factorial of an integer number.
"""
# 0) SECURITY CHECK
if not isinstance(x, int):
raise ValueError( "'Factorial' function only accepts integers" )
# 1) COMPUTE THE FACTORIAL
if x == 0 or x == 1:
return 1
else:
ret... | 24d53acfcb6a372025a648b761f12747a5e1fa25 | 669,200 |
def columns(thelist, n):
"""
Break a list into ``n`` columns, filling up each column to the maximum equal
length possible. For example::
>>> from pprint import pprint
>>> for i in range(7, 11):
... print '%sx%s:' % (i, 3)
... pprint(columns(range(i), 3), width=20)
... | 12379ae0fb852b9a91c82c464b2b75e9ce5b65f7 | 669,201 |
import torch
def soft_lu_bound2(x, l_limit, u_limit):
"""soft lower and upper bound: force argument into a range """
m = lambda x: torch.tanh(x)
y = l_limit + (1 + m(x))/2 *(u_limit - l_limit)
return y | 73afe3253a16c0d877e983177f1befce0a1f9b5e | 669,202 |
def encode_bigint_bitvec(value, bitlen=None):
"""Encode a Bit-Endian integer into a vector of bits"""
if bitlen is None:
bitlen = value.bit_length()
binval = '{{:0{:d}b}}'.format(bitlen).format(value)
return [int(x) for x in binval] | 8f55b0b65defc3dbc3c7782c084518d6b22b7e62 | 669,203 |
def motifPosCmp(motifOcc1, motifOcc2):
"""Compares two motif occurences according to their position on a given
sequence. The occurences must be on the same sequence."""
assert(motifOcc1.getSeqName() == motifOcc2.getSeqName())
motifOcc1Centre = motifOcc1.getCentre()
motifOcc2Centre = motifOcc2.getCe... | ef7fbff4fc40067f1b062841e36c9d6b4abf7390 | 669,204 |
import re
def _parse_cli_input(line):
""" Parses a command line input, which may include a transformation name
(optional), its occurrence ID, and its parameters (optional).
Syntax Examples:
* 5 - Chooses the fifth transformation
* MapReduceFusion$0 - First... | 5b75f32b3011ef4ea15dda15b3475a5261801a5f | 669,205 |
def colorHash(text):
"""
Stolen from https://github.com/zenozeng/color-hash
"""
SaturationArray = [0.66, 0.83, .95]
LightnessArray = [0.5, 0.66, 0.75]
h = hash(text)
Hue = h % 359 # (Note that 359 is a prime)
Saturation = SaturationArray[h // 360 % len(SaturationArray)]
Lightness =... | 14db23adb5528b1317414410ca528a1cea8795ce | 669,206 |
def GetJSObjectByTypeAndId(js, type, id, throw_on_fail = True):
"""."""
try:
for object in js['objects'][type]:
if object['id'] == id:
return object
except:
pass
if throw_on_fail:
raise RuntimeError("Object %s id:%d does not exist" % (type, id))
return None | 8eeaf3d04d98caae848afa31716720a4db946b61 | 669,207 |
from pathlib import Path
import os
def get_all_md(path):
"""get alls files markdown from folder and subfolders
Args:
path (Path): path for to search files md
Returns:
list: markdown files's list
"""
list_md = []
for file in Path(path).iterdir():
if file.is_dir():
... | 34de3e9a85ebc06e42cdc2388366ebb968fbbdd4 | 669,208 |
def getMeshToNetworkIdxMatchingLocations(settings):
""" Returns file path of saved dictionary associating location's idx in unstructured mesh with
its idx in array of clustered data (for locations present in all sub-domains, e.g. overlapping regions)"""
filename = "meshIdxToNetIdxMatching_" + str(settings.... | c3a845b68623285f39567744a9641419bb6e20b8 | 669,209 |
import os
def fixture_location(name):
"""
Get the file location of the fixture with the given name.
"""
return os.path.join(os.path.dirname(__file__), 'fixtures', name) | b6d5efbf4eba07e0feb2663af2f320f47ca5a1da | 669,211 |
def _add_default_fields(ds, fields):
"""
Add some default fields to rays to assure they can be processed correctly.
"""
if ("gas", "temperature") in ds.derived_field_list:
fields.append(("gas", 'temperature'))
# H_nuclei_density should be added if possible to assure that the _log_nH
# f... | e25139539ee9c53df5ab1d43b6aaf7f4e51db0ce | 669,212 |
import typing
import pkg_resources
def get_imagenet_classes() -> typing.List[str]:
"""Get the list of ImageNet 2012 classes."""
filepath = pkg_resources.resource_filename("vit_keras", "imagenet2012.txt")
with open(filepath) as f:
classes = [l.strip() for l in f.readlines()]
return classes | 66de4ad997c8002a3c8f82fe7b830d3e1fd1702d | 669,213 |
import math
def pts_near(gt_bbx, pred_bbx, rad): # change name
"""
Determine if two points are within a radius.
Parameters
----------
gt_bbx : dict
[centre_x, centre_y]
pred_bbx : dict
[centre_x, centre_y]
Returns
-------
True or False
"""
# creat... | f3a5b98b2e886aeb6c447591b7464d6a19631106 | 669,214 |
def getFilteredDivs(divs):
"""routine to filter elements corresponding to a comment/reply"""
filtered = list()
for div in divs:
if len(div.get("class")) == 1:
filtered.append(div)
return filtered | 95f047eb7a7fa9447aac97fc6ad291e63013e2ca | 669,215 |
def len4bytes(v1, v2, v3, v4):
"""Return the packet body length when represented on 4 bytes"""
return (v1 << 24) | (v2 << 16) | (v3 << 8) | v4 | 74d503e7b21dbc2c3c14ca968f0a9decec297292 | 669,216 |
def solution(n: int = 1000) -> int:
"""
returns number of fractions containing a numerator with more digits than
the denominator in the first n expansions.
>>> solution(14)
2
>>> solution(100)
15
>>> solution(10000)
1508
"""
prev_numerator, prev_denominator = 1, 1
result ... | 07f07e82642e42232fd8c02b1d607eeaa589a11a | 669,217 |
def create_word_count_dict(word_count_queryset):
"""
This function creates a dictionary where the keys are word names
and the values are word counts from a given queryset.
:param word_count_queryset: A WordCountQueryset containing word names
and their associated word counts.
:return: A dictionar... | d04d66e70927fd12b4a8343ba8fefdb952239c35 | 669,218 |
def unique_list(l):
"""Remove duplicate term from a list
Parameters
----------
l : list
A list potentially contains duplicate terms
Returns
ulist : list
A list without unique terms
"""
ulist = []
for item in l:
if item not in ulist:
u... | 3ff78c11a7b62ec48e53333ee274b293fc09939b | 669,219 |
import math
def euclidean_distance(p1: tuple, p2: tuple) -> float:
"""
:param p1:
:param p2:
:return:
"""
return math.hypot(p2[0] - p1[0], p2[1] - p1[1]) | 207c38de1469d8ebe0cdcc66425c05b1036d8e0e | 669,220 |
def prepare_html(payload):
"""
replace the user input with correct html code. so that we can submit the data to Jama in an expected format
@params:
payload -> user input
"""
return payload.replace('\n', '<br>') | ad2fcff5bfeece58995ce0d74b2b7d46c95390c6 | 669,221 |
def get_keys_or_list(data):
"""
Recursive function to go through .json file
"""
if isinstance(data,list):
num = int(input("Enter the number of element of list:\n"))
new_data = data[num-1]
indo = get_keys_or_list(new_data)
return (indo)
elif isinstance(data,dict):
... | 5d380ee6fd2c7e23625955b971b8cd64f8891e61 | 669,222 |
import pathlib
import shutil
def move_marc_files_check_tsv(*args, **kwargs) -> str:
"""Moves MARC files to migration/data/instances, sets XCOM
if tsv is present"""
task_instance = kwargs["task_instance"]
airflow = kwargs.get("airflow", "/opt/airflow")
source_directory = kwargs["source"]
marc... | 438efc657fe5ee10b1cb317c5473053c33cd5776 | 669,224 |
import jinja2
import json
def json_filter(val, indent=0):
"""Jinja2 filter function 'json' produces JSONified string of the value"""
if val is None or isinstance(val, jinja2.Undefined):
return "null"
return json.dumps(val, indent=indent, sort_keys=True) | 9b94eeb52e9f3afe3b1494dba0798f5a90dd989a | 669,225 |
import torch
def normalized_columns_initializer(weights, std=1.0):
"""normalize weights in Q-network"""
out = torch.randn(weights.size())
out *= std / torch.sqrt(out.pow(2).sum(1,keepdim=True).expand_as(out)) # thanks to this initialization, we have var(out) = std^2
return out | 9734a9ec8ea155fc3dee95cf8647418e9a5c9028 | 669,226 |
from typing import List
import subprocess
import sys
def shell_response(cmd: List) -> List[str]:
""" uses subprocess.run() """
process = subprocess.run(cmd, capture_output=True, encoding='utf-8')
output = process.stdout.split('\n')
if process.returncode != 0:
print(process.stderr)
sys.... | bd353a0234ca4076a6e6af1aea3431a44c3ec7ab | 669,228 |
import random
def mutUniform(individual, expr, pset):
"""Randomly select a point in the tree *individual*, then replace the
subtree at that point as a root by the expression generated using method
:func:`expr`.
:param individual: The tree to be mutated.
:param expr: A function object that can gen... | c389b942c8b11508dee92fd4d003bbc528623dcf | 669,229 |
import random
def randomize(applicants):
"""
Random permutation of applicant list. Typical usage is before
prioritization.
"""
return random.sample(applicants, k = len(applicants)) | 4dceff66041e1881df2c064bc56b8f2b0663fb0c | 669,230 |
def next_day(fishes):
"""Meh
>>> fishes = read_input('example')
>>> fishes = next_day(fishes)
>>> fishes
[1, 1, 2, 1, 0, 0, 0, 0, 0]
>>> fishes = next_day(fishes)
>>> fishes
[1, 2, 1, 0, 0, 0, 1, 0, 1]
>>> fishes = read_input('example')
>>> for n in range(18):
... fishes = ... | f60072ce2ed4f140dbfbf1c1387fa1b31ddbef7e | 669,231 |
def add_public_holidays(data_frame):
"""
Adds new column holidays into `data_frame` with default value 0. Than iterates
through whole data_frame and add 1 into holidays column to each time stamp that occurs on public holiday in
Czech Republic. Holiday dates for years 2017, 2018 and 2019 are listed in list below.
... | dbc98f722d2fde55d6002cadabeb7562edecf0ae | 669,232 |
import os
def get_base_fname_without_ext(fname: str) -> str:
"""Returns the file name without the extension (or without extensions if multiple) from the supplied path."""
base = os.path.basename(fname)
return os.path.splitext(base)[0] | 9d331822013a16effcef7b96c0ac0dd2b726cbd4 | 669,234 |
def choose(color):
"""
Used to convert the png into 4 color.
"""
r, g, b, a = color
if r < 90:
return (0, 0, 0, 255)
if r >= 77 and r < 160:
return (134, 30, 214, 255)
if r >= 160 and r < 208:
return (172, 143, 239, 255)
else:
return (255, 255, 255, 255) | e06fe6437ace905dca4d062d8e97a4de8d1eb369 | 669,235 |
import re
def check_if_balanced(my_string):
"""
Check if particular citation has balanced brackets.
:param: citation to be taken in consideration
"""
my_string = re.sub('\w|\s|[^{}]','', my_string)
brackets = ['()', '{}', '[]']
while any(x in my_string for x in brackets):
for br... | 7e94fed3b16aa0028c7f8e082cbfe333e3dc213c | 669,238 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.