content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import uuid
def random_string(string_length=10):
"""
:param string_length:
:return:
"""
random = str(uuid.uuid4())
random = random.replace("-","")
return random[0:string_length] | 331ec9cc1a7e699fd993f13209f8f0d8ac5ba503 | 656,460 |
import time
def utcut2dow(ut):
"""UTC UT -> day-of-week: 0..6 (Mon..Sun)."""
return time.gmtime(ut).tm_wday | 993c3ada97e9cea0ff96ebc0d16f5db8e8acdb97 | 656,462 |
import torch
def create_random_input(batch_size, n_features, gate, n_parameters,
seed=0, x_func=torch.randn, par_func=torch.randn):
"""Create input, parameters and gates.
Parameters
----------
gate : bool
If False, the returned gate will be None.
"""
# Make su... | 5acaae3851421b84a892a9efe32dc2f71c05184b | 656,463 |
import torch
def _safe_det_3x3(t: torch.Tensor):
"""
Fast determinant calculation for a batch of 3x3 matrices.
Note, result of this function might not be the same as `torch.det()`.
The differences might be in the last significant digit.
Args:
t: Tensor of shape (N, 3, 3).
Returns:
... | 24f326d520cdb55ed4332c5542226c188260472f | 656,464 |
import cProfile
def run_with_profile(func, *args, **kwargs):
"""Show reuslts and time profile using cProfile."""
prof = cProfile.Profile()
res = prof.runcall(func, *args, **kwargs)
prof.print_stats()
return res | 5fc1f3500a0cc81fac291cac50e00f69b33e02f0 | 656,465 |
def _relax_additional_properties(obj):
"""relax any `additionalProperties`"""
if isinstance(obj, dict):
for key, value in obj.items():
if key == 'additionalProperties':
value = True
else:
value = _relax_additional_properties(value)
obj[... | 257ebaa31a65035d12badcb25604f59726e6e2e0 | 656,466 |
import types
from typing import Sequence
from typing import Tuple
def get_public_symbols(
root_module: types.ModuleType) -> Sequence[Tuple[str, types.FunctionType]]:
"""Returns `(symbol_name, symbol)` for all symbols of `root_module`."""
fns = []
for name in getattr(root_module, "__all__"):
o = getattr(... | 7ad0c30e48a80650429cf7e07a6625cdfc31faa5 | 656,467 |
def bud_cons(c1, r, e1, e2):
""" Defines the budget constraint
e = e1 + e2/(1+r) is total endowment
"""
e = e1 + e2/(1+r)
return e*(1+r) - c1*(1+r) | e80657afde4578d7ceeaa3788ace1d6ac9bbbc63 | 656,468 |
def initialize_data_dict():
"""Initialize a Python dictionary containing the data for the UI"""
data_dict = {}
data_dict["HEADER"] = ["Performance indicator", "", ["Peak years", "Mid years", "Tail years", "Total"]]
data_dict["H2_utilized"] = ["H<sub>2</sub> consumption (ton)", "Accumulated hydrogen... | abd3f987e49a12fa00547951f23cb6ef3a586c31 | 656,469 |
def fibonacci_memoization(n):
"""Memoization implementation of fibonacci. O(n) runtime, O(n) max stack frames, O(n) pre-allocated space"""
d = [0] * (n + 1)
d[1] = 1
d[2] = 1
def fibonacci_memoization_helper(k):
if d[k] == 0:
d[k] = fibonacci_memoization_helper(k - 1) + fibonacc... | 82a607ce77dce1248a4de091129887676b28f438 | 656,470 |
def analyse_sample_attributes(sample):
""" To find sample attributes
Attributes:
min_position_value - [index, value]
max_position_value - [index, value]
up_or_down - up
- down
- variates
"""
attributes = {
"min_position_value": [... | ae7ee750693bfaeced69350a39e5b0b79dcf8f5e | 656,471 |
def get_account_emails(es_client, active_since=None, index="cas-credit-accounts"):
"""Returns account ids (active since a given date)"""
query = {"index": index, "size": 1000, "body": {}}
if active_since is not None:
query["body"]["query"] = {
"range": {"last_charge_date": {"gte": str(a... | 2aa17dc4c0aa4986b75e32d74fc5a2cc6ab19edf | 656,472 |
def with_metaclass(meta, *bases):
"""Compatible metaclass
:param meta: the metaclass
:param *bases: base classes
"""
print("with_metaclass")
return meta('temp_class', bases, {}) | fab1eff17c56da956a7aa4629cc710bf50ddbebb | 656,474 |
import importlib
def get_absolute_path_from_module_source(module: str) -> str:
"""Get a directory path from module source.
E.g. `zenml.core.step` will return `full/path/to/zenml/core/step`.
Args:
module: A module e.g. `zenml.core.step`.
"""
mod = importlib.import_module(module)
retur... | 3c089e7cc6e73b7490382ab9d4f5af0ad97c9f20 | 656,475 |
def write_peak_bedtool_string(cluster):
"""
Format Peak into NarrowBed format
:param cluster: Peak object
:return: str, format to NarrowBed format with tab-delimited, [chrom, start, stop, name, pval, strand, thick_start, thick_stop]
"""
cluster_info_list = [
cluster.chrom,
cluste... | 2890e478549a2a0e63d3056ce92397669697ce7b | 656,476 |
def save_kv_pairs(sreg, obj, qd, prefix):
"""
Look for keyvalue pairs in a query dict that match a certain prefix and
save them to obj's keyvalue store. This function doesn't catch exceptions.
If the key=='host_name' and value==fqdn, we don't need to save the key
because its the default.
"""
... | 1d4730bcc3f830a1308a80107d9e2a8e5f10a330 | 656,477 |
def check_rules(metrics_sequence: list, rules: list, best_so_far: dict, init_metr: dict, metric_names: list, cur_gc: int) -> tuple:
"""Checks custom conditions and adds/removes available metrics.
For each rule, we check the condition.
If it is true - we apply the action and remove the rule.
Args:
... | a0c21d6042c5e2a037f04d1d0e8f2bcb92eeff60 | 656,478 |
def map_structure(op, *param_dicts):
""" For a series of identically structured dicts, apply op to every same set of entries and return a single dict
of the same shape """
ret = {}
for k in param_dicts[0].keys():
ret[k] = op(*[param_dicts[i][k] for i in range(len(param_dicts))])
return ret | 60b047c78e772ba17a4c1fb73577184f983b32a3 | 656,479 |
def remove_empty_string_list(str_list):
"""
Removes any empty strings from a list of strings
:param str_list: List of strings
:return: List of strings without the empty strings
"""
return list(filter(None, str_list)) | d268796d753bdf34a29c44b76a68b1d032b50997 | 656,480 |
import math
def summer(n_terms, n_words):
""" Computed as log(log(t)) / log(log(w)), where t is the number of unique terms/vocab, and
w is the total number of words.
(Summer 1966)
"""
try:
math.log(math.log(n_terms)) / math.log(math.log(n_words))
except ValueError:
retu... | 97f6faa148c1a0746177fd70f4c0e1760ac84a64 | 656,481 |
from datetime import datetime
def sanitize_rrule(vevent):
"""fix problems with RRULE:UNTIL"""
if 'rrule' in vevent and 'UNTIL' in vevent['rrule']:
until = vevent['rrule']['UNTIL'][0]
dtstart = vevent['dtstart'].dt
# DTSTART is date, UNTIL is datetime
if not isinstance(dtstart, ... | 24cbb07f5c1ef41b53651b165aa8e4fd1d38dfc0 | 656,482 |
import re
def upper_to_under(var):
"""
Insert underscore before upper case letter followed by lower case letter and lower case all sentence.
"""
return re.sub('([a-z0-9])([A-Z])', r'\1_\2', re.sub('(.)([A-Z][a-z]+)', r'\1_\2', var)).lower() | 69e0b1f6b6d40688c9eac91e8026b1f1b7991a75 | 656,483 |
def compress(s: str) -> str:
"""
Compress `s` by dropping spaces before ' ,.' characters and
ensuring there is exactly one space before question mark
"""
dest = ""
for a, b in zip(s, s[1:]):
if a == ' ' and b in " ,.":
pass # do not append to dest
elif a != ' ' and b == '?':
dest += a + ' '
else:
d... | 306d088eff7ea9fd89e57ec5df79c3244d0295e9 | 656,485 |
from datetime import datetime
import pytz
def to_iso_time(timestamp):
"""Receives an arbitrary timestamp in UTC format (most likely in unix timestamp) and returns it as ISO-format.
:param timestamp: arbitrary timestamp
:return: timestamp in ISO 8601 and UTC timezone
"""
if isinstance(timestamp, (... | b180dd0f7ff581121b4f8f5ea0574e6df6825a42 | 656,486 |
def get_fields(feature):
"""Return a dict with all fields in the given feature.
feature - an OGR feature.
Returns an assembled python dict with a mapping of
fieldname -> fieldvalue"""
fields = {}
for i in range(feature.GetFieldCount()):
field_def = feature... | 5a9779fd74244fbd9b9611bb6158fce09bdba1b8 | 656,487 |
def calcChecksum(data):
"""
Calculate a checksum
"""
checksum = 0
for a in range(len(data)):
checksum += data[a]
return checksum.to_bytes(3, 'big') | 2b92932df6efd40683e5fc4265cbc5f87a608a06 | 656,488 |
import argparse
import ast
def cmdline_args():
"""Parse command line arguments
Returns:
[type]: Argparser values
"""
# Make parser object
p = argparse.ArgumentParser(
description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter,
)
p.add_argument("confi... | 0a51e58214d7af887fcd6ff309e95364e0e4fe6d | 656,489 |
def _format_inputs(x):
"""Transform inputs into (m,n,1) format for cost/activation functions.
Returns formatted array.
"""
if x.ndim == 1: # vector
return x.reshape(1, -1, 1)
elif x.ndim == 2:
if x.shape[0] == 1: # either single-row matrix or 1x1 matrix
return x.T.resh... | 106328e5c2612e64f385d5750b5ef1429a1b7778 | 656,490 |
def _GetPrincipleQuantumNumber(atNum):
"""
Get the principle quantum number of atom with atomic
number equal to atNum
"""
if atNum<=2:
return 1
elif atNum<=10:
return 2
elif atNum<=18:
return 3
elif atNum<=36:
return 4
elif atNum<=54:
return 5... | 3dc3b41e6e31ab61608e7e4138a88c017a19fb94 | 656,491 |
from typing import List
import os
def has_experiment_run(
save_dir: str, experiment_name: str, run_names: List[str]
) -> bool:
""" Verifies that the experiment ran for all run names """
base_path = f"{save_dir}/{experiment_name}"
for run_name in run_names:
if not os.path.exists(f"{base_path}/{... | 1d2dcec0e21b82a35caad49d8ce175b8f5a31df3 | 656,492 |
import re
def bash_newliner(line_decode,log=None):
"""Handle weird newlines in BASH streams."""
# note that sometimes we get a "\r\n" or "^M"-style newline
# which makes the output appear inconsistent (some lines are prefixed) so we
# replace newlines, but only if we are also reporting the log file on the li... | b027c2149f23d1f37a08d9914072a9de2736e904 | 656,493 |
def mjd2lst(mjd, lng):
""" Stolen from ct2lst.pro in IDL astrolib.
Returns the local sidereal time at a given MJD and longitude. """
mjdstart = 2400000.5
jd = mjd + mjdstart
c = [280.46061837, 360.98564736629, 0.000387933, 38710000.0]
jd2000 = 2451545.0
t0 = jd - jd2000
t = t0/36525.
... | 9df6b672fdf0c958e21cffd1f07938845974c95f | 656,494 |
import math
def orbittime_vrt(orbitalspeed,radius):
"""Usage: orbittime_vrt(orbital speed, radius of orbit)"""
return (2*math.pi*radius)/orbitalspeed | 1e61a510df5d066db25b613960914d36a2276b0d | 656,495 |
def __get_ip_address(request):
"""
Get ip address from request
:param request:
:return:
"""
ip = request.META.get("HTTP_X_FORWARDED_FOR", "")
if not ip:
ip = request.META.get('REMOTE_ADDR', "")
client_ip = ip.split(",")[-1].strip() if ip else ""
return client_ip | e66f968b3b0188490f5b839f92435c1e0117aac3 | 656,496 |
def rect(rng, lines, columns):
""" return i, j, width, height"""
w = rng.randint(1, max(1, lines // 2))
h = rng.randint(1, max(1, columns // 2))
i = rng.randint(0, lines - h)
j = rng.randint(0, columns - w)
return i, j, w, h | 01b909e2c581e3eb11b6276230d5fb7ecd16fe05 | 656,497 |
import os
def _is_file_newer(path, other_paths, no_exist=True):
"""
Check whether the file located in `path` is newer than all the files
located in `other_paths`.
:param path:
String with full path for the file.
:param other_paths:
String or list of strings with full paths for ot... | 7f1444a2224a294ed01d0352521e3e7f8402bcc2 | 656,498 |
def postpend_str(base_word: str, postpend: str, separator: str='') -> str:
"""Appends str:postpend to str:base_word
with default str:separator, returns a str
"""
return f'{base_word}{separator}{postpend}' | 6cf5c2e0fbd6f79e84c3b26fc27590904293b9eb | 656,499 |
def updates():
"""
Baseline for Thread updates.
"""
UPDATES_DATA = {
'em_resolutions': [
{
"em_id": 1,
"em_title": "EM title 1",
"em_text": "EM text 1",
"resolutions": [
{'id': 1, 'title': 'Resolution... | eb4eebd36919866d8904b42129305e4390a5d464 | 656,500 |
def uniform(n: int) -> tuple:
"""
Return a Uniform(n) distribution as a tuple.
"""
return (1.0 / n, ) * n | caabbe375f980339abf94356f9dca5f80e1b2014 | 656,501 |
def header(request_headers):
"""
将浏览器中的Request Headers头复制过来.进行改装成字典类型
:param request_headers: 浏览器中的Request Headers头信息
:return: 分割Headers头信息的键值对
"""
headers = dict()
request_headers = request_headers.strip()
for head in request_headers.rsplit('\n'):
name, values = head.split(':',... | 6f10ad6338969e510ec18c542b455866832bb715 | 656,502 |
import glob
import os
import logging
def _get_validity_issues_for_aggregated_projectcounts_generic(
csv_dir_abs, total_expected, desktop_site_expected,
mobile_site_expected, zero_site_expected, current_date_strs):
"""Gets a list of obvious validity issues for a directory of CSVs
:param csv_di... | 756ab503e3cddeb3317c7224d1c27e6e1ffa9067 | 656,503 |
def player_died(enemyy, enemyx, playery, playerx, enemy_rect):
"""This function checks if player died or not"""
pos_player = playerx, playery
if enemy_rect.collidepoint(pos_player):
return True
else:
return False | 0bfbb0a535291317e2686478327240bb7b9607ee | 656,506 |
def get_all_pipeline_names(scripts_dict):
"""
Returns the names of the supported pipelines on the cluster.
Does so by returning all keys in scripts dictionary except for "All Pipelines"
input:
scripts_dict: scripts dictionary described in get_scripts_dict function
"""
return [pipeline... | 09aba9f072c592a7ca2bdb42be504a43c38e8865 | 656,507 |
def extended_euclidean_algorithm(a, b):
"""Extended Euclidean algorithm
Returns r, s, t such that r = s*a + t*b and r is gcd(a, b)
See <https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm>
"""
r0, r1 = a, b
s0, s1 = 1, 0
t0, t1 = 0, 1
while r1 != 0:
q = r0 // r1
... | 7a121b3769bcbb7c11f8552503db23cf489addbf | 656,508 |
import os
import argparse
def FileType(f):
""" given a string path to a file, F, verify it can be used.
"""
f = os.path.abspath(f)
if not os.path.exists(f):
raise argparse.ArgumentTypeError('FileType:%s does not exist' % f)
if not os.path.isfile(f):
raise argparse.ArgumentTypeError... | cccdae0ac461ef8213dcbf4f3d84032e16537a5e | 656,509 |
def getRelevantInfoList (dataDict):
"""Returns a list of dictionaries (songs) with the relevant/useful information from JSON object string returned from API call given in the form of a dictionary."""
relevantInfoList = []
apiAllTracks = dataDict['tracks']['track']
for track in apiAllTracks:
rele... | 5f0ea1391262f4bf172e6649f6e48c235590afd7 | 656,510 |
def rotate(text, key):
"""
Caesar cipher the provided text with the provided key.
:param text string - Text to cipher.
:param key string - The key to use in the cipher.
:return text - ciphered text
"""
alpha = 'abcdefghijklmnopqrstuvwxyz'
out = ''
for index, char in enumerate(text):... | 3e0d4a80297f8b6f2884c1787e2a9eed909345d5 | 656,511 |
def isoformat(dt):
""" Formats a datetime object to an ISO string. Timezone naive datetimes are
are treated as UTC Zulu. UTC Zulu is expressed with the proper "Z"
ending and not with the "+00:00" offset declaration.
:param dt: the :class:`datetime.datetime` to encode
:returns: an en... | 621a0b652909bc171f421e17f578fde5797c5c96 | 656,512 |
def get_region_dir(hparams):
"""Return brain region string that combines region name and inclusion info.
If not subsampling regions, will return :obj:`'all'`
If using neural activity from *only* specified region, will return e.g. :obj:`'mctx-single'`
If using neural activity from all *but* specified ... | 3e06dc029b052f7f7c4e9998a7334bdfcfb653e8 | 656,513 |
import math
import random
def generate_next_population(individuals, toolbox):
"""
Perform truncated selection with elitism.
:param individuals:
:param toolbox:
:return:
"""
individuals = [toolbox.clone(ind) for ind in individuals]
individuals.sort(key=lambda x: x.error)
offspring ... | 82eb31355bc4f1dfb6547f49afb974982cd0998f | 656,514 |
import os
import time
def args_jupyter(args, seed):
"""
When using jupyter, arguments are entered as a dictionary :3
"""
if not(os.path.exists('data')):
os.makedirs('data')
logdir = args.get('exp_name', 'vpg') + '_' + args.get('env_name') + '_' + time.strftime("%d-%m-%Y_%H-%M-%S")
logd... | 7ac02859da1f4d9adbd580160575dfb133d26237 | 656,515 |
import random
def shuffle(context, value: str):
""" Sample filter """
letters = list(value)
random.shuffle(letters)
return ''.join(letters) | 9bc11920a684e54ea8cbaadc276778c4df0ace47 | 656,516 |
def _call(partial, *args, **kwargs):
"""Calls a partial created using `make`.
Args:
partial: The partial to be called.
*args: Additional positional arguments to be appended to the ones given to
make.
**kwargs: Additional keyword arguments to augment and override the ones
... | daec08955bc02642f7579bb68c8e68c0525da999 | 656,517 |
from datetime import datetime
def from_isoformat(t):
"""Converts time from ISO-8601 string to datetime object"""
return datetime.strptime(t, "%Y-%m-%dT%H:%M:%S.%f") | 3c606528093ec8807475a848b7388b04fded0018 | 656,519 |
def strip_figure(figure):
"""Strip a Plotly figure into multiple figures with a trace on each of them.
Parameters
----------
figure : dict or Figure
Plotly figure to strip into multiple figures.
"""
if figure is not None:
if isinstance(figure, dict):
pass
... | a1aff4297253c994016fe14cc1c87fe73adf3e7b | 656,521 |
def get_telemetry_data(data):
""" Returns tuple of telemetry data"""
pos_x = float(data["telemetry"]["pos_x"])
pos_y = float(data["telemetry"]["pos_y"])
time = float(data["telemetry"]["time"])
velocity = float(data["telemetry"]["velocity"])
return pos_x, pos_y, time, velocity | eb6fb39831005b0a88d168841d1c04717b9a01e3 | 656,522 |
def reformat_variable(var, n_dim, dtype=None):
"""This function takes a variable (int, float, list, tuple) and reformat it into a list of desired length (n_dim)
and type (int, float, bool)."""
if isinstance(var, (int, float)):
var = [var] * n_dim
elif isinstance(var, (list, tuple)):
if l... | 8b399d7449bcbeacb28a0c8f51949bd650630907 | 656,524 |
from typing import Callable
from typing import Optional
import types
def copy_definition(
definition: Callable, name: Optional[str] = None
) -> Callable:
"""
Copies a definition with same code, globals, defaults, closure, and
name.
Parameters
----------
definition
Definition to be... | abeebf6c97b1d8fa1da1cd8c05e636fecf2d1ecf | 656,525 |
import itertools
def sublists(lst, min_elmts=0, max_elmts=None):
"""Build a list of all possible sublists of a given list. Restrictions
on the length of the sublists can be posed via the min_elmts and max_elmts
parameters.
All sublists
have will have at least min_elmts elements and not more than m... | cb882a88498dbeb5352e935e794b5d45d92f2b42 | 656,526 |
import zipfile
def create_xml_list_from_zip(filepath):
"""
Opens the .zip file and extracts a list of .xml filenames
:param filepath: filepath to the .zip file
:return: list of .xml filenames
"""
return list(filter(lambda x: x[-3:] == 'xml', zipfile.ZipFile(filepath, 'r').namelist())) | b388d4e2728e4bc382de893a711732e46d065fea | 656,527 |
import os
def is_exe(path):
"""Check if a given path is an executable file
- from: http://stackoverflow.com/a/377028"""
return os.path.isfile(path) and os.access(path, os.X_OK) | 1325485e0b1333c5714624d568cbfd4a95f1f354 | 656,528 |
def predict(model, data_loader):
"""Runs the model on the given data."""
model.eval()
result = []
for i, batch in enumerate(data_loader, 1):
input_data = batch['img_stack']
z_slices = batch['z']
channels = batch['c']
ids = batch['file_name']
inputs = input_data.cuda()
outputs = model(... | eeef58681abb9191226d73b60566dea51ac520a1 | 656,530 |
import re
def extractIdentifierFromFullURL(url):
"""Extracts just the PID from a full URL. Handles URLs on v1 or v2 and
meta/object/resolve/etc endpoints.
Arguments:
url : str
Returns: None if no match. Otherwise returns the identifier as a string.
"""
if not isinstance(url, str):
... | 90da2fa4b2d9880a9f65eb2bde8c925288a12ea4 | 656,531 |
import pathlib
def helper_initial_state(ib):
"""Helper function for checking IGRABase initial state"""
state = (
isinstance(ib.filename, pathlib.PurePath),
ib.raw_data == {},
ib.converted_data == {},
ib._header_name_index == {},
ib._header_units == {},
ib._param... | 36e953f062d9b3be66cb3d43dc2e4c2941491d46 | 656,532 |
def find_length_from_labels(labels, label_to_ix):
"""
find length of unpadded features based on labels
"""
end_position = len(labels) - 1
for position, label in enumerate(labels):
if label == label_to_ix['<pad>']:
end_position = position
break
return end_position | 3c5a839ed2d2b1bcbb08f80ef908437a76c7f870 | 656,533 |
def normalize_sizes(sizes, dx, dy, minimum_size=0.01):
"""Give each size a value between 0-1
Arguments:
minimum_size (float, optional): Minimum size ratio, to keep
dominant values from completely obstructing the
view of smaller sizes
"""
minsize = max(sizes) * minimum_... | 170b105bb845bf59b52177e66ac2c6057fbb9f6b | 656,534 |
def fileContents(fn):
"""
Return the contents of the named file
"""
return open(fn, 'rb').read() | 2475af0b7d33956897a137d3d8a066f6c4ce725d | 656,535 |
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
minus_dict = dict()
for i in range(len(nums)):
if nums[i] in minus_dict:
return [minus_dict[nums[i]], i]
else:
minus_dict[target-nums[i]] = i | 69af6161301d2e4bb4065ea8dc45ffa3fefe61db | 656,536 |
def count_elements(seq) -> dict:
"""Tally elements from `seq`."""
hist = {}
for i in seq:
hist[i] = hist.get(i, 0) + 1
return hist | 6e0a37ec23faede811c203229aff08cd4eb848bb | 656,537 |
def identify_known_accounts(account_aliases, account_id):
"""
Given a known list of account IDs from yaml config, append note about their account if they're known to us.
:return: Account description
"""
# If the accounts custom aliases yaml file does not exist just default to normal behavior
if ... | a577c01fc814b4d7510ae496b9f2271342779d4b | 656,538 |
def binary_search_2(alist, item):
"""二分查找非递归实现"""
n = len(alist)
first = 0
last = n - 1
while first <= last:
mid = (first + last) // 2
if item == alist[mid]:
return True
elif item > alist[mid]:
first = mid + 1
else:
last = mid - 1... | 540371511a80ae5925fa64e0830f8f030eb8195f | 656,539 |
def func_bad_argname(NOT_GOOD): # [invalid-name]
"""Function with a badly named argument."""
return NOT_GOOD | bd34ac9ad2277f18dc6116c528492c6ced582b48 | 656,540 |
def _quote_header(s):
"""INTENAL: quote a string to be used in a stub header."""
return s.replace('\n', '\n ') | 2b96bf8056e752148bfa2cd0f902193b609b97ca | 656,541 |
import argparse
def EnvVarKeyType(key):
"""Validator for environment variable keys.
Args:
key: The environment variable key.
Returns:
The environment variable key.
Raises:
ArgumentTypeError: If the key is not a valid environment variable key.
"""
if not key:
raise argparse.ArgumentTypeErr... | 6a42dfa07a3fe89eaa2e0ef8d392cc3ae93b8bd6 | 656,542 |
def roar():
"""
Does a roar!
"""
return "Roarr!!" | 6321e38df35ca9733e376a5fb13fe82c4e07e14e | 656,543 |
import timeit
def singleTrial(n, items, m=2, M=4):
"""Conduct timing trials for sample values of m,M given n."""
numReps = 1
numTrials = 1
itemSet = 'items=[]\n'
for item in items:
itemSet = itemSet + 'items.append(Region' + str(item) + ')\n'
searchSet= '... | dae4e304ff7587dff2bd4034ca8adc3bb309f8f6 | 656,544 |
import re
def parse_attributes_block_identifier(block):
"""Return the identifier in `block`.
Parameters
==========
block : string
Block to search in
Returns
=======
Either:
identifier : string
If identifier found
None
If no identifier found... | 29792d4803003df84eb81ed63bfe994af5a35710 | 656,545 |
import re
def find_matching_pattern(List, pattern):
""" Return elements of a list of strings that match a pattern
and return the first matching group
"""
reg_pattern=re.compile(pattern)
MatchedElements=[]
MatchedStrings=[]
for l in List:
match=reg_pattern.search(l)
if m... | 07b013a5662f2ae3210c605f8938a95f3a020600 | 656,546 |
import os
def make_tmp_file(filename, output_dir=None):
"""
returns a temporary file of extension .pyccel that will be decorated with
indent/dedent so that textX can find the blocks easily.
filename: str
name of the file to parse.
output_dir: str
directory to store pyccel file
... | f28e3c222b93fcde1981715c4f75f3df977d448a | 656,547 |
import sys
def get_std_encoding(stream):
"""
Get encoding of the stream
Args:
stream: stream
Returns:
encoding or file system encoding
"""
return getattr(stream, "encoding", None) or sys.getfilesystemencoding() | 57eb1612c4e78dbf3d27f8a816f258d3981e42d8 | 656,548 |
def show_toolbar(request):
"""
Only show Django Toolbar for user "fasand" or "petr"
"""
return (not request.is_ajax() and
not request.user.is_anonymous and
(request.user.username == "fasand"
or request.user.username == "petr")) | 0476a160d7733b84288f28f95bcb736d1d93b15a | 656,549 |
import time
def time_configure(update_time: str) -> tuple:
"""
function uses time in a format 'HH:MM' to translate it to seconds left. Also function
considers a missing value for time and assume it as an instant update.
:param update_time: 'HH:MM' time of the update
:return: content for an update ... | d5a87f62c0613ed05ce6c666e7d9eb9d49c7f32b | 656,550 |
def modify_data(data):
"""
for easier use in templates, it joins the due_in and due today fields
together
"""
data["due_soon"] = {}
if "due_in" in data:
data["due_soon"].update(data["due_in"])
if "due_today" in data:
data["due_soon"].update(data["due_today"])
# combine "my_tasks" from multiple... | 3f52c5d8334ad503192598a6a5a7836d183a19c3 | 656,551 |
def get_total(taxa_list, delim):
"""Return the total abundance in the taxa list.
This is not the sum b/c taxa lists are trees, implicitly.
"""
total = 0
for taxon, abund in taxa_list.items():
tkns = taxon.split(delim)
if len(tkns) == 1:
total += abund
return total | f76b36cdf810ffdbbe3f8508dff2e90d2ce497e7 | 656,552 |
import re
def punctuation_density(text, punctuation=r'[^\w\s]'):
"""Returns the punctuation density of the given text.
Arguments:
text (str): The input text.
punctuation (str): A regex pattern for matching punctuation characters.
Defaults to r'[,.!?:;\\/]'.
Returns:
(f... | e8e61737f67e2473b7593a6db6b3070bf0bb5dba | 656,553 |
def _wrap_data_func(func, func_name):
"""
Wrapper to call func with data values
"""
def f(self, *args, **kwargs):
data = self._data
result = func(data.values, *args, **kwargs)
return result
f.__doc__ = (
"""
Call ``%s`` using automatic mapping.
- ``X`... | 4ae5044a60b92267629fa8bb80545fc51c09bd70 | 656,554 |
def create_subparser(subparsers):
"""Creates this module's subparser.
Args:
subparsers: Special handle object (argparse._SubParsersAction) which can
be used to add subparsers to a parser.
Returns:
Object representing the created subparser.
"""
parser = subparsers.add_pa... | d47704ca2bd5cd23d6c98f6984323c3dce248013 | 656,555 |
from datetime import datetime
import pytz
def GetCurrentDate():
"""The current date helper."""
return datetime.now(pytz.utc) | 50463fa78623f3d3c8c56b870b89462bc3b44dce | 656,556 |
def validate(message):
"""
Check if the message is in the correct format.
"""
if not ('x' in message and 'y' in message):
return False
if not(isinstance(message['x'], float)) or not(isinstance(message['y'], float)):
return False
return True | 2c8d16d2e789a47931b80bd13af028a220e5a4ae | 656,557 |
def GetMountSummary(mount):
""" Display a summary of mount on the system
"""
out_string = ("{mnt: <#020x} {mnt.mnt_data: <#020x} {mnt.mnt_devvp: <#020x} {mnt.mnt_flag: <#012x} " +
"{mnt.mnt_kern_flag: <#012x} {mnt.mnt_lflag: <#012x} {vfs.f_fstypename: >6s} " +
"{vfs.f_mn... | e17f4dbf47da5659919a57376cb9d387c7b96469 | 656,558 |
def get_document(document_name):
"""
This function responds to a request for /api/document-base
with the patient's records
:return: pdf document
"""
# Create the list of people from our data
with open(document_name, "r") as f:
return f.read() | 630a9f99913e3546ee9ab53b1d70486766297990 | 656,559 |
def linearize(solution):
"""Converts a level-ordered solution into a linear solution"""
linear_solution = []
for section in solution[0]:
for operation in section:
if not (operation.op[0] == 'P' and operation.op[1].isupper()):
linear_solution.append(operation)
return... | d2f9665890a336dee6abf7650596e5c58af19179 | 656,560 |
def option_to_cblas(x):
"""As above, but for CBLAS data-types"""
return {
'layout': "CBLAS_ORDER",
'a_transpose': "CBLAS_TRANSPOSE",
'b_transpose': "CBLAS_TRANSPOSE",
'ab_transpose': "CBLAS_TRANSPOSE",
'side': "CBLAS_SIDE",
'triangle': "CBLAS_UPLO",
'diago... | e333c99d0603a4dff89b382d2009a5d2a5db6d22 | 656,561 |
def get_remote_name(spec):
"""
Return the value to use for the "remote_name" parameter.
"""
if spec.mitogen_mask_remote_name():
return 'ansible'
return None | 1c9859ee69dc28db6da942dfb86f3c26c6756ec9 | 656,563 |
def _is_module(pkg):
""" Is this a module pacakge. Eg. foo-1-2.module+el8.1.0+2940+f62455ee.noarch
or for el9: foo-1-2.module_el9+96+b062886b """
return '.module+' in pkg.release or '.module_' in pkg.release | a630a4fbbabe45961afa46674832661673a11957 | 656,564 |
import pprint
def check_integrity(data_pool, simulation_list):
"""Check the integrity of a list of Simulation objects against a given
DataPool.
"""
# Process:
# 1. Check that the simulations are unique
# 2. Check that all the datastates are unique
# 3. Check that the links... | 3d2e08d5cca478803f4c101eec84bc2be65b43b0 | 656,565 |
def arg_hex2int(v):
""" Parse integers that can be written in decimal or hex when written with 0xXXXX. """
return int(v, 0) | 670354e4a227e0057ea3b5b41167ec22c929004c | 656,567 |
import itertools
def get_vocabulary(X, f):
"""Determine unique words on the dataset.
:param X: List of tokenized sentences
:param *preprocess: p_-like preprocessing functions
"""
f = f or (lambda x: x)
vocab = set(['<unk>', '<num>'])
for i, word in enumerate(itertools.chain(... | bd09678dfd961599408f9c8ae5c711c4929bbb49 | 656,568 |
import math
def Urms_calc(ua,ub,uc):
"""Function to calculate rms value of scalar phasor quantities."""
return math.sqrt((pow(abs(ua),2)+pow(abs(ub),2)+pow(abs(uc),2))/3.0)/math.sqrt(2) | ac6f370878d010e1bbc323185e1bd607e43a6b94 | 656,569 |
import csv
def load_log(filename):
""" Load the contents of a single log file.
"""
time = []
code = []
mesg = []
with open(filename, "r") as csvfile:
reader = csv.reader(csvfile)
for t, c, m in reader:
time.append(float(t))
code.append(int(c))
... | 4629b588d3ac65210f6116a94a6dcd116d88102a | 656,570 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.