content
stringlengths 39
9.28k
| sha1
stringlengths 40
40
| id
int64 8
710k
|
---|---|---|
import re
def MatchNameComponent(key, name_list, case_sensitive=True):
"""Try to match a name against a list.
This function will try to match a name like test1 against a list
like C{['test1.example.com', 'test2.example.com', ...]}. Against
this list, I{'test1'} as well as I{'test1.example'} will match, but
not I{'test1.ex'}. A multiple match will be considered as no match
at all (e.g. I{'test1'} against C{['test1.example.com',
'test1.example.org']}), except when the key fully matches an entry
(e.g. I{'test1'} against C{['test1', 'test1.example.com']}).
@type key: str
@param key: the name to be searched
@type name_list: list
@param name_list: the list of strings against which to search the key
@type case_sensitive: boolean
@param case_sensitive: whether to provide a case-sensitive match
@rtype: None or str
@return: None if there is no match I{or} if there are multiple matches,
otherwise the element from the list which matches
"""
if key in name_list:
return key
re_flags = 0
if not case_sensitive:
re_flags |= re.IGNORECASE
key = key.upper()
name_re = re.compile(r"^%s(\..*)?$" % re.escape(key), re_flags)
names_filtered = []
string_matches = []
for name in name_list:
if name_re.match(name) is not None:
names_filtered.append(name)
if not case_sensitive and key == name.upper():
string_matches.append(name)
if len(string_matches) == 1:
return string_matches[0]
if len(names_filtered) == 1:
return names_filtered[0]
return None
|
ad522feba9cabb3407e3b8e1e8c221f3e9800e16
| 5,342 |
def sign(num):
"""Returns the sign of num as an integer;
if ```num < 0```, returns ```-1```, ```num = 0```, returns ```0```, ```num > 0```, returns ```1```."""
return int(num > 0) - int(num < 0)
|
8f8cca093060f5c7ea3f62bc43577077136622b2
| 428,838 |
def kd(Cs, Cl):
"""
kd calculates a partition coefficient for a given set of measurements. For
igneous petrology, this is commonly the concentration of a trace element in
the mineral divided by the concentration of the same trace element in the
melt (e.g. Rollinson 1993 Eq. 4.3)
Inputs:
Cs = concnetration in the mineral
Cl = concentration in the melt
Returns:
kd = partition coefficient for the given input parameters
"""
kd = Cs / Cl
return kd
|
9debcdf367007192ce2bc2ec2b40cf5a6ee2b3f1
| 358,849 |
def _is_tachychardic(age: int, heart_rate: int):
"""
Determines if user is tacahychardic based on age and heart rate. Based on: https://en.wikipedia.org/wiki/Tachycardia
Args:
age (int): Age of the user.
heart_rate (int): Heartrate of the user.
Returns:
bool: Whether or not the user is tachychardic .
"""
if 1 <= age <= 2 and heart_rate > 151:
return True
elif 3 <= age <= 4 and heart_rate > 137:
return True
elif 5 <= age <= 7 and heart_rate > 133:
return True
elif 8 <= age <= 11 and heart_rate > 130:
return True
elif 12 <= age <= 15 and heart_rate > 119:
return True
elif age > 15 and heart_rate > 100:
return True
return False
|
c8c0a96b72d7dbcebc0ab8ea7394af7b5ca635e3
| 259,006 |
import csv
def load_review_data(path_data):
"""
Returns a list of dict with keys:
* sentiment: +1 or -1 if the review was positive or negative, respectively
* text: the text of the review
"""
basic_fields = {'sentiment', 'text'}
data = []
with open(path_data) as f_data:
for datum in csv.DictReader(f_data, delimiter='\t'):
for field in list(datum.keys()):
if field not in basic_fields:
del datum[field]
if datum['sentiment']:
datum['sentiment'] = int(datum['sentiment'])
data.append(datum)
return data
|
e19e51a37007ad308893c190a3629beef9e57f90
| 34,011 |
def _compute_mod(score: int) -> int:
"""Compute a mod given an ability score
Args:
score (int): Ability score
Returns:
(int) Modifier for that score
"""
return score // 2 - 5
|
c427d5ac3a438bfb210066ebe759fb1dac1a677b
| 367,386 |
def _DefaultAlternative(value, default):
"""Returns value or, if evaluating to False, a default value.
Returns the given value, unless it evaluates to False. In the latter case the
default value is returned.
@param value: Value to return if it doesn't evaluate to False
@param default: Default value
@return: Given value or the default
"""
if value:
return value
return default
|
63bfffb71545ee845c7f175bb924d6d45c4a6e0e
| 409,311 |
import shutil
def check_valid_shell_command(cmd):
"""
Determine if a shell command returns a 0 error code.
Args:
cmd (string or list): Shell command. String of one command or list with arguments.
Returns:
bool
"""
if isinstance(cmd, list):
return shutil.which(cmd[0])
else:
return shutil.which(cmd)
|
97d2ac7a24d15217481454fdd0a2c2b7ef11fa70
| 35,373 |
def dbamp(db):
"""Convert db to amplitude"""
return 10 ** (db / 20.0)
|
b66d96cbab2137c0b2f0efeb8bb36ea1a8bd75dc
| 245,166 |
import tempfile
def fill_directory_with_temp_files(directory, num_files, delete=False):
"""Fill up a directory with temporary files, that by default do not delete
themselves when they go out of scope.
Args:
directory (str): Path to the directory to fill.
num_files (int): Amount of files to put in the directory.
delete (boolean): Whether the files should be deleted when they go out of scope.
Returns:
List[str]: Paths to the temporary files.
"""
return [tempfile.NamedTemporaryFile(dir=directory, delete=delete).name
for _ in range(num_files)]
|
135307365194e8d88c764c1b65f8d4c2d6572ddf
| 499,728 |
def echo(request, string):
"""Returns whatever you give it."""
return string
|
25cdf4d43e8cdcb08c4e79daf8cd92c92263241e
| 462,515 |
from typing import Tuple
import random
def randRGB() -> Tuple[int, int, int]:
"""Returns a tuple containing an random RGB value"""
r = random.randint(0, 255)
g = random.randint(0, 255)
b = random.randint(0, 255)
return (r, g, b)
|
9a044974cbb704c3a932e4c4de07aede6ed0cef8
| 432,449 |
def calculate_catalog_coverage(y_test, y_train, y_predicted):
"""
Calculates the percentage of user-item pairs that were predicted by the algorithm.
The full data is passed in as y_test and y_train to determine the total number of potential user-item pairs
Then the predicted data is passed in to determine how many user-item pairs were predicted.
It is very important to NOT pass in the sorted and cut prediction RDD and that the algorithm trys to predict all pairs
The use the function 'cartesian' as shown in line 25 of content_based.py is helpful in that regard
Args:
y_test: the data used to test the RecSys algorithm in the format of an RDD of [ (userId, itemId, actualRating) ]
y_train: the data used to train the RecSys algorithm in the format of an RDD of [ (userId, itemId, actualRating) ]
y_predicted: predicted ratings in the format of a RDD of [ (userId, itemId, predictedRating) ]. It is important that this is not the sorted and cut prediction RDD
Returns:
catalog_coverage: value representing the percentage of user-item pairs that were able to be predicted
"""
y_full_data = y_test.union(y_train)
prediction_count = y_predicted.count()
#obtain the number of potential users and items from the actual array as the algorithms cannot predict something that was not trained
num_users = y_full_data.map(lambda row: row[0]).distinct().count()
num_items = y_full_data.map(lambda row: row[1]).distinct().count()
potential_predict = num_users*num_items
catalog_coverage = prediction_count/float(potential_predict)*100
return catalog_coverage
|
8ccab81e9590d0ec5702a18d96ce95656ce9eb74
| 547,683 |
def _default_with_off_flag(current, default, off_flag):
"""Helper method for merging command line args and noxfile config.
Returns False if off_flag is set, otherwise, returns the default value if
set, otherwise, returns the current value.
"""
return (default or current) and not off_flag
|
880d826d1c487005102fbacb9d4dcc94fb14f4db
| 618,507 |
def standardise_efficiency(efficiency):
"""Standardise efficiency types; one of the five categories:
poor, very poor, average, good, very good
Parameters
----------
efficiency : str
Raw efficiency type.
Return
----------
standardised efficiency : str
Standardised efficiency type."""
# Handle NaN
if isinstance(efficiency, float):
return "unknown"
efficiency = efficiency.lower().strip()
efficiency = efficiency.strip('"')
efficiency = efficiency.strip()
efficiency = efficiency.strip("|")
efficiency = efficiency.strip()
efficiency_mapping = {
"poor |": "Poor",
"very poor |": "Very Poor",
"average |": "Average",
"good |": "Good",
"very good |": "Very Good",
"poor": "Poor",
"very poor": "Very Poor",
"average": "Average",
"good": "Good",
"very good": "Very Good",
"n/a": "unknown",
"n/a |": "unknown",
"n/a": "unknown",
"n/a | n/a": "unknown",
"n/a | n/a | n/a": "unknown",
"n/a | n/a | n/a | n/a": "unknown",
"no data!": "unknown",
"unknown": "unknown",
}
return efficiency_mapping[efficiency]
|
07a712fc3f941f1b82a834940e05e4e4164bdf61
| 325,033 |
import json
def save_run_settings(run_settings):
"""
Takes a run_settings dictionary and saves it back where it was loaded from,
using the path stored in its own dictionary. Return None.
"""
# don't act on original dictionary
run_settings = run_settings.copy()
# store the raw log loss results back in the run settings json
with open(run_settings['run_settings_path'], 'w') as f:
# have to remove the settings structure, can't serialise it
del run_settings['settings']
json.dump(run_settings, f, separators=(',',':'), indent=4,
sort_keys=True)
return None
|
420f10bf961a89aed6426fbefca70097918236d0
| 283,615 |
import re
import string
def clean_text_round1(text):
"""Make text lowercase, remove text in square brackets, remove punctuation and remove words containing numbers."""
text = text.lower()
text = re.sub("\[.*?\]", "", text)
text = re.sub("[%s]" % re.escape(string.punctuation), "", text)
text = re.sub("\w*\d\w*", "", text)
return text
|
4b543a2036f5e48435100caec069f7d5b5541d51
| 164,696 |
from typing import Callable
import inspect
def local_kwargs(kwargs: dict, f: Callable) -> dict:
"""Return the kwargs from dict that are inputs to function f."""
s = inspect.signature(f)
p = s.parameters
if next(reversed(p.values())).kind == inspect.Parameter.VAR_KEYWORD:
return kwargs
if len(kwargs) < len(p):
return {k: v for k, v in kwargs.items() if k in p}
return {k: kwargs[k] for k in p.keys() if k in kwargs}
|
ba1f9753df754fe09a3b64e73f907ce8fed94e64
| 166,513 |
def int_array_to_bit_string(int_array: list) -> int:
"""
Integer array such as [1, 0, 0, 0] to integer (8).
Returns 0 if non-binary values found in the list.
Parameters
----------
int_array : list of int
Integer array.
Returns
-------
value : int
"""
try:
return int(''.join(str(int(c)) for c in int_array), 2)
except ValueError:
return 0
|
272f53d9376b10e3009ca48a09c78226d527ae04
| 242,672 |
def copyStream(src, dest, length = None, bufferSize = 16384):
"""Copy from one stream to another, up to a specified length"""
amtread = 0
while amtread != length:
if length is None:
bsize = bufferSize
else:
bsize = min(bufferSize, length - amtread)
buf = src.read(bsize)
if not buf:
break
dest.write(buf)
amtread += len(buf)
return amtread
|
b7ed47100cb226532f6acafc6598d5f5e1fdbe3f
| 124,460 |
def graph_list_to_features(graphs):
"""Get a TFRecord feature dictionary from a list of graphs.
The features from each graph is prepended with a prefix and all
added to the final dictionary at the same level.
Parameters
----------
graphs : [Graph]
Returns
-------
features : dict (str -> Feature)
"""
features = {}
for i in range(len(graphs)):
prefix = 'g{}_'.format(i)
graph_feats = graphs[i].to_features()
updated = {(prefix) + k : v for (k, v) in graph_feats.items()}
features.update(updated)
return features
|
97728caa1e5aedbb9e404b39fb6174361dd2b0cd
| 667,805 |
def get_function_name(fcn):
"""Returns the fully-qualified function name for the given function.
Args:
fcn: a function
Returns:
the fully-qualified function name string, such as
"eta.core.utils.function_name"
"""
return fcn.__module__ + "." + fcn.__name__
|
ae186415225bd5420de7f7b3aef98480d30d59f8
| 708,012 |
import json
def remove_dojo_report(path):
"""
Remove the `DOJO_REPORT` section from the pseudopotential file.
Write new file. Return dict with old_report, None if error.
"""
# Read lines from file and insert jstring between the tags.
with open(path, "rt") as fh:
lines = fh.readlines()
try:
start = lines.index("<DOJO_REPORT>\n")
except ValueError:
start = -1
if start == -1: return None
stop = lines.index("</DOJO_REPORT>\n")
report = json.loads("\n".join(lines[start+1:stop]))
del lines[start:stop+1]
# Write new file.
with open(path, "w") as fh:
fh.writelines(lines)
return report
|
f1b7cd76493e90f7334ca6f3d47625c5b3389dfa
| 150,146 |
def merge(b, a):
"""
Merges two dicts. Precedence is given to the second dict. The first dict will be overwritten.
"""
for key in a:
if key in b and isinstance(a[key], dict) and isinstance(b[key], dict):
b[key] = merge(b[key], a[key])
elif a[key] is not None:
b[key] = a[key]
return b
|
18b8c3da7928809ede3b07033fd9a2516d31879f
| 477,989 |
def _defaultHandler(packetNum, packet, glob):
"""default packet handler
Args:
packetNum (int): packet number
packet (obj): packet
glob (dict): global dict
Returns:
dict: glob
"""
print(packetNum, packet)
return glob
|
d4e92ce5d7b2943a6199db220f6fe80807219849
| 304,827 |
import random
def _generate_fwf_row(characterSet, offsets):
"""Generates a random fwf line
Args:
characterSet (str): valid to pick characters from
offsets (list[int]): lengths of each field
Returns:
line(str): line formatted in fwf
"""
return [
"".join(random.choices(characterSet, k=random.randint(0, off))) # nosec
for off in offsets
]
|
ac4c778335c173c0802ec8a225f7edc6465bd776
| 613,740 |
from typing import Callable
from typing import List
import inspect
def _get_fn_argnames(fn: Callable) -> List[str]:
"""Get argument names of a function.
:param fn: get argument names for this function.
:returns: list of argument names.
"""
arg_spec_args = inspect.getfullargspec(fn).args
if inspect.ismethod(fn) and arg_spec_args[0] == "self":
# don't include "self" argument
arg_spec_args = arg_spec_args[1:]
return arg_spec_args
|
a464f1fb21a454f4e6a854a64810ba48cdb6f9f8
| 24,381 |
def composeVideoMaskName(maskprefix, starttime, suffix):
"""
:param maskprefix:
:param starttime:
:param suffix:
:return: A mask file name using the provided components
"""
if maskprefix.endswith('_mask_' + str(starttime)):
return maskprefix + '.' + suffix
return maskprefix + '_mask_' + str(starttime) + '.' + suffix
|
0fe45da135f79086fa52ca2fdca55a6cc51b9a3d
| 664,845 |
def neighbor_idcs(x, y):
"""
Input x,y coordinates and return all the neighbor indices.
"""
xidcs = [x-1, x, x+1, x-1, x+1, x-1, x, x+1]
yidcs = [y-1, y-1, y-1, y, y, y+1, y+1, y+1]
return xidcs, yidcs
|
59f479014dddcb1d1de7558f870836bdfed121be
| 310,901 |
def loadWords(filename):
"""
Returns a list of valid words. Words are strings of lowercase letters.
Depending on the size of the word list, this function may
take a while to finish.
"""
print("Loading word list from file...")
inFile = open(filename, 'r')
line = inFile.readline()
wordlist = line.split()
print(" ", len(wordlist), "words loaded.")
return wordlist
|
655af114f7a6cafda830c563e351c425d11ecbee
| 445,332 |
def proportional(raw_value, factor, unit=None):
"""Applies a proportional factor."""
return (float(raw_value) * factor, unit)
|
0cdc5c14348f0d99e1de58d6445df69f8a8a39e8
| 584,731 |
def to_singular(name):
"""Convert the name to singular if it is plural
This just trims a trailing 's', if found.
"""
return name[:-1] if name.endswith("s") else name
|
5ae3c75b8bd43cb6c4e6eaa775d4a58712fd0121
| 352,526 |
def sampling(array, interval=1, offset=0):
"""
Down-sample the input signal with certain interval.
input:
array: numpy array. The input temporal signal. 1d or with multiple dimensions
interval: int. The interval to sample EEG signal. Default is 1, which means NO down-sampling is applied
offset: int. Sampling starts from "offset-th" data point
return:
sampled_array: numpy array. Down-sampled signal
"""
if len(array.shape) < 2:
return array[offset::interval]
else:
return array[:, :, offset::interval]
|
440df08b95619f446ee498022d509740e2d75637
| 689,278 |
import itertools
def champernowne_digit(n):
"""Get Champernowne constant's n-th digit (starting from 0)."""
# Implementation determines 3 pieces of info in that order:
# - the length of the number the digit belongs to : len_num
# - the index of the digit in the number : digit_index
# - the number the digit belongs to : num
base = 10
prev_pow = 1
for len_num in itertools.count(1):
nb_dig_block = len_num * (base - 1) * prev_pow
if nb_dig_block < n:
n -= nb_dig_block
prev_pow *= base
else:
num_index, digit_index = divmod(n, len_num)
num = prev_pow + num_index
return int(str(num)[digit_index])
|
021298a940de81729289c0bf0f9acb3ddd8d298a
| 226,448 |
import configparser
def submit_kaggle(notebook_name, submission_path, message):
""" Generate submission string that can be used to submit an entry for scoring by
kaggle on test data. Use python magic commands to run
Args:
notebook_name (str): Name of jupyter notebook for kaggle entry
submission_path (str): Path to run length encoded csv data
message (str): an optional message about data used for submission
Returns:
submit_string (str): correctly formatted string for kaggle submission
"""
config = configparser.ConfigParser()
config.read("/home/ubuntu/.kaggle-cli/config")
comp = config.get('user', 'competition')
uname = config.get('user', 'username')
password = config.get('user', 'password')
submit_string = 'kg submit {} -u \"{}\" -p \"{}\" -c \"{}\" -m \"{}: {}\"' \
.format(submission_path, uname, password, comp, notebook_name, message)
return submit_string
|
5661e291ac75776d8a5fcbba5154655a0452d5ed
| 563,982 |
def extent_to_wkt(extent):
"""Create a Polygon WKT geometry from extent: (xmin, ymin, xmax, ymax)"""
wkt = "POLYGON(("
for dx, dy in ((0, 0), (0, 1), (1, 1), (1, 0)):
wkt += "{0} {1},".format(str(extent[2 * dx]), str(extent[2 * dy + 1]))
wkt += "{0} {1}))".format(str(extent[0]), str(extent[1]))
return wkt
|
dfb40c85fade27f33861666647be1afa42dc75d8
| 515,391 |
from typing import Sequence
def is_overlapping_lane_seq(lane_seq1: Sequence[int], lane_seq2: Sequence[int]) -> bool:
"""
Check if the 2 lane sequences are overlapping.
Overlapping is defined as::
s1------s2-----------------e1--------e2
Here lane2 starts somewhere on lane 1 and ends after it, OR::
s1------s2-----------------e2--------e1
Here lane2 starts somewhere on lane 1 and ends before it
Args:
lane_seq1: list of lane ids
lane_seq2: list of lane ids
Returns:
bool, True if the lane sequences overlap
"""
if lane_seq2[0] in lane_seq1[1:] and lane_seq1[-1] in lane_seq2[:-1]:
return True
elif set(lane_seq2) <= set(lane_seq1):
return True
return False
|
155e3a962f3f457a868585798e1ab8d92c9f115f
| 701,826 |
def isacn(obj):
"""isacn(string or int) -> True|False
Validate an ACN (Australian Company Number).
http://www.asic.gov.au/asic/asic.nsf/byheadline/Australian+Company+Number+(ACN)+Check+Digit
Accepts an int, or a string of digits including any leading zeroes.
Digits may be optionally separated with spaces. Any other input raises
TypeError or ValueError.
Return True if the argument is a valid ACN, otherwise False.
>>> isacn('004 085 616')
True
>>> isacn('005 085 616')
False
"""
if isinstance(obj, int):
if not 0 <= obj < 10**9:
raise ValueError('int out of range for an ACN')
obj = '%09d' % obj
assert len(obj) == 9
if not isinstance(obj, str):
raise TypeError('expected a str or int but got %s' % type(obj))
obj = obj.replace(' ', '')
if len(obj) != 9:
raise ValueError('ACN must have exactly 9 digits')
if not obj.isdigit():
raise ValueError('non-digit found in ACN')
digits = [int(c) for c in obj]
weights = [8, 7, 6, 5, 4, 3, 2, 1]
assert len(digits) == 9 and len(weights) == 8
chksum = 10 - sum(d*w for d,w in zip(digits, weights)) % 10
if chksum == 10:
chksum = 0
return chksum == digits[-1]
|
cbabe4a84113cdc02f85922b0012e97c22b99e9e
| 90,464 |
def create_curl_command(authorization, payload, command, url, curl_options, show_api_key,
content_type='application/json'):
"""
cURL command generator
:param authorization: Authorization part e.g Bearer API key
:param payload: Payload data
:param command: GET, PUT, etc
:param url: API url
:param curl_options: E.g. '-v' for verbose
:param show_api_key: Showing actual api-key or not
:param content_type: Content type
:return: cURL command string
"""
if show_api_key is False:
authorization = 'Bearer API_KEY'
headers = '-H \'Authorization: {}\' -H \'Content-type: {}\''.format(authorization, content_type)
if payload is not None:
cc = 'curl {} -d \'{}\' -X {} \'{}\' {}'.format(headers, payload, command.upper(), url, curl_options)
else:
cc = 'curl {} -X {} \'{}\' {}'.format(headers, command.upper(), url, curl_options)
return cc
|
422d11c3837844111a1ef10a537ef4a52d0a988d
| 659,785 |
def area(circle):
"""Get area of a circle"""
return circle.get('radius') ** 2 * 3.14159
|
5d64b5fcfe8d82bc994e2e12aeab90c276943fa5
| 624,780 |
def get_intersection_area(box1, box2):
"""
compute intersection area of box1 and box2 (both are 4 dim box coordinates in [x1, y1, x2, y2] format)
"""
xmin1, ymin1, xmax1, ymax1 = box1
xmin2, ymin2, xmax2, ymax2 = box2
x_overlap = max(0, min(xmax1, xmax2) - max(xmin1, xmin2))
y_overlap = max(0, min(ymax1, ymax2) - max(ymin1, ymin2))
overlap_area = x_overlap * y_overlap
return overlap_area
|
d3c420597533236a210640f9d4b37a754c6f5a33
| 692,104 |
import time
def get_and_sleep(symbols, fetcher, sleep_time, log_data):
"""
:param symbols: [] of *
List of data to fetch
:param fetcher: func
Perform operations with this function on each data
:param sleep_time: int
After operations, sleep this amount of seconds
:param log_data: str
Extra log data to print
:return: [] of *
Performs function on each data, waits (after each operation) and
returns results
"""
data = []
for symbol in symbols: # scan all symbols
try:
result = fetcher(symbol)
data += result
print("Found", len(result), symbol, log_data)
time.sleep(sleep_time)
except:
print("Cannot get", symbol, log_data)
return data
|
ee7f93dc7e58f262053833480602451dd903afb8
| 541,276 |
import six
def binary_encode(text, encoding='utf-8'):
"""Converts a string of into a binary type using given encoding.
Does nothing if text not unicode string.
"""
if isinstance(text, six.binary_type):
return text
elif isinstance(text, six.text_type):
return text.encode(encoding)
else:
raise TypeError("Expected binary or string type")
|
185132f36f10a78db4d7a935aa3010eb0c8f29bc
| 574,613 |
def is_matrix(iterable):
"""
Check if a iterable is an matrix (iterable of iterables)
>>> is_recursive_iter([[1, 2, 3], [5, 6], [9, 10]])
True
>>> is_recursive_iter([1, 2, 3])
False
"""
if isinstance(iterable, (list, tuple)):
return all(
isinstance(i, (list, tuple))
for i in iterable
)
return False
|
3eb6731ad20f576933a52aed8acb80018d907554
| 302,617 |
def session(tmpdir_path):
"""A temp session file (pathlib.Path)
"""
return tmpdir_path / 'cr-session.sqlite'
|
ee8d0318e355c402ae5c4df24a20b1c6bcd9553c
| 490,783 |
def is_prolog_functor(json_term):
"""
True if json_term is Prolog JSON representing a Prolog functor (i.e. a term with zero or more arguments). See `swiplserver.prologserver` for documentation on the Prolog JSON format.
"""
return (
isinstance(json_term, dict) and "functor" in json_term and "args" in json_term
)
|
b3435672520b2be45e2194a016f73b987d3e1dc6
| 659,609 |
def branch(cuds_object, *args, rel=None):
"""
Like Cuds.add(), but returns the element you add to.
This makes it easier to create large CUDS structures.
:param cuds_object: the object to add to
:type cuds_object: Cuds
:param args: object(s) to add
:type args: Cuds
:param rel: class of the relationship between the objects
:type rel: OntologyRelationship
:return: The first argument
:rtype: Cuds
:raises ValueError: adding an element already there
"""
cuds_object.add(*args, rel=rel)
return cuds_object
|
56e18a2e7a8f6cc215cd75b2998142090c86ea79
| 224,080 |
def get_links_to_articles_of_appropriate_type(soup, article_type):
"""Get links to articles with given article type and return them as a list
Args:
soup (BeautifulSoup): BeautifulSoup object of the site
article_type (str): The type of article to look up for
Returns:
list: The list of links to the articles with the appropriate type
"""
articles = soup.find_all('article')
return [article.a.get('href')
for article in articles
if article.find('span', class_='c-meta__type').text == article_type]
|
dfa3c80e5f17f38a69d90808271a825d1a3334a1
| 229,113 |
from typing import Optional
from typing import Callable
import functools
import click
def group_create_and_update_params(
f: Optional[Callable] = None, *, create: bool = False
) -> Callable:
"""
Collection of options consumed by group create and update.
Passing create as True makes any values required for create
arguments instead of options.
"""
if f is None:
return functools.partial(group_create_and_update_params, create=create)
# name is required for create
if create:
f = click.argument("name")(f)
else:
f = click.option("--name", help="Name for the group.")(f)
f = click.option("--description", help="Description for the group.")(f)
return f
|
e2afc339de284e93b3afc805674c55adc9777fc4
| 563,598 |
def new_import_error(space, w_msg, w_name, w_path):
"""Create a new instance of ImportError.
The result corresponds to ImportError(msg, name=name, path=path)
"""
return space.appexec(
[w_msg, w_name, w_path], """(msg, name, path):
return ImportError(msg, name=name, path=path)""")
|
acafe1deebe98cbd97f0582c151c75395ecae147
| 405,368 |
def xPrime(t,x,y):
"""
Returns xPrime at a specified time, for specified value of y
"""
return(y)
|
02a4d357ab27e7ca232c66914a7bf16b6676da97
| 353,830 |
async def startlist() -> dict:
"""Create a startlist object."""
return {
"id": "startlist_1",
"event_id": "event_1",
"no_of_contestants": 0,
"start_entries": [],
}
|
f66299795bfb674b7e97396200d381022c4413a2
| 38,379 |
def _quote(s: str) -> str:
"""Surround keyword in quotes if it contains whitespace"""
return f'"{s}"' if ' ' in s else s
|
5e30de39e2a59574b5cb137bb7aa726904ce74ab
| 439,636 |
def ABCDFrequencyList_to_HFrequencyList(ABCD_frequency_list):
""" Converts ABCD parameters into h-parameters. ABCD-parameters should be in the form [[f,A,B,C,D],...]
Returns data in the form
[[f,h11,h12,h21,h22],...]
"""
h_frequency_list=[]
for row in ABCD_frequency_list[:]:
[frequency,A,B,C,D]=row
h11=B/D
h12=(A*D-B*C)/D
h21=-1/D
h22=C/D
h_frequency_list.append([frequency,h11,h12,h21,h22])
return h_frequency_list
|
d4f54e6864a34b8b24b1afe599a9338be52f29fd
| 31,250 |
def flatten_data(radiance):
"""Extracts radiance arrays for a whole month
from a dictionary into a list of arrays.
Meant for use with a single month of data.
Parameters
----------
radiance : dict
Dictionary containing one whole month of
radiance arrays, with days as keys and
arrays as values.
Returns
-------
array_list : list
List of numpy arrays (or masked numpy
arrays) containing masked radiance values.
Example
-------
>>> # Get September 2019 data (all days)
>>> radiance = radiance_sept_2019_apr_2020.get('2019').get('09')
>>> # Flatten dictionary to list of arrays
>>> radiance_arrays = flatten_data(radiance)
>>> # Display type
>>> type(radiance_arrays)
list
>>> Display number of days
>>> len(radiance_arrays)
30
"""
# Create list of arrays from dictionary
array_list = [radiance.get(key) for key in radiance.keys()]
# Return list of arrays
return array_list
|
a52cfb8ab6b6d520851c83c86425961c923b19ec
| 411,379 |
def get_color_index(color,palette):
"""Returns the index of color in palette.
Parameters:
color: List with 3 int values (RGB)
palette: List with colors each represented by 3 int values (RGB)
Returns:
Index of color in palette.
-1 if not found.
"""
for x in range(0,len(palette),3):
if palette[x:x+3]==color: return x//3
return -1
|
6131fdaa9fb0db7727a5e8ad6c30bd0b61e12031
| 603,555 |
def valid(snk, body, size, moves):
"""
Determines if a move is out of bound or in body
"""
# print("Snk is: ", snk)
x = snk['x']
y = snk['y']
# print("Body is: ", body)
b = []
for item in body:
b.append([item['x'], item['y']])
for move in moves:
if move == 'left':
x -= 1
elif move == 'right':
x += 1
elif move == 'up':
y += 1
elif move == 'down':
y -= 1
if not(0 <= x < size and 0 <= y < size):
return False #out of bounds
for item in b:
if x == item[0] and y == item[1]:
return False #body
return True
|
29ab50aeb8abdb6e38355ce558153ee798203bff
| 129,488 |
import asyncio
def create_task(coro, loop):
# pragma: no cover
"""Compatibility wrapper for the loop.create_task() call introduced in
3.4.2."""
if hasattr(loop, 'create_task'):
return loop.create_task(coro)
return asyncio.Task(coro, loop=loop)
|
8f41d15f1d7a9394b5e9ad7bb31aca83f81999d3
| 114,192 |
def wrapper(field, wrap_txt):
"""
Wrap a field in html.
"""
answer = "<%s>" % wrap_txt
answer += field
answer += "</%s>" % wrap_txt
return answer
|
7757531c3770c4d0c2994634741e693760fb21bd
| 291,803 |
def dEdL(E, L, P, Q, R):
"""
we know: E^2*P + E*Q + P = 0
therefore:
dEdL = E' = -(E^2*P' + E*Q' + R')/(2*E*P + Q)
input
P, Q, R: three polynomials that depend on L
E: the energy
L: the independent (scaling) variable
"""
Pp = P.deriv(1)(L)
Qp = Q.deriv(1)(L)
Rp = R.deriv(1)(L)
return -(E**2*Pp + E*Qp + Rp) / (2*E*P(L) + Q(L))
|
ef2543df52e78fb59c4001d07b09578dada52f62
| 527,626 |
def color_plot(x, y, color_s, plot_fcn, **kwargs):
"""
Plot a line with an individual color for each point.
:param x: Data for x-axis
:param y: Data for y-axis
:param color_s: array of colors with the same length as x and y respectively. If now enough colors are given,
use just the first (only) one given
:param plot_fcn: Matplotlib function, which should be used for plotting -> use ax.METHOD to ensure that the right
axis is used
:param kwargs: Additional d for matplotlib.pyplot.plot()
"""
h = []
for i in range(len(x)):
c = color_s[i%len(color_s)]
h.append(plot_fcn([x[i]], [y[i]], color=c, **kwargs))
return h
|
1daaf5af6aac26fb6278c9cc3068c154f67eb6a2
| 284,867 |
import json
def _get_codes(error_response_json):
"""Get the list of error codes from an error response json"""
if isinstance(error_response_json, str):
error_response_json = json.loads(error_response_json)
error_response_json = error_response_json.get("error")
if error_response_json is None:
return []
code = error_response_json.get('code')
if code is None:
raise ValueError("Error response does not contain an error code.")
codes = [code]
inner_error = error_response_json.get(
'inner_error', error_response_json.get('innerError', None))
while inner_error is not None:
code = inner_error.get('code')
if code is None:
break
codes.append(code)
inner_error = inner_error.get(
'inner_error', inner_error.get('innerError', None))
return codes[::-1]
|
86e73be80735df115f1d24b5a45f091b62db4d42
| 681,965 |
from typing import Optional
from typing import List
def convert_to_base(
number: int, base: int, min_length: Optional[int] = None
) -> List[int]:
"""
Convert number to its representation in a given system.
:param number:
positive integer number to be converted
:param base:
positive integer number to be used as base
:param min_length:
if result length is less than it, zero padding is added to the left
:return:
list where each element represents a digit in a given system
"""
digits = []
if number == 0:
digits = [0]
while number > 0:
remainder = number % base
digits.append(remainder)
number //= base
if min_length is not None:
padding = [0 for _ in range(max(min_length - len(digits), 0))]
digits.extend(padding)
digits = digits[::-1]
return digits
|
bc8bb7a6fb966fc89e66b85c44bb7086e3d062d3
| 162,218 |
def get_option(args, config, key, default=None):
"""Gets key option from args if it is provided, otherwise tries to get it from config"""
if hasattr(args, key) and getattr(args, key) is not None:
return getattr(args, key)
return config.get(key, default)
|
54d77c6ae3e40b2739156b07747facc4a952c237
| 708,580 |
import yaml
def load_config(yamlfile):
"""load yaml to a dict"""
with open(yamlfile, 'r') as stream:
_dict = yaml.safe_load(stream)
return _dict
|
344fd620fad860d7bd24c757aafaa428c1d5a70b
| 69,583 |
def remove_character(s, position):
"""Removes the character at the given position ie. 'abc', 1 -> 'ac'"""
s = s[0:position] + s[position+1:len(s)]
return s
|
7260137e7cef2e2a324bb386e6e90732cb9be823
| 420,011 |
def from_digits(digits):
"""
Make a number from its digit array (inverse of get_digits)
"""
n = 0
multiplier = 1
for d in reversed(digits):
n += multiplier * d
multiplier *= 10
return n
|
c4aaf996b6fbce4e5ba0569eefbb41f1f96b92d8
| 526,071 |
def sumCounts(a, b):
""" Add up the values for each word, resulting in a count of occurences """
return a + b
|
e7830e2376399a54d9d23b57b41bfedf63e897bd
| 202,839 |
from typing import List
from typing import Dict
from typing import Set
def get_unique_affected_entity_ids(security_problems: List[Dict]) -> Set[str]:
"""Extract all unique affected entity IDs from a list of security problems.
:param security_problems: the security problems, parsed from JSON to Dicts of Dicts
:return: the set of unique affected entity IDs across all provided security problems
"""
if not all(['affectedEntities' in x for x in security_problems]):
raise ValueError("Security problems need to contain attribute 'affectedEntities'")
return {entry for sp in security_problems for entry in sp['affectedEntities']}
|
ffcfd9189e83ac7f0aa4c252216f47e2361713d7
| 664,413 |
def make_hit(card, cards, deck):
"""
Adds a card to player's hand
"""
if card in deck:
cards.append(card)
deck.remove(card)
return cards
|
2420676fa793d07ee2674d2870428eeb6d580a97
| 691,338 |
def pl2_to_pl(src_dict, scale=1000.):
"""Convert integral flux of PL2 to prefactor of PL"""
index = src_dict['spectral_pars']['Index']['value']
emin = src_dict['spectral_pars']['LowerLimit']['value']
emax = src_dict['spectral_pars']['UpperLimit']['value']
f = src_dict['spectral_pars']['Integral']['value']
prefactor = f * (1. - index)
prefactor /= (emax ** (1. - index) - emin ** (1. - index))
prefactor *= scale ** -index
return prefactor
|
7cc1a57ac8763e08968ea32a93c867311c242785
| 72,551 |
def pct_to_kelvin(pct, max_k=6500, min_k=2700):
"""Convert percent to kelvin."""
kelvin = ((max_k - min_k) * pct / 100) + min_k
return kelvin
|
860a9716733249f3a4ee6076db5fad4926befc04
| 624,892 |
def split_X_y(df, column_name='label'):
"""
Split the data into a feature values (X) and targets or labels (y).
:param df: pandas dataframe to split
:param target: Name of the column holding the labels
:return: tuple containing X, y values
"""
if column_name not in df.columns:
return df, None
y = df.pop([column_name])
return df, y
|
022015ba93d93adf66ad1b1734a38c6864ee3b40
| 344,192 |
def degrees_of_freedom(s1, s2, n1, n2):
"""
Compute the number of degrees of freedom using the Satterhwaite Formula
@param s1 The unbiased sample variance of the first sample
@param s2 The unbiased sample variance of the second sample
@param n1 Thu number of observations in the first sample
@param n2 The number of observations in the second sample
"""
numerator = (s1**2/n1 + s2**2/n2)**2
denominator = ((s1**2/n1)**2)/(n1-1) + ((s2**2/n2)**2)/(n2-1)
degrees_of_freedom = numerator/denominator
return degrees_of_freedom
|
5f076e33584c61dca4410b7ed47feb0043ec97cb
| 397 |
def atc_station_tracer_query(station_code, samp_height, tracer, level=2):
"""
Return SPARQL query to get a data object for
a specific ICOS Atmospheric station, sampling height and tracer
CO2, CO or MTO, level 2 or level 1 (=NRT)
:input: ATC station code, sampling height, tracer, ICOS data level (default=2)
:return: SPARQL query to get all ATC Level <level> products for tracer <tracer>
:rtype: string
"""
station_label = 'AS_' + station_code
tracer = tracer.lower().title()
dataobject = ['NrtGrowingDataObject','L2DataObject']
#Define URL:
url = 'https://meta.icos-cp.eu/sparql'
query = """
prefix cpmeta: <http://meta.icos-cp.eu/ontologies/cpmeta/>
prefix prov: <http://www.w3.org/ns/prov#>
select ?dobj ?spec ?fileName ?size ?submTime ?timeStart ?timeEnd ?samplingHeight
where {
VALUES ?spec {<http://meta.icos-cp.eu/resources/cpmeta/atc"""+tracer+dataobject[level-1]+""">}
?dobj cpmeta:hasObjectSpec ?spec .
VALUES ?station {<http://meta.icos-cp.eu/resources/stations/"""+station_label+""">}
?dobj cpmeta:wasAcquiredBy/prov:wasAssociatedWith ?station .
?dobj cpmeta:hasSizeInBytes ?size .
?dobj cpmeta:hasName ?fileName .
?dobj cpmeta:wasSubmittedBy/prov:endedAtTime ?submTime .
?dobj cpmeta:hasStartTime | (cpmeta:wasAcquiredBy / prov:startedAtTime) ?timeStart .
?dobj cpmeta:hasEndTime | (cpmeta:wasAcquiredBy / prov:endedAtTime) ?timeEnd .
FILTER NOT EXISTS {[] cpmeta:isNextVersionOf ?dobj}
?dobj cpmeta:wasAcquiredBy / cpmeta:hasSamplingHeight ?samplingHeight .
FILTER( ?samplingHeight = '"""+str(samp_height)+"""'^^xsd:float )
}
order by desc(?submTime)
"""
return query
|
d4d3a57c6d6a245b9b636c345f14248551e00fe0
| 440,980 |
def is_root_soul(s):
"""
Returns a boolean indicating whether the key s is a root soul.
Root soul is in the form 'schema://id'
"""
return "://" in s
|
24e0853f556e7c1a65bcb44881912cd67167d8b7
| 511,918 |
from typing import Tuple
def __nb_xy2rowcol(
xy: Tuple[float, float], inverse_transform: Tuple[float, ...]
) -> Tuple[float, float]:
"""numba version of xy2rowcol
Parameters
----------
xy : Tuple[float, float]
coordinate
inverse_transform : Tuple[float, ...]
affine parameter as tuple
Returns
-------
Tuple[float, float]
row, column
"""
# x, y = xy
# a, b, c, d, e, f, _, _, _ = inverse_transform
# return x * d + y * e + f, x * a + y * b + c
return (
xy[0] * inverse_transform[3]
+ xy[1] * inverse_transform[4]
+ inverse_transform[5],
xy[0] * inverse_transform[0]
+ xy[1] * inverse_transform[1]
+ inverse_transform[2],
)
|
acc1e9c98fc27bca383430b6e472d3a866f2a44d
| 449,898 |
def add_dividers(row, divider, padding):
"""Add dividers and padding to a row of cells and return a string."""
div = ''.join([padding * ' ', divider, padding * ' '])
return div.join(row)
|
7cbe235ddf8c320cadfcc4b4a3f17a28c2aaac1c
| 695,365 |
def myComb(n, p):
"""
C(n, p), polyfill for python < 3.7. For higher python version, math.comb should be better.
Parameters
----------
n, p : int
Returns
-------
int
C(n, p)
"""
res = 1
for i in range(p):
res *= (n - i)
for i in range(p):
res = res // (i + 1)
return res
|
88295b319cee5ac3911ffc5823dd58a4d44d14e1
| 394,147 |
def to_equation(coefficients):
"""
Takes the coefficients of a polynomial and creates a function of
time from them.
"""
def f(t):
total = 0.0
for i, c in enumerate(coefficients):
total += c * t ** i
return total
return f
|
32562826f4ffbf1bc502c715a0430358694a1e6c
| 296,106 |
def funcparser_callable_space(*args, **kwarg):
"""
Usage: $space(43)
Insert a length of space.
"""
if not args:
return ''
try:
width = int(args[0])
except TypeError:
width = 1
return " " * width
|
1033297ff5ce10b26e19d12a378e719afa6261d3
| 448,296 |
import fcntl
import errno
def obtain_lock(lock_filepath):
""" Open and obtain a flock on the parameter. Returns a file if successful, None if not
"""
lock_file = open(lock_filepath, 'w')
try:
fcntl.flock(lock_file, fcntl.LOCK_EX | fcntl.LOCK_NB)
return lock_file
except IOError as err:
if err.errno != errno.EAGAIN:
raise
lock_file.close()
return None
|
1159860a436eb7e94054e031ae852b6491c1f937
| 549,734 |
def safeInt(v):
"""helper function for parsing strings to int"""
try:
ret = int(v)
return ret
except:
return None
|
bfd75432d459e083188b6f60b759edca0a395121
| 613,813 |
def _worker_one_task(incoming,outgoing):
"""A thread. Takes stuff from the incoming queue and puts stuff on
the outgoing queue. calls execute for each command it takes off the
in queue. Return False when we receive a terminator command"""
#msgb("WORKER WAITING")
item = incoming.get()
#msgb("WORKER GOT A TASK")
if item.terminator:
outgoing.put(item)
return False
item.execute()
incoming.task_done()
outgoing.put(item)
return True
|
840f14dc158a315f12c3a4300744ca7b5fc994fc
| 381,059 |
def freeze(d):
"""Convert the value sets of a multi-valued mapping into frozensets.
The use case is to make the value sets hashable once they no longer need to be edited.
"""
return {k: frozenset(v) for k, v in d.items()}
|
b8e3b287838e5f8e52c71eb2d10e41823896dfe0
| 581,843 |
def read_file(filename):
"""
read the text of a file
:param filename: name of the file to read
:return: text of the file
"""
with open(filename, encoding="utf-8") as file:
return file.read()
|
0df9e7f7df0cbf8896b62502efb0023f8c30f2b0
| 428,966 |
def istype(obj, allowed_types):
"""isinstance() without subclasses"""
if isinstance(allowed_types, (tuple, list, set)):
return type(obj) in allowed_types
return type(obj) is allowed_types
|
5c441a69030be82e4d11c54ea366ee3463d388c8
| 691,257 |
from typing import Any
import inspect
def _representable(value: Any) -> bool:
"""
Check whether we want to represent the value in the error message on contract breach.
We do not want to represent classes, methods, modules and functions.
:param value: value related to an AST node
:return: True if we want to represent it in the violation error
"""
return not inspect.isclass(value) and not inspect.isfunction(value) and not inspect.ismethod(value) and not \
inspect.ismodule(value) and not inspect.isbuiltin(value)
|
6705869a4368316d926b10c0221cdce75b0160f2
| 432,656 |
import functools
def needs_semaphore(func):
"""Decorator for a "task" method that holds self.semaphore when running"""
@functools.wraps(func)
async def wrapper(self, *args, **kwargs):
async with self.semaphore:
result = await func(self, *args, **kwargs)
return result
return wrapper
|
3c34ae0b4e1d06e8b4c14de61eb81bf1427d4ec6
| 229,890 |
def find_bucket_key(s3_path):
"""
This is a helper function that given an s3 path such that the path is of
the form: bucket/key
It will return the bucket and the key represented by the s3 path
"""
s3_components = s3_path.split("/")
bucket = s3_components[0]
s3_key = ""
if len(s3_components) > 1:
s3_key = "/".join(s3_components[1:])
return bucket, s3_key
|
a75fb1b10216c9a36ac7428e3ae945b29c3045b8
| 485,107 |
def from_uniform(r, a, xmin):
"""
Inverse CDF of the power law distribution
"""
x = xmin*(1.-r)**(-1./(a-1.))
return x
|
a2d58f460a8a35874253377ec8b1b4cee913533a
| 269,934 |
def indices(s):
"""Create a list of indices from a slice string, i.e. start:stop:step."""
start, stop, step = (int(x) for x in s.split(':'))
return list(range(start, stop, step))
|
8930bb7f32e65b8f40e2efe56b7aff7ce43731d6
| 353,134 |
def flatten(iter_of_iters):
"""
Flatten an iterator of iterators into a single, long iterator, exhausting
each subiterator in turn.
>>> flatten([[1, 2], [3, 4]])
[1, 2, 3, 4]
"""
retval = []
for val in iter_of_iters:
retval.extend(val)
return retval
|
0a2132fc2c9e1dc1aef6268412a44de699e05a99
| 675,974 |
from typing import Tuple
def diagonal_distance(pa : Tuple[int, int], pb : Tuple[int, int]) -> int:
"""
Gets manhattan distance with diagonals between points pa and pb.
I don't know what this is called, but the fastest route is to take the
diagonal and then do any excess.
"""
(ax, ay) = pa
(bx, by) = pb
xdist = abs(ax - bx)
ydist = abs(ay - by)
dist = min(xdist, ydist) + abs(xdist - ydist)
return dist
|
5f4fb653ab8d8bb77172b1637af3edb7c2f0b704
| 659,684 |
def is_iterable(var):
"""This function identifies if a given variable is an iterable.
.. versionadded:: 3.5.0
:param var: The variable to check
:returns: A boolean value indicating whether or not the variable is an iterable
"""
is_iter = any((isinstance(var, list), isinstance(var, tuple), isinstance(var, set),
isinstance(var, type({}.keys())), isinstance(var, type({}.values()))))
return is_iter
|
49ed1945e3c66dfcaa875f1e607a89066630a831
| 370,739 |
def get_full_asetup(cmd, atlas_setup):
"""
Extract the full asetup command from the payload execution command.
(Easier that generating it again). We need to remove this command for stand-alone containers.
Alternatively: do not include it in the first place (but this seems to trigger the need for further changes).
atlas_setup is "source $AtlasSetup/scripts/asetup.sh", which is extracted in a previous step.
The function typically returns: "source $AtlasSetup/scripts/asetup.sh 21.0,Athena,2020-05-19T2148,notest --makeflags='$MAKEFLAGS';".
:param cmd: payload execution command (string).
:param atlas_setup: extracted atlas setup (string).
:return: full atlas setup (string).
"""
pos = cmd.find(atlas_setup)
cmd = cmd[pos:] # remove everything before 'source $AtlasSetup/..'
pos = cmd.find(';')
cmd = cmd[:pos + 1] # remove everything after the first ;, but include the trailing ;
return cmd
|
ce899a3872e2c5c8a0d13f4c90ff2ff3688c15d9
| 562,349 |
def doAddition(a,b):
"""
The function doAddition accecpts two integer numbers and returns the sum of it.
"""
return a+b
|
c4afcdab6c5e4570eff848b2f6a0aa07713f0dda
| 17,507 |
def get_note_key(timestamp):
"""Generates redis keyname for note"""
return "note_%s" % timestamp
|
d092a104d6840dd96de2a19ca73902fa12c36465
| 405,126 |
def rle_encode(s: bytes) -> bytes:
"""Zero-value RLE encoder
Parameters:
s (``bytes``):
Bytes to encode
Returns:
``bytes``: The encoded bytes
"""
r = b""
n = 0
for b in s:
if b == 0:
n += 1
else:
if n > 0:
r += bytes([0, n])
n = 0
r += bytes([b])
if n > 0:
r += bytes([0, n])
return r
|
081d1998c56b7978592dbee451185f086499affc
| 398,500 |
def Clamp(col):
"""
Makes sure col is between 0 and 255.
"""
col = 255 if col > 255 else col
col = 0 if col < 0 else col
return int(col)
|
9e7049834f2026ea1e6f3d379880338834cdc562
| 225,386 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.