content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def strip_hyphen(s):
"""
Remove hyphens and replace with space.
Need to find hyphenated names.
"""
if not s:
return ''
return s.replace('-', ' ') | 7cc0c23e3c414ec742a86bf651b507aa0df31485 | 652,235 |
def last_column(worksheet) -> int:
"""
Quick way to determine the number of columns in a worksheet. Assumes that data is within the `CurrentRegion` of cell A1.
:param worksheet: Excel Worksheet COM object, such as the one created by code like:
app = win32com.client.Dispatch("Excel.Application")
... | dfd8231214aede9fa9e9f362e8bad70b02ff4489 | 652,236 |
def GetTag(node):
"""Strips namespace prefix."""
return node.tag.rsplit('}', 1)[-1] | 8796a1a42db5c97c173301a1d671b2adc0f60235 | 652,237 |
def base_url() -> str:
"""External url of flask app, for linking nodes in slack messages"""
return 'http://127.0.0.1:5000/pipelines' | b7af476958cba4254ae25a5ae74c169ef3a08f3a | 652,238 |
def pad_func(before, after):
"""
Padding function. Operates on vector *in place*, per the np.pad
documentation.
"""
def pad_with(x, pad_width, iaxis, kwargs):
x[:pad_width[0]] = before[-pad_width[0]:]
x[-pad_width[1]:] = after[:pad_width[1]]
return
return pad_with | 3996e40231a03b2fa5dd6a50a7307259f13662ca | 652,239 |
def readme():
"""Reads the README.md file to use as the 'long description'"""
with open('README.md') as f:
return f.read() | 46c06a5b2f3c8f6e0dd1b21e6d139646969af771 | 652,241 |
def squared_differences(x, y):
"""elementwise squared differences.
Computes element-wise
.. math::
(x-y)^2
broadcasting applies as in any
operations.
`Wikipedia <https://en.wikipedia.org/wiki/Loss_function#Quadratic_loss_function>`_
Parameters
----------
x: tensor-like... | 83b7906e2856b39e3121b8d59c3eff8851f9410d | 652,242 |
def build_rosinstall(repo_name, uri, vcs_type, version, prefix):
"""
Build a rosinstall file given some basic information
"""
rosinstall = []
repo_name = repo_name if not prefix else '/'.join([prefix, repo_name])
if version:
rosinstall.append({vcs_type: {'local-name': repo_name,
... | da5a043a3a6da7710b545d1d6329da235307ddeb | 652,243 |
def update_shape(obs_shape, act_shape, rew_shape, wrapper_names):
"""
Overview:
Get new shape of observation, acton, and reward given the wrapper.
Arguments:
obs_shape (:obj:`Any`), act_shape (:obj:`Any`), rew_shape (:obj:`Any`), wrapper_names (:obj:`Any`)
Returns:
obs_shape (:ob... | 27e926134860feb81b85fabf80888e1728558a3b | 652,247 |
def merge_blocks(a_blocks, b_blocks):
"""Given two lists of blocks, combine them, in the proper order.
Ensure that there are no overlaps, and that they are for sequences of the
same length.
"""
# Check sentinels for sequence length.
assert a_blocks[-1][2] == b_blocks[-1][2] == 0 # sentinel size... | 04991de7c8c0ac2896bc81451a8c2d76dd2ccfa4 | 652,248 |
def transform_list_of_dicts_to_desired_list(curr_list, nested_key_name, new_list=[]):
"""
Returns a list of key values specified by the nested key
Args:
curr_list (list): list of dicts to be dissected
nested_key_name (str): key name within nested dicts desired
new_list (list): used ... | 2b44b2b6b94ac48f17ccf29cb3558139b75e406a | 652,249 |
def evaluate_findings(findings):
"""Evaluate the findings of the scan against local policy."""
total = 0
total += findings.get('malware', 0)
total += findings.get('unresolved', {}).get('defcon1', 0)
total += findings.get('unresolved', {}).get('critical', 0)
total += findings.get('unresolved', {}... | 1dc6e76f8fd48903c1bb62d5381fb8460294f59f | 652,250 |
def insert_at(alist, i, x):
"""This function returns a new list, with x inserted
at location i
"""
# CHANGE OR REMOVE THE LINE BELOW
return alist[:i] + [x] + alist[(i+1):] | bfd74263c26313039d451bf34bd2c173987dc361 | 652,251 |
import re
def _fix_evidence_text(txt):
"""Eliminate some symbols to have cleaner supporting text."""
txt = re.sub('[ ]?\( xref \)', '', txt)
# This is to make [ xref ] become [] to match the two readers
txt = re.sub('\[ xref \]', '[]', txt)
txt = re.sub('[\(]?XREF_BIBR[\)]?[,]?', '', txt)
txt ... | 7e1747d96979cf628a790fefada4a8e2e3a82010 | 652,252 |
import math
def direction(a,b):
"""Figure out the clockwise/anticlockwise direction."""
# a and b are between 0 and 2 pi
# Check if they are equal or opposite
if a == b or a == b + math.pi or a == b - math.pi:
return 0
if a < math.pi:
# a is in the first part
# so if b is ... | f2f267371f063a3b718c04af82186c948ae491b6 | 652,253 |
import mmap
def map_fb_memory(fbfid, fix_info):
"""Map the framebuffer memory."""
return mmap.mmap(
fbfid,
fix_info.smem_len,
mmap.MAP_SHARED,
mmap.PROT_READ | mmap.PROT_WRITE,
offset=0
) | 0b87815b09f6cdc58c033a1a7e41faf465a11dbc | 652,255 |
def get_path(folder_name, model_type, exchange_id, trading_pair, ext):
"""
Example models/model_trade_binance_eth_usd.pkl
preds/model_trade_binance_eth_usd.csv
"""
return f'{folder_name}/model_{model_type}_{exchange_id}_{trading_pair}{ext}' | 668b633ff7729581152bc414b38faaa31ccee45e | 652,256 |
def keys_(tbl):
""" table keys
"""
return tuple(tbl.columns) | 2cba0cfa32cb3c1b0f77c5cd0d5773ed5d19dd3e | 652,257 |
import os
import json
from typing import OrderedDict
def load_reader_options():
"""
Retrieve Pandoc Reader options from the environment
"""
options = os.environ['PANDOC_READER_OPTIONS']
options = json.loads(options, object_pairs_hook=OrderedDict)
return options | d8ae6d3545e533d49a007cb0cf08cdcb7701835a | 652,258 |
def square_of_digits(number: int) -> int:
"""Return the sum of the digits of the specified number squared."""
output = 0
for digit in str(number):
output += int(digit) * int(digit)
return output | 7b1e1d6de1db292970d346b99d7048088b6a4fca | 652,259 |
def check_int(x):
"""
Check whether a int is valid
:param x: The int
:return: The result
"""
return 0 <= x <= 2147483647 | 9a53ea1afb0f50e2528eb811d03f949517cdd652 | 652,260 |
import argparse
def parse_args():
"""[summary]
Returns:
[type]: [description]
"""
parser = argparse.ArgumentParser(description='Rescale videos')
parser.add_argument('video_path', type=str,
help='root directory for the input videos')
parser.add_argument('out_pat... | 36d183f5fb33cd8c68f06c900a42ff650e537297 | 652,261 |
import os
def getFolderName(path: str):
"""
获取文件夹名称
:param path: 文件夹路径
:return: 文件夹名称
"""
return os.path.basename(path) | bb753b3b84833acfb9e89aa23b852922531df662 | 652,262 |
import sys
def _urllib_has_timeout():
"""Determines if our version of urllib2.urlopen has a timeout argument."""
# NOTE: This is a terrible hack, but there's no other indication that this
# argument was added to the function.
version = sys.version_info
return version[0] >= 2 and version[1] >= 6 | dc851b9ba42053b4dad3b26f5f657b435ad226cb | 652,263 |
def index(predicate, seq):
"""
Returns the index of the element satisfying the given predicate, or None.
"""
try:
return next(i for (i, e) in enumerate(seq) if predicate(e))
except StopIteration:
return None | c0a7b055e386a6766d4a280aadbfb523e1060514 | 652,264 |
def extract(data, itemid, **kwargs):
"""
Extract item data from scrubbed info.
"""
# singles
try:
price01, sell01 = data[itemid]['median'], True
# do not sell items without a price
if price01 <= 0:
price01, sell01 = None, False
except KeyError:
price... | 040a786f27a370d8963b7d541e5dc2dbe69f36dc | 652,266 |
def player_input():
"""
OUTPUT: (Player 1 marker, Player 2 marker)
while not (marker == 'X' or marker 'O'):
:return:
"""
marker = ''
while marker not in ('X', 'O'):
marker = input('Player 1: Do you want to be X or O? ').upper()
if marker == 'X':
return 'X', 'O'
else:
... | 40b0141812e2f1a64e11614066aba8e50fb5b1a5 | 652,267 |
import warnings
def validate_relativities(df_factors):
"""Checks on formatted Relativities"""
if not df_factors.apply(lambda col: (col > 0)).all().all():
warnings.warn(
"Factor relativities: At least one relativity is below zero."
)
return None | 378ee635698c0c2a7c2f559113792fb97d1a0123 | 652,268 |
import os
def psplit(s):
"""
Split a path given as a string into a list.
This is the inverse of os.path.join.
"""
head, tail = os.path.split(s)
path = [tail]
while head:
head, tail = os.path.split(head)
path.append(tail)
path.reverse()
return path | 508c29f8f7faa064a4fc6785bd37bace975e09aa | 652,269 |
def get_score(winner):
"""
You get 1 point for winning, and lose 1 point for losing.
>>> get_score('tie')
0
>>> get_score('human')
1
>>> get_score('ai')
-1
"""
if winner == 'human':
return +1
if winner == 'ai':
return -1
return 0 | 591b91c97218ab074929011707d79d7b52c143db | 652,270 |
def strip_markup(text):
"""Strip yWriter 6/7 raw markup. Return a plain text string."""
try:
text = text.replace('[i]', '')
text = text.replace('[/i]', '')
text = text.replace('[b]', '')
text = text.replace('[/b]', '')
except:
pass
return text | 026f72fc9dcbf91d8ff87157a69140537911e5bd | 652,271 |
def tokenize_spec(spec):
"""Tokenize a GitHub-style spec into parts, error if spec invalid."""
spec_parts = spec.split('/', 2) # allow ref to contain "/"
if len(spec_parts) != 3:
msg = 'Spec is not of the form "user/repo/ref", provided: "{spec}".'.format(spec=spec)
if len(spec_parts) == 2 ... | 994e0b3d8043db3779bf1ad7a2303b43e28c5363 | 652,272 |
def get_overall_misclassifications(H, training_points, classifier_to_misclassified):
"""Given an overall classifier H, a list of all training points, and a
dictionary mapping classifiers to the training points they misclassify,
returns a set containing the training points that H misclassifies.
H is repr... | e940f29ac43eacae0c0642285319cad0fb8eb644 | 652,273 |
def mutation_freq_conditional(df_freq, S_gen):
""" Calculate the conditonal probability of a mutation given it's trinucleotide context
(Normalizes mutation frequencies in a region by trinucloetide frequencies
in that region)
Each trinucloetide sequence is treated as a four-sided die: one si... | 7e07735d5874a19c2f63657f33095a36118715ac | 652,274 |
import os
import subprocess
import re
def create_cmd(args, basename_binary=False):
"""
Takes an array of strings to be passed to subprocess.Popen and creates
a string that can be pasted into a terminal
:param args:
The array containing the binary name/path and all arguments
:param basena... | be6c9d58fb33650f7dc5091abbe52beadac1512a | 652,275 |
def list_to_string(list_):
"""
Returns a string from the given list
>>> list_to_string(['1,', '2', '3'])
>>> # 1, 2, 3
:param list_: list
:return:str
"""
list_ = [str(item) for item in list_]
list_ = str(list_).replace("[", "").replace("]", "")
list_ = list_.replace("'", "").rep... | 28185348a5f983905e6d8ce74c636b9dd4216d9e | 652,276 |
import torch
def _gaussian_kernel_1d(size: int, sigma: float) -> torch.Tensor:
""" Create 1-D Gaussian kernel with shape (1, 1, size)
Args:
size: the size of the Gaussian kernel
sigma: sigma of normal distribution
Returns:
1D kernel (1, 1, size)
"""
coords = torch.arange(size).to(dtype=torch.flo... | 6440154b8cb24ab776161affbffe9bc09899af63 | 652,277 |
def validate_password_rules(password: str,
min_number: int,
max_number: int,
test_char: str) -> bool:
"""
Old Password Rules
The password policy indicates the lowest and highest number of times a given letter must
appea... | d83b27f7c62a6149e141c6a0f6c05e36ed83ab0a | 652,278 |
import os
def get_current_instance_id():
"""Returns the id of the current instance.
If this is instance 2 of version "v1" of server "server5" for app "my-app",
this function will return "2".
This is only valid for manually-scheduled servers, None will be returned for
automatically-scaled servers.
Retur... | 3062de2763b4180788efdf53fda2f4ef8880b9bd | 652,280 |
import os
def resolve_path(path):
"""Returns resolved canonical path removing symbolic links if present"""
return os.path.realpath(path)
# return str(pathlib.Path(path).resolve()) | 63f467c4f73334c05e46e1604aabe83a9036ec4f | 652,281 |
def addDice(arrLen2Int):
"""function that adds the values of two dice
_____________________________________________________________________
SYNTAX : sum = addDice(listWithALengthOfTwoIntegers)
_____________________________________________________________________
PARAMS (1): arrLen2Int : literally an... | dd4fd6f3dae305803df06e604af7181207f7ae6d | 652,282 |
import numpy
import itertools
def embed_unitary_into_orthogonal(unitary: numpy.ndarray) -> numpy.ndarray:
"""
Since the O(2n) transformation of Majorana modes is a generalization of the
particle-number-conserving U(n) transformation (basis rotations), one may
embed the U(n) matrix into an O(2n) matrix... | 1e442f384dfbe8de755e688ae6de71b43a5c7b0e | 652,283 |
from typing import Set
def check_uniques(example, unique_signatures_: Set[str], unique_repos_and_filenames_: Set[str], exclude_duplicate_repos_and_filenames: bool = False, repos_to_exclude=None,
files_excluded_because_of_repos_=None, files_excluded_because_of_repos_and_filenames_=None,
... | 37193ca5ea522ede5b426d2220cc6d1f7a784892 | 652,284 |
def save_image_pixels(session, localfile, image_tags=None):
"""
put a local image on the server and return the URL
to the METADATA XML record
@param: session - the local session
@param: image - an BQImage object
@param: localfile - a file-like object or name of a localfile
... | 9664b90aad237d1fc52e197b83f45e51abd87a74 | 652,285 |
def merge_paths(base_uri, relative_path):
"""Merge a base URI's path with a relative URI's path."""
if base_uri.path is None and base_uri.authority is not None:
return '/' + relative_path
else:
path = base_uri.path or ''
index = path.rfind('/')
return path[:index] + '/' + rel... | f2cda0ad9a49cb92187d5318d80f459080b9657b | 652,286 |
def _df_to_vector(distance_matrix, df, column):
"""Return a grouping vector from a ``DataFrame`` column.
Parameters
----------
distance_marix : DistanceMatrix
Distance matrix whose IDs will be mapped to group labels.
df : pandas.DataFrame
``DataFrame`` (indexed by distance matrix ID... | 7b205f8783b0e11cfbe9206f9ff381f18ca74ae7 | 652,288 |
def exception_to_bool(fn, exception=Exception):
"""
:Returns: wrapped function objects that caste exceptions to `False`
and returns `True` otherwise.
>>> exception_to_bool(lambda: True)()
True
>>> exception_to_bool(lambda: arst)() # NameError
False
"""
def new(*args, **kwargs):... | 36fff16ba5515f55e9c780ce063d6fc093834a78 | 652,289 |
import os
def load_resource(filename: str) -> str:
"""Load external resource files."""
src_path = os.path.dirname(__file__)
src = os.path.join(src_path, filename)
try:
with open(src, mode="rt", encoding="utf-8") as fp:
resource = fp.read()
except IOError:
errmsg = "IOEr... | ac87dcf3c1d1e89a28de2aeebd4fe3a6769d213f | 652,290 |
def make_name_abbreviation(words):
"""Will make some kind of company acronym.
eg: BASF, AT&T, A&W
Returns a single string of the new word combined.
"""
return ''.join([word[:1].upper() for word in words]) | d43ac7a724b591a33a9a14ec71b219582bd14293 | 652,291 |
def _compute_negative_examples(
label,
all_items,
pos_items,
item_to_labels,
label_graph,
assert_ambig_neg
):
"""
Compute the set of negative examples for a given label.
This set consists of all items that are not labelled
with a descendant of the ... | 1e09ea6b88f03801eeb04103deeb62f642d54747 | 652,293 |
from typing import Any
from typing import Dict
def process_column(
name: str,
data_type: Any,
) -> Dict[str, Any]:
"""
Here we transform some column data from Notion into the format which
this script requires to generate the ORM. It's very similar dbcrossbar's
column schema, but it includes an... | a045f2f14040b184247b608a1dfd75d8ff00751a | 652,294 |
import collections
def find_nested_types(bv, t):
""" Find all user-defined types in `t` """
# Find sub-types to research
haystack = set()
if t.return_value is not None:
haystack.add(t.return_value)
if t.element_type is not None:
haystack.add(t.element_type)
if t.target is not None:
haystack.add(t.target)
... | 29a3acde5fec281d9b6d70da44c921df274e2c55 | 652,296 |
import time
import torch
def train(model, data, optimizer, criterion, device, args, epoch, writer):
"""
:param model: (nn.Module) model
:param data: tuple of iterators of data (dataX, dataY)
:param optimizer:
:param criterion: loss function(pred, actual)
:param args:
:return:
"""
... | 9c23d9ea3fe4257ac141fcd859cec6fd74786d8c | 652,297 |
def PID_dict(which,T): #Dictionary of PID setting to try for the ARPES chamber
"""Dictionary for common PID setting for the ARPES system.
Since the PID is dependent on the cooling power, this will change with the cryogen and the flow rate:
- Flow = "LHe,LN" => LHe = needle valve = "on" and flow = 70
... | 333502a734bb133cf657c67569dcf737bfb54793 | 652,298 |
def is_legacy(user_agent: str) -> bool:
"""
Process the Django HttpRequest.headers['user-agent'] which is the same
that request.META['HTTP_USER_AGENT'] to gets the browser and the
version if the user agent is from firefox version less or equal than
33 return True ( is a legacy browser )
Refe... | 85ff1c91241eea03619b7980def6d9aadc88d5c2 | 652,299 |
def get_or_create(table, **fields):
"""
Returns record from table with passed field values.
Creates record if it does not exist.
'table' is a DAL table reference, such as 'db.spot'
fields are field=value pairs
Example:
xpto_spot = get_or_create(db.spot, filename="xptoone.swf", \
descrip... | 55e1fea3dfa3df2548bbd525bef17b762a4be06a | 652,300 |
def get_py_param_type(context):
"""convert a param type into python accepted format.
Related to the formats accepted by the parameter under dynamic reconfigure
Args:
context (dict): context (related to an interface description)
Returns:
str: variable type in python format related to pa... | e8703b4d89350f2388a1d9bbcea894a5e1f4685f | 652,301 |
import tempfile
def _new_xyz_file():
"""Generate PDB file using tempfile.NamedTemporaryFile.
Return
------
_ : file-object
Temporary PDB file.
"""
return tempfile.NamedTemporaryFile(suffix=".xyz", delete=False) | ae41abd132bb79c96acc4958f961bd348e9e4486 | 652,302 |
def get_city_by_id(item_id):
"""Get City by Item ID.
Given the item ID of a luxury good, return which city it needs to be brought to.
Args:
item_id (str): Item ID
Returns:
str: City name the item should be brought to.
"""
ids_to_city = {
"RITUAL": "Caerleon",
... | a596de15dfa96e75fd468ef0a38af294b64ba677 | 652,303 |
def pose_dict_to_numpy(pose):
"""
Conert pandaset pose dict to a numpy vector in order to pass it through the network
"""
pose_np = [pose["position"]["x"],
pose["position"]["y"],
pose["position"]["z"],
pose["heading"]["w"],
pose["heading"][... | 3ea6d839e5550fa758c0532f178440f729936bc1 | 652,304 |
def _related(f1, f2):
"""return True if f1 and f2 filectx have a common ancestor
Walk back to common ancestor to see if the two files originate
from the same file. Since workingfilectx's rev() is None it messes
up the integer comparison logic, hence the pre-step check for
None (f1 and f2 can only b... | d63da31f7915a06a669575549d8493cf5c859362 | 652,305 |
import requests
def fetch_label_id(label_name, page):
"""Service to create a messenger label using FB graph API.
:param label_name: A string containing name of a label to be created.
:param page: FacebookPage model instance
:returns: ID of newly created messenger label
:raises: Abstract excepti... | e6ff0df7d00a4666e87bf5a4816939d69d6b9b3a | 652,306 |
def part2(data):
"""
>>> part2([
... ({'trh', 'fvjkl', 'sbzzf', 'mxmxvkd'}, {'dairy'}),
... ({'mxmxvkd', 'kfcds', 'sqjhc', 'nhms'}, {'dairy', 'fish'}),
... ({'sqjhc', 'fvjkl'}, {'soy'}),
... ({'sqjhc', 'mxmxvkd', 'sbzzf'}, {'fish'})
... ])
'mxmxvkd,sqjhc,fvjkl'
>>> pa... | 3d44941a56ccead9eab5482802fe93d433d759df | 652,307 |
def set_quality(image, **kwargs):
"""
Sets JPG images' quality.
"""
image.quality = kwargs['quality']
return image | 75031030524c4e78ff8ad101f75b07204d10afe0 | 652,308 |
from typing import Any
from typing import Optional
def maybe_add_length(obj: Any, length: Optional[int]) -> Any:
"""Change the class of obj to a subclass with predefined __len__ if needed."""
# By adding length to the dataset we let HF calculate steps per epoch
# and other such values. Without length, it'... | bdeb8c9a08a77b6367bb13d6126a4e0cfb9afb08 | 652,310 |
def Descending_Order(num):
""" descending_order == PEP8 """
return int(''.join(sorted(str(num), reverse=True))) | 6e3fa968ca208135146132b86797ec93cd828df4 | 652,311 |
import pkg_resources
def closures_filename():
"""A filename for closures."""
return pkg_resources.resource_filename(__name__, "data/opensUnix150807.txt") | 8d7f4339d23e6a28439b00f56c12fd99cf3208b4 | 652,312 |
import json
def get_url_mapping(api, headers=None):
"""Fetch the mapping of project id to url from luci-config.
Args:
headers: Optional authentication headers to pass to luci-config.
Returns:
A dictionary mapping project id to its luci-config project spec (among
which there is a repo_url key).
"... | 5fe78885f9423758a9b356189c10b4b5567397cd | 652,313 |
def filter_sublists_with_id(input_list, length):
"""
:param input_list: [id, start, end, list of raw clusters]
:param length:
"""
if length > len(input_list[1]):
length = len(input_list[1])
return ([input_list[0], i, i + length - 1, input_list[1][i: i + length]] for i in
ran... | e922a1c0844e49c52a77b81bcf4c7b6bbf18b2c4 | 652,315 |
def low16(i):
"""
:param i: number
:return: lower 16 bits of number
"""
return i % 65536 | fbb4aab069ccc2cdecec86517dde820df73559fe | 652,316 |
import re
def validate_str_like_alphabet(i_str):
"""检查str模式是否只含大小写字母,以及下划线
Args:
i_str: str
Returns:
: bool
"""
url_pattern = r"^[\w_]+$"
pattern = re.compile(url_pattern)
res = re.findall(pattern=pattern, string=str(i_str))
res = True if res else False
return res | ddea4a36b6b154cb42def68821dd79ceb8de6922 | 652,317 |
def scheme_c_number_continuous(start_value=10, end_value=30):
"""Generate a continuous series
Args:
start_value (int or float): First number in continuum
end_value (int or float): Last number in continuum
Returns:
lambda: generates a descriptor for a continuous mapping
See Als... | c57f0e9bd9e41f78bf2e5f4bcfa91acb4bd8fc13 | 652,319 |
def _check_gradients():
"""Verify some borderline gradient computation
>>> a = torch.zeros(1, 3, 1, 1, requires_grad=True)
>>> b = torch.zeros(1, 3, 1, 1, requires_grad=True)
>>> deltaE(a, b).backward()
>>> torch.any(torch.isnan(a.grad)).item()
0
>>> torch.any(torch.isnan(b.grad)).item()
... | cb080d37733aba54ac29a4a6828819717b75dfa8 | 652,320 |
from numpy import exp
def Guinier(q,I0,Rg):
"""Returns Guinier approximation to the SAXS intensity distribution, as
parameterized by I0 and Rg, as a function of q."""
return I0*exp(-(q*Rg)**2/3) | 9fc2a333dd9d249216c15c7795c9d355353d63d5 | 652,321 |
def scaleYAxis(scl):
""" Calculates Y-axis scaling factor for internal data correction
:returns:
A float, Y-axis scaling correction for data
"""
if scl== 0:
return 1
elif scl == 1:
return 1/3
elif scl == 2:
return 1/9 | dea746f99034278cb46ab251a5631e7fcd2e8cc6 | 652,323 |
def client_bash(client, command, verbose=True):
"""
small wrapper for ssh client calls, always want to print
console in and console errors, will save from printing
every single time
"""
stdin, stdout, stderr = client.exec_command(command)
if verbose:
print('\n'.join(stdout.readlines... | 65cbae51661e5987e6421f858d0742c2153ab115 | 652,324 |
import sys
from os import access, F_OK
import os
def set_python_dll_path():
""" On windows, find which of the two usual hiding places the python
dll is located.
If the file can't be found, return None.
"""
version = sys.version[:3]
v = version.replace('.','')
dllfilename = 'python%s.dll' %(v)
libs... | 14e1aac0cf5eef9c3d6088025aaa0f429864aee1 | 652,325 |
def gcd(a,b):
"""gcd(a,b) returns the greatest common divisor of the integers a and b."""
a = abs(a); b = abs(b)
while (a > 0):
b = b % a
tmp=a; a=b; b=tmp
return b | 1c97e04e39b4aff0f97b58e98b500965f58b9c66 | 652,326 |
def average_height(team, num_team_players):
"""Calculates the average height(inches) for the team"""
team_total_height = 0
for player in team['team_players']:
team_total_height += player['height']
return round(team_total_height / num_team_players, 1) | 087097e46d8267d82fac7c03193bf932f611a2fd | 652,327 |
from pathlib import Path
def get_test_data_path(request, name) -> Path:
"""Helper method to retrieve the path of test data."""
return Path(request.fspath).parent.joinpath("data").joinpath(name) | 2e87df1c52154e56f9ae9f4f1f9aa826c2c4c4f1 | 652,328 |
def flesch_kincaid_grade_level(word_count, syllable_count):
"""Given a number of words and number of syllables in a sentence, computes the
flesch kincaid grade level.
Keyword arguments:
word_count -- number of words in the sentence
syllable_count -- number of syllables in the sentence
"""
r... | 1bf91db4e5bd0aa8aff88a99f383bfa756e67ebf | 652,329 |
def _convert_to_seconds_and_microseconds(date):
"""Converts a PyEphem date into seconds"""
microseconds = int(round(24 * 60 * 60 * 1000000 * date))
seconds, microseconds = divmod(microseconds, 1000000)
seconds -= 2209032000 # difference between epoch 1900 and epoch 1970
return seconds, microseconds | dbe0e48dfd26d11298a4cf508396c6dd46408f95 | 652,330 |
def is_vulnerable(myversion,minversion,maxversion):
"""
is_vulnerable(tuple,tuple,tuple) -> boolean
function checks whether a given kernel version is in a certain range of vulnerable kernel versions
"""
if ((minversion <= myversion) and (maxversion >= myversion)):
return True
else... | c620e19768c11dec1dd15e3543b37fdbfe96edc4 | 652,331 |
def is_diacritical(character):
"""Determine whether the current character is a diacritical.
Includes rough breathing mark, accent, iota subscript, umlaut/dieresis.
"""
return ")(\\/=|+".find(character) > -1 | 5455bed9db0ee4d3536dffe895b22721446d2b43 | 652,332 |
import socket
def get_ip_address():
""" This function returns the IP of your machine."""
return {
"message": "The IP address is: %s!" % socket.gethostbyname(socket.gethostname())
} | c823c1606685114960cb285b6642c82ca7abff8d | 652,333 |
import collections
def namedtuple_make():
"""cls._make(...): Create new instance from a tuple."""
kart_class = collections.namedtuple('Kart', 'celerity size')
rocket_kart = kart_class._make((1000, 'small'))
return "{} km/h is faaast!!".format(rocket_kart.celerity) | 0c30d1cfad2e747d415c4ccb6ff03a796b2f451c | 652,334 |
def concat_words(text):
"""
This method will concat first and last
words of given text
The below line is for unit tests
>>> concat_words('This is for unit testing')
'Thistesting'
"""
words = text.split()
first_word = words[0]
last_word = words[len(words) - 1]
return first_w... | 0e0f8bb3ce2aa995d5cbd15130c2a9a6f8d9fb2f | 652,336 |
def from_args_fallback(args, key, fallback):
"""
Lazy look into args for key, else fallback message.
:param args:
:param key:
:param fallback:
:return:
"""
return args[key] if args.__contains__(key) else f'{fallback}' | 454ef474c0708c6ed26bf0331673a5d62478ee24 | 652,338 |
import re
def remove_urls(text):
"""
Utility function to clean the text by removing urls.
: param path
: return text(str)
"""
url_pattern = r'(?:(?:http|https|https://www|https://|http://|):\/\/)' \
'?([-a-zA-Z0-9.]{2,256}\.[a-z]{2,4})\b(?:\/[-a-zA-Z0-9@:' \
'%_\+.~... | 550ea78b1aa7d7daf47e37074524449c4e426dd5 | 652,339 |
def merge(defaults, file, env):
"""Merge configuration from defaults, file, and environment."""
config = defaults
# Merge in file options, if they exist in the defaults.
for (k, v) in file.items():
if k in config:
config[k] = v
# Merge in environment options, if they exist in t... | bc79ae7041a82bcddb190f292db3aefc2d88bac2 | 652,340 |
import uuid
def generate_uuid():
"""Fenerates a unique user id based the host ID and current time"""
return str(uuid.uuid1()) | 6dce830e5feffe8d96c19d6c66946c41c986ec2e | 652,341 |
import os
def path_to_valid_filepaths_list(data_path):
"""
Make list of valid filepaths from data_path which could be a directory
or a filepath.
:param data_path: path to directory or file
:type data_path: str
:returns: list of file paths
"""
data_path = os.path.abspath(os.path.expand... | 53a62835d9c2520a37538760ce76ab952135bfa3 | 652,342 |
def factorial(number):
"""Return the factorial of a number."""
accumulator = 1
for n in range(1, number + 1):
accumulator *= n
return accumulator | 8d52e741feb0555b674a3f9fbeabacc8a13a333c | 652,343 |
def remove_whitespace(x):
"""
Helper function to remove any blank space from a string
x: a string
"""
try:
# Remove spaces inside of the string
x = "".join(x.split())
except:
pass
return x | d592d72959fc3096acee89d43b13a66f35a54d18 | 652,344 |
def _auc_for_metrics_set(metrics_set):
"""
Assuming the set is in threshold sorted order.
"""
last_precision = None
last_recall = None
total_area = 0.0
for m in metrics_set:
precision = float(m["tpr"])
recall = float(m["ppv"])
if last_precision and last_recall:
total_area += (rec... | c8938ccb026f9ec6e283833a635052fa721aaa1b | 652,345 |
def get_clean_messages(author, dataframe, limit=None, min_interval=None, max_interval=None, rand=False):
"""Retrieve the cleaned messages by a given author from a dataframe.
min_interval, max_interval allow for only messages with a certain range of
messageInterval to be selected. if True, rand will randomiz... | a3cb78d208e154c8a04fad1584d44a479636c048 | 652,346 |
def binaryArrayXOR(arr1: list, arr2: list) -> list:
"""
将两个二进制字符数组进行异或运算,如['0', '1', '0']^['0', '0', '1']=['0', '1', '1']
:param arr1: 二进制字符数组1
:param arr2: 二进制字符数组2
:return: list
"""
res = []
for i in range(len(arr1)):
res.append(str(int(arr1[i]) ^ int(arr2[i])))
return res | 6e5d6ea86cc3bed749410eef593a61801172a2a9 | 652,347 |
def progressBar(curr, total, b_length=60, prefix='', suffix='', decimals=0):
"""Return the progress bar
Code from https://gist.github.com/aubricus/f91fb55dc6ba5557fbab06119420dd6a
"""
str_format = "{0:." + str(decimals) + "f}"
percents = str_format.format(100 * (curr/ float(total)))
filled_len ... | e91e516707800fbb901b710199bc625affc69af6 | 652,348 |
import os
def expand_user(path):
"""Expand '~'-style usernames in strings.
This is similar to :func:`os.path.expanduser`, but it computes and returns
extra information that will be useful if the input was being used in
computing completions, and you wish to return the completions with the
origina... | 90d4b1641a373c80fb44d48ee6db9af33ebf2838 | 652,349 |
import binascii
def hex_decode(string):
"""
Hex decode string
Parameters
----------
string : str
String to be decoded from hexadecimal
Returns
-------
str
Text string with ASCII / unicode representation of hexadecimal input string
"""
return binascii.a2b_hex(st... | 5513101514bded4b28f1a6b0038ce9a6f2dfac87 | 652,350 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.