content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
from pathlib import Path
def get_file_size_in_bytes_3(file_path):
""" Get size of file at given path in bytes"""
# get file object
file_obj = Path(file_path)
# Get file size from stat object of file
size = file_obj.stat().st_size
return size | 0dfdcdcdf0e3b77a8664d9e9161498ae6f7e712a | 675,011 |
from typing import List
import re
def get_assignees(content: str) -> List[str]:
"""Gets assignees from comment."""
regex = r"\+([a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+)"
matches = re.findall(regex, content)
return [m for m in matches] | 0c5c90237eff1c3d07767bfb7434d5ca977e03e2 | 675,013 |
def unpad_list(listA, val=-1):
"""Unpad list of lists with which has values equal to 'val'.
Parameters
----------
listA : list
List of lists of equal sizes.
val : number, optional
Value to unpad the lists.
Returns
-------
list
A list of lists without the padding... | 8354f3c78168aafa86a0a07997895d964d81cb31 | 675,015 |
def decode_outputs(probs, inds, decoder):
"""
Decode from network probabilities and compute CER
Arguments:
probs: Tensor of character probabilities
inds: List of character indices for ground truth
decoder: instance of a Decoder
Returns:
Tuple of (ground truth transcript,... | 1571df5ac1fcea9e3dd5206357c920cbfd1a1011 | 675,016 |
from typing import Tuple
def _get_ds_file_offset(
parm_start: int, span: Tuple[int, int], inclusive: bool = False
) -> Tuple[int, int]:
"""Get the file offsets for the parameter.
:param parm_start: The start position of the parm.
:param span: The span of the parm data.
:param inclusive: Whether t... | acd8055564400cf59d73642707695b51a3c38e99 | 675,018 |
def _join_tokens_to_string(tokens, master_char_set):
"""Join a list of string tokens into a single string."""
token_is_master = [t[0] in master_char_set for t in tokens]
ret = []
for i, token in enumerate(tokens):
if i > 0 and token_is_master[i - 1] and token_is_master[i]:
ret.append(u" ")
ret.app... | a5545ca25b039ee3b343a7889b024e9dacdde372 | 675,021 |
def parse_games_wins(r):
""" Used to parse the amount of games won by a team.
"""
return int(r.get("wedWinst", 0)) | e305507c297d923eab5181da0b5b9531914e5ec6 | 675,023 |
def _num_two_factors(x):
"""return number of times x is divideable for 2"""
if x <= 0:
return 0
num_twos = 0
while x % 2 == 0:
num_twos += 1
x //= 2
return num_twos | d122f5a084c38e9b6a8de251f2a0658957f23b63 | 675,025 |
def isaudio(file: str)->bool:
"""
test whether param file is has a known ending for audio formats
:param file: str
:return: bool
"""
audio_files = ["mp3", "aac", "ogg", "m4a"]
end = file.rsplit(".", 1)[-1]
return True if end in audio_files else False | 150e937266cd971a1fdd7bf2dce5deb96bec1fae | 675,027 |
def choose_gc_from_config(config):
"""Return a (GCClass, GC_PARAMS) from the given config object.
"""
if config.translation.gctransformer != "framework": # for tests
config.translation.gc = "marksweep" # crash if inconsistent
classes = {"marksweep": "marksweep.MarkSweepGC",
... | 93af505e0dd81bed6fedfcce206e01a6a3835ff9 | 675,030 |
import re
def format_kwargs(string, *args):
"""Return set or dict (optional) of keyword arguments ({keyword}) in provided text"""
keywords = {x.strip('{}') for x in re.findall(r'((?<!{){(?!{).*?(?<!})}(?!}))', string)}
if args and args[0] == "dict":
return {sub: "" for sub in keywords}
return ... | b828223072d8c8e3902af7b5e1d4400b6bd93e8c | 675,031 |
import random
def randcolor(mode):
"""Makes a random color for the given mode"""
ri = lambda v: random.randint(0, v)
if mode == 'L':
return ri(255)
elif mode == '1':
return ri(1)
elif mode == 'I':
return ri(2**23-1)
elif mode == 'F':
return random.random()
e... | 7dcc9fc09c792c7919e9aafff6e5c5733186116c | 675,035 |
def drop_columns(df, columns, inplace=False):
"""drop a list of columns from a Pandas dataframe,
in place"""
if not inplace:
df = df.copy()
for c in columns:
df.pop(c)
return df | 91eb261c184f20ed9051976c5c65afe1f2439fd2 | 675,036 |
def merge_lists(two_d_list):
"""Merges a 2d array into a 1d array. Ex: [[1,2],[3,4]] becomes [1,2,3,4]"""
# I know this is a fold / reduce, but I got an error when I tried
# the reduce function?
return [i for li in two_d_list for i in li] | 24ff74a9345cdfb1590a053a20f45fea21164454 | 675,037 |
def char(int):
"""
CHAR int
outputs the character represented in the ASCII code by the input,
which must be an integer between 0 and 255.
"""
return chr(int) | 7fa90e06d9b4498a1603fa2439776789c98bd2be | 675,039 |
def to_port(port_str):
"""
Tries to convert `port_str` string to an integer port number.
Args:
port_str (string): String representing integer port number in range
from 1 to 65535.
Returns:
int: Integer port number.
Raises:
ValueError: If `port_str` ... | 3ed89b058d7658d6faec307031252238351ffba2 | 675,041 |
def get_best_alignment(record_list):
"""
Get the best alignment from a list of alignments. The best alignment has the lowest distance to the reference. If
more than one alignment has the minimum distance, then the first one in the list is returned.
:param record_list: List of records.
:return: Bes... | 133956b0ecac5b948e3ff7dd20e6a9167f362d9e | 675,043 |
def isAdditivePrimaryColor(color):
"""
return True if color is a string equal to "red", "green" or "blue", otherwise False
>>> isAdditivePrimaryColor("blue")
True
>>> isAdditivePrimaryColor("black")
False
>>> isAdditivePrimaryColor(42)
False
>>>
"""
return ( (color == "r... | 91a13b47d4143adab9fe27135044dcc6df58de56 | 675,044 |
def map_attributes(properties, filter_function):
"""Map properties to attributes"""
if not isinstance(properties, list):
properties = list(properties)
return dict(
map(
lambda x: (x.get("@name"), x.get("@value")),
filter(filter_function, properties),
)
) | cfb6d22fdaccc21ba3ff7b957a4d8379313f9e12 | 675,048 |
def checking_features(columns:list, lst_features:list) -> bool:
"""
Parameters:
* columns [list]: list of columns in the dataframe.
* lst_features [list]: list of required features.
Return:
True/False [bool]: If all / not all the required features
are in the dataframe.
"""
if all([feat in columns f... | 5cdaa5751a6fee832b378e12db3263976a88f89a | 675,050 |
def _Delta(a, b):
"""Compute the delta for b - a. Even/odd and odd/even
are handled specially, as described above."""
if a+1 == b:
if a%2 == 0:
return 'EvenOdd'
else:
return 'OddEven'
if a == b+1:
if a%2 == 0:
return 'OddEven'
else:
return 'EvenOdd'
return b - a | 5708a934b18e87b3719e16df967d8320b9be7e8d | 675,053 |
import difflib
def diff_files(filename1, filename2):
"""
Return string with context diff, empty if files are equal
"""
with open(filename1) as file1:
with open(filename2) as file2:
diff = difflib.context_diff(file1.readlines(), file2.readlines())
res = ""
for line in diff:
... | 37031f9918bc02cb63365b5206847bbf8671b957 | 675,054 |
def min_list(lst):
"""
A helper function for finding the minimum of a list of integers where some of the entries might be None.
"""
if len(lst) == 0:
return None
elif len(lst) == 1:
return lst[0]
elif all([entry is None for entry in lst]):
return None
return min([entr... | 5287286c843086c271f6fc709b275796cc68f314 | 675,056 |
def inherit_params(
new_params,
old_params):
"""Implements parameter inheritance.
new_params inherits from old_params.
This only does the top level params, matched by name
e.g., layer0/conv is treated as a param, and not layer0/conv/kernel
Args:
new_params: the params doing the inheriting
ol... | 0129494a09d34e54b48214c3a7619a89027c462a | 675,058 |
def tabescape(unescaped):
""" Escape a string using the specific Dovecot tabescape
See: https://github.com/dovecot/core/blob/master/src/lib/strescape.c
"""
return unescaped.replace(b"\x01", b"\x011")\
.replace(b"\x00", b"\x010")\
.replace(b"\t", b"\x01t")\
... | fb275d2d1e775e8038f32fcc03584ab07930c273 | 675,060 |
import re
def header_anchor(text, level):
"""
Return a sanitised anchor for a header.
"""
# Everything lowercase
sanitised_text = text.lower()
# Get only letters, numbers, dashes, spaces, and dots
sanitised_text = "".join(re.findall("[a-z0-9-\\. ]+", sanitised_text))
# Remove multip... | 13aa875b90e4e2cf9ce258e6af2bb3e3610c03db | 675,061 |
import re
def parse_show_dhcp_server(raw_result):
"""
Parse the 'show dhcp-server' command raw output.
:param str raw_result: vtysh raw result string.
:rtype: dict
:return: The parsed result of the show ntp trusted-keys command \
in a dictionary of the form:
::
{
... | b5e4cd8d39e08cad8c4d24fd36ff19c373c00825 | 675,066 |
def list_to_err(errs):
"""convert list of error strings to a single string
:param errs: list of string errors
:type errs: [str]
:returns: error message
:rtype: str
"""
return str.join('\n\n', errs) | a01e12d282ed3419f1c3cccf4dbfc70704c32efe | 675,067 |
def gcd(a, b):
"""
Greatest common divisor (greatest common factor)
Notes
---------
Euclidean algorithm:
a > b > r_1 > r_2 > ... > r_n
a = b*q + r
b = r_1*q_1 + r_2
...
r_n-1 = r_n*q_n
gcd(a,b) = gcd(b,r)
gcd(a,0) = a
"""
while b != 0:
a, b = b, a % ... | 62c2301013458fae6cb2827e087bb5266fb2fafa | 675,070 |
def group_device_names(devices, group_size):
"""Group device names into groups of group_size.
Args:
devices: list of strings naming devices.
group_size: int >= 1
Returns:
list of lists of devices, where each inner list is group_size long,
and each device appears at least once in an inner list.... | 9685bdae126a42738425334de98a33b2263fdf51 | 675,074 |
import time
def gmtime_for_datetime(dt):
"""
Pass in a datetime object, and get back time.gmtime
"""
return time.gmtime(time.mktime(time.strptime(dt.strftime("%Y-%m-%d %H:%M:%S"), "%Y-%m-%d %H:%M:%S"))) if dt is not None else None | 136992420c1c181441c70dc6747d15cadae0ff19 | 675,078 |
def is_palindrome(s):
"""
Check whether a string is a palindrome or not.
For example:
is_palindrome('aba') -> True
is_palindrome('bacia') -> False
is_palindrome('hutuh') -> True
Parameters
----------
s : str
String to check.
Returns
-------
bool
... | cb233ad7eccfa22d7e0ccdfb7e7041d57d9eee05 | 675,082 |
def suffix(n: int) -> str:
"""Return number's suffix
Example:
1 -> "st"
42 -> "nd"
333 -> "rd"
"""
return "th" if 11 <= n <= 13 else {1: "st", 2: "nd", 3: "rd"}.get(n % 10, "th") | ed8ccd0d6db63a04509f4ea14b5f85337e566ffb | 675,083 |
def switch_string_to_numeric(argument):
"""
Switch status string to numeric status (FLAT - POOR: 0, POOR - POOR TO FAIR = 1, FAIR TO GOOD - EPIC = 2)
"""
switcher = {
"FLAT": 0,
"VERY POOR": 0,
"POOR": 0,
"POOR TO FAIR":1,
"FAIR":1,
"FAIR TO GOOD":2,
... | 009a6e7e994fcc3cff0e4e3944b159a36bfc224e | 675,084 |
def get_printable_banner(input_str=None):
"""
Returns a string that when printed shows a banner with the given string in the center.
Args:
input_str: str. Any string of moderate length roughly less than 30 that you want placed inside a
pound/hashtag (#) banner.
Returns:... | d5f90bc7063107941387c4579f932f6f6636f31f | 675,087 |
def weight_combination(entropy, contrast, visibility, alpha1, alpha2, alpha3):
"""
Combining the entropy, the contrast and the visibility to build a weight layer
:param entropy: The local entropy of the image, a grayscale image
:param contrast: The local contrast of the image, a grayscale image
:pa... | 6d0ef8b58204ad90bed1f07097c23473463ed577 | 675,088 |
def mk_inclusion_filter(include=(), key=None):
"""
Creates a function to perform inclusion filtering (i.e. "filter-in if x is in include list")
:param include: a list-like of elements for an inclusion filter
:param key: None (default), a callable, or a hashable. If
* None, the filter will be det... | 4ba96f257cb2ba267b551f00bc573bee0969a839 | 675,089 |
def map256(vals):
""" Map dictionary key values to a 0-255 range.
Your input dictionary will have a smaller range than 0-256. For instance
you may have 49-91. The return dictionary will contain keys 0, 255 and some
values in between. The point is to normalize the span of the input acrouss
and 8-bit... | 359b9e4149a45f1f22b5c341f52bec108d8e0a77 | 675,091 |
def _calc_tstop(n_bins, bin_size, t_start):
"""
Calculates the stop point from given parameters.
Calculates the stop point `t_stop` from the three parameters
`n_bins`, `bin_size`, `t_start`.
Parameters
----------
n_bins : int
Number of bins
bin_size : pq.Quantity
Size o... | 995ea49417cfd4c2a036af86e7ac7463ccbf0ed2 | 675,092 |
import requests
def goa_calmgr(user_request, verbose=False):
"""
Query the GOA galmgr API
Parameters
user_request: Search request URL string, it should not contain 'calmgr'
\
Return
request_xml: Query result in XML format
"""
response = requests.get(
'https://arc... | 7d39de8256a7f25e432b8acfd9e5d879a2e268c7 | 675,093 |
def camel_case_to_under_score(x):
"""
CamelCase --> camel_case
:param x: (str)
The CamelCase string to
be converted to pep8.
:return: (str)
The formatted pep8 string.
lower case
upper case prefixed with underscore.
"""
string = ''
x = str(x)
for i,... | 84ee9f5ae79170a6db832282c4fcff6178a3b2cf | 675,094 |
def _datesplit(timestr):
"""
Split a unit string for time into its three components:
unit, string 'since' or 'as', and the remainder
"""
try:
(units, sincestring, remainder) = timestr.split(None, 2)
except ValueError:
raise ValueError(f'Incorrectly formatted date-time unit_strin... | 587293853afbf5cfee1103c1a48c087f59c9d3d8 | 675,095 |
import requests
import json
def move_hosts_to_new_group(platform, key, client, group):
"""
Move hosts defined by a filter to a new group, specified by group ID.
:param platform: URL of the RiskSense platform to be queried.
:type platform: str
:param key: API Key.
:type key: ... | 41eed8e50a7917e21f39d5f5d37aad6e271f0dcf | 675,096 |
def get_bollinger_bands(rm, rstd):
"""Return upper and lower Bollinger Bands."""
upper_band = rm + 2 * rstd
lower_band = rm - 2 * rstd
return upper_band, lower_band | 1c63ba90047cdfc902606f5978b38db00256d31c | 675,097 |
import calendar
def timestamp_from_datetime(dt):
"""
Returns a timestamp from datetime ``dt``.
Note that timestamps are always UTC. If ``dt`` is aware, the resulting
timestamp will correspond to the correct UTC time.
>>> timestamp_from_datetime(datetime.datetime(1970, 1, 1, 0, 20, 34, 500000))
... | 3a46b739e6b15b904b2bb13cb424ec6688aaa3ed | 675,099 |
def _parse_bond_line( line ):
"""Parse an AMBER frcmod BOND line and return relevant parameters in a dictionary. AMBER uses length and force constant, with the factor of two dropped. Here we multiply by the factor of two before returning. Units are angstroms and kilocalories per mole per square angstrom."""
tm... | 892637a597e80724e1285bc32646ed1a25978c61 | 675,101 |
def _find_code_cell_idx(nb, identifier):
"""
Find code cell index by provided ``identifier``.
Parameters
----------
nb : dict
Dictionary representation of the notebook to look for.
identifier : str
Unique string which target code cell should contain.
Returns
-------
... | 53e3ff071e0d5b9266ad3f6cfc44d26355553362 | 675,102 |
def _get_QActionGroup(self):
"""
Get checked state of QAction
"""
if self.checkedAction():
return self.actions().index(self.checkedAction())
return None | 0581a9176c6291714f81b5f6570fac1504153ddb | 675,103 |
import time
def seconds_per_run(op, sess, num_runs=50):
"""Number of seconds taken to execute 'op' once on average."""
for _ in range(2):
sess.run(op)
start_time = time.time()
for _ in range(num_runs):
sess.run(op)
end_time = time.time()
time_taken = (end_time - start_time) / num_runs
return t... | a16abfa914f2069ca9b91281d1999af7303946b3 | 675,104 |
def to_pandas(modin_obj):
"""Converts a Modin DataFrame/Series to a pandas DataFrame/Series.
Args:
obj {modin.DataFrame, modin.Series}: The Modin DataFrame/Series to convert.
Returns:
A new pandas DataFrame or Series.
"""
return modin_obj._to_pandas() | 740a84989f0c24e2671cce0a1029d457b447af74 | 675,107 |
import time
def get_range_query_args_from_duration(duration_secs=240):
"""Get start and end time for a duration of the last duration_secs."""
return (int(time.time()) - duration_secs, int(time.time())) | bb46469b1489bdf3759709269bdaee4ca45acdfd | 675,108 |
def search_non_residue(p):
"""Find a non residue of p between 2 and p
Args:
p: a prime number
Returns:
a integer that is not a quadratic residue of p
or -1 if no such number exists
"""
for z in range(2, p):
if pow(z, (p - 1) // 2, p) == p - 1:
... | d74762a11f7557089f58be6b41840aa60074c00d | 675,112 |
def unique_list(obj, key=None):
"""
Remove same element from list
:param obj: list
:param key: key function
:return: list
"""
checked = []
seen = set()
for e in obj:
_e = key(e) if key else e
if _e not in seen:
checked.append(e)
seen.add(_e)
... | 5391a34c91c38da461402eb9a5c7ade68bb9972e | 675,113 |
def get_function_input(function):
"""
Return a with the single input that is documented using
api.decoratos.input
"""
parameters = []
if hasattr(function, 'doc_input'):
(description, return_type, required) = function.doc_input
parameters.append({
'name': 'body',
... | 4f733818dc02752e8ed98d5b6c20466c048c9524 | 675,115 |
def same_orientation(lineA, lineB):
"""Return whether two paired end reads are of the same orientation."""
# SAM flags
reverse = 16
mate_reverse = 32
flagA = int(lineA.split()[11])
flagB = int(lineB.split()[11])
return ((flagA & reverse) == (flagB & reverse) and
(flagA & mate_... | edc352006163794acd5c41629305f7f8df2320a8 | 675,119 |
def latest_lines(lines, last):
"""Return lines after last and not empty
>>> latest_lines(['a', 'b', '', 'c', '', 'd'], 1)
6, ['c', 'd']
"""
last_lnum = len(lines)
latest = [l for n, l in enumerate(lines, 1) if n > last and l.strip()]
return last_lnum, latest | b0890ae4cb11face42efd01937165f14a7f2ba79 | 675,120 |
def gradient_t(prev_image, image):
"""Find gradient along time: time derivative using two images
Arguments:
prev_image {tensor} -- image at timestamp 1
image {tensor} -- image at timestamp 2
Returns:
tensor -- time derivative of image
"""
return prev_image-image | 509848cdc51bfd5783febca3722d7474c5b510b6 | 675,122 |
def _indentation(line):
"""Returns the length of the line's leading whitespace, treating tab stops
as being spaced 8 characters apart."""
line = line.expandtabs()
return len(line) - len(line.lstrip()) | 4f43618f642ad9b50a80901a31fadfd44a7dfce2 | 675,123 |
def sum_fuel_across_sectors(fuels):
"""Sum fuel across sectors of an enduse if multiple sectors.
Otherwise return unchanged `fuels`
Arguments
---------
fuels : dict or np.array
Fuels of an enduse either for sectors or already aggregated
Returns
-------
sum_array : np.array
... | 6a9dea9be2899bd9884106333c550e1ccf619883 | 675,125 |
import itertools
def element_ancestry(element):
"""Iterates element plus element.parents."""
return itertools.chain((element,), element.parents) | 523fb5b4749ba33e2ddee9bad23c480ffcf5f66b | 675,126 |
def dasherize(word: str) -> str:
"""Replace underscores with dashes in the string.
Example::
>>> dasherize("foo_bar")
"foo-bar"
Args:
word (str): input word
Returns:
input word with underscores replaced by dashes
"""
return word.replace("_", "-") | 4a255f0d68106fd8a169e5a2a3ad63b86ba069cf | 675,127 |
def log2floor(n):
"""
Returns the exact value of floor(log2(n)).
No floating point calculations are used.
Requires positive integer type.
"""
assert n > 0
return n.bit_length() - 1 | d29fb7e60bfc233aa6dbad7ffb8a1fe194460645 | 675,128 |
def standardize(X):
""" Standardize data set by mean and standard deviation """
mu = X.mean(axis=0, keepdims=True)
s = X.std(axis=0, keepdims=True)
return (X-mu)/s | 1857d60191415c91bacec8d066d0d70bede1129a | 675,131 |
def detection_center(detection):
"""Computes the center x, y coordinates of the object"""
#print(detection)
bbox = detection['bbox']
center_x = (bbox[0] + bbox[2]) / 2.0 - 0.5
center_y = (bbox[1] + bbox[3]) / 2.0 - 0.5
return (center_x, center_y) | c3a3465abea09ff9952fccbdec55563c26989d39 | 675,132 |
import requests
def get_countries_names() -> list:
"""
Function for getting list of all countries names procived by public
COVID-19 api on site "https://api.covid19api.com"
Returns
-------
List with all countries names.
Example
-------
>>> countries_names = get_countries_names()
... | ce15682922799a8ece5590ce51184a92d628788f | 675,134 |
def overlaps(pattern_a, pattern_b):
"""Returns a boolean indicating if two patterns are overlapped.
Args:
pattern_a: SimilarPattern or TimeSpan.
pattern_b: SimilarPattern or TimeSpan.
Returns:
boolean indicating if the patterns are overlapped.
"""
start_a = pattern_a.start_time
start_b = patter... | ab0e00ef8503107b72f1e819eca91f5ce5c87d3c | 675,136 |
def distance_residues(r1, r2):
"""Return the distance between two residues."""
center_1 = r1.get_mass_center()
center_2 = r2.get_mass_center()
return (sum(map(lambda t: (t[0] - t[1])**2, zip(center_1, center_2))))**0.5 | d927d6ab0575f1c11cf24b7d2ddfe498f1532afd | 675,139 |
def max_weighted_independent_set_in_path_graph(weights):
""" Computes the independent set with maximum total weight for a path graph.
A path graph has all vertices are connected in a single path, without cycles.
An independent set of vertices is a subset of the graph vertices such that
no two vertices ... | 3be9d7dd54b939260f37ff2c97c18f18df0644b5 | 675,141 |
def select_with_processing(selector, cluster_sim):
"""A selection wrapper that uses the given operator to select from
the union of the population and the currently processing individuals.
"""
def select(population):
return selector(population + cluster_sim.processing)
return select | 76cf35e02dfe391ff3e2b6f552a36b87d2ce5cf9 | 675,143 |
def get_si(simpos):
"""
Get SI corresponding to the given SIM position.
"""
if ((simpos >= 82109) and (simpos <= 104839)):
si = 'ACIS-I'
elif ((simpos >= 70736) and (simpos <= 82108)):
si = 'ACIS-S'
elif ((simpos >= -86147) and (simpos <= -20000)):
si = ' HRC-I'
elif ... | fadf3d641c30cec35e73b100cd78a55d5808cbd0 | 675,144 |
import json
def get_parameters(template):
"""
Builds a dict of parameters from a workflow manifest.
Parameters
----------
template : dict
Returns
-------
dict
Parameters.
"""
parameters = {}
prefix = "PARAMETER_"
for var in template["container"]["env"]:
... | 2f31f2729a9127606df5f7847827dac746addcce | 675,145 |
def create_index_of_A_matrix(db):
"""
Create a dictionary with row/column indices of the A matrix as key and a tuple (activity name, reference product,
unit, location) as value.
:return: a dictionary to map indices to activities
:rtype: dict
"""
return {
(
db[i]["name"],
... | 2abb7f67f358127f659588599a9f02f691614422 | 675,147 |
import io
def decode_int8(fh: io.BytesIO) -> int:
"""
Read a single byte as an unsigned integer.
This data type isn't given a special name like "ITF-8" or "int32" in the spec, and is only used twice in the
file descriptor as a special case, and as a convenience to construct other data types, like ITF... | b20de27afb0af997449f7e178bba0d91322e234c | 675,150 |
def full_qualified(pkg, symbols):
"""
パッケージ名と、文字列表記されたシンボルのリスト(このEus_pkgクラスと対応するEuslispのパッケージ以外のシンボルが含まれていても良い)を受け取る。
対応するパッケージ内のシンボルのみを取り出し、それぞれパッケージ接頭語(大文字)をつけ、リストにして返す。
>>> full_qualified("TEST", ['var1', 'OTHER-PACK::var2', 'LISP::var3'])
['TEST::var1', 'LISP::var3']
Args:
pkg (str... | 0599e6efa4ddd12a3a11a976e3de731623fe550c | 675,154 |
import pickle
def LoadModel(filname):
"""
Load a model using pickle
Parameters
----------
filname : str
model file name.
Returns
-------
model : dict
Output of BuildModel methode, a dict with:
-"model" an sklearn trained random forest classifier.
... | ccf500e02c912a7fc9db15924524ce21ca1e651f | 675,155 |
import ctypes
def _malloc_char_array(n):
"""
Return a pointer to allocated UTF8 (C char) array of length `n'.
"""
t = ctypes.c_char * n
return t() | a67c6101e243392388fcba723dd37e4fe00cc0a1 | 675,156 |
def configure_camera_url(camera_address: str,
camera_username: str = 'admin',
camera_password: str = 'iamironman',
camera_port: int = 554,
camera_stream_address: str = 'H.264',
camera_protocol: s... | ef06089e84b00c070e4fe89b0bfc34afd21e3f40 | 675,158 |
def filer_elements(elements, element_filter):
"""Filter elements.
Ex.: If filtered on elements [' '], ['a', ' ', 'c']
becomes ['a', 'c']
"""
return [element for element in elements if element not in element_filter] | 205c9bae6bb28f96d67bc6a02c5bd1ed5ed6c534 | 675,159 |
def any_true_p (seq, pred) :
"""Returns first element of `seq` for which `pred` returns True,
otherwise returns False.
"""
for e in seq :
if pred (e) :
return e
else :
return False | 24c374cfbbef49be7a76ba471b61e4122f0619e3 | 675,161 |
def _resize(im, width, height):
"""
Resizes the image to fit within the specified height and width; aspect ratio
is preserved. Images always preserve animation and might even result in a
better-optimized animated gif.
"""
# resize only if we need to; return None if we don't
if im.size.width ... | 3729e1a75b1187846818489ded4a7a2b47fb67f5 | 675,162 |
def valid(x, y, n, m):
"""Check if the coordinates are in bounds.
:param x:
:param y:
:param n:
:param m:
:return:
"""
return 0 <= x < n and 0 <= y < m | 407ed497ea97f8a133cdffe0756d322853841ed3 | 675,169 |
def _is_control_defined(node, point_id):
""" Checks if control should be created on specified point id
Args:
name (str): Name of a control
point_id (int): Skeleton point number
Returns:
(bool)
"""
node_pt = node.geometry().iterPoints()[point_id]
... | 77aced682fbe6c3f414c9781cee2d49e9ef54a14 | 675,172 |
def levelFromHtmid(htmid):
"""
Find the level of a trixel from its htmid. The level
indicates how refined the triangular mesh is.
There are 8*4**(d-1) triangles in a mesh of level=d
(equation 2.5 of
Szalay A. et al. (2007)
"Indexing the Sphere with the Hierarchical Triangular Mesh"
ar... | 86a2ca1c7176b06c38ff1acd028349690fb34aee | 675,177 |
import pprint
def fargs(*args, **kwargs):
"""
Format `*args` and `**kwargs` into one string resembling the original call.
>>> fargs(1, [2], x=3.0, y='four')
"1, [2], x=3.0, y='four'"
.. note:: The items of `**kwargs` are sorted by their key.
"""
items = []
for arg in args:
i... | 034ebee17ada81afee7973e53d913385a0e5f799 | 675,180 |
from typing import Tuple
from pathlib import Path
def operating_system() -> Tuple[str, str]:
"""Return what operating system we are running.
Returns:
A tuple with two strings, the first with the operating system and the
second is the version. Examples: ``('ubuntu', '20.04')``,
``('cen... | f16081081f3616e2bc1d0592d49487dcb07b9ef0 | 675,183 |
def get_max_key(d):
"""Return the key from the dict with the max value."""
return max(d, key=d.get) | 966f5b1be593a9266d0e3239c37d5ef83cec17fc | 675,186 |
def generate_sample(id, name, controlled_metadata, user_metadata, source_meta):
"""
Create a sample record
"""
sample = {
'node_tree': [{
"id": id,
"type": "BioReplicate",
"meta_controlled": controlled_metadata,
"meta_user": user_metadata,
... | 5657d367642f8a3dd5b0b6a921c1fe8d9dc30672 | 675,187 |
def readline_comment(file, symbol='#'):
"""Reads line from a file object, but ignores everything after the
comment symbol (by default '#')"""
line = file.readline()
if not line:
return ''
result = line.partition(symbol)[0]
return result if result else readline_comment(file) | bd964dfb2c9bc877e9c8ed3c9f280131468a7a10 | 675,189 |
import re
def collect_subroutine_calls(lines,ifbranch_lines):
"""
Collect a dictionary of all subroutine call instances. In the source code
on entry the "subroutine call" is given in the form of a function call, e.g.
t5 = nwxc_c_Mpbe(rhoa,0.0d+0,gammaaa,0.0d+0,0.0d+0)
we need to know the "nwxc_c_Mpbe(r... | 1c11cd4ae028323f6439dbb86693c3999ddc93cb | 675,193 |
import xxhash
def get_hash(fname: str) -> str:
"""
Get xxHash3 of a file
Args:
fname (str): Path to file
Returns:
str: xxHash3 of file
"""
xxh = xxhash.xxh3_64()
with open(fname, "rb") as f:
for chunk in iter(lambda: f.read(4096), b""):
xxh.update(chun... | 677be15e6082d84aa3cb0408fe231ebe27faefa6 | 675,195 |
def split_dataset_sizes(stream_list, split_sizes):
"""Splits with different sizes
Args:
stream_list (list): list of stream path
split_sizes (list): batch size per worker
"""
out = []
start = 0
total = sum(split_sizes)
for split_size in split_sizes[:-1]:
num = int(spl... | cdfd37f15c852881f9c38c860d8856e1d2a7de9c | 675,204 |
def all_nums(table):
"""
Returns True if table contains only numbers (False
otherwise)
Example: all_nums([[1,2],[3,4]]) is True
all_nums([[1,2],[3,'a']]) is False
Parameter table: The candidate table to modify
Preconditions: table is a rectangular 2d List
"""
result = True... | 8a0f1358d3ec729b04f4171aa171cf141acc702d | 675,206 |
def _itemNames(comb):
""" Item names from result of knapsack01
Args:
comb tuple of tuples result of knapsack01
Returns:
tuple sorted item ids
"""
return tuple(sorted(item for item,_,_ in comb)) | fa865f2b612e63debd4a1392b7a318ccf0b69f31 | 675,208 |
def split_def_command(command):
"""Split command in parts: variable name, specific command, definition.
Return None if command is invalid.
"""
# procedo per casi
# il che significa che dopo un '@' non posso usare un ':'
# perché verrebbe intercettato per primo!
valid_commands = [":", ... | 0bb00aae0c66f7b183bb49e0a87bf6a111891135 | 675,209 |
def get_ingredients(drink_dict):
""" Create a list of ingredients and measures
Form data is passed as a dictionary. The functions iterates through
the key/value pairs and appends the ingredients and measures to its
own list called ingredients.
Args:
drink_dict : The dictionary containing t... | 5ec86b71ab8bf0d9b1d6291d7d14cbfbeff2d867 | 675,210 |
def linear (x, parameters):
"""Sigmoid function
POI = a + (b * x )
Parameters
----------
x: float or array of floats
variable
parameters: dict
dictionary containing 'linear_a', and 'linear_b'
Returns
-------
float or array of floats:
function re... | 3e2f42cdb5fa1b722c7f3fd15294e4488b99649d | 675,211 |
def rax_clb_node_to_dict(obj):
"""Function to convert a CLB Node object to a dict"""
if not obj:
return {}
node = obj.to_dict()
node['id'] = obj.id
node['weight'] = obj.weight
return node | 14526744ef608f06534011d1dcdd5db62ac8b702 | 675,212 |
from typing import List
import random
def unique_floats_sum_to_one(num: int) -> List[float]:
"""return a list of unique floats summing up to 1"""
random_ints = random.sample(range(1, 100), k=num)
total = sum(random_ints)
return [(n / total) for n in random_ints] | e84e5e081571aa2a385019b522fb05d2775964d6 | 675,215 |
def get_timeouts(builder_cfg):
"""Some builders require longer than the default timeouts.
Returns tuple of (expiration, hard_timeout). If those values are None then
default timeouts should be used.
"""
expiration = None
hard_timeout = None
if 'Valgrind' in builder_cfg.get('extra_config', ''):
expirat... | 4e519235a8b205621b8c99964e6fc7c4f4ab0175 | 675,216 |
import torch
def _skip(x, mask):
"""
Getting sliced (dim=0) tensor by mask. Supporting tensor and list/dict of tensors.
"""
if isinstance(x, int):
return x
if x is None:
return None
if isinstance(x, torch.Tensor):
if x.size(0) == mask.size(0):
return x[mas... | 320e96b24a703e5e5c976eda643c3f39efd04b1b | 675,217 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.