content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def check_previewUrls(search_results):
""" Checks if a result provides a previewUrl for thumbnails. Otherwise a placeholder will be set.
This function is needed to avoid too much logic in template rendering.
Args:
search_results: Contains all search results
Returns:
search_results
... | 4f78f3d14167970a7988aea310fe2eaeae498ec3 | 670,103 |
import re
def starts_with_auth(s):
"""Checks is string s starts with standard name type
Args:
s (str): WhatsApp message string
Returns:
bool: True if matches regex for name, False if not
"""
patterns = [
r'([\w]+):', # 1st Name
r'([\w]+[\s]+... | a910375fb82151e938f4a2cb8b897002d24cb14e | 670,104 |
import socket
def is_port_open(host, port):
"""
determine whether `host` has the `port` open
"""
# creates a new socket
s = socket.socket()
try:
# tries to connect to host using that port
s.connect((host, port))
# make timeout if you want it a little faster ( less accur... | 5c974c912196d02fa5ae536998f380f1f2fac90c | 670,106 |
def format_num_3(num):
"""
Format the number to 3 decimal places.
:param num: The number to format.
:return: The number formatted to 3 decimal places.
"""
return float("{:.3f}".format(num)) | 94cbb801539dd72538ffb39bdbfab4675d9e8eed | 670,108 |
import secrets
import string
def generate_secret_key() -> str:
"""Securely generate random 50 ASCII letters and digits."""
return "".join(secrets.choice(string.ascii_letters + string.digits) for _ in range(50)) | efd23fd8e572f86372c3765ebb946e666370fce0 | 670,109 |
import re
def camelcase(value):
"""
Convert a module name or string with underscores and periods to camel case.
:param value: the string to convert
:type value: str
:returns: the value converted to camel case.
"""
return ''.join(x.capitalize() if x else '_' for x in
re.... | 9e751cb4d3cc8fc5a43733e9a5e0cafa98f18584 | 670,116 |
import math
def _compute_effect_size(slice_metric: float, slice_std_dev: float,
base_metric: float, base_std_dev: float):
"""Computes effect size."""
metric_diff = abs(slice_metric - base_metric)
slice_var = slice_std_dev * slice_std_dev
base_var = base_std_dev * base_std_dev
return... | f7865beff061b7df61a39bfdf968e0db63ce5fd9 | 670,117 |
def hex2dec(s):
"""return the integer value of a hexadecimal string s"""
return int(s, 16) | 7f97aabe590c1e434f03870c3d43af33cbf113a1 | 670,119 |
def isNumber(string):
"""
check if a string can be converted to a number
"""
try:
number = float(string)
return True
except:
return False | 40916ab8a206e4fdb068b2986146dde0d0cb64dc | 670,121 |
def uniqueValues(aDict):
"""
Write a Python function that returns a list of keys in aDict that map
to integer values that are unique (i.e. values appear exactly once in aDict).
The list of keys you return should be sorted in increasing order.
(If aDict does not contain any unique values, you should ... | 5663dcdc7c11df3902ebe5f35ef400e2542dddc1 | 670,122 |
import string
import random
def generate_random_string(size=6, chars=string.printable):
"""
generates a random printable string of the given size using the given characters
:param size: length of the string to be generated
:param chars: set of characters to be used
:return: a random string
"""... | 80b5fec638e3865434bbc0af2503a66507a3b486 | 670,124 |
def subset_df(df, nrows=None, ncols=None, row_seed=0, col_seed=0):
"""Randomly subset a dataframe, preserving row and column order."""
if nrows is None:
nrows = len(df)
if ncols is None:
ncols = len(df.columns)
return (df
.sample(n=nrows, random_state=row_seed, axis='rows')
... | c7933fd5609982b1eae01ef2e6cfb1d057f6acb3 | 670,130 |
def get_bucket(timestamp, resolution):
""" Normalize the timestamp to the given resolution. """
return resolution * (int(timestamp) // resolution) | 67985fa9d875211c5a55749d353d93de0f2df670 | 670,133 |
def get_data(features, labels_aud, labels_foc, files, indices):
"""Return features, labels and files at given indices """
features = [features[idx] for idx in indices]
labels_aud = [labels_aud[idx] for idx in indices]
labels_foc = [labels_foc[idx] for idx in indices]
files = [files[idx] for idx in i... | 5da68f72a17084a019e2bf2971023187aaff1ba1 | 670,136 |
def model_app_name(value):
"""
Return the app verbose name of an object
"""
return value._meta.app_config.verbose_name | c4fd7b138b4edeceb957beb2dbe1a1f28ebe4f95 | 670,137 |
import yaml
def pretty(d):
"""Pretty object as YAML."""
return yaml.safe_dump(d, default_flow_style=False) | 058b55f31f127cf932679312b14c4034f2bd5ed0 | 670,138 |
def locale_dict_fetch_with_fallbacks(data_dict, locale):
"""
Take a dictionary with various locales as keys and translations as
values and a locale, and try to find a value that matches with
good fallbacks.
"""
# try returning the locale as-is
if data_dict.has_key(locale):
return dat... | f81e37a4dcb5286619308832bd01b8740218ee6d | 670,139 |
import math
def _ceil_partial(value, grid_spacing):
"""Ceil to next point on a grid with a given grid_spacing."""
return math.ceil(value / grid_spacing) * grid_spacing | 4876dc28c5281315ed467e8f0d11fa8145e82e44 | 670,141 |
import copy
def swap_variables(self, r, s, in_place = False):
"""
Switch the variables `x_r` and `x_s` in the quadratic form
(replacing the original form if the in_place flag is True).
INPUT:
`r`, `s` -- integers >= 0
OUTPUT:
a QuadraticForm (by default, otherwise none)
EX... | 9a8fb0e6e0424efb39cf7861949961e88a147ad8 | 670,144 |
def totuples(data):
""" Convert python container tree to key/value tuples. """
def crawl(obj, path):
try:
for key, value in sorted(obj.items()):
yield from crawl(value, path + (key,))
except AttributeError:
if not isinstance(obj, str) and hasattr(obj, '__... | e44b404dff2bc9d552d510f386dcc4793ad5e0b7 | 670,146 |
def create_navigator_apt_entry(nav_info, appointment_timestamp):
"""
This function takes a dictionary popluated with navigator information and an appointment timestamp and creates
an dictionary containing appointment information corresponding to the information given.
:param nav_info:
:param appoin... | 461e9ef73c291d7c74ea01aa4fccd764c6e53767 | 670,152 |
import re
def clean(sentence):
"""
Clean up a sentence. Remove non alpha number letters. Lower cased.
>>> clean('all done.')
'all done'
>>> clean('ALL DONE.')
'all done'
>>> clean('here we go:')
'here we go'
:param sentence:
:return:
"""
return re.sub('[^A-Za-z0-9]', ... | 1d45d61b897d49073f6bd5a5e2147b5d6494b2fd | 670,154 |
import struct
def bytes_to_integer(bytes_):
"""Convert bytes to integer"""
integer, = struct.unpack("!I", bytes_)
return integer | 7ab9128a1336f4e642da52766effe89e23f0aaac | 670,156 |
def to_rpc_byte_order(internal_byte_order):
"""
Returns a given internal byte order hash (bytes) to the format expected by
the RPC client.
"""
return internal_byte_order[::-1] | 0d7f47e3e57175e9a88bad8de2a47d536564e309 | 670,158 |
import secrets
def token_url() -> str:
"""Return random and URL safe token."""
return secrets.token_urlsafe() | 03e73a6757ccf25854f1e3cd9ae0922c782bf1e0 | 670,160 |
import sympy
def antal_l_coefficient(index, game_matrix):
"""
Returns the L_index coefficient, according to Antal et al. (2009), as given by equation 1.
L_k = \frac{1}{n} \sum_{i=1}^{n} (a_{kk}+a_{ki}-a_{ik}-a_{ii})
Parameters
----------
index: int
game_matrix: sympy.Matrix
Return... | 39dd5dab87f29db5a85a55e8bbb3d0d98ff4ad3c | 670,161 |
import requests
def copy_job(job_id, key):
"""Helper function to create a Figure 8 job based on existing job.
Args:
job_id: ID number of job to copy instructions and settings from when creating new job
key: API key to access Figure 8 account
Returns:
int: ID number of job created... | 810fc44c636fa6bdb4e05f023321313036f3807e | 670,163 |
def most_common_bit_for_position(numbers: list[str], position: int) -> int:
"""calculates the most common bit for a given position (if equal, returns 1)"""
sum_for_position = 0
for number in numbers:
sum_for_position += int(number[position])
return int(sum_for_position >= len(numbers) / 2) | 1e58a5d36a6ab033cc4750dcfacb29cd1eb178be | 670,164 |
def getattr_(entity, attribute):
"""Either unpack the attribute from every item in the entity
if the entity is a list, otherwise just return the attribute
from the entity. Returns None if the entity is either None
or empty."""
if entity in (None, []):
return None
if isinstance(entity, li... | 42dbfb2c0cdb1bd59d627cd6d509e6dc43ba7a2d | 670,168 |
import binascii
def HexifyBuffer(string_buffer):
"""Return a string with the hex representation of a string buffer."""
chars = []
for char in string_buffer:
chars.append(binascii.hexlify(char))
return '\\x{0:s}'.format('\\x'.join(chars)) | b3091daa7d8b2be3e778ab763619fdd05c8ea051 | 670,171 |
def finished_prediction(status):
"""
Gets prediction of finished game
:param status:
:return: 1.0 if white wins, 0.0 if black wins, 0.5 if draw
"""
finished_dict = {"w": 1.0, "b": 0.0, "d": 0.5}
return finished_dict[status] | 595f4ef557e78fef482a2780e80a8cddb6b799a3 | 670,174 |
import json
def pp(s):
"""
Pretty print JSON string.
"""
return json.dumps(s, indent=4) | 2300fead2a6ff63bf5b2e8a4298d74fb44789425 | 670,179 |
def transform_coords(coords, swap, reflect):
"""
coords - a set of coordinates
swap - the swap transformation (i.e. (0, 2, 1) --> (x, z, y))
reflect - the reflection transformation (i.e. (1, -1, 1) --> (x, -y, z))
Returns the transformed coordinates
"""
new_coords = []
for i in range(le... | 0ae4f7f046099d16a0eb7926f4c60946b70a1562 | 670,184 |
def compute_trapped_rain_water(heights: list[int]) -> int:
"""
Given n non-negative integers representing an elevation map (height)
where the width of each bar is 1,
compute how much water it can trap after raining.
Notes:
if `left_max_height` and `right_max_height` are the maximum heights
... | 520060057fc4526927f23ca398d9e0d096b9499e | 670,187 |
from typing import Optional
from pathlib import Path
def _try_touch_file(target) -> Optional[Path]:
"""Test to see if we have permissions to create a file at ``target``.
If the target already exists, it will not be touched. If it does not
exist, this function attempts to create it and delete it (i.e... | 7854c1139946a5ff0969e79876b1c0e377030c55 | 670,188 |
def read_to_whitespace(fptr, track):
"""
Read, skipping over white space. Then read all non-whitespace until one
character of white space is consumed. Return the non-whitespace that was
read. If the end of the file is encountered, return any non-whitespace if
available, or an empty bytes string.
... | 80d246f578af932830169306816acb5f0d6bfffb | 670,190 |
def reopen_to(fhandle, path, mode):
"""
close a filehandle and return a new one opened for the specified path and mode.
example: sys.stdout = reopen_to(sys.stdout, "/tmp/log.txt", "w")
Parameters:
fhandle (file): the file handle to close (may be None)
path (str): the new path to open
... | 17eb5da556899e80962866b9229d3cde478ec7df | 670,191 |
import re
def check_input(new_ver):
""" Ensure that user input matches the format X.X.X """
pat = r'\d+.\d+.\d+'
if not re.match(pat, new_ver):
print("The new version must be in the format X.X.X (ex. '0.6.0')")
return True | 7e632a45c0e8f4c71ef85c18b316e7f81de908c9 | 670,194 |
def ignore_exception_handler(ex):
""" acts as if no exception was raised, equivalent to except: pass"""
return None | 0e52bac1d9f13b65edbee94c2def8c9eaba422a0 | 670,199 |
def modNeg90To90(angle_deg):
"""Returns a modulo between -90 and 90"""
return (angle_deg + 90)%180-90 | f79d6bb1cba93b0d4bbbfcf6fd3c581b14da518c | 670,200 |
def image(title, desc, image_name, group=None, height=None):
"""
Builds an image element. Image elements are primarily created
and then wrapped into an image gallery element. This is not required
behavior, however and it's independent usage should be allowed depending
on the behavior required.
... | 301f7831567e8845ef32ec33da4d5d273e50ac65 | 670,202 |
def flatten(l):
"""Utility function to flatten an iter of iters into an iter."""
return [item for sublist in l for item in sublist] | e9deb14a37676aaff78ba5080f792793f8ff06ce | 670,203 |
def _int_str_to_bit_str(int_str, num_bits, msb_first):
"""
Convert an integer string to num_bits bits string.
Example:
int_string_to_bit_str('0x5', 4) -> '0101'
int_string_to_bit_str('0x3', 4, msb_first=false) -> '1010'
"""
data = int(int_str, 0) # use radix 0 to automatically deduc... | 237b87ecf578834517b5137ed7ffbb92b284520d | 670,205 |
def get_padding(kernel, dilations, axis):
"""
Calculates required padding for given axis
Args:
kernel: A tuple of kernel height and width
dilations: A tuple of dilation height and width
axis: 0 - height, 1 width
Returns:
An array that contains a length of padding at the ... | 7c8918c8abcd3590efe3f80b5d4b7e28d183f98b | 670,207 |
def update_variables(variables, constraints):
"""Updates all variables with their neighboring variables and constraints."""
for constraint in constraints:
scope = constraints[constraint].variables
for var in scope:
variables[var].add_constraint(constraint)
variables[var].... | 3a4c9d2b8cf86dc26fe93bafca4e4bf0071ca1cb | 670,210 |
def are_elements_oriented(subgraph_elements):
"""Check wheter all the elements of a subgraph have
an orientation value `[+/-]`.
"""
for id_, orientation in subgraph_elements.items():
if orientation is None:
return False
return True | a4f730f8b46e13033cba112124b599dd0448d4e6 | 670,213 |
def ramp(s, width, annealing_time):
"""Schedule with a ramp shape.
Args:
s (float):
The mid-point of the ramp, as a fraction of the annealing time.
width (float):
The width of the ramp, as a fraction of the annealing time. Note
that QPUs have a maximum slope... | cbffad367302c75e44279a483b8691f751f2f0a2 | 670,214 |
import optparse
def LoadOptionsFromFlags(argv):
"""Parse command-line arguments.
Args:
argv: The program argument vector (excluding the script name)
Returns:
A dictionary with key-value pairs for each of the options
"""
usage_string = 'python dsplcheck.py [options] [DSPL XML file or zip archive]'
... | 6de6289cb33a8369808d7c295158d839d3dffdc3 | 670,218 |
from typing import Dict
def create_result_dict() -> Dict:
""" Create the results dictionary """
return {"Title": None, "Issue Type": None, "Severity": None,
"CWE": None, "Vulnerable File": None, "Details": []} | 6fab9750cac1201e3d8f530f03919e05db668bd8 | 670,220 |
def new_merged_dict(*dicts):
"""Merges dictionaries into a new dictionary. Necessary for python2 and
python34 since neither have PEP448 implemented."""
# Necessary for python2 support
output = {}
for d in dicts:
output.update(d)
return output | d431bd1587d05f26caed9181c58315bf309d3d04 | 670,223 |
import six
def commalist(value):
"""
Convert a comma separated string into a list
If ``value`` is already a list or tuple it will
be returned.
"""
if isinstance(value, six.string_types):
return [v.strip() for v in value.split(',')]
if isinstance(value, (set, list)):
return ... | 3ffa6c9662d15ace3a59812bdf71a7c2394cc969 | 670,226 |
def MaskField(**kwargs):
"""Create a new field for a :py:class:`~.KeyspacesRegion` that will write
out a mask value from a keyspace.
Parameters
----------
field : string
The name of the keyspace field to store the mask for.
tag : string
The name of the keyspace tag to store the ... | 29db1753257d397de50e8d317b10ec057a82f4d6 | 670,230 |
def search_linear(xs, target):
""" Find and return the index of target in sequence xs """
for (i, v) in enumerate(xs):
if v == target:
return i
return -1 | 91b719857decfe4818f2843ac1df6e423ea966ef | 670,236 |
def check_private_exponent(a, B=512):
"""
Checks the bit length of the given private exponent.
If you've asked for a random number of bit length at least :param:`B`, but are retrieving
numbers that are smaller than said size, you might want to check your RNG.
>>> B = 8
>>> a = 0b11111111
>... | a1d4e0c6d1345057f4c2648ded655fa9e31585c5 | 670,238 |
def _is_removed(tensor_name, removed_op_names):
"""Determine whether the named tensor is an output of a removed op."""
for removed_op_name in removed_op_names:
if tensor_name.split(':')[0] == removed_op_name:
return True
return False | 55915465adeecf5ba33aff8daa3de04a35c28ac1 | 670,240 |
def map_title_from_list(number, title_list):
"""Used during the iterative inserts in fn:write_to_db - if number matches
the number within title_list, write title to db.
:arg number: string containing RFC number
:arg title_list: list of all rfc titles from fn:get_title_list
:returns result: string ... | 25b6dcafbd9eb56ad8d5068fdb51950c60b90498 | 670,241 |
def find_instance_of_digit(train_labels, digit):
""" find_instance_of_digit function
Find the first instance of a digit within the given labels and returns
its index.
Args
----
train_labels : np.array
list of labels
digit : Number
digit to search for
Returns
------... | 680a8db67f95c42212fcbd02b632a5a79aa8f84a | 670,246 |
def get_string_content(line):
"""
Get the quoted string content from a line.
:param line: a string which contains a quoted substring
:return: the string between the quotes
"""
first_index = line.find('\"') + 1
last_index = line.rfind('\"')
content = line[first_index:last_index]
conte... | a11bd8721ac9cf5be6a8bdb19ee5e97ab3174983 | 670,248 |
def sum_2d(a):
"""
Sum all the values in a matrix together.
:param a: (list) 2D matrix containing values to be summed
:return: (int/float) sum value of the matrix.
"""
# Check if given matrices are of "list" type
if type(a) != list:
raise TypeError('Error xm01: Incorrect type, m... | a41a2dce6d49e102f2d35e15aef43efc6f49d829 | 670,249 |
def number_of_tweets_per_day(df):
"""
Function will count number of tweets per day
Arguments:
takes a Pandas DataFrame as input
Returns:
a new DataFrame grouped by day
(new column 'Date') with the
number of tweets for that day
"""
df["D... | 86d3d2ec85424ae3fbe17b3ad475d802cab9eb11 | 670,250 |
def allowed_to_preview(user):
"""
Is the user allowed to view the preview?
Users are only allowed to view the preview if they are authenticated, active and staff.
:param user: A User object instance.
:return: Boolean.
"""
if (
user.is_authenticated and
user.is_active and
... | 3f628939f79ffcb7f0802b71a9433eaa58c48946 | 670,251 |
def filter(nodes, labels=[]):
"""Filter nodes which matches labels"""
labels = set(labels)
filterd_nodes = {}
for k, spec in nodes.items():
node_labels = set(spec.get('labels', []))
matched_labels = labels & node_labels
if matched_labels == labels:
filterd_nodes[k] = ... | 5b81de38ccdef8b8271b29445328f90d4f7bfd79 | 670,252 |
import hashlib
def generate_unique_key(master_key_path, url):
"""
master_key_path: str Path to the 32-byte Master Key (for S3 Encryption)
url: str S3 URL (e.g. https://s3-us-west-2.amazonaws.com/bucket/file.txt)
Returns: str 32-byte unique key generated for that URL
"... | f254a57fa02eafe7363e65859cfc3710e0b97f47 | 670,253 |
from string import digits
def remove_numbers(string: str) -> str:
"""Strips numbers from a string
Eg, a1b2c3 -> abc
Args:
string (str): String to clean
Returns:
str: Provided string without numbers
"""
return string.translate(str.maketrans("", "", digits)) | 621ded81a05412b17f6cfdeb14dd71d393cee8fb | 670,255 |
import re
def add_uuid_dashes(uuid):
"""Convert a plain UUID (i.e. "65ea51744ce54bee...") to a dashed
UUID (i.e. 65ea5174-4ce5-4bee-...)
"""
if uuid is None:
return None
else:
p = re.compile(r"(\w{8})(\w{4})(\w{4})(\w{4})(\w{12})")
return p.sub(r"\1-\2-\3-\4-\5", uuid) | 14e94716804c8a5f86a1076e62926da1e4d20a5f | 670,257 |
def service(func):
"""
Service decorator
This will add a tag property to a function called 'is_service' so that
the function/method can be identified as a service.
When writing a Measurement class, any method that is to be offered as
a service can be tagged with the @service decorator
e.g.
... | acae0b71c5a5bbdb0835c11ffc765aab2f988b4f | 670,258 |
def transpose_list(values):
"""Transposes a list of lists. Can be used to convert from `time-major` format to `batch-major` format and vice
versa.
Example:
Input::
[[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]]
Output::
[[1, 5, 9],
... | fccc1f54dd51090e0add9f860b9ddd24a593357e | 670,262 |
def add_or_merge(dictionary, key, values):
"""
Add or merge the values in 'values' to 'dictionary' at 'key'
"""
if key in dictionary:
if isinstance(values, list):
dictionary[key] = dictionary[key] + values
else:
dictionary[key].update(values)
else:
dic... | f627fbbbb9aa3ab1af05b25a6c7fb2033109e316 | 670,265 |
def is_toa5(record):
""" Utility function to check if a supplied record (as generated by hievpy.search) is in TOA5 format
Input
-----
Required
- record: record object returned by the search function
Returns
-------
True or False
"""
if record['format'] == 'TOA5' and record['f... | 91e1e541cf48c80f8f5bc6a3d8a2a4dda44c335c | 670,267 |
def get_icon_name(x):
"""
Returns the icon name from a CDragon path
"""
return x.split('/')[-1] | 9df409d5e4dd6083f054114beac5261aae1f43e7 | 670,271 |
def get_gz(tar):
"""Get list of files in tarfile ending with 'gz'"""
batch_results = [tar.extractfile(f) for f in tar.getmembers()
if f.name.endswith('gz')]
return batch_results | 397bf013918beee9f2dc054197ced352299711f1 | 670,275 |
import re
def max_num1(x: str)->int:
"""
Input: String
Output: Integer
Finds the maximum integer in the string
"""
c = re.findall("\d+",x)
n = map(int,c)
return max(n) | e5a715a56ca16b265762ac10c7ef847d8bd89f21 | 670,277 |
def whitespace_normalize_name(name):
"""Return a whitespace-normalized name."""
return ' '.join(name.split()) | 0bff5c66818cc2ee635a612f17bed2b189b98dfb | 670,278 |
def _GetSuspectedCLFoundByHeuristicForCompile(analysis):
"""For compile failure, gets the suspected revision found by heuristic."""
if not analysis or not analysis.result:
return None
for failure in analysis.result.get('failures', []):
if (failure['step_name'].lower() == 'compile' and
len(failure... | 43117676bd1ac0bd91528291bed46278882a31f4 | 670,279 |
def pxe_mac(mac):
"""
Create a MAC address file for pxe builds.
Add O1 to the beginning, replace colons with hyphens and downcase
"""
return "01-" + mac.replace(":", "-").lower() | 483ccf559b5cb014070be3cc9e0237ac5d1a0b34 | 670,281 |
def getDistance(posn1, posn2):
"""Helper for getSeeds that calculates the cartesian distance between two tuple points."""
distX = (posn1[0] - posn2[0]) ** 2
distY = (posn1[1] - posn2[1]) ** 2
return (distX + distY) ** 0.5 | 6c121db4bad8c24d9a8b668cb312c07f019eac90 | 670,284 |
def make_safe_filename(name):
"""Replace characters that are not allowed in windows file names."""
for char in ('/', '\\', ':', '*', '?', '"', '<', '>', '|'): # Windows illegal folder chars
if char in name:
name = name.replace(char, " ")
# replacables: ['∕','⧵' ,'˸','⁎','ॽ','“'... | 776da54097ce3fcb0f4aae23f80ac0932654d800 | 670,286 |
from datetime import datetime
def _valid_date(date_value):
"""Validate a transaction date."""
try:
transaction_date = datetime.strptime(date_value, "%d/%m/%Y")
return transaction_date is not None
except ValueError:
return False | bdcc3b993c5b2ec6a1d0ae13fe850450c685b84e | 670,288 |
import math
def pressure_lrc ( density, r_cut ):
"""Calculates long-range correction for Lennard-Jones pressure."""
# density, r_cut, and the results, are in LJ units where sigma = 1, epsilon = 1
sr3 = 1.0 / r_cut**3
return math.pi * ( (32.0/9.0) * sr3**3 - (16.0/3.0) * sr3 ) * density**2 | 29f74ba1bb522ce80f91c7032fe1e4f46cd92ed8 | 670,290 |
import torch
def load_checkpoint(checkpoint_path, model, optimizer, lr_scheduler, epoch, best_score, best_val_logs):
"""Load training states from a checkpoint file.
Args:
checkpoint_path (srt): path to the checkpoint file to load.
model (torch.nn.Module): model.
optimizer (torch.optim... | 35063b9cddbd6a6f691e27aaa5a7722fc0c7795b | 670,291 |
def check_refs(fn):
"""Decorator to check if required references for an object
are set. If it finds missing references, it will raise an
exception. Example:
@requires("retiring", "bad_speculation", "frontend_bound")
class BackendBound(object):
@check_refs
def _compute(self, ev):
... | f711ac1551b7ce6d73e93537b4034c02710edadc | 670,293 |
def predicate_1(x: int) -> bool:
"""Return true if the integer is 3."""
return x == 3 | 69c78e0478e012a4bed45f52661f8b2561a4eb2c | 670,295 |
def split_train(sequence, numInputs, numOutputs, numJumps):
""" Returns sets to train a model
i.e. X[0] = sequence[0], ..., sequence[numInputs]
y[0] = sequence[numInputs+1], ..., sequence[numInputs+numOutputs]
...
X[k] = sequence[k*numJumps], ..., sequence[k*numJumps+n... | e09f819f24f8136ee231e500d420b0ce336812b5 | 670,296 |
def runtest(name, args):
"""
Run the named test.
"""
print("\x1B[1m:: {} \x1B[0m".format(name))
if name not in globals():
print("ERROR: Unrecognized test: '{}'".format(name))
return
return globals()[name].run(args) | b783e1f4c7d0699f9049dab67bbbbc8baf2f7326 | 670,298 |
def filter_lines(code, line_spec):
"""Removes all lines not matching the line_spec.
Args:
code The code to filter
line_spec The line specification. This should be a comma-separated
string of lines or line ranges, e.g. 1,2,5-12,15
If a line range starts with -... | 931306963eac16f52d33aa045175454302087ab1 | 670,300 |
def max_elements(seq):
"""Return list of position(s) of largest element"""
max_indices = []
if seq:
max_val = seq[0]
for i, val in ((i, val) for i, val in enumerate(seq) if val >= max_val):
if val == max_val:
max_indices.append(i)
else:
... | 14e5322e8be8b452bfa941859702d4d3752e49a9 | 670,302 |
import textwrap
def wrap_text(text, width):
"""
Wraps text to a maximum width, keeping newlines intact.
"""
lines = []
for line in text.split('\n'):
if line:
lines += textwrap.wrap(line, width)
else:
# textwrap ignores empty lines, we want to keep them
... | 5e3cd2864d16dfd76e738583ad54e2e8edc632df | 670,303 |
def isreadable(f):
"""
Returns True if the file-like object can be read from. This is a common-
sense approximation of io.IOBase.readable.
"""
if hasattr(f, 'readable'):
return f.readable()
if hasattr(f, 'closed') and f.closed:
# This mimics the behavior of io.IOBase.readable
... | 04530ed6bc40c19b22c0f3d694cb0418202e2949 | 670,306 |
def find_singleton(input_dict):
"""
Given an input dictionary of sequences, find a length 1 sequence and return its key and element
"""
for key, seq in input_dict.items():
if len(seq) == 1:
return key, seq.pop()
# No length 1 sequence (e.g. singleton set) found in the input dicti... | fa90f4fda369fb532f58307c673f1db25858b685 | 670,308 |
def flat_list(l):
"""
Flattens an input list made by arbitrarily nested lists.
:param l: the input list
:return: the flattened list
"""
if not isinstance(l, list):
return [l]
else:
return [e for k in l for e in flat_list(k)] | 8c76bda73c99d03ddc58bd84071963f184d537a3 | 670,309 |
def get_output_size(height, width, filter_height, filter_width, padding, stride):
"""
return (output_height, output_width)
You can see below by drawing a figure.
height + 2 * padding = filter_height + (output_height - 1) * stride
width + 2 * padding = filter_width + (output_width - 1) * stride
... | e2b346320fd44314db72277e0b8be57bd2af9168 | 670,310 |
def get_image_value(x, y, img):
"""Get pixel value at specified x-y coordinate of image.
Args:
x (int): horizontal pixel coordinate
y (int): vertical pixel coordinate
img (numpy.ndarray): image from which to get get pixel value
Returns:
float: pixel value at specified coord... | 466815a7d84ae76ece32f1da01d2a103086e1e67 | 670,311 |
def str_to_dict(text):
"""
This function converts a string to a dictionary
:type text: string
:param text: string to be converted
String to be converted should be as follow :
string_to_convert="key1:value1,key2:value2..."
result={'key1':'value1', 'key2':'value2'}
:rtype: dic... | 8485f79115131d850950ea4847129f6f7fc82cc2 | 670,314 |
def get_rectangle_point_intersect(rect, pt):
"""Returns the intersection of a rectangle and point.
Parameters
----------
rect : libpysal.cg.Rectangle
A rectangle to check for an intersection.
pt : libpysal.cg.Point
A point to check ``rect`` for an intersection.
Returns
----... | 2db9ffb51343d12abce6c869f43102d80cab08c6 | 670,315 |
import click
def trim_dependent_repos(repos):
"""Remove dependent repos (an obsolete feature of this program).
Repos with 'parent-repo' in their 'openedx-release' data are removed from
the `repos` dict. A new dict of repos is returned.
"""
trimmed = {}
for r, data in repos.items():
... | c5b79edf889d8f2ecbbc6745a527f2bed214dc08 | 670,316 |
def check_keys_exist(vglist,my_keys):
"""
Accepts a list of dicts and checks the specified keys exist in each list element.
"""
for d in vglist:
if not all(key in d for key in my_keys):
return False
return True | c97835c39813dce88370e4679179b61aa8f9e55d | 670,317 |
def has_resistance_heat(heat_type):
"""Determines if the heat type has resistance heating capability
Parameters
----------
heat_type : str
The name of the heating type
Returns
-------
boolean
"""
if heat_type == "heat_pump_electric_backup":
return True
return F... | c93788583ca3a6be49689bd8a7163c2188ca4086 | 670,318 |
def aic(model):
"""Given a model, calculates an AIC score."""
k = model.num_of_params
L = model.lnlikelihood()
return 2*(k-L) | bd8d719537e4e3c2a1e7a6ec97f8237f870b6f5f | 670,320 |
def hex_color_for(rgb):
"""
Convert a 3-element rgb structure to a HTML color definition
"""
opacity_shade = 0.3
return "rgba(%d,%d,%d,%f)" % (rgb[0], rgb[1], rgb[2], opacity_shade) | b360019ba1b744ca7952ae33cef9284da6fa18d3 | 670,326 |
def input_data_job_id(conf):
# type: (dict) -> str
"""Retrieve input data job id
:param dict conf: configuration object
:rtype: str
:return: job id
"""
return conf['job_id'] | b0244719b55dfc9d36f1ecd8a58474d19f982f76 | 670,328 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.