content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def is_within_boundary(boundary_right_most_x, boundary_top_most_y,
boundary_left_most_x, boundary_bottom_most_y,
cursor):
"""
Checks if cursor is within given boundary
:param boundary_right_most_x:
:param boundary_top_most_y:
:param boundary_left_most_x... | d53106c9d525eb1bb51cfe4c30bc7e143ac6a517 | 707,332 |
import requests
from bs4 import BeautifulSoup
def get_game_page(url):
"""
Get the HTML for a given URL, where the URL is a game's page in the Xbox
Store
"""
try:
response = requests.get(url)
except (requests.exceptions.MissingSchema, ConnectionError):
return None
game_pag... | 40d578ce8cda0b5139515e03f8308911169e0442 | 707,333 |
import math
def normalise_angle(angle: float) -> float:
"""Normalises the angle in the range (-pi, pi].
args:
angle (rad): The angle to normalise.
return:
angle (rad): The normalised angle.
"""
while angle > math.pi:
angle -= 2 * math.pi
while angle <= -math.pi:
... | 0a4cfa6e9da58bfdbb6cd4a04e7a742e8c432002 | 707,334 |
import re
def normalize_url(url):
"""Function to normalize the url. It will be used as document id value.
Returns:
the normalized url string.
"""
norm_url = re.sub(r'http://', '', url)
norm_url = re.sub(r'https://', '', norm_url)
norm_url = re.sub(r'/', '__', norm_url)
return norm_url | 79197b9fa1c47da601bdb9c34d626d236b649173 | 707,335 |
import fsspec
def is_remote_filesystem(fs: fsspec.AbstractFileSystem) -> bool:
"""
Validates if filesystem has remote protocol.
Args:
fs (``fsspec.spec.AbstractFileSystem``): An abstract super-class for pythonic file-systems, e.g. :code:`fsspec.filesystem(\'file\')` or :class:`datasets.filesystem... | c40f9bb4845bbd1fc1a4cf9fce2c1b366cd22354 | 707,336 |
def get_element_attribute_or_empty(element, attribute_name):
"""
Args:
element (element): The xib's element.
attribute_name (str): The desired attribute's name.
Returns:
The attribute's value, or an empty str if none exists.
"""
return element.attributes[attribute_name].va... | dbc7f5c24d321c40b46f1c78950d7cf254719b5c | 707,337 |
def substitute_word(text):
"""
word subsitution to make it consistent
"""
words = text.split(" ")
preprocessed = []
for w in words:
substitution = ""
if w == "mister":
substitution = "mr"
elif w == "missus":
substitution = "mrs"
else:
... | 0709f4223cb06ddfdc5e9704048f418f275429d1 | 707,338 |
def escape(line, chars):
"""Escapes characters 'chars' with '\\' in 'line'."""
def esc_one_char(ch):
if ch in chars:
return "\\" + ch
else:
return ch
return u"".join([esc_one_char(ch) for ch in line]) | f69409c92eacbbcab4232f7bb0ee244c77a4f219 | 707,339 |
def polinomsuzIntegralHesapla(veriler):
"""
Gelen verileri kullanarak integral hesaplar.
:param veriler: İntegrali hesaplanacak veriler. Liste tipinde olmalı.
"""
a,b=5,len(veriler)
deltax = 1
integral = 0
n = int((b - a) / deltax)
for i in range(n-1):
integral += deltax * (v... | 468e02da8ff077b04456f71f0af6d77bf5a47d68 | 707,340 |
def _keep_extensions(files, extension):
""" Filters by file extension, this can be more than the extension!
E.g. .png is the extension, gray.png is a possible extension"""
if isinstance(extension, str):
extension = [extension]
def one_equal_extension(some_string, extension_list):
return... | 009233e381e2015ff4d919338225057d94d40a82 | 707,341 |
import os
def check_racs_exists(base_dir: str) -> bool:
"""
Check if RACS directory exists
Args:
base_dir: Path to base directory
Returns:
True if exists, False otherwise.
"""
return os.path.isdir(os.path.join(base_dir, "EPOCH00")) | efad779a5310b10b2eeefdc10e90f0b78d428bf4 | 707,342 |
import os
def keypair_to_file(keypair):
"""Looks for the SSH private key for keypair under ~/.ssh/
Prints an error if the file doesn't exist.
Args:
keypair (string) : AWS keypair to locate a private key for
Returns:
(string|None) : SSH private key file path or None is the private ke... | 0f544fd7d67530853bc4d8a91df01458d6408255 | 707,344 |
def hex2int(s: str):
"""Convert a hex-octets (a sequence of octets) to an integer"""
return int(s, 16) | ecdb3152f8c661c944edd2811d016fce225c3d51 | 707,345 |
def get_selection(selection):
"""Return a valid model selection."""
if not isinstance(selection, str) and not isinstance(selection, list):
raise TypeError('The selection setting must be a string or a list.')
if isinstance(selection, str):
if selection.lower() == 'all' or selection == '':
... | 996d0af844e7c1660bcc67e24b33c31861296d93 | 707,346 |
def calc_hebrew_bias(probs):
"""
:param probs: list of negative log likelihoods for a Hebrew corpus
:return: gender bias in corpus
"""
bias = 0
for idx in range(0, len(probs), 16):
bias -= probs[idx + 1] + probs[idx + 5] + probs[idx + 9] + probs[idx + 13]
bias += probs[idx + 2] +... | 565be51b51d857c671ee44e090c5243e4d207942 | 707,347 |
from datetime import datetime
import sys
import glob
import os
def get_log_name(GLASNOST_ROOT, start_time, client_ip, mlab_server):
"""Helper method that given a test key, finds the logfile"""
log_glob = "%s/%s.measurement-lab.org/%s_%s_*" % (start_time.strftime('%Y/%m/%d'), mlab_server, start_time.strftim... | 2492ad96563a7a93a9b00d9e5e20742b7f645ec3 | 707,348 |
import sys
import os
def caller_path(steps=1, names=None):
"""Return the path to the file of the current frames' caller."""
frame = sys._getframe(steps + 1)
try:
path = os.path.dirname(frame.f_code.co_filename)
finally:
del frame
if not path:
path = os.getcwd()
if na... | 74d617d970df49854e98c7147d7b830e2dc230cf | 707,349 |
def is_hitachi(dicom_input):
"""
Use this function to detect if a dicom series is a hitachi dataset
:param dicom_input: directory with dicom files for 1 scan of a dicom_header
"""
# read dicom header
header = dicom_input[0]
if 'Manufacturer' not in header or 'Modality' not in header:
... | c039c0535823edda2f66c3e445a5800a9890f155 | 707,350 |
import numpy
def readcrd(filename, REAL):
"""
It reads the crd file, file that contains the charges information.
Arguments
----------
filename : name of the file that contains the surface information.
REAL : data type.
Returns
-------
pos : (Nqx3) array, positions of the... | efafc2e53eebeacbe6a1a5b1e346d0e121fa7a62 | 707,351 |
def get_mention_token_dist(m1, m2):
""" Returns distance in tokens between two mentions """
succ = m1.tokens[0].doc_index < m2.tokens[0].doc_index
first = m1 if succ else m2
second = m2 if succ else m1
return max(0, second.tokens[0].doc_index - first.tokens[-1].doc_index) | 84052f805193b1d653bf8cc22f5d37b6f8de66f4 | 707,352 |
def FindDescendantComponents(config, component_def):
"""Return a list of all nested components under the given component."""
path_plus_delim = component_def.path.lower() + '>'
return [cd for cd in config.component_defs
if cd.path.lower().startswith(path_plus_delim)] | f9734442bbe3a01460970b3521827dda4846f448 | 707,353 |
def _get_source(loader, fullname):
"""
This method is here as a replacement for SourceLoader.get_source. That
method returns unicode, but we prefer bytes.
"""
path = loader.get_filename(fullname)
try:
return loader.get_data(path)
except OSError:
raise ImportError('source not ... | af43b79fa1d90abbbdb66d7d1e3ead480e27cdd1 | 707,354 |
from bs4 import BeautifulSoup
def create_bs4_obj(connection):
"""Creates a beautiful Soup object"""
soup = BeautifulSoup(connection, 'html.parser')
return soup | b3956b13756e29cd57a0e12457a2d665959fb03d | 707,355 |
import toml
def parse_config_file(path):
"""Parse TOML config file and return dictionary"""
try:
with open(path, 'r') as f:
return toml.loads(f.read())
except:
open(path,'a').close()
return {} | 599164f023c0db5bffa0b6c4de07654daae1b995 | 707,356 |
def courses_to_take(input):
"""
Time complexity: O(n) (we process each course only once)
Space complexity: O(n) (array to store the result)
"""
# Normalize the dependencies, using a set to track the
# dependencies more efficiently
course_with_deps = {}
to_take = []
for course, deps in input.items():
... | eb0fe7271497fb8c5429360d37741d20f691ff3c | 707,357 |
def base_round(x, base):
"""
This function takes in a value 'x' and rounds it to the nearest multiple
of the value 'base'.
Parameters
----------
x : int
Value to be rounded
base : int
Tase for x to be rounded to
Returns
-------
int
The rounded value
... | e5b1a1b81c7baf990b7921fe27a20075c0305935 | 707,358 |
def _update_schema_1_to_2(table_metadata, table_path):
"""
Given a `table_metadata` of version 1, update it to version 2.
:param table_metadata: Table Metadata
:param table_path: [String, ...]
:return: Table Metadata
"""
table_metadata['path'] = tuple(table_path)
table_metadata['schema... | 6b0c8bc72100cceeb1b9da5552e53bc3c9bad3fa | 707,359 |
def encode_integer_leb128(value: int) -> bytes:
"""Encode an integer with signed LEB128 encoding.
:param int value: The value to encode.
:return: ``value`` encoded as a variable-length integer in LEB128 format.
:rtype: bytes
"""
if value == 0:
return b"\0"
# Calculate the number o... | b74832115a58248f4a45a880f657de6dd38b0d8d | 707,360 |
def process_name(i: int, of: int) -> str:
"""Return e.g. '| | 2 |': an n-track name with track `i` (here i=2) marked.
This makes it easy to follow each process's log messages, because you just
go down the line until you encounter the same number again.
Example: The interleaved log of four processes th... | bc3e0d06544b61249a583b6fa0a010ec917c0428 | 707,361 |
def cards_db(db):
"""
CardsDB object that's empty.
"""
db.delete_all()
return db | 9649b309990325eca38ed89c6e9d499b41786dab | 707,362 |
def get_best_trial(trial_list, metric):
"""Retrieve the best trial."""
return max(trial_list, key=lambda trial: trial.last_result.get(metric, 0)) | c5ddbb9ad00cddaba857d0d0233f6452e6702552 | 707,363 |
def convert_to_clocks(duration, f_sampling=200e6, rounding_period=None):
"""
convert a duration in seconds to an integer number of clocks
f_sampling: 200e6 is the CBox sampling frequency
"""
if rounding_period is not None:
duration = max(duration//rounding_period, 1)*rounding_period
... | 602b00af689cc25374b7debd39264b438de44baa | 707,364 |
def multiply(x):
"""Multiply operator.
>>> multiply(2)(1)
2
"""
def multiply(y):
return y * x
return multiply | 77d983090e03820d03777f1f69cfc7b0ef6d88a2 | 707,365 |
def expose(policy):
"""
Annotate a method to permit access to contexts matching an authorization
policy. The annotation may be specified multiple times. Methods lacking any
authorization policy are not accessible.
::
@mitogen.service.expose(policy=mitogen.service.AllowParents())
de... | 74caed36885e5ea947a2ecdac9a2cddf2f5f51b0 | 707,366 |
import base64
def didGen(vk, method="dad"):
"""
didGen accepts an EdDSA (Ed25519) key in the form of a byte string and returns a DID.
:param vk: 32 byte verifier/public key from EdDSA (Ed25519) key
:param method: W3C did method string. Defaults to "dad".
:return: W3C DID string
"""
if vk ... | 9991491ab486d8960633190e3d3baa9058f0da50 | 707,367 |
import pickle
def load_dataset(datapath):
"""Extract class label info """
with open(datapath + "/experiment_dataset.dat", "rb") as f:
data_dict = pickle.load(f)
return data_dict | 3a0d8ef9c48036879b32ab0e74e52429418297c0 | 707,368 |
from typing import Dict
from pathlib import Path
import json
def load_json(filename: str) -> Dict:
"""Read JSON file from metadata folder
Args:
filename: Name of metadata file
Returns:
dict: Dictionary of data
"""
filepath = (
Path(__file__).resolve().parent.parent.joinpat... | 37d9f08344cf2a544c12fef58992d781556a9efd | 707,369 |
def get_short_size(size_bytes):
"""
Get a file size string in short format.
This function returns:
"B" size (e.g. 2) when size_bytes < 1KiB
"KiB" size (e.g. 345.6K) when size_bytes >= 1KiB and size_bytes < 1MiB
"MiB" size (e.g. 7.8M) when size_bytes >= 1MiB
size_bytes: File siz... | ebc9ba25c01dedf0d15b9e2a21b67989763bc8c8 | 707,370 |
import argparse
def get_arguments():
"""parse provided command line arguments"""
parser = argparse.ArgumentParser()
parser.add_argument(
"--server",
help="Where to send the output - use https URL to POST "
"to the dognews server API, or a file name to save locally as json",
... | bc7aa7fefda65ade99820e786a460e07a5037f46 | 707,371 |
def summed_timeseries(timeseries):
"""
Give sum of value series against timestamps for given timeseries containing several values per one timestamp
:param timeseries:
:return:
"""
sum_timeseries = []
for i in range(len(timeseries)):
if len(timeseries[i])>1:
sum_timeserie... | 618505f8f0960900a993bb6d9196d17bf31d02a6 | 707,372 |
import pathlib
def path_check(path_to_check):
"""
Check that the path given as a parameter is an valid absolute path.
:param path_to_check: string which as to be checked
:type path_to_check: str
:return: True if it is a valid absolute path, False otherwise
:rtype: boolean
"""
path = p... | 41b3537b0be2c729ba993a49863df4a15119db8b | 707,373 |
import time
def timefunc(f):
"""Simple timer function to identify slow spots in algorithm.
Just import function and put decorator @timefunc on top of definition of any
function that you want to time.
"""
def f_timer(*args, **kwargs):
start = time.time()
result = f(*args, **kwargs)
... | 56d5d052fa559e1b7c797ed00ee1b82c8e2126d6 | 707,374 |
def gen_endpoint(endpoint_name, endpoint_config_name):
"""
Generate the endpoint resource
"""
endpoint = {
"SagemakerEndpoint": {
"Type": "AWS::SageMaker::Endpoint",
"DependsOn": "SagemakerEndpointConfig",
"Properties": {
"EndpointConfigName": ... | bc658e6aebc41cfddefe0e77b2d65748a84789c5 | 707,375 |
def float_or_none(val, default=None):
"""
Arguments:
- `x`:
"""
if val is None:
return default
else:
try:
ret = float(val)
except ValueError:
ret = default
return ret | 00beabbd2fe4633e6738fea2220d55d096bfa91e | 707,376 |
from typing import List
async def get_sinks_metadata(sinkId: str) -> List: # pylint: disable=unused-argument
"""Get metadata attached to sinks
This adapter does not implement metadata. Therefore this will always result
in an empty list!
"""
return [] | 458b674cc59a80572fd9676aec81d0a7c353a8f3 | 707,377 |
def fn_lin(x_np, *, multiplier=3.1416):
""" Linear function """
return x_np * multiplier | e64f112b486ea6a0bdf877d67c98417ae90f03b3 | 707,378 |
def get_MACD(df, column='Close'):
"""Function to get the EMA of 12 and 26"""
df['EMA-12'] = df[column].ewm(span=12, adjust=False).mean()
df['EMA-26'] = df[column].ewm(span=26, adjust=False).mean()
df['MACD'] = df['EMA-12'] - df['EMA-26']
df['Signal'] = df['MACD'].ewm(span=9, adjust=Fal... | b5eb25c9a5097fb2a0d874d62b6ab1957bbe3f11 | 707,379 |
import random
def summary_selector(summary_models=None):
"""
Will create a function that take as input a dict of summaries :
{'T5': [str] summary_generated_by_T5, ..., 'KW': [str] summary_generted_by_KW}
and randomly return a summary that has been generated by one of the summary_model in summary_model
if summar... | b8a2336546324d39ff87ff5b59f4f1174e5dd54c | 707,380 |
from typing import Match
def _replace_fun_unescape(m: Match[str]) -> str:
""" Decode single hex/unicode escapes found in regex matches.
Supports single hex/unicode escapes of the form ``'\\xYY'``,
``'\\uYYYY'``, and ``'\\UYYYYYYYY'`` where Y is a hex digit. Only
decodes if there is an odd number of b... | 3fdb275e3c15697e5302a6576b4d7149016299c0 | 707,382 |
from pathlib import Path
import os
def get_absolute_filename(user_inputted_filename: str) -> Path:
"""Clean up user inputted filename path, wraps os.path.abspath, returns Path object"""
filename_location = Path(os.path.abspath(user_inputted_filename))
return filename_location | d8d704f4adcaa443658789c6d178b3ddb05552d0 | 707,383 |
def check_answer(guess, a_follower, b_follower):
"""Chcek if the user guessed the correct option"""
if a_follower > b_follower:
return guess == "a"
else:
return guess == "b" | acd1e78026f89dd1482f4471916472d35edf68a7 | 707,384 |
import argparse
def command_line_arg_parser():
"""
Command line argument parser. Encrypts by default. Decrypts when --decrypt flag is passed in.
"""
parser = argparse.ArgumentParser(description='Parses input args')
parser.add_argument('input_file', type=str,
help='Path to i... | c1e9305e2967368fb36ad8fcdbb654ef04f8d3bf | 707,385 |
from typing import Dict
def canonical_for_code_system(jcs: Dict) -> str:
"""get the canonical URL for a code system entry from the art decor json. Prefer FHIR URIs over the generic OID URI.
Args:
jcs (Dict): the dictionary describing the code system
Returns:
str: the canonical URL
""... | f111a4cb65fa75799e799f0b088180ef94b71cc8 | 707,386 |
from typing import List
def create_unique_views(rows: list, fields: List[str]):
"""Create views for each class objects, default id should be a whole row"""
views = {}
for r in rows:
values = [r[cname] for cname in fields]
if any(isinstance(x, list) for x in values):
if all(isin... | 24b311c8b013f742e69e7067c1f1bafe0044c940 | 707,387 |
def add_merge_variants_arguments(parser):
"""
Add arguments to a parser for sub-command "stitch"
:param parser: argeparse object
:return:
"""
parser.add_argument(
"-vp",
"--vcf_pepper",
type=str,
required=True,
help="Path to VCF file from PEPPER SNP."
... | 5fd6bc936ba1d17ea86a49499e1f6b816fb0a389 | 707,389 |
def escape_html(text: str) -> str:
"""Replaces all angle brackets with HTML entities."""
return text.replace('<', '<').replace('>', '>') | f853bcb3a69b8c87eb3d4bcea5bbca66376c7db4 | 707,390 |
import torch
def calc_driver_mask(n_nodes, driver_nodes: set, device='cpu', dtype=torch.float):
"""
Calculates a binary vector mask over graph nodes with unit value on the drive indeces.
:param n_nodes: numeber of driver nodes in graph
:param driver_nodes: driver node indeces.
:param device: the d... | 2d2a08a86629ece190062f68dd25fc450d0fd84e | 707,391 |
def open_file(name):
"""
Return an open file object.
"""
return open(name, 'r') | 8921ee51e31ac6c64d9d9094cedf57502a2aa436 | 707,392 |
import math
def _bit_length(n):
"""Return the number of bits necessary to store the number in binary."""
try:
return n.bit_length()
except AttributeError: # pragma: no cover (Python 2.6 only)
return int(math.log(n, 2)) + 1 | bea6cb359c7b5454bdbb1a6c29396689035592d7 | 707,393 |
def solution(n):
"""
Return the product of a,b,c which are Pythagorean Triplet that satisfies
the following:
1. a < b < c
2. a**2 + b**2 = c**2
3. a + b + c = 1000
>>> solution(1000)
31875000
"""
product = -1
d = 0
for a in range(1, n // 3):
"""Solving t... | a0bf0f0bde50f536f6c91f2b52571be38e494cea | 707,394 |
import sys
def python2_binary():
"""Tries to find a python 2 executable."""
# Using [0] instead of .major here to support Python 2.6.
if sys.version_info[0] == 2:
return sys.executable or "python"
else:
return "python2" | 054870972e68aa5b9e8609d93b8a82ad5e95d634 | 707,395 |
def with_metaclass(meta, *bases):
"""A Python 2/3 compatible way of declaring a metaclass.
Taken from `Jinja 2 <https://github.com/mitsuhiko/jinja2/blob/master/jinja2
/_compat.py>`_ via `python-future <http://python-future.org>`_. License:
BSD.
Use it like this::
class MyClass(with_metacla... | 0fe8e95fe29821e4cda8b66ff54ddd1b73e51243 | 707,396 |
from typing import List
def join_with_and(words: List[str]) -> str:
"""Joins list of strings with "and" between the last two."""
if len(words) > 2:
return ", ".join(words[:-1]) + ", and " + words[-1]
elif len(words) == 2:
return " and ".join(words)
elif len(words) == 1:
return ... | ecb2c1fa060657f2ea4173c4382a81c9b42beeb9 | 707,397 |
def is_url_relative(url):
"""
True if a URL is relative, False otherwise.
"""
return url[0] == "/" and url[1] != "/" | 91e1cb756a4554973e53fd1f607515577bc63294 | 707,398 |
from heapq import heappop, heappush
def dijkstra(vertex_count: int, source: int, edges):
"""Uses Dijkstra's algorithm to find the shortest path in a graph.
Args:
vertex_count: The number of vertices.
source : Vertex number (0-indexed).
edges : List of (cost, edge) (0-indexed... | d33f8dc28bf07154ffd7582a5bdd7161e195f331 | 707,399 |
def contains(poly0, poly1):
""" Does poly0 contain poly1?
As an initial implementation, returns True if any vertex of poly1 is within
poly0.
"""
# check for bounding box overlap
bb0 = (min(p[0] for p in poly0), min(p[1] for p in poly0),
max(p[0] for p in poly0), max(p[1] for p in poly... | 26ea4bd17a55ed05afa049a9aaab5237f0965674 | 707,400 |
import os
import json
def get_ids_in_annotations(scene, frame, quality):
"""
Returns a set of all ids found in annotations.
"""
annotations_path = os.path.join(scene, '%sPose3d_stage1' % quality,
'body3DScene_%s.json' % frame)
if not os.path.exists(annotations_... | 9e754af7ec397e9a36151b7f49f69d2de6ca0128 | 707,401 |
import os
import errno
def _ReapUntilProcessExits(monitored_pid):
"""Reap processes until |monitored_pid| exits, then return its exit status.
This will also reap any other processes ready to be reaped immediately after
|monitored_pid| is reaped.
"""
pid_status = None
options = 0
while True:
try:
... | ef540cc60634fe13ddc58b434f7fabe01109ddda | 707,402 |
def compute_wolfe_gap(point_x, objective_function, feasible_region):
"""Compute the Wolfe gap given a point."""
grad = objective_function.evaluate_grad(point_x.cartesian_coordinates)
v = feasible_region.lp_oracle(grad)
wolfe_gap = grad.dot(point_x.cartesian_coordinates - v)
return wolfe_gap | f2b09a232063599aa7525a70e6d3a0d8bafb57e7 | 707,403 |
import numpy
def ifft(a, axis):
"""
Fourier transformation from grid to image space, along a given axis.
(inverse Fourier transform)
:param a: numpy array, 1D or 2D (`uv` grid to transform)
:param axis: int; axes over which to calculate
:return: numpy array (an image in `lm` coordinate space... | 3a96d6b615c8da63deaeca5e98a4f82f18fec8dd | 707,404 |
from typing import Dict
from typing import Any
def addon_config() -> Dict[str, Any]:
"""Sample addon config."""
return {
"package-name": "djangocms-blog",
"installed-apps": [
"filer",
"easy_thumbnails",
"aldryn_apphooks_config",
"parler",
... | f4266735ef2f0809e5802abed54dfde4c1cbd708 | 707,406 |
import math
def to_half_life(days):
"""
Return the constant [1/s] from the half life length [day]
"""
s= days * 3600*24
return -math.log(1/2)/s | af7724dfb9442bf1f5e931df5dd39b31d0e78091 | 707,407 |
import numpy
def TransformInversePoints(T,points):
"""Transforms a Nxk array of points by the inverse of an affine matrix"""
kminus = T.shape[1]-1
return numpy.dot(points-numpy.tile(T[0:kminus,kminus],(len(points),1)),T[0:kminus,0:kminus]) | 7e04a741c6ad0ec08e40ab393a703a1878ef784a | 707,408 |
import inspect
def get_default_args(func):
"""
Return dict for parameter name and default value.
Parameters
----------
func : Callable
A function to get parameter name and default value.
Returns
-------
Dict
Parameter name and default value.
Examples
--------... | dcc75dceae1385868866d668aa021584547190df | 707,409 |
def sec_to_time(seconds):
"""Transform seconds into a formatted time string.
Parameters
-----------
seconds : int
Seconds to be transformed.
Returns
-----------
time : string
A well formatted time string.
"""
m, s = divmod(seconds, 60)
h, m = divmod(m, 60)
r... | 59fcfe2f53d11ea7daac736b59b5eaeb72172dba | 707,410 |
import logging
def getLog():
"""simple wrapper around basic logger"""
return logging | b51942d2ed02f9ea7faf0a626715ec07e1677c88 | 707,411 |
from datetime import datetime
def _date(defval, t):
"""
支持的格式:
unix 时间戳
yyyy-mm-dd 格式的日期字符串
yyyy/mm/dd 格式的日期字符串
yyyymmdd 格式的日期字符串
如果年月日其中有一项是0,将被转换成 1
"""
if t is None:
return defval
if isinstance(t, (int, float)):
return datetime.fromtimes... | e8a1121da89d9dc46bdce5d1b8c70ec973909abb | 707,412 |
import re
def get_requirements(filename):
"""
Helper function to read the list of requirements from a file
"""
dependency_links = []
with open(filename) as requirements_file:
requirements = requirements_file.read().strip('\n').splitlines()
requirements = [req for req in requirements if... | 292d45ab8e7f8523734326869bb1dd05c6f395f1 | 707,413 |
import os
def normalise_dir_pattern(repo_dir, d):
"""
if d is a relative path, prepend the repo_dir to it
"""
if not d.startswith(repo_dir):
return os.path.join(repo_dir, d)
else:
return d | ea240eda35f7c85e652f78f5e80eb3ac16ce4e98 | 707,414 |
import subprocess
def get_disk_usage():
"""
Handle determining disk usage on this VM
"""
disk = {}
# Get the amount of general disk space used
cmd_out = subprocess.getstatusoutput('df -h | grep "/dev/xvda1"')[1]
cmd_parts = cmd_out.split()
disk["gen_disk_used"] = cmd_parts[2]
disk... | e4f65e1c652a74086c111a3c80d5f6c9db94a66e | 707,415 |
from typing import OrderedDict
def _find_in_iterable_case_insensitive(iterable, name):
"""
Return the value matching ``name``, case insensitive, from an iterable.
"""
iterable = list(OrderedDict.fromkeys([k for k in iterable]))
iterupper = [k.upper() for k in iterable]
try:
match = ite... | 548c951b08fb07251fda1b8918282462c8d0351a | 707,416 |
def _amplify_ep(text):
"""
check for added emphasis resulting from exclamation points (up to 4 of them)
"""
ep_count = text.count("!")
if ep_count > 4:
ep_count = 4
# (empirically derived mean sentiment intensity rating increase for
# exclamation points)
ep_amplifier = ep... | 8f78a5f24aa22b5f2b4927131bfccf22ccc69ff3 | 707,417 |
import argparse
def options_handler():
"""Validates and parses script arguments.
Returns:
Namespace: Parsed arguments object.
"""
parser = argparse.ArgumentParser(description="Downloads XSOAR packs as zip and their latest docker images as tar.")
parser.add_argument('-p', '--packs',
... | d3a650d58d0444981b010e230cb5111245a00bc7 | 707,418 |
import os
def get_prefix_by_xml_filename(xml_filename):
"""
Obtém o prefixo associado a um arquivo xml
Parameters
----------
xml_filename : str
Nome de arquivo xml
Returns
-------
str
Prefixo associado ao arquivo xml
"""
file, ext = os.path.splitext(xml_filena... | 169b5571ae0bfca2a923c4030325002503790f6e | 707,419 |
import base64
def create_api_headers(token):
"""
Create the API header.
This is going to be sent along with the request for verification.
"""
auth_type = 'Basic ' + base64.b64encode(bytes(token + ":")).decode('ascii')
return {
'Authorization': auth_type,
'Accept': 'applicatio... | 41ba1e22898dab2d42dde52e4458abc40640e957 | 707,420 |
def counting_sort(array, low, high):
"""Razeni pocitanim (CountingSort). Seradte zadane pole 'array'
pricemz o poli vite, ze se v nem nachazeji pouze hodnoty v intervalu
od 'low' po 'high' (vcetne okraju intervalu). Vratte serazene pole.
"""
counts = [0 for i in range(high - low + 1)]
for elem i... | bd4ccccdb24786ec3f3d867afe1adf340c9e53b5 | 707,421 |
import re
def normalize_archives_url(url):
"""
Normalize url.
will try to infer, find or guess the most useful archives URL, given a URL.
Return normalized URL, or the original URL if no improvement is found.
"""
# change new IETF mailarchive URLs to older, still available text .mail archive... | e8a5351af28338c77c3e94fdf2b81e22c7a6edfd | 707,422 |
def getIsolatesFromIndices(indices):
"""
Extracts the isolates from the indices of a df_X.
:param pandas.index indices:
cn.KEY_ISOLATE_DVH, cn.KEY_ISOLATE_MMP
:return dict: keyed by cn.KEY_ISOLATE_DVH, cn.KEY_ISOLATE_MMP
values correspond to rows element in the index
"""
keys = [n for n in indice... | 4e9200c722ce0c478d13eddcc799f4a8f7cab6db | 707,423 |
import os
def ensuredir(dirpath):
"""
ensure @dirpath exists and return it again
raises OSError on other error than EEXIST
"""
try:
os.makedirs(dirpath, 0o700)
except FileExistsError:
pass
return dirpath | 447f4542faa00e8928e30f0a9793436b8377964a | 707,424 |
import ast
from typing import Optional
def get_qualname(node: ast.AST) -> Optional[str]:
"""
If node represents a chain of attribute accesses, return is qualified name.
"""
parts = []
while True:
if isinstance(node, ast.Name):
parts.append(node.id)
break
eli... | 0d08b25a50b7d159f5df3b0b17282725eb748f38 | 707,425 |
import re
def d(vars):
"""List of variables starting with string "df" in reverse order. Usage: d(dir())
@vars list of variables output by dir() command
"""
list_of_dfs = [item for item in vars if (item.find('df') == 0 and item.find('_') == -1 and item != 'dfs')]
list_of_dfs.sort(key=lambda x:int(... | 4961ae70a61e45b81e06e55ee9553ff61fd45d18 | 707,426 |
def get_reset_state_name(t_fsm):
"""
Returns the name of the reset state.
If an .r keyword is specified, that is the name of the reset state.
If the .r keyword is not present, the first state defined
in the transition table is the reset state.
:param t_fsm: blifparser.BlifParser().blif.fsm ob... | c65ea80f94f91b31a179faebc60a97f7260675c4 | 707,427 |
def border_msg(msg: str):
"""
This function creates boarders in the top and bottom of text
"""
row = len(msg)
h = ''.join(['+'] + ['-' * row] + ['+'])
return h + "\n" + msg + "\n" + h | cdd9d17ba76014f4c80b9c429aebbc4ca6f959c3 | 707,428 |
def _qual_arg(user_value,
python_arg_name,
gblock_arg_name,
allowable):
"""
Construct and sanity check a qualitative argument to
send to gblocks.
user_value: value to try to send to gblocks
python_arg_name: name of python argument (for error string)
gbl... | 7bf6717ee3dbeb533902773c86316d2bbdcd59a9 | 707,430 |
def is_valid_ip(ip_addr):
"""
:param ip_addr:
:return:
"""
octet_ip = ip_addr.split(".")
int_octet_ip = [int(i) for i in octet_ip]
if (len(int_octet_ip) == 4) and \
(0 <= int_octet_ip[0] <= 255) and \
(0 <= int_octet_ip[1] <= 255) and \
(0 <= int_octet_ip... | 7d776107f54e3c27a2a918570cbb267b0e9f419e | 707,431 |
def overlapping_community(G, community):
"""Return True if community partitions G into overlapping sets.
"""
community_size = sum(len(c) for c in community)
# community size must be larger to be overlapping
if not len(G) < community_size:
return False
# check that the set of nodes in the... | da9e3465c6351df0efd19863e579c49bbc6b9d67 | 707,432 |
from typing import Any
def linear_search(lst: list, x: Any) -> int:
"""Return the index of the first element of `lst` equal to `x`, or -1 if no
elements of `lst` are equal to `x`.
Design idea: Scan the list from start to finish.
Complexity: O(n) time, O(1) space.
For an improvement on linear se... | 47e73d53ff68954aadc6d0e9e293643717a807d8 | 707,434 |
def checksum(number):
"""Calculate the checksum. A valid number should have a checksum of 1."""
check = 0
for n in number:
check = (2 * check + int(10 if n == 'X' else n)) % 11
return check | 8ada40ca46bc62bbe8f96d69528f2cd88021ad6a | 707,437 |
def instanceof(value, type_):
"""Check if `value` is an instance of `type_`.
:param value: an object
:param type_: a type
"""
return isinstance(value, type_) | 3de366c64cd2b4fe065f15de10b1e6ac9132468e | 707,438 |
import torch
def SPTU(input_a, input_b, n_channels: int):
"""Softplus Tanh Unit (SPTU)"""
in_act = input_a+input_b
t_act = torch.tanh(in_act[:, :n_channels, :])
s_act = torch.nn.functional.softplus(in_act[:, n_channels:, :])
acts = t_act * s_act
return acts | a03cc114cf960af750b13cd61db8f4d2e6c064ad | 707,439 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.