content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import platform
def is_os_64bit():
"""
returns True if os is 64bit, False if 32bit
"""
return platform.machine().endswith('64') | 12a1d0c5c6bfa87044aa134e2b48fa113b7efd0e | 625,335 |
import os
def prepare_train(df, train_ratio, data_dir, task, x_column, y_column):
"""
Prepare data for the training/evaluation process
:param df: a clean and ready for training/evaluation DataFrame
:param train_ratio: the train and evaluation split ratio
:param data_dir: the data directory
:pa... | 0d7d7dad88a24cc3a37844d07362b6ab40db4de8 | 625,336 |
import torch
def inference(model, inputs_list, hparams):
"""
Do an inference with the model for each input tensor from the provided list and
return three lists, one with the inference results, another with the differences
in the [-1,1] range and a third one with the differences scaled up and shifted f... | 264ddd17edfa9b44e35b946baf46fb58f5c552c7 | 625,338 |
import glob
def is_flagged(grid):
"""
:param grid: :class:`gridInfo`
:rtype: bool
:returns: true if flagged_grid_file_name exists and false if it doesn't
exist
"""
return bool(glob.glob(grid.file_name)) | 083821e878bd70cdd4ec727f4fd23a63af77a03a | 625,339 |
import textwrap
def format_ordinary_line(source_line, line_offset):
"""Format a single C++ line with a diagnostic indicator"""
return textwrap.dedent(
f"""\
```cpp
{source_line}
{line_offset * " " + "^"}
```
"""
) | 504f23b9ac2026ff59cd3d1ab184d9ad236fca96 | 625,340 |
def check_NWIS_site(input):
"""Checks that the USGS station site id is valid.
"""
msg = "NWIS station id(s) should be a string or list of strings, \
often in the form of an eight digit number enclosed in quotes. \
Actual value: {}".format(input)
output = ""
if input is None:
... | 21f43c3fac1cb08c210312d5f3034f6223ba68df | 625,342 |
def recta(p1,p2):
"""
Modela una linea recta, devuelve su pendiente y la funcion
que modela la recta.
"""
m = (p2[1]-p1[1])/(p2[0]-p1[0])
b = m*(-p1[0]) + p1[1]
return m, (lambda x : m*x + b) | 15819d4fff39073e54adc92f461c34e01e56c5af | 625,343 |
import argparse
import sys
def argparser():
"""parse command line arguments"""
parser = argparse.ArgumentParser(prog='parse')
parser.description = 'Earley parser'
parser.formatter_class = argparse.ArgumentDefaultsHelpFormatter
parser.add_argument('grammar',
type=str,
help... | 44f6fd6c349894643ae6d9a41b21b5568de90712 | 625,344 |
def transpose(collection):
"""
Turn a list of index upside down
[[1,2,3] --- [[1,4]
[4,5,6]] --- [2,5]
--- [3,6]]
@param collection: The original collection of indexes
@return: The transposed values
"""
return map(list, zip(*collection)) | 0228969459774ecc587f35e7b91f9ba17ac0f20e | 625,345 |
def _flatten_list_of_lists(_2d_list):
"""Input a list of lists and output one single list"""
flat_list = []
# Iterate through the outer list
for element in _2d_list:
if type(element) is list:
# If the element is of type list, iterate through the sublist
for item in ele... | 40c5ba01d789cf80cc1bf59c1ec2875cce3eff6f | 625,346 |
def has_core_metadata(response, file_type):
"""
Return True if a query response contains core metadata, False otherwise.
"""
try:
# try to access the core_metadata
response["data"][file_type][0]["core_metadata_collections"][0]
except:
return False
return True | 57d472d8f8311dcd981c8e39f9918fc271e0ab70 | 625,348 |
import argparse
def parser_get_args():
"""Collect the path to the SNP data (forward and reverse), vcf data, and
base name for output files"""
parser = argparse.ArgumentParser(
description="""Input the desired information to run POPEase."""
)
parser.add_argument(
"--runst... | b2b02c0f5144a29985cc5885274ac45852d2581c | 625,349 |
import datetime
import time
def list_datetime_to_unixtime(date_list:list)-> list:
"""
날짜데이터를 unixtime으로 바꿔주는 함수
date_list : list type
"""
# db로부터 조회한 데이터를 데이터프레임에 씌우면 컬럼값이 0, 1, 2 ...
# 보통 첫번째 컬럼이 date컬럼인 경우가 많아 0으로 설정
for index in range(len(date_list)):
# string 타입의 날짜... | e9a43b042e023fe47b393fa5a36749befdc87f9f | 625,350 |
import json
def render_values(context, value):
"""
Render query to their value
"""
if value in context.dicts[-1]:
return json.dumps(context.dicts[-1][value])
return "" | b073d7bfd4d70fe81a6e5a3f4ed71b876c7f4856 | 625,352 |
import sys
def running_under_virtualenv():
"""
Return True if we're running inside a virtualenv, False otherwise.
Note: copied from pip.
"""
if hasattr(sys, 'real_prefix'):
return True
elif sys.prefix != getattr(sys, "base_prefix", sys.prefix):
return True
return False | e4c53d74dd01ae37db34021b4b906244083f55b9 | 625,353 |
def delete_behavior_validator(value):
"""
Property: SchemaChangePolicy.DeleteBehavior
"""
valid_values = [
"LOG",
"DELETE_FROM_DATABASE",
"DEPRECATE_IN_DATABASE",
]
if value not in valid_values:
raise ValueError("% is not a valid value for DeleteBehavior" % value)... | 773d8e82f876592383ef94e38b688f3967f83ca2 | 625,354 |
import platform
def get_system_type() -> str:
"""Attempts to determine what type of system we're on, limited to systems this addon can usefully do things with"""
system = platform.uname()[0].lower()
if system in ["windows"]:
return system
return "unknown" | a10f417089eecbff138cdfa3c7eb216bdb95828d | 625,355 |
import string
def filter_unicode(data):
"""
Function to remove all non-printable characters from a string
:param data: str: String to be analysed
:return: String with all non-printable characters removed
"""
return "".join(c for c in str(data) if c in string.printable) | 97acaabbe0d67cc4733d6f94d421517e06cb3e09 | 625,356 |
def bdev_get_histogram(client, name):
"""Get histogram for specified bdev.
Args:
bdev_name: name of bdev
"""
params = {'name': name}
return client.call('bdev_get_histogram', params) | 08929f759fff30a6832b23e5ec5b162b55e19799 | 625,357 |
def _set_shapes(img_bl, img_fu, mask):
""" Sets the shapes of the tensors inside tf.Dataset object.
# Arguments
image_bl: array, contains the baseline image.
image_fu: array, contains the follow-up image.
mask: array, contains the segmentation mask.
# Returns
A tuple containi... | 320aa7ceb0951e99f6b7f4395d3a2854a8146700 | 625,358 |
def quantile(xs, q=(0.25, 0.5, 0.75), sort=True):
"""Returns the qth quantile of an unsorted or sorted numeric vector.
There are a number of different ways to calculate the sample quantile. The
method implemented by igraph is the one recommended by NIST. First we
calculate a rank n as q(N+1), where N i... | 1a5fc9eff79118a4b4b31bb1b7d35174b640ffe2 | 625,359 |
def clean_currency(x):
""" Remove comma in currency numeric
Add space between currency symbol and value
"""
if isinstance(x, int) or isinstance(x, float):
return ('', x)
if isinstance(x, str):
numeric_start_at = 0
for i in range(len(x)):
if x[i].isnumeric():
... | 88cc5f896fb4add0860f2f5af7945cedf31f1bd5 | 625,360 |
import asyncio
def create_checked_task(coro_or_future):
"""
Wrapper for `asyncio.ensure_future` that always propagates exceptions.
"""
def raise_any_exc(task):
return task.result()
task = asyncio.ensure_future(coro_or_future)
task.add_done_callback(raise_any_exc)
return task | f1c0df2858bacf679ff07de28463b677d33d40bd | 625,361 |
def scalar_function(x, y):
"""
Returns the f(x,y) defined in the problem statement.
"""
if x <= y:
return x * y
return x / y | 8a18b4a1f0e6c67a2b9331cf8a819ebc7fda9525 | 625,363 |
def wikigapfinder_campaign_filter(item):
"""People who are women or identify themselves as women"""
return (item.claims.get('P31', [{}])[0]
.get('mainsnak', {}).get('datavalue', {}).get('value', {})
.get('id', '') == 'Q5')\
and \
(item.claims.get('P21', [{}])[0]
... | 86771ea79b51062e1cd727ec63b7e7c9ee7c4a6a | 625,364 |
def _clean_accounting_column(x: str) -> float:
"""
Perform the logic for the `cleaning_style == "accounting"` attribute.
This is a private function, not intended to be used outside of
`currency_column_to_numeric``.
It is intended to be used in a pandas `apply` method.
:returns: An object with... | a14d717ca4d37b7e443f64d78c78cedfa885b8b9 | 625,365 |
def merge_and_count(array_b, array_c):
"""Merge two arrays and sort them"""
count = 0
merged_array = []
b_ptr = 0
c_ptr = 0
while b_ptr < len(array_b) and c_ptr < len(array_c):
if array_c[c_ptr] < array_b[b_ptr]:
merged_array.append(array_c[c_ptr])
c_ptr += 1
... | 657653c3e9578200fc03eb0a88989724165831dd | 625,368 |
def data_sanity_check(data, inplace=True):
"""
DOCSTRING: Eliminates viewing of empty and duplicate rows from input DataFrame based on repeated 'Order ID' and 'Order Item ID', if any. But those empty rows still hold their Index position as we are only excluding them ffrom future operations, once passed through ... | e6a7635e2fcf13abc68f0b83a3703baedbdd9028 | 625,369 |
def bytes_to_int(b: bytes):
"""
Convert a byte array to an integer.
:param b: the byte array
:return: the integer
"""
neg = False # Have we determined the value to be negative? We'll see.
i=0 # This is the variable in which we'll store the value.
# Now we need to do some tap dancing ... | db9b1e205def6e3652aa6de0aca0a00c54dad4a2 | 625,370 |
def merge(source, destination, overwrite=True):
"""Deep merge 2 dicts
Warning: the source dict is merged INTO the destination one. Make a copy
before using it if you do not want to destroy the destination dict.
"""
for key, value in list(source.items()):
if isinstance(value, dict):
... | fa6546f0f687c0134eae967d816321419105fb2e | 625,371 |
import re
def get5words_en_2(n=2700):
"""Return sorted word list, most frequent on top.
Corpus size 2700 seems to be about what Wordle uses.
"""
words = open('data/wordlist-en-freq.txt').read().split('\n')
exp = re.compile('[A-Za-z]{5}$')
words = [
w.lower()
for w in words
... | 1dac80b6162ca2c00ebd2415afb948e1b2a7a630 | 625,372 |
import functools
def with_sync_paused(func):
"""
Decorator which pauses syncing before a method call, resumes afterwards. This
should only be used to decorate Maestral methods.
"""
@functools.wraps(func)
def wrapper(self, *args, **kwargs):
# pause syncing
resume = False
... | 192f7a775a67c70d7e2769caf38272a89babac31 | 625,373 |
import string
import random
def passwordGenerator(lenght=12):
"""assumes lenght is an int, representing how long the password should be
returns a string of ASCII characters, representing a suggested password"""
if not isinstance(lenght, int):
raise TypeError("lenght must be an int")
password =... | 66651a9c15d2fb1b6c73f64ae25926b6efde467e | 625,374 |
import os
def get_result_file(result_idx, save_folder):
"""Gets the jsonl label file for the `result_idx` batch.
Args:
result_idx: result index of the result batch
save_folder: save folder
Returns: string
"""
return os.path.join(save_folder, f"result_label_file_{result_idx}.jsonl... | 2f8363c957f9853f38ed208adc3489fdea409f6a | 625,375 |
import argparse
def get_args() -> argparse.Namespace:
"""
Get hyperparameters from arguments and set default parameters.
"""
parser = argparse.ArgumentParser()
parser.add_argument("--gpu", type=str, default='0',
help="The GPU to train the agent on")
parser.add_argument... | c06bf8e97fbcf6909b4a47c5c406048ae0d32841 | 625,376 |
import pickle
import hashlib
def generate_hash(data_in):
"""
Generate a hash from the data_in that can be used to uniquely identify
equivalent data_in.
Args:
data_in (any):
The data from which a hash is to be generated. This can be of any
type that can be pickled.
... | 3d7b2fb97c3d82325a8f4819247b33365a3042cc | 625,377 |
import os
import codecs
def load_tsv_data(input_file):
"""load data from tsv file"""
if os.path.exists(input_file):
context_data = []
response_data = []
label_data = []
context_lookup = {}
item_separator = "\t"
subitem_separator = "|"
with codecs.getread... | 453b89c03fe6842ba137e857eed4b3924d82293b | 625,378 |
def eat_ghost(power_pellet_active: bool, touching_ghost: bool) -> bool:
"""
Args:
power_pellet_active (bool): does the player have an active power pellet?
touching_ghost (bool): is the player touching a ghost?
Returns:
bool
"""
return power_pellet_active and touching_ghost | 0123309f491b5773b08460f4c0411bf3e238f571 | 625,379 |
def _check_values(set1: set, set2: set) -> int:
"""This checks how many of the values present inside of the first set are in the second set."""
match = 0
if set1.issuperset(set2):
match += 1
for item in set2:
if set1.issuperset({item}):
match += 1
return match | fe951f4471471eeb83bd2b666c74868fc42f16b7 | 625,381 |
def render_event_time(datetime, whole_day, request, no_time=''):
"""Render time of event human readable and localized to locale of user."""
if whole_day:
return no_time
formatter = request.locale.dates.getFormatter(
'time', 'short')
time = formatter.format(datetime)
if request.locale... | 1cd93a78021ee8ab51f8d652a44cb58fe4f301c4 | 625,382 |
import subprocess
def have_minio():
"""Check if minio is available."""
try:
subprocess.check_output(["minio", "--version"])
return True
except:
raise ImportError("minio: command not found") from None | f1540f4d6aaac2086534757cd48f57ea65598bf6 | 625,383 |
def getFile(path):
"""
Extract report metadata from top of report
"""
print(path)
with open(path, "r") as in_file:
data = {"data_file": [], "site_code": ""}
append_lines = False
current_channel = ""
for i, line in enumerate(in_file):
if len(line) < 5: ... | e4c7dd5b18428f7ac9d2f5c50ff6d7f6a8908906 | 625,384 |
import pathlib
def load_words():
"""
Loads words from english-words repo.
:return: Set of valid words.
"""
words_repo_path = pathlib.PurePath(__file__).parent
words_repo_path = str(words_repo_path / 'english-words' / 'words_alpha.txt')
with open(words_repo_path, 'r') as word_file:
... | 980f42113e86561071864f25be8670b40a2b5167 | 625,386 |
def fastaRecordSizer(recordLines):
"""
Returns the number of charcters in every line excluding:
the first (header) line
whitespace at the start and end of lines
"""
size=0
for i in range(1,len(recordLines)):
size+=len(recordLines[i].strip())
return size | 328b2e6fca07098616ba305520c7c64d754d4225 | 625,387 |
def argmin(list_obj):
"""Returns the index of the min value in the list."""
min = None
best_idx = None
for idx, val in enumerate(list_obj):
if min is None or val < min:
min = val
best_idx = idx
return best_idx | 6b01fff02d9be5dc0bda6ad170f0b964b10373d9 | 625,388 |
def remove_prefix(text, prefix):
"""
Remove the prefix from the text if it exists.
>>> remove_prefix('underwhelming performance', 'underwhelming ')
'performance'
>>> remove_prefix('something special', 'sample')
'something special'
"""
null, prefix, rest = text.rpartition(prefix)
re... | 90399fec8ede1cbd2b13e8ec93d1d5ef6624d069 | 625,389 |
def get_map_bounds(cat1, cat2=None):
"""Generate map bounds and gridsize."""
if cat2 is not None:
minlat1, maxlat1 = cat1['latitude'].min(), cat1['latitude'].max()
minlon1, maxlon1 = cat1['longitude'].min(), cat1['longitude'].max()
minlat2, maxlat2 = cat2['latitude'].min(), cat2['latitud... | f0bf59a027daacc647f3fb6cf12a8660f7646e0e | 625,390 |
import requests
def find_answer(question_url: str) -> str:
"""
Return answer link.
"""
answer_url = None
# Prepare mark scheme links
if "https://pmt.physicsandmathstutor.com" in question_url:
# This is how physicsandmathstutor organizes URL. The question paper
# has "QP.pdf" a... | ccd1a92be6e14625d718d2607940e4c3a3068f71 | 625,391 |
def flip_v(grid):
"""Flip grid vertically."""
return '\n'.join(reversed(grid.split('\n'))) | ee5096714a0f1916a8ec2ff5dfa35b2edc839585 | 625,392 |
import ipaddress
def parse_ip(ip_bytes):
"""
Convert an IPv4/IPv6 address in bytes to a valid IP address in string format,
if it is indeed valid.
:param bytes ip_bytes: bytes of IPv4/IPv6 address.
:returns: IP address in string format, None if input invalid.
"""
try:
retu... | 0a6f48281da50d89418f6f48b22b2e5ddfd53adb | 625,393 |
import struct
def extract_string_packet(packet: bytes):
"""
:rtype: (bytes, str)
"""
strlen = struct.unpack('i', packet[:4])[0]
packet = packet[4:]
s = packet[:strlen].decode('utf-8')
packet = packet[strlen:]
return packet, s | 2d57393ebbd9a804ed9a20ec1e7babe864123da7 | 625,394 |
def _insert_type_to_globals(kind: type, globals: dict) -> str:
"""
Inserts the given type into the namespace
"""
name = kind.__name__
globals[name] = kind
return name | 085394db7c3c24238c2258853f6173b9d9887dd7 | 625,395 |
import struct
import socket
import fcntl
def get_interface_IP(interface_name):
"""Retrieve IP address of the specified network interface.
Args:
interface_name (str): Name of the interace.
Returns:
str: Standard dotted-quad string representation of the IP address.
"""
IFNAMSIZ = 1... | 0191e325447dfe9b6a7dcb330fdb3f2fe8329454 | 625,396 |
def calcCorrelates(n1, n2, period=None, maxstep=3):
"""
For two input vectors n1 and n2 this returns the value of their correlation
in the timeframe 'period' and for each # days offset up to 'maxstep', in
the format of a list of (offset, correlation_coefficient)
"""
# period = period (range of t... | 854b4c9bf4c354bef3e30ac421c26723e5a23da9 | 625,397 |
def mlo(i, j): # pragma: no cover
"""Auxiliary function for La Budde's algorithm.
See `arXiv:1104.3769 <https://arxiv.org/abs/1104.3769v1>`_.
.. note::
The La Budde paper uses indices that start counting at 1 so this function
lowers them to start counting at 0.
Args:
matrix (... | 6d3a6279dde492d260675f9f2c9300db46a2b3c4 | 625,398 |
def load_dataset(filename):
"""Load data from a csv file.
Args:
filename (string): path of input file.
CSV format
[coordinate, ...] + [label]
Returns:
Dataset: dataset
"""
return [(
lambda point: {
'coordinate': tuple(map(float, point[:-... | 10272891d08040faf9af6f25ddeab2aa20615df3 | 625,399 |
import textwrap
def format_tooltip(text, *args, **kwargs):
"""
Wrapper around textwrap.fill that preserves newline characters
"""
return '\n'.join(textwrap.fill(t, *args, **kwargs) \
for t in text.splitlines()) | 231ee50f092e6fc29b88bb36ed13458e67c1d193 | 625,400 |
def months_interval(start_date, end_date):
"""
Generate the monthly intervals between a start date and an end date
"""
months_num = [str(i+1).zfill(2) for i in range(12)]
start_year = int(start_date[0:4])
start_month = int(start_date[4:6])
end_year = int(end_date[0:4])
end_month = int(en... | 2e25ec3d129993c50c39a167b58eddf7d84dcd40 | 625,401 |
def calculate_reff(fit):
"""
Calculate number of effective samples divided by
the number of actual samples.
"""
df_summary = fit.summary()
neff = float(df_summary[['N_Eff']].astype(int).mean())
return neff / (fit.chains * fit.draws) | 6faeac089bc77009263e35999105be85480fb973 | 625,402 |
def update_message_command():
"""Fixture for mocking an incoming update of type message/command."""
return {
"update_id": 1,
"message": {
"message_id": 1,
"from": {
"id": 12345678,
"is_bot": False,
"first_name": "Firstname",... | 0c1f85c50ad3c058d8ec9d64198ebfd1613a4cd3 | 625,403 |
from typing import Sequence
from typing import Tuple
def named_range(name, stop: int) -> Sequence[Tuple[str, int]]:
"""Equivalent to `range()` but suitable for use with ``named_parameters``."""
return tuple(((f"{name}_{i}", i) for i in range(stop))) | dab4b7c8f4fec0717e98608f1b7277c207797727 | 625,406 |
from typing import Any
from typing import Iterable
def stringify(value: Any) -> Any:
"""Creates an equivalent data structure representing data values as string
Parameters
----------
value
Value to be stringified
Returns
-------
stringified_value
"""
if value is None or is... | 87504cd807af6ed50e610c8676d51e3037e0f673 | 625,407 |
def filter_kwargs(keywords, **kwargs):
"""
Filter provided keyword arguments and remove all but
those matching a provided list of relevant keywords.
Parameters
----------
keywords : list of string
Keywords to search for within the provided keyword arguments
kwargs : dict
Diction... | 5bf8493e81a0e3e0db18cd94e152d65f691817ca | 625,408 |
import asyncio
import time
def _get_timediff():
"""Return the difference between loop and Unix time bases."""
loopnow = asyncio.get_running_loop().time()
unixnow = time.time()
return unixnow - loopnow | bf4356740b34fb7135ace3ea51c1f5fa83daf392 | 625,409 |
def centralize_gradient(x, gc_conv_only=False):
"""credit - https://github.com/Yonghongwei/Gradient-Centralization """
size = len(list(x.size()))
# print(f"size = {size}")
if gc_conv_only:
if size > 3:
x.add_(-x.mean(dim=tuple(range(1, size)), keepdim=True))
else:
if si... | 6e7c322c5343874c8463a9a72386ea9822916b00 | 625,410 |
def dummy_permissions_exclude(model):
"""
A dummy function that excludes nothing,
:param model:
:return:
"""
return False | dbd4d497b720c227fc8de940b28f47ebb75fc8d6 | 625,411 |
def elementwise_list_addition(increment, list_to_increment):
"""
Simple method to element-wise increment a list by the values in another list of the same length.
"""
if not list_to_increment:
return increment
assert len(increment) == len(list_to_increment), 'Attempted to add two lists of di... | 7e7020604ebeb3ab227e3d64999bb0e8cf255986 | 625,412 |
def visible_organizations(vesting_user, viewing_user):
"""
Return just the orgs that viewing_user is allowed to know about.
"""
if viewing_user.is_staff:
return vesting_user.organizations.all()
elif viewing_user.is_registrar_member():
return vesting_user.organizations.filter(reg... | 1c2331183e14138a5f336f6576458581d637743e | 625,413 |
def merge_cliques(clique1,clique2):
"""
Merge two sets of cliques, return a new dictionary
of clique. As always, dict keys are random.
"""
# copy clique1 into new one
new_clique = {}
new_clique.update( zip( range(1,len(clique1)+1), clique1.values() ) )
clique_id = len(clique1)
# reve... | 9486c0bb968280a48d5d0474fb2737adc56c53ea | 625,414 |
def CppMutableToNonMutable(scope, type_defn, expr):
"""Gets the string converting a mutable expression to a non-mutable one.
Args:
scope: a Definition for the scope in which the expression will be written.
type_defn: a Definition for the type.
expr: a string for the mutable expression.
Returns:
... | 89e8e656ca7e1ad442d0c3674afb64c74e547b2f | 625,416 |
def top_ties(data, num, sort_by='summ'):
"""
A function that handles top ties problem.
:param sort_by: the name of columns which dataframe was sorted by
:param data: pandas dataframe type that contains sorted value
:param num: the number of values that we want to get
:return: a pandas dataframe ... | 4fb6af2f83b5696753e508f63b73bf28ecdc5227 | 625,417 |
import typing
import math
def line(
x1: float, y1: float, x2: float, y2: float, color: int = 1
) -> typing.List[int]:
"""Return a pixel data with a line."""
pixels: typing.List[int] = list()
dx: float = x2 - x1
dy: float = y2 - y1
hip: float = math.sqrt(dy ** 2 + dx ** 2)
sin: float = dy /... | 6cd5891aef4c1abd349237b6c8fb0d72d95be563 | 625,418 |
def expand_differentia(differentia_code):
"""
In most cases, the differentia remains unmodified
:param differentia_code:
:return:
"""
return "No differentia" if "*" in differentia_code else differentia_code | bc8941ee67b9d696f2d290e66f41facd8758ab06 | 625,420 |
import os
def CEELAN():
"""
Returns True if the current machine appears to be on the Sandia CEE LAN.
"""
if os.environ.get( 'SNLSYSTEM', '' ) == 'cee':
return True
netfile = '/etc/sysconfig/network'
if os.path.exists( netfile ):
try:
fp = open( netfile, 'r' )
... | 7d02c952ed68c583188fafbcc2ed5297a0d2f01c | 625,421 |
import re
def apply_annotations_to_sql(raw_query, aliases):
"""
Django's ORM understandably doesn't allow aliases to be the same names as other fields available. However, if we
want to use the efficiency of psql's \copy method and keep the column names, we need to allow these scenarios. This
function ... | 5e3840ebfb2872341cc7a9b1c1eda94a8a453a97 | 625,423 |
import click
def validate_delete_input(ctx, param, value):
"""This function validates the device delete input"""
if not value.isalnum():
click.secho(f"[x] Provided input is not supported!", fg="red")
click.secho(f"[*] Use comma separated values", fg="cyan")
ctx.abort()
else:
... | 7e8b8e1bb62d604228912fc76283d3aca2c77c99 | 625,424 |
def i2c_bus_id():
"""Return the I2C bus ID. It varies depending on the version of your Pi.
"""
revision = ([l[12:-1] for l in open('/proc/cpuinfo', 'r').readlines() if l[:8] == "Revision"]+['0000'])[0]
return 1 if int(revision, 16) >= 4 else 0 | 8b77202f40b70e4d09d76c81811596eb85368e92 | 625,425 |
import numpy
def get_pause_length(pauses):
"""Compute the length of pause.
Args:
pauses (numpy array, bool): True indicates occurrence of pause.
Returns:
res (numpy array): The length of consecutive pauses.
"""
res = []
cnt = 0
for pause in pauses:
... | 3fc187e355cf26bafb4355a87320eb777cf18020 | 625,426 |
def _payload_check_(args, creation=False, cmd=None):
"""
Checks payload for correct JSON format for a given command.
Args:
args (dict): Pass in payload
creation (bool): True if "create", false otherwise
cmd (None or str): str if "Add...", None otherwise
Returns:
... | 74eedd11e5c5fb5f106e89a62d9220a96d73e40a | 625,427 |
import os
def getproxies_environment():
"""Return a dictionary of scheme -> proxy server URL mappings.
Scan the environment for variables named <scheme>_proxy;
this seems to be the standard convention. In order to prefer lowercase
variables, we process the environment in two passes, first matches an... | 1ed31e40e493397ab5b9124a53ee9da5cd890c4d | 625,428 |
import torch
def _get_triplet_mask(targets):
"""Generates a mask (anchor, positive, negative).
Taken from:
https://github.com/omoindrot/tensorflow-triplet-loss/blob/master/model/triplet_loss.py
"""
indexes_not_equal = ~torch.eye(len(targets)).bool().to(targets.device)
i_not_j = indexes_n... | 97fbf057fa7a5095ebdcdd69f6073fdb7938a269 | 625,429 |
import os
def open_output_file(name, mode="w"):
"""Helper function to open a file even if it doesn't exist."""
if os.path.dirname(name) != "" and \
not os.path.exists(os.path.dirname(name)):
os.makedirs(os.path.dirname(name))
return open(name, mode) | 2386faec0b565dec7d82739d28ec8d9ecffe5a32 | 625,430 |
def utc_iso8601(datetime):
"""Convert a UTC datetime into an ISO8601 timestamp string."""
return datetime.strftime("%Y-%m-%dT%H:%M:%S.%f+00:00") | 985f6333f7977f9709b652fe992dc06cfba3403d | 625,431 |
import torch
def proj(x, epsilon=0.00001):
"""
Projects a matrix of vectors in hyperbolic geometry back into the unit ball
Parameters
----------
x
the matrix with each row representing a vector
epsilon
the small difference to subtract to ensure that vectors remain in the unit b... | 79cf720790d325f811888ff9e93fd1c489a9cd53 | 625,433 |
def quotes_finder(sentence):
"""
Returns 1 if sentence contains question mark, 0 otherwise
"""
if "'" or "`" in sentence:
return 1
else:
return 0 | fb021ba96b3a69a89814181be923f9c924ab24cb | 625,434 |
import socket
def get_host_name() -> str: # pragma: no cover - we're just proxying
"""Get hostname of the machine
Returns:
str: host name
"""
return socket.gethostname() | e060a7a0efe1a5cf327aa36219091cb249bbd27f | 625,435 |
def reverse_complement(dna, reverse=True, complement=True):
"""
Make the reverse complement of a DNA sequence. You can also just make the
complement or the reverse strand (see options).
Input: A DNA sequence containing 'ATGC' base pairs and wild card letters
Output: DNA sequence as a string.
... | a7e651721df61241200fe50e8006956b2c982dba | 625,436 |
def _check_if_provider_is_defined(documents):
"""Make sure "provider" is defined for all documents."""
return all(
"provider" in item and item["provider"] == "any"
for item in documents
) | 44c9d548633803fbe5ec02b4b270fbffed77a92e | 625,437 |
def predict(x_tst, model):
"""
The method predicts labels for testing data samples by using trained learning model.
Parameters
----------
x_tst: features of testing data
model: trained learning model
"""
predictions = model.predict(x_tst)
return predictions | ef0e23bbd70a1d8340b5893b42f7fd72f0ee17d0 | 625,438 |
from typing import Any
import re
def __is_condition_met(condition_type: str, condition_value: Any, value: Any) -> bool:
"""
Checks if given value meets the given condition
Args:
condition_type: condition type, could be "equal" or "regex"
condition_value: the value of the condition, in case... | 1bf7a80df9c12bedc6e843851947bf94c64ae120 | 625,439 |
def y_coordinate(block):
"""Returns the y-coordinate component in block as a string."""
start = block.find(',')+1
# Skip the first space
end = block.find(' ', block.find(' ')+1)
return block[start:end] | 4714d9646d9f80a9218c9d8b3f85e17ca205e4f3 | 625,440 |
def is_just_a_number(line):
"""
:param line: Tag instance
:return:
"""
if line.text.isdigit():
return True
return False | 5ab3c2bd9fd0900953341a61414971324bd8df83 | 625,441 |
def checkPatch_index_inImages_naive(Index_check_patch,Num_patches_perImage,num_col,num_row):
"""check the index of patches and the size of images"""
aaa = int(Index_check_patch/Num_patches_perImage)
nn = Index_check_patch%Num_patches_perImage
bbb = int(nn/num_col)
ccc = nn%num_col
# aaa = np.wher... | d7614e088a6a830ae7caf6cfbbe52b437f9104bc | 625,442 |
import subprocess
def minimap2_proc(ref, fast5, threads=1, spliced=0, sensitive=1):
"""Run minimap2 and return its stdout"""
mode = ["-axmap-ont", ]
if spliced:
mode = ["-axsplice", "-uf"]
args1 = ["minimap2", "--MD", "-Y", "-t%s"%threads] + mode
if sensitive:
args1 += ["-k7", "-w... | 42e40945bc9c2e73a1cbd3084637b8658e5c6aa1 | 625,443 |
def write_coord(coord):
""" Adjusts whitespace for coordinates """
return "{:06.8f}".format(coord) if coord < 0.0 else " " + "{:06.8f}".format(coord) | 4782c6ab2940dd35516d7c373a3f2e6d93ad3671 | 625,444 |
import torch
def compute_batch_accuracy(output, target):
"""Computes the accuracy for a batch"""
with torch.no_grad():
batch_size = target.size(0)
_, pred = output.max(1)
correct = pred.eq(target).sum()
return correct * 100.0 / batch_size | c264a863cbf45afaddbf3c5a9e1cad23f515cff9 | 625,446 |
from typing import List
def get_card_colors(mana_cost: str) -> List[str]:
"""
For some cards, we may have to manually determine the card's color.
:param mana_cost: Mana cost string
:return: Colors based on mana cost
"""
color_options: List[str] = ["W", "U", "B", "R", "G"]
ret_val = []
... | cd8f7e11b3b32512c93cfe0ba0f69a214a71d470 | 625,447 |
def WrapText(text, max):
"""Inserts a newline if any line of a file is > max chars.
Note that the newline is inserted at the first whitespace
character, so there may be lines longer than max.
"""
char_list = list(text)
last_linebreak = 0
for i in range(0, len(char_list)):
if char_list[i] == '\n' or c... | 22ba518e265ada6d44fecf949cf712f9e2cb9e5e | 625,448 |
def client(api_client, service):
"""
1. Test if request with default session have status code 200
2. Delete default service mapping rule
3. Create session without retry for session
"""
assert api_client().get('/get').status_code == 200
proxy = service.proxy.list()
proxy.mapping_rules.d... | 220892bd661904a987c44376972dbe734cc15c62 | 625,449 |
def twitter_auth_required(view_func):
"""
Decorator for views that requires the authenicated
user to have authorized the site on Twitter. If no
credentials are on record, user will be directed to
a page to authorize the site.
"""
view_func.twitter_auth_required = True
return view_func | 6f39b325f876af8d4b499c88324152b7caed545e | 625,450 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.