content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def sec2ts(time_s):
""" Convert time in seconds to timestamp """
return int(time_s * 1e9) | 40cc4240a17c502182562224264c283571e6f33c | 681,469 |
import re
def find_cites(f):
"""Return keys to cited papers.
"""
with open(f) as fp:
lst = re.findall(r"{{(.+?)}}", fp.read())
refs = []
for l in lst:
if "site.data.refs" in l:
refs.append(l.split(".")[3])
return sorted(set(refs)) | c54033c52e995dcfed331f68d73897756bbb125c | 681,470 |
import torch
def plusminus(mean, std):
"""Helper function for generating 95% CIs as the first dim of a tenson"""
p95 = 1.96 * std
return torch.stack([mean - p95, mean, mean + p95]) | 3855ced9ae53b873ca118acfd11ce91a69a3fae0 | 681,471 |
import os
def get_pants_cachedir() -> str:
"""Return the pants global cache directory."""
# Follow the unix XDB base spec: http://standards.freedesktop.org/basedir-spec/latest/index.html.
cache_home = os.environ.get("XDG_CACHE_HOME")
if not cache_home:
cache_home = "~/.cache"
return os.pat... | f899872df4fdf4e050bd6c0badfb240dbedd269e | 681,472 |
def replace_dictated(data):
"""
This is a workaround to handle dictation (spoken word audio containing punctuation),
in case the cloud api does not provide adequate support for properly converting dictation to punctuation.
:param data:
:return:
"""
return data.replace(" period", ".") \
... | 6277075f9e6b02e41bed1c8a9e3fbda6b5495335 | 681,473 |
from typing import Dict
from typing import Any
def flipm(table: Dict[Any, Dict[Any, Any]]) -> Dict[Any, Dict[Any, Any]]:
"""Handles shuffles for a particular kind of table."""
ret = {}
for k, m in table.items():
for k2, v in m.items():
ret.setdefault(k2, {})[k] = v
return ret | 50513bc396210836af7a32151f964b35d4234480 | 681,474 |
import os
def last_timestamp(filename):
"""
find the most recent timestamp in a csv File
"""
if not os.path.exists(filename):
return 0
with open(filename, "rb") as file_handle:
file_handle.seek(0, os.SEEK_END)
taille = min(file_handle.tell(), 100)
if taille != 0:
... | 1145948c6a469ab3e19e8d546a3bccdcafced778 | 681,475 |
def GetParents(obj):
"""Recursively search for the highest parent object"""
if obj.parent == None:
return obj
elif obj.parent != None:
GetParents(obj.parent) | af3f983b5da921cd84e8d30b1872da02a5694aba | 681,476 |
def mag(*args):
""" Magnitude of any number of axes """
n = len(args)
return (sum([abs(arg)**2 for arg in args]))**(1/2) | 61ac6e83c251e47afa8f94e1ffa214e72d9b16cb | 681,477 |
def c(n, alpha, beta, x):
"""The third term of the recurrence relation from Wikipedia, * P_n-2^(a,b)."""
term1 = 2 * (n + alpha - 1)
term2 = (n + beta - 1)
term3 = (2 * n + alpha + beta)
return term1 * term2 * term3 | da3ddfc81f96385478e526594af91a749081b0f8 | 681,478 |
def optimization_closure(iter_number, original_image_torch, image_net, original_input,
reg_noise_std, loss_function):
"""
:param original_image_torch: the original image as pytorch tensor
:param float reg_noise_std: additional noise for the input
:param loss_function: the loss ... | 83b389acb3deee86eb9b9744bb3d09a105c213c9 | 681,479 |
def probe_id(subscription_id, resource_group_name, load_balancer_name, name):
"""Generate the id for a probe"""
return '/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Network/loadBalancers/{}/probes/{}'.format(
subscription_id,
resource_group_name,
load_balancer_name,
na... | 64cacdcc4a084ddc551532fac1f71decc4c286fc | 681,480 |
def baumgartner_rating(baumgartner_index):
""" Compute Baumgartner Danger Rating.
Parameters
----------
baumgartner_index : array
Baumgarner index value.
Returns
-------
class
Baumgarner index value at current timestep.
"""
# TO DO
return baumgartner_index | 1494a4f365c83a451577b90dd119890e2266dae0 | 681,481 |
def get_bricks_loc(catalog_dir, data_release):
"""
Returns:
(str) location of bricks catalog, including center and exposure counts.
Input file for DR1, DR2. Calculated from brick_coordinates_loc and brick_exposures_loc for DR5.
"""
if data_release == '5' or data_release == '3':
... | a390e0a92c2997dadff737b7e89db8b1ac0db68f | 681,482 |
def bubble_sort(items):
"""Sorts a list of items.
Uses inserstion sort to sort the list items.
Args:
items: A list of items.
Returns:
The sorted list of items.
"""
for i in range(1, len(items)):
for j in range(1, len(items)):
if items[j] < items[j - 1... | 22709b87eb569e6247e49a544631d21e5ad7f58a | 681,483 |
def search_by_sware_hware(nodes: list, option: int) -> dict:
"""
Search by software/hardware.
Return all unique entries in ``nodes`` list at ``option`` index as
keys and all hostnameswhich contains the entry in list as value.
:param nodes: list of nodes.
:param option: Index in the nodes list(... | 5ee7978f26bccbe577c6e2c8deff23745de595f2 | 681,486 |
def get_default():
""" "Define mcflu default parameters as dictionary. """
settings = {'metrics': ['accuracy'],
'model_types': ['CNN', 'DeepConvLSTM', 'ResNet', 'InceptionTime'],
'cnn_min_layers': 1,
'cnn_max_layers': 10,
'cnn_min_filters': 10,
... | 231595158774ea3afe58bd4b2d835ffc642a29a3 | 681,487 |
def sort_columns(args, all_columns, column_types):
"""Put columns into an order useful for displaying."""
columns = [args.group_by, args.key_column]
if args.user_column:
columns += [args.user_column]
columns += [c['name'] for c
in sorted(column_types.values(), key=lambda x: x['or... | 0d2b57d31364c13405d37c64badc745d9b4f9311 | 681,488 |
from typing import Iterable
from typing import List
import string
def quote_args(args: Iterable[str]) -> List[str]:
"""Quote the arguments which contain whitespaces"""
r = []
for arg in args:
if any(map(lambda c: c in string.whitespace, arg)):
r.append(f'"{arg}"')
else:
... | bcc59d7b684e8330b31fc240edcbf28b1c69c33f | 681,490 |
import hashlib
def get_file_md5(path):
"""
Retrieves the md5sum of a file's contents.
Args:
path: string path of the file to hash.
Returns:
string md5sum hash.
"""
hash_md5 = hashlib.md5()
with open(path, 'rb') as in_file:
hash_md5.update(in_file.read())
ret... | afbc03e2da7b6140db54cf0e1d268db1c44a8ceb | 681,491 |
import subprocess
def perform_flattening(tag):
"""Parse the command line args
Args:
tag: Image Tag in image-name:image tag format
Returns:
int: pass / fail status
"""
# First detect which docker/podman command to use
cli = ''
image_prefix = ''
cmd = 'which podman || t... | 049f3d8645190c4c3032dd8b942ce86e2a4e73fa | 681,492 |
import os
import time
import json
import hashlib
def cache(function):
"""
Simple decorator function for caching.
Usage:
1 import cache from cache
2
3 @cache
4 def example(self, text):
5 return text * 2
In this example the result of the example function is cached.
Current lim... | a940eef5d49ebf1c8e1aec5026ce1f967ad9f33f | 681,493 |
def finite_diff(expression, variable, increment=1):
"""
Takes as input a polynomial expression and the variable used to construct
it and returns the difference between function's value when the input is
incremented to 1 and the original function value. If you want an increment
other than one supply ... | d216fd03af231c25ca786ca191a27e0ce498de87 | 681,494 |
def parse_file(file_path):
"""Parse file with lines: retailer url
Args:
file_path: The path to the url file
Returns:
dict: {'retailer1': 'url1', 'retailer2': 'url2'...}
"""
file = open(file_path)
retailer_dict = {}
for line in file:
try:
words_in_lin... | d7047aee3f9171264f49b97cf422f9b0ad94ca2a | 681,495 |
def simulate_expected_results_R():
"""
obtained from ets.simulate in the R package forecast, data is from fpp2
package.
library(magrittr)
library(fpp2)
library(forecast)
concat <- function(...) {
return(paste(..., sep=""))
}
error <- c("A", "M")
trend <- c("A", "M", "N")
... | 3bf63b296bc5f3f13380202e9dc2b7b60bb965ea | 681,496 |
def civic_eid1409_statement():
"""Create test fixture for CIViC Evidence 1406."""
return {
"id": "civic.eid:1409",
"description": "Phase 3 randomized clinical trial comparing vemurafenib with dacarbazine in 675 patients with previously untreated, metastatic melanoma with the BRAF V600E mutation.... | 75eb2ae573966fe4d84ea0f26904f66fbd0b47a9 | 681,497 |
def param_enabled(param_obj):
"""Return True if param is enabled, False otherwise"""
enabled=True
if "enabled" in param_obj:
if param_obj['enabled'].lower() == "no":
enabled=False
del param_obj["enabled"]
return enabled | 6824b7bc5d34bb836436f7b83a19c28815db1c9d | 681,498 |
async def screen(
# see lines 32-45 to see purposes of args
firstName,
lastName,
email,
stateCode,
schoolCode,
session,
answer1=0,
answer2=0,
answer3=3,
floor="",
):
"""
Function to fill out doe health screening.
Variables are all as their name implies.
"""
... | 874be3f9956f1c891069b39a187307366e8ddf3c | 681,499 |
def _sar_range(dicoms):
"""Find the minimum and maximum SAR values in a list of DICOM headers."""
sars = set([float(d.SAR) for d in dicoms])
return str(min(sars)), str(max(sars)) | ab2eab38a491d15af15e9301ecb7ff783207e954 | 681,500 |
def get_from_list(list, name):
""" searches through list of objects with a .name attribute or surface_shaders and returns the object if it exists or None if not """
for item in list:
if item.name == name:
return item
return None | 3013b60f19be5f7b425762717b990ed4c7ae9081 | 681,501 |
import argparse
def _ParseCLIArgs():
"""Parses the command line arguments.
Returns:
tuple<Namespace, list<str>> The first value of the tuple is a Namespace
holding the value of the optional args. The second value of the tuple is
a list of the remaining arguments.
"""
parser = argparse.ArgumentPar... | 72f182a76641c5af843906bf173b0bdc7e84786f | 681,502 |
def range_constructor10():
"""Solution to exercise R-1.10.
What parameters should be sent to the range constructor, to produce a
range with values 8, 6, 4, 2, 0, −2, −4, −6, −8?
"""
return range(8, -10, -2) | 236c8e7d8bdc51f911f8fc82360acf3ee07ef16a | 681,503 |
def format_size(nb_bytes):
"""
Format a size expressed in bytes as a string
Parameters
----------
nb_bytes : int
the number of bytes
Return
------
formated : str
the given number of bytes fromated
Example
-------
>>> format_size(100)
'100.0 bytes'
>... | 0a3147d75571bc862749c41d0465ffe89b3c4ab4 | 681,504 |
def get_method_color(method):
"""
Return color given the method name.
"""
color = {}
color['Random'] = 'blue'
color['Target'] = 'cyan'
color['Minority'] = 'cyan'
color['Loss'] = 'yellow'
color['BoostIn'] = 'orange'
color['LeafInfSP'] = 'brown'
color['TREX'] = 'green'
colo... | 42cb4c7a8ecac135697a335dbc72a10fcb4e2da9 | 681,505 |
import gzip
import bz2
import lzma
def fopen(filename, mode=None):
"""GZ/BZ2/XZ-aware file opening function."""
# NOTE: Mode is not used but kept for not breaking iterators.
if filename.endswith('.gz'):
return gzip.open(filename, 'rt')
elif filename.endswith('.bz2'):
return bz2.open(fi... | b384cae1b40b409b3d16b4431565d493da8d363f | 681,506 |
from typing import Type
from typing import Any
def public_members_as_dict(class_: Type[Any]) -> dict:
"""
Converts a class into a dict of its public values
:param class_: the class to be converted
:return: the public values from the class
"""
result = {}
for i in class_.__dict__.items():
... | 399d102e48c3cb89ebf3661a52f11898b032d459 | 681,508 |
def determine_final_freq(base, direction, modifier):
"""Return integer for frequency."""
result = 0
if isinstance(direction, bytes):
direction = direction.decode("utf-8")
if direction == "+":
result = base + modifier
elif direction == "-":
result = base - modifier
return ... | 4d790f2d149a5021251a9a152755444db4c5b578 | 681,509 |
def to_celsius(fahrenheit):
"""
Accepts degrees Fahrenheit (fahrenheit argument)
Returns degrees Celsius
"""
celsius = (fahrenheit - 32) * 5/9
return celsius | ddb0b75550d623802bcbde70be39ed53d7c3d0c6 | 681,511 |
import warnings
def deprecated(message):
""" definition for deprecated methods """
def deprecated_decorator(func):
def deprecated_func(*args, **kwargs):
warnings.simplefilter('always', DeprecationWarning)
warnings.warn(\
"{}() is a deprecated function. {}".format(... | 2dd131b9d25c5058c19b2e16df154c07cb1d6753 | 681,512 |
def keep_matched_keys(dict_to_modify,model_keys):
"""
Drops only the keys of a dict that do **not** have the same name as the keys in a source dictionnary.
Return dictionnary containing the rest.
Args:
dict_to_modify (TYPE): DESCRIPTION.
source_dict (TYPE): DESCRIPTION.
Returns:
... | 6baaa0f52da0a86697ab798e11fe288f5849a8e1 | 681,513 |
def replace_first_sentence(text, replacement):
""" Replace the first sentence in text with replacement. This makes
some incredibly simplifying assumptions - so buyer beware. """
no_periods_replacement = replacement.replace('.', '')
sentences = text.split('.', 1)
if len(sentences) > 1:
sente... | 5c51d60d90b47e59a013de7a10d193af6385575d | 681,514 |
import argparse
def parse_args():
"""Parse command line arguments"""
parser = argparse.ArgumentParser(
description="Confluent Python Client example to produce messages \
to Confluent Cloud")
parser._action_groups.pop()
required = parser.add_argument_group('required argu... | fb61f4fa75cb960d0d8b5887cfb09ed346c5a7ef | 681,515 |
from typing import List
def quote(*seps, strip=False):
"""Rule: Prevent splits between quote characters."""
stored, inners, match = [], [], []
for _sep in seps:
_sep, _size = list(_sep), len(_sep)
# noinspection PyDefaultArgument,PyShadowingNames
def inner(buffer: List[str], sep=... | d1a29b17820b6a64e6038eb9bc510576d62e0e14 | 681,516 |
def length_vs_references(articles):
"""
:param collection A PyMongo collection object
:return Histogram as a dictionary in the form described above
"""
match_1_stage = {
"$match": {
"references": {"$exists": True, "$ne": []},
"page_start": {"$exists": True, "$ne": ""... | 43afc522544339874b50d76dc198fd48c114596e | 681,517 |
def get_build_info(input_file):
"""Get build information in UCSC notation, if possible."""
build_dict = {
"hg38": ["GRCh38"],
"hg19": ["GRCh37", "b37"],
"mm10": ["GRCm38"],
"mm9": ["MGSCv37"],
"rn6": ["Rnor_6.0"],
}
with open(input_file, "r") as tfile:
bu... | 54fa87f95b92462bb1879a040213746b0aa99c41 | 681,518 |
import subprocess
def get_total_ram():
""" Return the total amount of ram of the system in kB as an integer.
"""
proc = subprocess.Popen(["cat /proc/meminfo"],
stdout=subprocess.PIPE, shell=True)
(output, error) = proc.communicate()
ram_info = output.decode("utf-8").spl... | 838ffd10011475175974665f2045e0dc3bc5c2a5 | 681,519 |
def vector2d_to_facing(vector):
"""
Convert a string facing to a vector2d.
Parameter
---------
vector: vector2d to convert in facing (tuple(int, int)).
Return
------
facing: facing <up|down|left|right|up-left|up-right|down-left|down-right>(str).
Version
-------
Specificati... | 3b8445a765bd39b53053ba19df6f8cf889c6c3d7 | 681,520 |
def check_brack_c(inp, brack, count):
"""
Help funktion for balance brackets
"""
if inp == brack:
if count != 1:
print("No match")
return 0
else:
count -= 1
return 1 | 47a3f06e6296986a08534d286934675d620a7457 | 681,521 |
def is_even(number: int) -> bool:
"""
This method will find if the number passed is even or not
:param number : a number
:return: True if even False otherwise
"""
if number <= 0:
return False
return number % 2 == 0 | f39ff3ac60c1a9a6c4c08df62fba01b0ad940726 | 681,523 |
def _parse_ref_dict(reference_dict, strict=True):
"""Parse the referenced dict into a tuple (TYPE, ID).
The ``strict`` parameter controls if the number of keys in the
reference dict is checked strictly or not.
"""
keys = list(reference_dict.keys())
if strict and len(keys) != 1:
raise V... | fd15711b5c3abda9e4f1246a84a407cd29f3dd38 | 681,525 |
import re
def search_content(key, content, fmat='attr'):
"""
@brief Search content from xml or html format
@param key String
@param content String
@param fmat attr
xml
@return String
"""
if fmat == 'attr':
pm = re.searc... | 616075fbe4974c1303d523eefe6bff09e78f361c | 681,526 |
def clone(src, **kwargs):
"""Clones object with optionally overridden fields"""
obj = object.__new__(type(src))
obj.__dict__.update(src.__dict__)
obj.__dict__.update(kwargs)
return obj | 85795b14c12dd5e592b0339cf9986f098c9ef2fa | 681,527 |
import requests
import logging
def delete_catalog(access_token, catalog) -> bool:
"""Tries to delete the catalog."""
headers = {
"Authorization": f"Bearer {access_token}",
}
url = catalog["identifier"]
response = requests.delete(url, headers=headers)
if response.status_code == 204:
... | 39492d7bbef08dc442a37ac3d304bc709c96655a | 681,529 |
def yLP2DP(lpY, lptLT, lPix = 1.0):
"""Convert logical coordinates into device coordinates
lpY - y logical coordinate
lptLT - logical coordinates of left top screen corner
lPix - zoom value, number of logical points inside one device point (aka pixel)
return coordinate in device c... | 8f0bb59f882bd9b33b37235bd064cd4bc21b35c8 | 681,531 |
def dot_dir_dir(direction1, direction2):
""" Evaluates the dot product of a direction with another direction.
PARAMETERS
----------
direction{1, 2}: Point
RETURN
------
: float
"""
return sum((dir_coord1*dir_coord2 for dir_coord1, dir_coord2 in zip(direction1.coords, direct... | bb0364394b961f427156a01b7a4361d889f46e8f | 681,532 |
import socket
def find_available_port():
"""Return an IPv4 port number that is not in use right now.
We assume whoever needs to use the returned port is able to reuse
a recently used port without waiting for TIME_WAIT (see
SO_REUSEADDR / SO_REUSEPORT).
Some opportunity for races here, but it's b... | ae51664b0132486f6f8edba183bbe45d723dd2cb | 681,533 |
def getpgid(pid):
"""Return the process group id of the process with process id *pid*. If *pid* is 0,
the process group id of the current process is returned."""
return 0 | db2ccc93824b48083b6f0e6e32bb6563daad2afc | 681,535 |
def to_bolean(value, default_value=False):
"""
Convert string value to a boolean.
"""
if value is None:
return default_value
if isinstance(value, bool):
return value
return not (value.lower() == 'false') | 0f12bcd8d62715246300ff1f5d7cd500f796ad1c | 681,536 |
def lowercase_words(text):
"""
Method used to transform text to lowercase"
Parameters:
-----------------
text (string): Text to clean
Returns:
-----------------
text (string): Text after transforming to lowercase.
"""
text = text.lower()
return text | 941a23032dd7416eb03570c2629edb74b3d315d9 | 681,537 |
def remove_zeros(r, M):
"""
image processor to remove zero
:param r: Source image measure
:param M: Cost matrix
:return: Processed r and M with zeros removed
"""
M = M[r > 0]
r = r[r > 0]
return r, M | d742326d0a18f08b26badd06095677bec9bd03d2 | 681,538 |
def cycle_slice(sliceable, start, end):
"""Given a list, return right hand cycle direction slice from start to end.
Usage::
>>> array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> cycle_slice(array, 4, 7) # from array[4] to array[7]
[4, 5, 6, 7]
>>> cycle_slice(array, 8, 2) # from arra... | 15ef9e3cb5243e31d2d4cbb4717955ff0e611a6e | 681,539 |
import importlib
def make_checker(checker_cls, tmp_dir, **kwargs):
"""Returns a checker object.
Parameters
-----------
checker_cls : str
the Checker class absolute path name.
tmp_dir : string
directory to save temporary files in.
kwargs : dict
keyword arguments needed ... | 4a617e58b6e4cffc95b1c9aabe4ceca5e0f65f2a | 681,540 |
def index_by_iterable(obj, iterable):
"""
Index the given object iteratively with values from the given iterable.
:param obj: the object to index.
:param iterable: The iterable to get keys from.
:return: The value resulting after all the indexing.
"""
item = obj
for i in iterable:
... | b167775ba331244361492e64e01cb1db92410f67 | 681,541 |
def alias_map(templ):
"""
aliases map
Expand all the aliases into a map
This maps from the alias name to the proper column name
"""
aliases = dict()
for field in templ:
aliases[field] = field
aliases[field.lower()] = field
for alias in templ[field].get('aliases',[]):
... | c543bd956410e9a180752df4e40d92c44d8eb900 | 681,542 |
def create_8021Q_vea_cmd(lpar_id, slotnum, port_vlan_id, addl_vlan_ids):
"""
Generate IVM command to create 8021Q virtual ethernet adapter.
:param lpar_id: LPAR id
:param slotnum: virtual adapter slot number
:param port_vlan_id: untagged port vlan id
:param addl_vlan_ids: tagged VLAN id list
... | b0d745c12e9f6c192f1d9c54d94c33a737e1d011 | 681,543 |
def rgb_2_luma(color: tuple) -> int:
"""
Calculate the "brightness" of a color.
...and, yes I know this is a debated subject
but this way works for just fine my purposes.
:param color: a tuple of RGB color values eg. (255, 255, 255)
:returns: luminance "brightness" value
"""
r, g, b = ... | d00760dee46a2bb7e9cb1ae45d540e431a227590 | 681,544 |
import re
def find_time_span(question, pred):
"""
验证“有效时间是多久”类型问题的答案的有效性,对预测的答案返回一个修剪的答案
:param question:对应的问题
:param pred:预测的答案
:return:修剪过后的答案
"""
if question.find('有效时间是多久') >= 0:
all_number = "零一二三四五六七八九十"
pattern1 = re.compile(r'自?[0-9]+年[0-9]+月[0-9]+日[0-9{}]*[时]?[起]?[... | 574ae6724d451de830c7b829c62cd03a76cc5e3c | 681,545 |
import torch
def get_accuracy(data_loader, classifier_fn, batch_size):
"""
compute the accuracy over the supervised training set or the testing set
"""
predictions, actuals = [], []
# use the appropriate data loader
for (xs, ys) in data_loader:
# use classification function to compute... | 0afaf3b9600c56b413b9bd6c417b0f4abeb27fb0 | 681,546 |
from typing import Sequence
from typing import List
from typing import Set
def expand_ranges(ranges: Sequence[Sequence[int]], inclusive: bool = False) -> List[int]:
"""Expand sequence of range definitions into sorted and deduplicated list of individual values.
A range definition is either a:
* one eleme... | bd18736f6def6f22195b3802046fc77dea3c8623 | 681,547 |
import uuid
def get_mac_address():
"""获取电脑的mac地址
"""
mac=uuid.UUID(int = uuid.getnode()).hex[-12:]
return ":".join([mac[e:e+2] for e in range(0,11,2)]) | 335695f01731f71608d4c34dd4bf7284b6da54ea | 681,549 |
import subprocess
import os
def git_repo():
"""
Returns the git repository root if the cwd is in a repo, else None
"""
try:
reldir = subprocess.check_output(["git", "rev-parse", "--git-dir"])
reldir = reldir.decode("utf-8")
return os.path.basename(os.path.dirname(os.path.abspat... | 158a667432b315f6bd440b29cfb96a288be889c8 | 681,550 |
def GetJidFromHostLog(host_log_file):
"""Parse the me2me host log to obtain the JID that the host registered.
Args:
host_log_file: path to host-log file that should be parsed for a JID.
Returns:
host_jid: host-JID if found in host-log, else None
"""
host_jid = None
with open(host_log_file, 'r') as... | 4e8f7d7ff3284026025fb97d59b9be4af16c81ee | 681,551 |
def compose2(f, e):
"""Compose 2 functions"""
return lambda x: f(e(x)) | 9e48818b5c4150d1af138935c712e31c58a1f9c1 | 681,553 |
import pandas
def _parser_top_10(items):
"""
:param items:
:return:
"""
for inner in items:
if inner["style"] == 2:
table = inner["table"]
columns = table["schema"][0]
rows = []
for value in table["tr"]:
rows.append(value["td"... | 6279d29cceb1cede54282bbcf823c8bab14fd360 | 681,554 |
from numpy import sum, add, argsort, sort
def weighted_median(x, w):
"""
Calculates the weighted median, that is the minimizer of
argmin {\sum w_i |x_i - \mu|}
@param x: input array
@param w: array of weights
"""
w = w / w.sum()
w = w[argsort(x)]
x = sort(x)
j = sum(add.accum... | c74214bfe263fd216b92403308abca74a9d6fe57 | 681,555 |
def filtered_tooltip(options, filter):
"""Returns tooltip for the filter icon if the filter matches one of the filter options
"""
for option in options:
if filter == option[1]:
return "Showing only %s"%option[0]
return "" | 28cb83a353f007a1e6042e91c8f3f66ac2279ea1 | 681,556 |
def _valvar(unk, vardict):
"""Determines if an unknown string is a value or a dict variable.
Parameters
----------
unk : float or str
The unknown value, either a float or a dictionary key.
vardict : dict
The dictionary to be searched if unk is not a float.
Returns
-------
... | 88d70cd5e62578ae90d699627791eb6c5fe33fc7 | 681,557 |
def rectangle(a, b):
""" Return classic logic rect function:
^ ......
| | |
|___|____|___
a b
"""
return lambda x, a=a, b=b: 1. if a <= x <= b else 0. | f8673d1edf43f4d898b21742c401af8f818166a3 | 681,559 |
def render_field_width(field):
"""."""
form = field.form
if hasattr(form, "field_widths") and field.name in form.field_widths:
width = form.field_widths[field.name]
else:
width = 5
return "col-sm-{0}".format(width) | 4f69d930e330044da6b6d9353f52c15db1fdda77 | 681,560 |
import os
def create_app_folder(root_folder, app_name, appid):
"""
Attempt to create a folder with the app name. If it fails, uses the appid.
(It could fail if the name still somehow has invalid characters after sanitizing).
Returns:
Name of the folder that was created (either app_name or app... | 5b37ea937f4ef70a8e0878858516253547dfe2ab | 681,561 |
def default_error_encode(
errors, encoding, msg, u, startingpos, endingpos):
"""A default handler, for tests"""
assert endingpos >= 0
if errors == 'replace':
return '?', endingpos
if errors == 'ignore':
return '', endingpos
raise ValueError | d0dc27975d3edf2acc71bf0f92bf43774bfaf266 | 681,562 |
import torch
def parrallel_recomb(q_t, kv_t, att_type='all', local_context=3, bin_size=None):
""" Return mask of attention matrix (ts_q, ts_kv) """
with torch.no_grad():
q_t[q_t == -1.0] = float('inf') # We want padded to attend to everyone to avoid any nan.
kv_t[kv_t == -1.0] = float('inf') ... | 285759b74fb2f8fcc01694614382dc17e872630a | 681,563 |
def noindex_create_dicts(rows, columns):
""" creating dictionary from dictonary table"""
details_dict = {}
for row in rows:
strid = row[0]
inner_dict = dict(zip(columns[0::], row[0::]))
details_dict[strid] = inner_dict
# breakpoint()
return details_dict | b603f7badeb4f47cfac9a934e2ae1cc75f55d997 | 681,564 |
def fnCalculate_Bistatic_RangeRate(speed_light,tau_u1,tau_d1,tau_u2,tau_d2,tc):
"""
Calculate the average range rate. eqn 6.37 in Montenbruck 2000.
tc = length of integration interval, i.e. length of CPI
Created: 04/04/17
"""
range_rate = (speed_light/tc)*(tau_u2+tau_d2-tau_u1-tau_d1); # removed 0.5 factor. 19.0... | 68093a69b3290d43fd42ce62489167b4e50a51c6 | 681,565 |
def unichr(i):
"""Return the Unicode string of one character whose Unicode code is the
integer i.
:type i: numbers.Integral
:rtype: unicode
"""
return '' | d02a9f8df93d2a3f76d6c786d15001d3aa4ef1cc | 681,566 |
from typing import List
def blockdiag(n: int, block_size: int = 2) -> List[List[int]]:
"""Block diagonal matrix.
Requires mod(n, block_size)==0. Is a quadratic matrix
"""
if (n % block_size) != 0:
raise Exception("n must be a multiple of block_size")
# prepare variables
n_blocks = n //... | 26e072f8878b6fb7e92a07edef48e2f9de1e5c9c | 681,567 |
from typing import OrderedDict
def get_wall_duration(op_names, all_ops, pid_list=(11, 7, 13, 15, 9)):
"""
Calculates wall duration for each op in op_names.
Params:
op_names: list (str), names of ops of interest.
pid_list: list (str), names of pid to include.
all_ops: output of get_all_ops().
... | ba2af449c1c1b96108ca3ddbc97ff0bc31064651 | 681,569 |
import os
def path_exists(path):
"""Wrapper around Google/OSS check for if file/directory exists."""
return os.path.exists(path) | 8e96e44e75881dcb9f9841b1f5061f2231ccf188 | 681,570 |
def read_biosids(bdfiles, verbose=False):
"""
REad the biosample ID files.
:param bdfiles: iterable of Files with biosample IDs
:param verbose: more output
:return: a dict of the sample_name and biosample ID
"""
biosids = {}
for fl in bdfiles:
with open(fl, 'r') as f:
... | 02d8f6790645c85a8257a9ed1bf635e5ac89da63 | 681,571 |
def tag_from_contents(contents):
"""Retrieve class name from function"""
return contents.__class__.__name__ | 1ad79a60ba148086c6735f84b27da55054a13686 | 681,572 |
import cmath
def sigmoid_integral(l, d, a, b, x):
"""
DPT Balance Function (Not Used)
:param l:
:param d:
:param a:
:param b:
:param x:
:return: balance in DPT contract
"""
return -a*d*cmath.log((1+cmath.exp((l-x)/d))/(1+cmath.exp(l/d)))+b*x | 67d8ff9e76c84036973d11c713542bf70e84765d | 681,573 |
import importlib
def _get_module_attr(module_name, attribute_name):
"""Import a module and get an attribute from it.
Args:
module_name (str): The module name.
attribute_name (str): The attribute name.
Returns:
Any: The attribute.
Raises:
ModuleNotFoundError: The modu... | 485f36fbedc2784968bcc5f393bbd3f2c5867883 | 681,574 |
def simple_app(environ, start_response):
"""Simplest possible WSGI application object"""
status = '200 OK'
response_headers = [('Content-type','text/plain')]
start_response(status, response_headers)
return ['Hello world!\n' for i in range(100)] | 59fa4d9978cf29cfb2989afb5ae6197c1b8ee054 | 681,575 |
import os
import sys
def FindExecutableOnPath(executable, path=None, pathext=None):
"""Searches for 'executable' in the directories listed in 'path'.
If 'executable' contains any directory components then 'path' is ignored. If
'pathext' is specified and 'executable' does not have any of those extensions
the... | 0ec801e754a27ee7a0ab20daae8827618628cb05 | 681,576 |
def ozone_ppm(results, temperature=22):
"""
Calculate ppm for given results array with Mol/m3 concentrion
:param results: array of results in Mol/m3
:param temperature: gas measurement temperature in celsius
:return: array of ppm
"""
P = 1e5 # pascal
V = 1 # m3
R = 8.314472 # JK-... | 01f01ab2f91d36c2fd2e3dfbddab598fe4e490e5 | 681,577 |
def css_class(field):
"""
Returns widgets class name in lowercase
"""
return field.field.widget.__class__.__name__.lower() | e6a555199c9b6762758837e0f7794bd69dc7fe09 | 681,578 |
from pathlib import Path
def get_file(filepath):
"""Return the content of a file in the test_files directory."""
full_path = Path(__file__).parent / 'test_files' / filepath
with open(full_path, 'rb') as file:
return file.read() | 8f0a03bb85cb3d0fdb26ad683bf103c5df1b30a9 | 681,579 |
def hyperbolic_formulation(duration, param, a_start=20.0, b_start=15.0, param_mean=None, duration_mean=None):
"""
Args:
duration:
param:
a_start:
b_start:
param_mean:
duration_mean:
Returns:
"""
# ---------------------------------------------------... | 825c0455763c6cc5d705ac25545d1a98fd54c65e | 681,580 |
def is_anagram(s, t):
"""
# Find if strings are anagram. t anagram of s
# @param {string, string} input strings
# @return bool if strings are anagram of each other or not
"""
s = list(s)
# Sort a string and then compare with each other
s.sort() # Quick sort O(n*log(n))
return s == ... | f884f03515088f1ebd337031870e212dd7ad0228 | 681,581 |
def eng_to_i18n(string, mapping):
"""Convert English to i18n."""
i18n = None
for k, v in mapping.items():
if v == string:
i18n = k
break
return i18n | 9287d5aa86b87f5c6585a842941657327aec35c8 | 681,582 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.