content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import os
import tempfile
import uuid
def tmpdir():
"""
Return a new temporary directory path (under the OS temp location).
"""
path = os.path.join(
tempfile.gettempdir(),
str(uuid.uuid4())
)
return path | ebd6482743fb7bf1721a32dd93ef63316c86b9bb | 670,259 |
def _metrics_type_from_req_ctxt(req):
"""Utility method to get a metrics path for the API type."""
p = req.path.split('/')
if (p[1] == 'api') and len(p) > 3:
# Metrics are in format of 'imei.v1' to allow metrics to be aggregated across versions for the same API
api_type = p[3]
api_ve... | 58682918d262a5372d4b08596e0057fe9550d4c0 | 670,260 |
from os.path import getmtime
def mtime(filename):
"""Modication timestamp of a file, in seconds since 1 Jan 1970 12:00 AM GMT
"""
try: return getmtime(filename)
except: return 0 | 89ca31687475b24cfd32e2102566825ca29e169d | 670,261 |
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 adjust_index(idx, default=None):
"""Convert from python indexing convention to nvim indexing convention."""
if idx is None:
return default
elif idx < 0:
return idx - 1
else:
return idx | 3fadb2c09fc1d7080aaf857a4f84ed432b93aec7 | 670,263 |
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 process_timepoint_list(img_obj_list, config):
"""Make sure all members of timepoints are part of io_obj.
If timepoints = 'all', replace with actual list of timepoints
Parameters
----------
img_obj_list: list
list of mManagerReader instances
config: obj
ConfigReader instance
... | 620aca1523ae42a110b34a4cf87391314e6a1b69 | 670,268 |
def last(iterable):
"""
Get the last item in the iterable.
Warning, this can be slow due to iter step by step to last one.
"""
item = None
for item in iterable:
pass
return item | 354e23eeb072762c8a158692a5b8f2e23b90091e | 670,269 |
import glob
import os
def get_latest_model():
"""Gets the latest model path for training classifier"""
list_of_models = glob.glob('models/*')
list_of_models_modified = []
for model in list_of_models:
if 'cae' in model:
pass
else:
list_of_models_modified.append(... | 5cb85510c79f85f5b0dcf9bfa6f133fa96e7715b | 670,270 |
def get_icon_name(x):
"""
Returns the icon name from a CDragon path
"""
return x.split('/')[-1] | 9df409d5e4dd6083f054114beac5261aae1f43e7 | 670,271 |
def collect(group, p, meta, barrier_token):
""" Collect partitions from partd, yield dataframes """
res = p.get(group)
return res if len(res) > 0 else meta | 01683d49e1d03e9eadf783fe4cd3021c316f631b | 670,272 |
import math
def solution(A, B, K):
"""
While the previous problem was mathematically challenging, this one is a
doodle.
"""
return math.floor(B / K) - math.ceil(A / K) + 1 | ed899bec0c2ee2d2045d07b2c7256e0b7b5a5340 | 670,273 |
import numpy as np
def random_vector():
"""Returns a random unit vector as a numpy array of 3 elements."""
zeta = np.random.rand(2) # Two uniformly sampled random numbers in range (0,1)
c = 2.0*zeta[0] - 1.0 # Random cos(theta) uniformly sampled in range (-1,+1)
if c >= 1.0: # Guard a... | f07df4c80bd9799636e7c2ec6f85fd2c2a5ddb0e | 670,274 |
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 |
def paranoia_mode(data: dict) -> dict:
"""
Strips secret data (mnemonic, password, BIP85, private Keys)
from wallet dict.
:param data: source dictionary
:return: stripped source dictionary
"""
return {
k: {
"account_extended_keys": {
"path": v["account_ex... | db99072e4ed9c0651a1af995f2b16a08c86fe622 | 670,276 |
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 |
import subprocess
def cmd (cmds, stdin=None, cmd_input=None, err="exec error"):
"""exec a local (external) CLI command"""
proc = subprocess.Popen(cmds, stdin=stdin, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = proc.communicate(cmd_input)
if proc.returncode != 0:
raise IOEr... | 750d89a7b9a1c084f08b548f733254034208c015 | 670,280 |
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 findkey(d, *keys):
"""
Get an object in the dict based on a list of keys and/or indexes
"""
if keys:
keys = list(keys)
key = keys.pop(0)
return findkey(d[key], *keys)
else:
return d | fcd00c62be3c9e7e61ee408dedc210ff1e2869f8 | 670,282 |
from time import time
import decimal
import sys
def wiener(N, e, minutes=10, verbose=False):
"""
Wiener's attack against weak RSA keys:
https://en.wikipedia.org/wiki/Wiener%27s_attack
Developed by Maxime Puys.
Inputs:
``int`` N - modulus of the RSA key to factor using Wiener's attack.
``int`` ... | f3861d5e575adc1f8607fda10b774b15a8a322e2 | 670,283 |
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 string_is_unique(string):
"""
Question 1: Implement an algoithm to determine if a string has all unique
characters. What if you cannot use additional data structures.
Big O:
Time: O(n)
Space: O(1)
Possible solution in python is to use a set and compare the length of
the set... | db2bb3d36f8360790e6b096f9aab0b2fc0418066 | 670,285 |
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 |
def compute_frequencies(words):
"""
Args:
words: list of words (or n-grams), all are made of lowercase characters
Returns:
dictionary that maps string:int where each string
is a word (or n-gram) in words and the corresponding int
is the frequency of the word (or n-gram) in wo... | 6cb0835caf27d23a767c274d4ff3fd6d09a42f33 | 670,287 |
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 random
import string
def random_password(length):
"""
Generates a random password which consists of digits, lowercase and uppercase characters
:param length:
:return:
"""
return ''.join(random.SystemRandom().choice(string.ascii_letters + string.digits + "_") for _ in range(length)) | fa7c06f49b2bf508c3afd9b5fc9fbd375cc7ecb9 | 670,289 |
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 __list_to_events(list_of_headers):
"""converts list of headers to events with header as key, and value as next header"""
event_dict = {}
for title_idx in range(len(list_of_headers)-1):
event_dict[list_of_headers[title_idx]] = list_of_headers[title_idx+1]
return event_dict | ff7ad9a2b8778e6a2558392ea9edbf962da37adf | 670,292 |
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 build_invoice_dict_by_keys(keys, obj, transaction):
"""Takes a transaction and adds a nested dictionary of the keys
provided in order (with the first key as the top level and the
last key as the bottom level of the dictionary). If the keys exist
in the `obj` parameter, then transaction is added unde... | bec6f2a0c53e3e92b5ae2575330377ac572a0a4c | 670,294 |
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 sol(s, n, lookup):
"""
This counts the no. of solutions. To reduce the complexity we have used
a lookup table.
"""
#print(lookup)
if lookup[s][n] != None:
return lookup[s][n]
if n == 0 and s == 0:
return 1
# Leading zeroes are not counted because in that case s will ... | 4dd293ade8a3ce09929731517962bcafaaf0cb8b | 670,297 |
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 |
from typing import List
def search(nums: List[int], target: int) -> bool:
"""
思路:根据中间数和任意边界的大小确定有序区间
理解:中间元素把待搜索区间分成了两部分,两部分具有的性质是至少有一部分是有序的。
https://leetcode-cn.com/problems/search-in-rotated-sorted-array/solution/er-fen-fa-python-dai-ma-java-dai-ma-by-liweiwei141/
"""
length = len(nums)
... | ea1f7e1513b44152d20bc2f6161505be2e0d1048 | 670,299 |
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 |
import re
def is_short_uuid(s):
"""Return non-None if uid is a uuid."""
uuid_short_regex = re.compile(r"[0-9a-f]{8}\Z", re.I)
return uuid_short_regex.match(s) | 5ba6213125c8d8cbf025f24f4d609994c5b8039e | 670,304 |
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 extract_and_blast(region, het_fasta, output_folder):
"""Create commands for blasting a region (format "name:start-stop") against all the other het regions (needs a fasta
file with all the het regions: "het_fasta").
This will be use with multiprocessing
Returns the commands (strings) to:
E... | 270b6ddb324ac81579cb8baeb88eaf298ca9f215 | 670,307 |
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 |
import torch
def _to_cpu(state):
""" store in cpu to avoid GPU0 device, fp16 to save space """
if isinstance(state, torch.Tensor):
ret = state.cpu()
if 'Float' in state.type():
ret = ret.half()
return ret
elif isinstance(state, list):
new_state = [_to_cpu(t) for... | 865fd8034b520d01643cb03019108d928a337a52 | 670,312 |
import six
import random
def random_split(dataset, prob=.5):
"""
Utility for performing a random split for text data that is already in
bag-of-words format. For each (word, count) pair in a particular element,
the counts are uniformly partitioned in either a training set or a test
set.
Parame... | 4b0f7ebb0f7f2635b26c138e8709a478f7f2e860 | 670,313 |
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 __splitVersionPattern(versionPattern):
"""
Split the version pattern in parts.
"""
prefix = ''
padding = ''
suffix = ''
for char in versionPattern:
if char != '#' and not padding:
prefix += char
elif char != '#' and padding:
suffix += char
... | 677be964b3eac92e5143dfe0773067b47bf4c196 | 670,319 |
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 add_ao_by_variant_seq(ao_str, variant_seq_str):
"""
Takes a pair of strings like ao_str="7,7,24" and
variant_seq_str="T,T,T" or "8,21,3" and "T,T,A".
Output should be a string "T=38" (first case) or "T=29, A=3" (
second case).
"""
ao_list = ao_str.split(',')
ao_list = [int(x) for x i... | 5c4b609749190ad36ce36178ade46382517698f3 | 670,321 |
def is_exception(e, string):
"""Check if the given exception is a known Libcloud exception with the
given content."""
try:
if string in e.args[0]:
return True
except Exception:
pass
return False | e82e8b0a6cd51e5c7972242440d53b60fe341510 | 670,322 |
from typing import Union
from pathlib import Path
import os
def get_relative_path_to_cwd(path: Union[Path, str]) -> str:
"""Get a relative path to current working directory."""
absolute_path = os.path.abspath(path)
return os.path.relpath(absolute_path, os.getcwd()) | 24724a0c5650f69dc8337fef6d4c4ba24a3fff79 | 670,323 |
import os
import uuid
def random_folder(parent_folder='./', mkdir=True):
"""Generate a random folder name, create it inside parent_folder, and return the path to it
Parameters
----------
parent_folder : str
folder inside which the random_folder is desired
mkdir : bool
whether the... | 24eb0ecf8ad5dca0170afe733cd20794263a88e4 | 670,324 |
def syndic_master(request, salt_factories, master_of_masters, configure_syndic):
"""
This is a second master, which will connect to master-of-masters through the syndic.
We depend on the minion_1 fixture just so we get both the master-of-masters and minion-1 fixtures running
when this master starts.
... | 58eedfbb36756cf523f28181ee4fd1326740f788 | 670,325 |
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 rate_look_up(file_to_open):
"""
skip the first line of the file, and reiterate line by line
find the commercial rate (line[6] given the .csv structure)
calculate average, lowest and highest rates
"""
# variables to find
num_of_rates = 0
cumulative_rate_sum = 0
high_rate = {
... | 43732fdeaa186a64ff92d35ffb99b2d7f066d252 | 670,327 |
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 |
def transpose_callable(f):
"""Returns a callable whose output is the transposed of the input callable."""
def transposed(x):
return f(x).T
return transposed | 5a3caa3b5f7b98f1cdfe0271ecd8dd6607f1dd66 | 670,329 |
from typing import List
def unsentencise(ts: List[str]) -> str:
"""Join a list of sentences into a string"""
return ". ".join(ts) | 40521539359a08f5544d3fb9bc0a7d58c45ebbb7 | 670,330 |
import yaml
def load_yaml(config_path):
"""Tries to load a config file from YAML.
"""
with open(config_path) as f:
return yaml.load(f, Loader=yaml.FullLoader) | a24328da04e4a7c42aff5a3eaa7ff552b5e96d85 | 670,331 |
def eval_median_spend(simulation):
"""median spend metric for current trial
Returns:
float: Median real spending for current trial
"""
return simulation.latest_trial.trial_df['spend'].median() | 063efe44b8daf0357a99a6c41d565144745084f7 | 670,332 |
def FirstTrue(values, default=None):
"""Gets first True (not None, not empty...) value or default.
Used to determine a meaningful name for a machine.
Args:
values (iterable): list of values to choose from.
default (optional): default return.
Returns:
object: first True object.
"""
for value i... | fddb27ef75dd4a9c92415b022d10c370b68d6b79 | 670,333 |
from datetime import datetime
import json
def sfn_run(session, arn, input_={}):
"""Start executing a StepFunction
Args:
session (Session): Boto3 session
arn (str): ARN of the StepFunction to execute
input_ (Json): Json input data for the first state to process
Returns:
st... | d47b84ce707e6d7d2ead95be078e879860c23731 | 670,334 |
def RangeInside(context, locationSet):
"""
<location-set> range-inside(<location-set>)
The range-inside function returns ranges covering the content of the
locations in the argument location-set. For each location x in the
argument location-set, a range location is added to the result location-set... | 983e145617913dfdc780194b5d901c3b199025e2 | 670,336 |
from typing import List
from typing import Dict
from typing import Any
import itertools
def chain(*configs: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
"""Chain given iterable config dictionaries."""
chained_configs: List[Dict[str, Any]] = list()
for instance in itertools.product(*configs):
mer... | bc1f087a8212b8071c345c1594d6324f2531cd0b | 670,337 |
def handler_bad():
"""Return False for a bad event handler."""
return False | 2080d7f3a5a930fe0a40524cb3f9c866a53d01a3 | 670,338 |
import torch
def batch_randint(start, batch_end):
"""
Sample k from start to end (both inclusive)
Return the same shape as batch_end
"""
return start + (torch.rand_like(batch_end.float()) * (batch_end - start + 1).float()).long() | e2591aae46618223724d4b1560f7c287fa51cffb | 670,339 |
def get_chamfer_profile(y, weld):
"""
Outputs the profile of the weld chamfer (a simple mapping from the
horizontal coordinate(y) to the vertical coordinate(z)).
Used for checking whether a certain point is inside the weld or not.
Parameters:
---
y: float, horizontal coordinate
a: float... | 6746244bd71a99f1f3353551f2a8b72a38e0868b | 670,341 |
import zlib
def compress_data(data):
"""Gzip data
:param data: The data to compress
:type data: bytes
:return: The compressed data
:rtype: bytes
"""
z_obj = zlib.compressobj(-1, zlib.DEFLATED, 31)
return z_obj.compress(data) + z_obj.flush() | 278b3c3c42d1917f3e41b352611b1859cbffba99 | 670,342 |
def survey(survey_no_stats, request):
"""Return surveys with and without collected stats."""
if request.param:
# copy is needed since otherwise survey_no_stats will be updated inplace and only surveys with collected stats
# will be returned
return survey_no_stats.copy().collect_stats()
... | 67d0a6b5cfd6ec7cb81bb5c30b35b87f8f977e67 | 670,343 |
def ping():
"""Load balancer ping view."""
return 'OK' | 170f53b5f21e66ee389ae0a7681527c505b262a8 | 670,344 |
import os
def osi_path(linux_path):
"""convert a linux path to os-independent path"""
return linux_path.replace('/', os.path.sep) | c03c49e39719c10c5a57025025bb769acfc023cb | 670,345 |
import string
def is_tag(arg: str):
"""
check if string is tag format
>>> is_tag('Abc_1234')
"""
for ch in arg:
if ch not in string.ascii_letters and ch not in string.digits and ch not in '_':
return False
return True | 2cc5740fe7c2fb6183376c32b46507772fd22342 | 670,347 |
import os
def get_cfg_files():
"""获取目标路径下所有的配置文件名"""
file_names = os.listdir("./configs")
return sorted([x for x in file_names if (not x.startswith('.')) and x.endswith('.config')]) | 0d7e3e01c0cf836853e8b0f3d0fafe5a644da3c0 | 670,348 |
def response_to_dict(resp):
"""Converts a suds response into a dictionary suitable for JSON"""
return dict((k, getattr(resp, k)) for k in resp.__keylist__) | 378cbbb1889e9e3140284cdbc682471df649bd63 | 670,349 |
def extract_email(msg):
"""Extract all the interesting fields from an email"""
msg_obj = {}
msg_obj["from"] = msg.getheaders('From')[0]
msg_obj["to"] = msg.getheaders('To')[0]
msg_obj["subject"] = msg.getheaders('Subject')[0]
msg_obj["date"] = msg.getheaders('Date')[0]
msg_obj["contents"] = ... | 1ed737fb280fd999beade57a46202380d4e9fa6a | 670,350 |
def solution(A, B):
"""
DINAKAR
start points A
end points B - sorted
take first point of segment and compare with all other segment points
when overlap is found, mark current segment to prev_seg_end_point
prev_seg_end_point - is the last non overlap segment end point
(1,5) - self first i... | d876762bf6e0aa376785f86d38e2205c07d9a8aa | 670,351 |
def feature_pairs(f):
"""Expand features to include pairs of features
where one is always a f=v feature."""
pairs = [x + ".x." + y for x in f for y in f if u'=' in y]
return pairs + f | 92a880db82773aa87da052aca7bff44c3d5e9091 | 670,352 |
import re
def has_timestamp(text):
"""Return True if text has a timestamp of this format:
2014-07-03T23:30:37"""
pattern = r'[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}'
find = re.findall(pattern, text)
return bool(find)
pass | d17aeae04061feb5aacb60e946912d08914a3339 | 670,353 |
def convert_ipv4_to_rpz(subject: str) -> str:
"""
Converts the given IPv4 into a policy format which can later be used in the
tests.
"""
return ".".join(reversed(subject.replace("/", ".").split("."))) | 537eb7f738a8822d502dec5e2984ef9827086362 | 670,354 |
def first_character_valid(check_str):
"""
check first chinese character from string
in: print(first_character_valid('中文'))
out: True
in: print(first_character_valid('english'))
out: False
:param check_str:
:return:
"""
for index, ch in enumerate(check_str):
if u'\u4e... | 908f4f56c5937ae7f02d147fcaab7abe1089d780 | 670,355 |
def get_words(message):
"""Get the normalized list of words from a message string.
This function should split a message into words, normalize them, and return
the resulting list. For simplicity, you should split on whitespace, not
punctuation or any other character. For normalization, you should conver... | e365e5b2ff4dad072eba66bcbd299d704272f9cf | 670,356 |
def split_list(list_to_split: list, num_chunks: int):
"""Splits a list into num_chunks"""
chunks = []
err_msg = "You have more users than you have buckets"
assert len(list_to_split) >= num_chunks, err_msg
size_of_chunk = len(list_to_split) // num_chunks
size_of_uneven_chunk = size_of_chunk + 1... | c81d763961f2b81b5f76968b6b1eec15292fa0e1 | 670,357 |
def marching(arg):
"""Return "The ants go marching..." part of the song.
arg - "one", "two", "three" ..."""
return "The ants go marching {} by {},".format(arg,arg) | 76c6575ec1ba14e579c59596221be0f142af9317 | 670,358 |
import subprocess
def get_version():
"""
Helper to extract a version number for this module.
:returns: A major.minor.patch[.sub] version string or "dev".
"""
# Try to extract the version number from git
# this will work when installing from a locally cloned repo, or directly from
# github... | fca0883ff63ec65a40ec46b4d0da77f69b5fdabe | 670,359 |
def book_name_strings(bk):
"""Returns a list of the named range names in
as workbook.
Arguments:
bk {xw.Book} -- Workbook to retrieve list from.
Returns:
list -- named range names.
"""
return [nm.name for nm in bk.names] | 7fb4f35018d840e7fc1369993fcecf54e594cf83 | 670,360 |
import os
def is_file(raw_path):
"""Check if input data is a file name
:param raw_path: possible path to file
:return: True if raw_path is file
:return: False if raw_path is not file
"""
if os.path.isfile(os.path.normpath(raw_path)):
return True
else:
return False | 37ba651d7f768e0d4d127935facc35d05f1e983e | 670,361 |
def get_text(elem, name, default=None):
"""Retrieve text of an attribute or subelement.
Parameters
----------
elem : xml.etree.ElementTree.Element
Element from which to search
name : str
Name of attribute/subelement
default : object
A defult value to return if matching a... | a17a92b16831ac7ff793cab59f2588eb6130afc4 | 670,362 |
def harmonic_mapping(fg):
"""Get all peaks from a FOOOFGroup and compute harmonic mapping on the CFs."""
f_mapping = []
for f_res in fg:
cfs = f_res.peak_params[:, 0]
if len(cfs) > 0:
f_mapping.append(list(cfs / cfs[0]))
return f_mapping | 1878e3cfd3e99d688ec20f5b294a8fe9faaa240c | 670,363 |
def remain(answer):
"""
Arguments:
- `answer`:
"""
for i in range(len(answer)):
if answer[i] > 0.9725:
answer[i] = 1.0
return answer | ea5c8b4e4c9caa7c0017236c98d987234bdb22c4 | 670,364 |
import numpy
def bit_decode(x, numseqs):
"""Convert an integer into a boolean array"""
result = numpy.empty([numseqs], bool)
bit = 1 << (numseqs-1)
for i in range(numseqs):
result[i] = bit & x
bit >>= 1
return result | 7e9a000d09654d2be792c49a67811bb1b112638b | 670,365 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.