content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def read_file(filename):
"""
This function reads the names of wallpapers out of the configuration
file, filename. Assumed data:
"""
with open(filename, 'r') as f:
file_lines = f.read().split('\n')
if file_lines.count('') != 0:
file_lines.remove('')
return file_lines | db1a1b0673f1889bd65bc921ca72397aeb03d0f8 | 14,606 |
import os
def recReadDir(baseDir, contain = ''):
""" read filenames recursively """
# no dir to expand, return
if len([x for x in baseDir if os.path.isdir(x)]) == 0:
# filter before return results
baseDir = [x for x in baseDir if contain in x]
return baseDir
# expand dirs
o... | 7d18e5cd3243d386eb44481622e5c60ac8f1fde3 | 14,607 |
def dailystats_date_json():
"""Return a /dailystats/<DATE> response."""
return {
"id": 0,
"day": "2018-06-04",
"mint": 12.779999999999999,
"maxt": 33.329999999999998,
"icon": 2,
"percentage": 100,
"wateringFlag": 0,
"vibration": [100, 100, 100, 100... | 7bffa4d1f7d2a00aa51f1cc8929a2cd3383375fe | 14,608 |
def char_fun(A, b):
"""
Returns True if dictionary b is a subset
of dictionary A and False otherwise.
"""
result = b.items() <= A.items()
return result | e8d2f9bc69f1d3b164e5d80a35fca870f66a632a | 14,609 |
def safe_check_lens_eq(arr1, arr2, msg=None):
"""
Check if it is safe to check if two arrays are equal
safe_check_lens_eq(None, 1)
safe_check_lens_eq([3], [2, 4])
"""
if msg is None:
msg = 'outer lengths do not correspond'
if arr1 is None or arr2 is None:
return True
els... | 09163acf03148710f670cda180e7c026f507b0df | 14,610 |
import os
def getArchSpec(architecture):
"""
Helper function to return the key-value string to specify the architecture
used for the make system.
"""
arch = architecture if architecture else None
if not arch and "ARCH" in os.environ:
arch = os.environ["ARCH"]
return ("ARCH=" + arc... | ec27283e79698fb0525d2464836f5ddaaca2d399 | 14,611 |
import random
def generate_exact_cover(num_of_subsets):
"""Generates a new exact cover problem with the given number of random filled subsets"""
subset = set()
while len(subset) < num_of_subsets:
subset.add(frozenset(random.sample(range(1 ,num_of_subsets + 1), random.randint(0, num_of_subsets))))
... | 2e63bdc7181caa312ed42d48578989c8ddc29050 | 14,612 |
def read_long_description(path: str) -> str:
"""Utility function to read the README file."""
with open(path) as file:
data: str = file.read()
return data | c206f2cec2613fde5217845c1e36cd507924716e | 14,613 |
def permute(nums: list[int]) -> list[list[int]]:
"""ALGORITHM"""
# DS's/res
uniq_perms = [[]]
for curr_num in nums:
uniq_perms = [
perm[:insertion_idx] + [curr_num] + perm[insertion_idx:]
for perm in uniq_perms
for insertion_idx in range(len(perm) + 1)
... | 3da21c4bdaf77a1e55c3ece4b90a90d53a3565f7 | 14,614 |
def update_par_helper(row, blocks, add_num):
"""The current function accepts line, line constraint, and integer.The
purpose of the function is to update the parameters it receives (those
parameters which the main function receives) according to the
pointer value. For each of the three possible values, i... | 732bba078066418312c454dd4fbb7132632f25d2 | 14,616 |
def _get_seeds_to_create_not_interpolate_indicator(dense_keys, options):
"""Get seeds for each dense index to mask not interpolated states."""
seeds = {
dense_key: next(options["solution_seed_iteration"]) for dense_key in dense_keys
}
return seeds | e3ee4260309be644f11becba19f1ef3386d182d9 | 14,617 |
def make_bigrams(bigram_mod, texts):
"""Gera bigrama dos textos."""
return [bigram_mod[doc] for doc in texts] | 9ac129f72a5dd4fdf4fb64694073df2482a76a9e | 14,618 |
def _case_convert_snake_to_camel(token: str) -> str:
"""Implements logic to convert a snake case token to a camel case one.
"""
while True:
try:
# find next underscore
underscore_loc = token.index('_')
except ValueError:
# converted all underscores
... | 3796f627cc836f884aeab765769cf652f8fd1ff9 | 14,619 |
def make_reduce_compose(obj, hook_cls, hooks: list):
"""only keeps the overridden methods not the empty ones"""
def _get_loop_fn(fns):
def loop(*args, **kwargs):
for fn in fns:
fn(*args, **kwargs)
return loop
method_list = [func for func in dir(hook_cls)
... | 03cc81714ec1309e2db896d0e59f98ac528f5adb | 14,620 |
def _truncate_float(matchobj, format_str='0.2g'):
"""Truncate long floats
Args:
matchobj (re.Match): contains original float
format_str (str): format specifier
Returns:
str: returns truncated float
"""
if matchobj.group(0):
return format(float(matchobj.group(0)), form... | 7fc4e90e496ea6f04838a1ccefb810c2467fafaf | 14,621 |
import base64
def to_base64(data):
"""
Utility function to base64 encode.
:param data: The data to encode.
:return: The base64 encoded data.
"""
return base64.b64encode(data) | 014ca1e1534e9350034e148abcceac525b0f0349 | 14,622 |
def json_set_check(obj):
"""
json.dump(X,default=json_set_check)
https://stackoverflow.com/questions/22281059/set-object-is-not-json-serializable
"""
if isinstance(obj, set):
return list(obj)
raise TypeError | d8b632c54938aac4797794d5d40fcd93c3415e04 | 14,623 |
import zipfile
def get_pfile_contents(pfile):
"""
Get a list of files within the pfile Archive
"""
if zipfile.is_zipfile(pfile):
zip = zipfile.ZipFile(pfile)
return zip.namelist()
else:
return None | 8f67b87a0e35fe42d0c20cb9ed0c3cdc93a89163 | 14,624 |
def rate(report, rate_type):
"""generate gamma or epsilon rate
report (list of str): diagnostic report
rate_type (str): gamma or epsilon
return: binary result in form of str"""
pre_rate = []
if rate_type == "gamma":
rt = 1
elif rate_type == "epsilon":
rt = -1
else:
... | 3e08ea470bcbdc7805f2f056086f2965aa4bc91f | 14,625 |
import re
def twitter_preprocess(
text: str,
no_rt: bool = True,
no_mention: bool = False,
no_hashtag: bool = False
) -> str:
"""
Preprocessing function to remove retweets, mentions and/or hashtags from
raw tweets.
Examples
--------
>>> twitter_preproce... | 1644b7da6b43ebd77a33bcb186f2634b6d3bc8db | 14,628 |
def calculate_diff_metrics(util1, util2):
"""Calculate relative difference between two utilities"""
util_diff = {}
for metric_k1, metric_v1 in util1.items():
if metric_k1 not in util2:
continue
util_diff[metric_k1] = {}
for avg_k1, avg_v1 in metric_v1.items():
... | 45b8dc7a2441333870c8a0faa5b6e8da56df8a40 | 14,629 |
def rpht_output(file_name):
""" Read the projected frequencies
"""
# Read the file and read in the non-zero frequencies
freqs = []
with open(file_name, 'r') as freq_file:
for line in freq_file:
if line.strip() != '':
freqs.append(float(line.strip()))
# Build... | e2f7e181f68c23be276588e662dd7db9f7355270 | 14,630 |
from typing import List
from typing import Tuple
import re
def extract_format_items(s: str) -> List[Tuple[int, str]]:
"""Return a list (index, format item) pairs from a c-style format string.
Based on:
https://stackoverflow.com/questions/30011379/how-can-i-parse-a-c-format-string-in-python
"""
c... | 93ce59d40dd60772a9ea6235c945a17d71ca07d0 | 14,633 |
def text_progress(current, total):
"""Opens the photo_import_settings.json file in a text editor
Parameters:
current (String): The currently completed progress
total (String): The total amount
Returns:
progress (String): A formatted string with the current progress [current/total]... | b04b5bf018ff96c2e0f4ed5f1ce60c20c21e9574 | 14,634 |
def _householder_factor(newton, halley, hh3):
"""
:param newton:
:param halley:
:param hh3:
:return:
"""
return (1 + 0.5 * halley * newton) / (1 + newton * (halley + hh3 * newton / 6)) | 373e3155557a2403ec79e78a5239d54f2ca651f5 | 14,635 |
def toy_reward(config):
""" The reward function to maximize (ie. returns performance from a fake training trial).
Args:
config: dict() object defined in unit-test, not ConfigSpace object.
"""
reward = 10*config['b'] + config['c']
reward *= 30**config['a']
if config['d'] == '... | cc8ae7dfc31c8867fd1fb14720521d0b52e11074 | 14,636 |
def compute_length(of_this):
"""
Of_this is a dict of listlikes. This function computes the length of that object, which is the length of all of the listlikes, which
are assumed to be equal. This also implicitly checks for the lengths to be equal, which is necessary for Message/TensorMessage.
"""
le... | 4f8e2b3b17ba6bed29e5636de504d05a028304d8 | 14,637 |
import socket
def client(
host: str,
port: str,
use_sctp: bool = False,
ipv6: bool = False,
buffer_size: int = 4096,
timeout: float = 5.0
) -> int:
"""Main program to run client for remote shell execution
:param host: Server name or ip address
:type host: str
:param port: Port on which server listens, c... | 196de595f6d6573c6bc1a2b2209688060b246cdc | 14,638 |
def gamma_approx(mean, variance):
"""
Returns alpha and beta of a gamma distribution for a given mean and variance
"""
return (mean ** 2) / variance, mean / variance | 8103a69d807c39c95c1604d48f16ec74761234c4 | 14,639 |
def public_coverage_filter(data):
"""
Filters for the public health insurance prediction task; focus on low income Americans, and those not eligible for Medicare
"""
df = data
df = df[df['AGEP'] < 65]
df = df[df['PINCP'] <= 30000]
return df | e8a579437fe484a738deefe6b32defaf405b5a58 | 14,641 |
def get_snippet(soup):
"""obtain snippet from soup
:param soup: parsed html by BeautifulSoup
:return: snippet_list
"""
tags = soup.find_all("div", {"class": "gs_rs"})
snippet_list = [tags[i].text for i in range(len(tags))]
return snippet_list | 8955aa6eee837f6b1473b8de2d02083d35c3b46e | 14,642 |
import yaml
def read_config(file_name="config.yaml"):
"""Read configurations.
Args:
file_name (str): file name
Returns:
configs (dict): dictionary of configurations
"""
with open(file_name, 'r') as f:
config = yaml.safe_load(f)
return config | 51faf47b4c28d1cbf80631d743d9087430efb148 | 14,643 |
def filter_dual_selection_aromatic(sele1_atoms, sele2_atoms, aromatic1_index, aromatic2_index):
"""
Filter out aromatic interactions that are not between selection 1 and selection 2
Parameters
----------
sele1_atoms: list
List of atom label strings for all atoms in selection 1
sele2_at... | b1cb590510e45b0bfb5386e1514f24911156d01b | 14,645 |
def no_numbers(data: str):
"""
Checks whether data contain numbers.
:param data: text line to be checked
:return: True if the line does not contain any numbers
"""
numbers = "0123456789"
for c in data:
if c in numbers:
return False
return True | d6f0f306c980da2985d906fa0eaee96d2f598e7b | 14,648 |
def splinter_webdriver():
"""Use Chrome, which is simpler to launch in headless mode.
Firefox needs the Gecko driver to be manually installed first.
Moreover, as of 22/07/2018, Firefox in headless mode is not yet
available in python:3.6-alpine3.7 (version 52).
"""
return 'chrome' | 6586567f423c12475b2a084d9945667bc34636bc | 14,649 |
def lung_capacity(mass):
"""Caclulate lung capacity
Args
----
mass: float
Mass of animal
Return
------
volume: float
Lung volume of animal
References
----------
Kooyman, G.L., Sinnett, E.E., 1979. Mechanical properties of the harbor
porpoise lung, Phocoena ... | 75bddd298ad7df69cda6c78e2353ee4cef22865a | 14,651 |
def correlation_calculator(x_points: list[float], y_points: list[float]) -> float:
"""Return a correlation of the association between the x and y variables
We can use this to judge the association between our x and y variables to determine if
we can even use linear regression. Linear regression assumes tha... | 3fa697a15ff86511cff2a1b37b532f3d14caf7d8 | 14,652 |
async def database_feeds(db):
"""Get database metrics pertaining to feeds"""
metrics = {
"database_feeds_count_total": await db.feeds.count(),
"database_feeds_status_error_total": 0,
"database_feeds_status_unreachable_total": 0,
"database_feeds_status_inaccessible_total": 0,
... | c7ebbda9acc37edafb22103395904c2863379cf6 | 14,653 |
import math
def count_ctdd(aa_set, sequence):
"""
helper function for ctdd encoding
:param aa_set:
:param sequence:
:return:
"""
number = 0
for aa in sequence:
if aa in aa_set:
number = number + 1
cutoffNums = [1, math.floor(0.25 * number), math.floor(0.50 * num... | bc4f55855794d073397b471652e8dbab18520d1b | 14,654 |
def generate_where_in_clause(field_name, feature_list):
"""
Args:
field_name (str): Name of column to query
feature_list (list): List of values to generate IN clause
Returns:
string e.g. `WHERE name IN ('a' ,'b', 'c')`
"""
# Build up 'IN' clause for searching
where_str = f"... | d00179cfa6a9841b00195b99863d7b37f60c45e4 | 14,655 |
def set_username(strategy, details, user, social, *args, **kwargs):
"""This pipeline function can be used to set UserProfile.has_username_set = True
Normally not used if the auto-generated username is ugly
"""
if not user:
return None
response = None
if hasattr(user, 'profile'):
... | 1c217a8c0b75e2acb38c06b8f9cefdf70e272e91 | 14,656 |
import requests
def get_wait_time(token):
"""
The item in entries schema:
{
u'waitTime': {
u'status': u'Down', # or u'Operating'
u'postedWaitMinutes': 5,
u'fastPass': {
u'available': True,
u'endTime':... | d3915ee70c83b6eae0f2b491c99010bf2ee79754 | 14,657 |
def _zero_out_datetime(dt, unit):
"""To fix a super obnoxious issue where datetrunc (or SQLAlchemy) would
break up resulting values if provided a datetime with nonzero values more
granular than datetrunc expects. Ex. calling datetrunc('hour', ...) with
a datetime such as 2016-09-20 08:12:12.
Note t... | adac3a5c84b0b7def93c044488afb57074cf2d09 | 14,660 |
def fitness_score_distance(id1, id2, to_consider, distance):
"""A value to choose between two resources considering the distance"""
return max(distance(id1,to_consider), distance(to_consider, id2))/distance(id1,id2) | ab6dd14f0e3ac3ef5b26abe3136ff5a61c3b74a5 | 14,661 |
import pandas
def update_context(df_context) -> pandas.DataFrame:
"""replaces unspecified air and water flows for impact categories that
don't rely on sub-compartments for characterization factor selection."""
single_context = ['Freshwater acidification',
'Terrestrial acidification... | 5fb3420e5af4bfd10653b8246c370ab5ed5ec254 | 14,664 |
import math
def ln(x):
"""
x est un nombre strictement positif.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Retourne l'image du nombre x par la fonction logarithme népérien.
"""
return math.log(x) | 3612dce0120c6b8b3d4176f1883ee8fb1694d7f4 | 14,665 |
import os
def find_file_named(root, name):
"""
Find a file named something
:param root: Root directory to search recursively through
:param name: The name of the file to search for
:return: Full path to the (first!) file with the specified name found,
or None if no file was found of that name... | f914dab8a0e775f3033047e368e75ff408294be0 | 14,666 |
def remove(S, rack):
"""removes only one instance of a letter in a rack"""
if rack == []:
return []
if S == rack[0]:
return rack[1:]
return [rack[0]] + remove(S, rack[1:]) | 28041197da6a7978dacbfe65d413d4e6fd9c3a03 | 14,668 |
from typing import Iterable
from typing import Any
from typing import Union
from typing import List
def remove_from_iterable(
the_iterable: Iterable[Any], items_to_remove: Iterable[Any]
) -> Union[Iterable[Any], None]:
"""
remove_from_iterable removes any items in items_to_remove from the_iterable.
:... | 9ac800fb69f46c8b65ed2ac73158678b4c0ae7d6 | 14,669 |
def import_data(filename):
""" Take data from txt file"""
dataset = list()
with open(filename) as f:
lines = f.readlines()
for line in lines:
dataset.append(line.split())
return dataset | d360506f2015f31b09dbac632427390eca10cf1b | 14,670 |
def to_bytes(data: str):
"""
将unicode字符串转换为bytes
"""
try:
bytes_data = data.encode("GBK")
return bytes_data
except AttributeError:
return data | 9a3777d5ec52daa0a063a089c42943abf4e5c8a9 | 14,671 |
import re
def find_config_file_line_number(path: str, section: str, setting_name: str) -> int:
"""Return the approximate location of setting_name within mypy config file.
Return -1 if can't determine the line unambiguously.
"""
in_desired_section = False
try:
results = []
with ope... | 03b1f77b051f260471653df6e7ddd7a599c8e100 | 14,672 |
def flatten_nested_list(l):
"""Flattens a list and provides a mapping from elements in the list back
into the nested list.
Args:
l: A list of lists.
Returns:
A tuple (flattened, index_to_position):
flattened: The flattened list.
index_to_position: A list of pairs (r, c) such that
... | 14e20ef2a29dc338a4d706e0b2110a56447ae84e | 14,676 |
def get_owner_email_from_domain(domain):
"""Look up the owner email address for a given domain.
Returning dummy addresses here - implement your own domain->email lookup here.
Returns:
str: email address
"""
email = {
'example-domain-a.example.com': 'owner-a@example.com',
'ex... | 2d3851c87c5ba3c19af4c989887bf750b66ffbe1 | 14,677 |
def stringify_dict(d):
"""create a pretty version of arguments for printing"""
if 'self' in d:
del d['self']
s = 'Arguments:\n'
for k in d:
if not isinstance(d[k], str):
d[k] = str(d[k])
s = s + '%s: %s\n' % (k, d[k])
return(s) | e79220bf7d1d769f5408cd0532ea97390ad35541 | 14,679 |
def rules(host, _args, _old_graph, graph, _started_time):
"""list all the rules"""
for rule_name in sorted(graph.rules):
host.print_out("%s %s" % (rule_name,
graph.rules[rule_name]['command']))
return 0 | c4d094a90634101b754debde637685b95fcde556 | 14,680 |
import torch
def linear_regression(X, Y=None, order=None, X_test=None):
"""Closed form linear regression
"""
if X.dim() == 1:
X = X.unsqueeze(1)
if Y is None:
if order is None:
beta_left = torch.matmul(torch.matmul(X.t(), X).inverse(), X.t())
return beta_left
... | 07420512f176955b394aeaa67a0eb0add168b38d | 14,682 |
def extract_secondary_keys_from_form(form):
"""Extracts text (autocomplete capable) secondary keys list from Indexes form.
@param form: is a MUI secondary indexes form object (Django Form() object)"""
keys_list = []
for field_id, field in form.fields.iteritems():
if 'field_name' in field.__dict... | bf73217293f379257f7e8f0ab33b45d735b04edb | 14,683 |
def update_name(name, mapping):
""" Update the street name using the mapping dictionary. """
for target_name in mapping:
if name.find(target_name) != -1:
a = name[:name.find(target_name)]
b = mapping[target_name]
c = name[name.find(target_name)+len(target_name):]
... | 8046fc9ef83f262251fac1a3e540a607d7ed39b9 | 14,684 |
import re
def annotation_version(repo, tag_avail):
"""Generates the string used in Git tag annotations."""
match = re.match("^(.*)-build([0-9]+)$", tag_avail[repo.git()]["build_tag"])
if match is None:
return "%s version %s." % (repo.git(), tag_avail[repo.git()]["build_tag"])
else:
re... | 484eada27b698c2d7a9236d7b86ea6c53050e1e8 | 14,685 |
import math
def _scale_absolute_gap(gap, scale):
"""Convert an absolute gap to a relative gap with the
given scaling factor."""
assert scale > 0
if not math.isinf(gap):
return gap / scale
else:
return gap | 29c1b03e53c66bf7728066ff3503118a266acd3d | 14,686 |
def yolo_label_format(size, box):
"""
Rule to convert anchors to YOLO label format
Expects the box to have (xmin, ymin, xmax, ymax)
:param size: Height and width of the image as a list
:param box: the four corners of the bounding box as a list
:return: YOLO style labels
"""
dw = 1. /... | c958f75ffe3de8462ed25c5eb27bcaa21d52c46c | 14,688 |
def upload_dir(app, filename):
""" Returns the upload path for applications.
The end result will be something like:
"uploads/applications/Firefox/icons/firefox.png"
"""
path = ('applications/' + app.name + '/icons/' + filename)
# Note: if the file already exist in the same path, django will... | e188c6c11733e0b88313c65b6be67c8db2fd69a9 | 14,689 |
import itertools
def get_elements_by_attr(xml_node, attribute, value):
"""helper function for xml trees when using minidom"""
def recur_get_element_by_attr(xml_node, attribute, value):
if xml_node.attributes:
test_list = xml_node.attributes.keys()
if attribute in test_list:
... | 8ea494665393cc6c885ad4f611dbf0c3302617b2 | 14,690 |
def is_instance_id(instance):
""" Return True if the user input is an instance ID instead of a name """
if instance[:2] == 'i-':
return True
return False | f4389c340b21c6b5e0f29babe49c556bd4b4c120 | 14,692 |
def readiness() -> tuple[str, int]:
"""A basic healthcheck. Returns 200 to indicate flask is running"""
return 'ready', 200 | de1072809a32583a62229e390ea11f6b21f33b1e | 14,694 |
def name_sep_val(mm, name, sep='=', dtype=float, ipos=1):
"""Read key-value pair such as "name = value"
Args:
mm (mmap): memory map
name (str): name of variable; used to find value line
sep (str, optional): separator, default '='
dtype (type, optional): variable data type, default float
ipos (i... | 4eee14e88ca2a6f43cb1b046de239c6847d57931 | 14,695 |
def remove_inactive(batch, live_bus, sim=False):
##### CHANGE ARGS NAMING CONVENTION #####
"""
remove buses from live_bus absent in the new stream batch
sim: stream_batch -> live_bus [FALSE]
live_bus -> active_bus [TRUE]
FUTURE: also remove ones that reaches the last stop
"""
if sim... | 404373b5c3fe607af667bb388ba41737704ae164 | 14,696 |
def binary_search_two_pointers_recur(sorted_nums, target, left, right):
"""Util for binary_search_feast_recur()."""
# Edge case.
if left > right:
return False
# Compare middle number and recursively search left or right part.
mid = left + (right - left) // 2
if sorted_nums[mid] == targ... | 553c6217b29f3507290a9e49cd0ebd6acaccec63 | 14,697 |
def _decode_list(vals):
""" List decoder
"""
return [l.decode() if hasattr(l, 'decode') else l for l in vals] | b0018f40628e64132c62095a5d87f84d5b0d7323 | 14,698 |
def extract_class(query):
"""Extract original class object from a SQLAlchemy query.
Args:
query (query): SQLAlchemy query
Returns:
class: base class use when setting up the SQL query
"""
first_expression = query.column_descriptions[0]['expr']
try:
# query returns subset of columns as tuples
... | 48bfec4301c752c68bda613334dcb7dfc17f3f15 | 14,699 |
def get_restore_user(domain, couch_user, as_user_obj):
"""
This will retrieve the restore_user from the couch_user or the as_user_obj
if specified
:param domain: Domain of restore
:param couch_user: The couch user attempting authentication
:param as_user_obj: The user that the couch_user is atte... | 09ad1783236860779064f2929bb91c05915cdd6e | 14,700 |
import os
import fnmatch
def has_html(folder_path):
"""Simple function that counts .html files and returns a binary:
'True' if a specified folder has any .html files in it, 'False' otherwise."""
html_list = []
for dirpath,dirnames,filenames in os.walk(folder_path):
for file in fnmatch.fil... | 44b262c7ea3f51078d234e9f65e007cf30cea8e8 | 14,701 |
def capitalize_column_names(dataframe):
"""Capitalize column names of the model's input dataframe.
Keep column names consistent with the dataframe used for
training the model."""
dataframe.columns = [x.upper() for x in dataframe.columns]
cols = []
for col in dataframe.columns:
if col.en... | 52486a58b72099ebd73c38876604743a386905fe | 14,702 |
from tempfile import mkdtemp
def create_temporary_directory(prefix_dir=None):
"""Creates a temporary directory and returns its location"""
return mkdtemp(prefix='bloom_', dir=prefix_dir) | b2a1ddeb8bcaa84532475e3f365ab6ce649cd50c | 14,705 |
def get_num_clones(pop_size, clone_factor):
"""
:param pop_size: 100
:param clone_factor: 0.1
:return:
"""
return int(pop_size * clone_factor) | 2cc9639b4aa598793d305980ad76aecb59157f8b | 14,706 |
import random
import string
import uuid
def create_customer():
"""
Create a customer entity.
:return: A dict with the entity properties.
"""
name = "".join(random.choice(string.ascii_lowercase) for _ in range(10))
return {
'entity_id': str(uuid.uuid4()),
'name': name.title(),... | 48434187249164992d81694070f027f5ca8b862c | 14,707 |
from typing import Sequence
def in_bbox(point: Sequence, bbox: Sequence):
"""
Checks if point is inside bbox
:param point: point coordinates [lng, lat]
:param bbox: bbox [west, south, east, north]
:return: True if point is inside, False otherwise
"""
return bbox[0] <= point[0] <= bbox[2] ... | fb95e2506adee4ff425997a0211ee53095894f35 | 14,708 |
def group(extracted_iter, sample_names, gene_ids):
"""Given the raw dictionary results, group into per-sample,
per-gene dictionary."""
samples = {s: {} for s in sample_names}
dns = ("vep", "varscan")
for lined in extracted_iter:
for sampled in lined:
sample = sampled["sample"]
... | 1e5360a5d67636c46f60bcb440ef6c6d185b94de | 14,709 |
import subprocess
def has_latex():
"""Return whether the 'latex' command is available on the system."""
try:
subprocess.check_output(['latex', '--version'])
return True
except OSError:
return False | d8808cf17da9c24c0ff588449cbf01cf036cfbfd | 14,713 |
def _FinalElement(key):
"""Return final element of a key's path."""
return key.path().element_list()[-1] | 80ecac3fe3eb3d2587d64dd759af10dcddb399fe | 14,714 |
def cs_metadata(cursor, cs_id):
"""Get metadata for a given ``cs_id`` in a NEPC database.
Parameters
----------
cursor : cursor.MySQLCursor
A MySQLCursor object. See return value ``cursor`` of :func:`.connect`.
cs_id : int
The ``cs_id`` for a cross section dataset in the NEPC databa... | 57262d8e22be7cf9166d4edd0a658fe4662f68f6 | 14,715 |
import torch
from typing import Optional
def clamp(data: torch.Tensor, min: float, max: float, out: Optional[torch.Tensor] = None) -> torch.Tensor:
"""
Clamp tensor to minimal and maximal value
Args:
data: tensor to clamp
min: lower limit
max: upper limit
out: output tenso... | 3e835f134fd9eedefb5ca7841d8c3a9960063389 | 14,716 |
def clean_command_level(text: str) -> str:
"""Remove parents from the command level"""
return text.replace("Command.", "") | 0fbe2a82fa9f802e2e2118c5adb6dd5057a3f490 | 14,718 |
import json
def export_to_json(dict_data,e):
"""Fonction export au format json"""
try:
with open(e.path, "w") as outfile:
json.dump(dict_data, outfile)
return True
except IOError:
return False | b18d6c9ecebb83a4f69514af381e6a01f5a4529c | 14,720 |
def rtiInputFixture(rtiConnectorFixture):
"""
This `pytest fixture <https://pytest.org/latest/fixture.html>`_
creates a session-scoped :class:`rticonnextdds_connector.Input` object
which is returned everytime this fixture method is referred.
The initialized Input object is cleaned up at the end
of a testing... | b9fbd841e1640fb77b2991583a2b167e714a0a7b | 14,721 |
from functools import reduce
from operator import mul
def multiply(*args):
"""\
这里可以写单元测试
>>> multiply(2,3)
6
>>> multiply('baka~',3)
'baka~baka~baka~'
"""
return reduce(mul,args) | c09f240ce67192e5d079569c75e2c1d852b6d0e7 | 14,723 |
def unfreeze_net(net):
"""
Unfreezing all net to make all params trainable
Args:
net: net to unfreeze
Returns:
unfreezed net
"""
print("SystemLog: Unfreezing all net to make all params trainable")
for p in net.parameters():
p.requires_grad = True
return net | a3deb31271c34c072c59f609f6520a29be8979ed | 14,724 |
import binascii
def base64(data):
"""
Get base64 string (1 line) from binary "data".
:param (bytes, bytearray) data: Data to format.
:raises TypeError: Raises an error if the data is not a bytearray of bytes
instance
:return str: Empty string if this failed, otherwise the base64 encoded
... | a51e138beddb788c248c5f2423b3fde2faacdb63 | 14,725 |
def split_name_version(script_name):
""" 返回分割的脚本名称,版本。"""
name_version = script_name.rsplit('-', 1)
if len(name_version) == 1:
name, version = name_version[0], None
else:
name, version = name_version
try:
version = float(version)
except ValueError:
... | 7ca30aa26eb07faa75f206574d083c7f13f89625 | 14,728 |
import time
def set_time_stamp(actual_log_size, log_file):
"""
Write the time stamp for each sample of cpu performance to the file
:param actual_log_size: Number of
:param log_file: log_file_pointer
:return:
"""
if(log_file):
time_stamp = "[ " + str(time.time()) + " ]\n"
lo... | 668b40b3a3b689cb96e483b74dd38f517b3cc0e1 | 14,729 |
def RotorAndMagnetsDesign(main):
"""Definition of the rotor and magnets design on ANSYS.
Args:
main (Dic): Contains the parameters of the rotor and magnets design.
Returns:
Dic: The same input dont modified only is readed by the following lines.
"""
# oEditor definition
oEdito... | 03c83eaf8ca28514cf836119ee45c7befd4fed7d | 14,730 |
def get_exp_data(diff_fname):
"""
Parse genes with differential expression score.
The file expects genes with a score in a tab delimited format.
"""
gene_exp_rate=dict()
dfh=open(diff_fname, "rU")
for line in dfh:
parts=line.strip('\n\r').split('\t')
try:
float(pa... | b376f9e8f42ed2e1f3c0209696de7e85b8bed082 | 14,732 |
import time
def timestamp() -> float:
"""
Returns fractional seconds of a performance counter.
It does include time elapsed during sleep and is system-wide
Note: The reference point of the returned value is undefined,
so that only the difference between the results of two calls is valid.
Ret... | e2c4d8c06d8d07ca67ec4f857a464afde19b6c2a | 14,734 |
def verify_user_prediction(user_inputs_dic: dict, correct_definition_dic: dict):
"""
Verifies user prediction json against correct json definition
returns true if correct format, false if not
"""
if user_inputs_dic.keys() != correct_definition_dic.keys():
return False
for user_key, use... | de1d2b579ab312929f64196467a3e08874a5be42 | 14,735 |
def _maybe_format_css_class(val: str, prefix: str = ""):
"""
Create a CSS class name for the given string if it is safe to do so.
Otherwise return nothing
"""
if val.replace("-", "_").isidentifier():
return f"{prefix}{val}"
return "" | c5c615b9e0894807a020186cdade9c031f904c06 | 14,736 |
import string
def rhyme_codes_to_letters(rhymes, unrhymed_verse_symbol="-"):
"""Reorder rhyme letters so first rhyme is always an 'a'."""
sorted_rhymes = []
letters = {}
for rhyme in rhymes:
if rhyme < 0: # unrhymed verse
rhyme_letter = unrhymed_verse_symbol
else:
... | f0cbeac514be1f67e2487cf1fe267445a89d1485 | 14,737 |
def to_days(astring, unit):
""" No weeks in QUDT unit library: days or years """
factors = {
"week": 7.0, "weeks": 7.0,
"Week": 7.0, "Weeks": 7.0,
"day": 1.0, "Day": 1.0,
"days": 1.0, "Days": 1.0,
... | b3cb66d0db77c394aa932aba8200c116f7eae6ae | 14,738 |
def get_text(soup, file_path):
"""Read in a soup object and path to the soup source file,
and return an object with the record's text content"""
text = ""
text_soup = soup.find('div', {'id': 'Text2'})
for o in text_soup.findAll(text=True):
text += o.strip() + "\n"
return {
"text": text
} | 764d3751742584c657613f5c2d00ef544a060a1d | 14,740 |
def get_item_from_list_by_key_value(items, key, value):
"""Get the item from list containing sequence of dicts."""
for item in items:
if item[key] == value:
return item
return None | fcf70b8fccebfc2995fb4fec903559bc587b4576 | 14,742 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.