content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def decimal_to_hex(number):
"""
Calculates the hex of the given decimal number.
:param number: decimal number in string or integer format
:return string of the equivalent hex number
"""
if isinstance(number, str):
number = int(number)
hexadec = []
hex_equivalents = {... | d580acb55681089a8896c45b389533936fcbb19d | 652,459 |
import math
def t_score(own_team_scores, enemy_team_scores, neutral_scores, assassin_scores, weights=(1, 1, 1, 1)):
"""
Performs an independent two-sample t-test on own_team_scores and the combination of enemy_team_scores, neutral_scores and assassin_scores.
The formula used accounts for the fact that the sample s... | e34da4953db9bfd616df6a4dad951572f0d3032f | 652,460 |
import json
def load_config(filename):
""" load config file
Arguments:
----------
filename {str} -- file name of configuration file
Returns:
{dict} -- parameter dictionary
Examples:
---------
>>> data = load_config("../config/DecisionTreeConfig.json") # Preset pa... | b7ffee9196c1bfff44013e38d7790e063f7eea2e | 652,461 |
def perplexity(self, text):
"""
Calculates the perplexity of the given text.
This is simply 2 ** cross-entropy for the text.
:param text: words to calculate perplexity of
:type text: Iterable[str]
"""
return pow(2.0, self.entropy(text)) | 3959f87c4b765f7db2e50542a7d896a0fcf70cea | 652,462 |
import copy
def mat_shift(mat, way = 'down', inplace = False):
"""
Shifts a matrix's rows by one position
"""
assert mat.size != None
if inplace:
cmat = mat
else:
cmat = copy.deepcopy(mat)
temp_mat = copy.deepcopy(cmat)
if way.lower() == 'down':
for r in rang... | e73954a68fbe6a0cea6d21f76cfc01f875d786f6 | 652,463 |
def bulkStress(dp, dV, V0):
"""variables:
dp=change in fluid pressure
dV=change in subject volume
V0=original subject volume"""
# B = bulk stress / bulk strain
B = dp/(dV/V0)
return B | af348c684b67ddb5e63455d6d26cab6ad254d41a | 652,464 |
def superTuple(name, attributes):
"""Creates a Super Tuple class."""
dct = {}
#Create __new__.
nargs = len(attributes)
def _new_(cls, *args):
if len(args) != nargs:
raise TypeError("%s takes %d arguments (%d given)." % (cls.__name__,
... | 6193e079e7bc3404d736358b49e6b2f38ecbd31e | 652,465 |
import os
def is_missing_or_empty_file(path):
"""
Returns true, if the given file_path does not exist or if the content of
the file is empty.
"""
if path is None:
return True
return not os.path.isfile(path) or os.path.getsize(path) == 0 | 54522d8e5e4bfdaed6250f4319b43a628739729d | 652,466 |
import os
import zipfile
def unzip_file(file_name : str) -> str:
""" Unpacks a ZIP file
Keyword arguments:
file_name -- path of the ZIP file
Returns path to the folder containing the unpacked files.
"""
extraction_dir = os.path.join(os.path.dirname(file_name), os.path.bas... | 8f9f9d961372582d0bd51b8c88b82b42aebea9b1 | 652,467 |
def valid_limit(limit, ubound=100):
"""Given a user-provided limit, return a valid int, or raise."""
limit = int(limit)
assert limit > 0, "limit must be positive"
assert limit <= ubound, "limit exceeds max"
return limit | abfcfa5de9f51055f0bfc8910ce8d98e03159af7 | 652,468 |
def real_model(source_model):
"""
Get the source model whenever user give a source index or proxy index or proxy model.
"""
return source_model | f23118eb3beb6092737bb3a7bd51a3ec1c216e00 | 652,469 |
def crop(image):
"""Crop the image (removing the sky at the top and the car front at the bottom)
Credit: https://github.com/naokishibuya/car-behavioral-cloning
"""
return image[60:-25, :, :] | d2ae9039b8941a7b7a10d3659d6272de3d6f0987 | 652,470 |
def get_content_type(result_set):
""" Returns the content type of a result set. If only one item is included
its content type is used.
"""
if len(result_set) == 1:
return result_set[0].content_type
else:
return "multipart/related" | a771110f6db874ea9cc5284e95db2e023395e1de | 652,471 |
import torch
def _get_nms_kernel3d(kd: int, ky: int, kx: int) -> torch.Tensor:
"""Utility function, which returns neigh2channels conv kernel"""
numel: int = kd * ky * kx
center: int = numel // 2
weight = torch.eye(numel)
weight[center, center] = 0
return weight.view(numel, 1, kd, ky, kx) | f03ccfe41b4ee9a799d6ca4150aef0029ed57397 | 652,472 |
def cover_website(website):
"""
>>> cover_website('https://unilexicon.com/vocabularies/')
'unilexicon…'
"""
www = website.replace('http://', '').replace('https://', '')
return f'{www[:10]}…' | c739688d58cdd367b2e4e5461156578c48384a87 | 652,473 |
import os
def basicname(path):
"""Return the basename of the path without the extension"""
return os.path.splitext(os.path.basename(path))[0] | a6e7582cd71637999e822639bc99d44445349e97 | 652,474 |
def chk_enum_arg(s):
"""Checks if the string `s` is a valid enum string.
Return True or False."""
if len(s) == 0 or s[0].isspace() or s[-1].isspace():
return False
else:
return True | 25d906b539b75031bf2ec040f2531bd78caecf8e | 652,475 |
from pathlib import Path
def _sqlite_uri_to_path(uri: str) -> Path:
"""Convert a SQLite URI to a pathlib.Path"""
return Path(uri.split(':')[-1]).resolve() | 1cd71c8f6957f84818086f3382449c55c2004f2c | 652,476 |
def BytesFromFile(filename):
"""Read the EDID from binary blob form into list form.
Args:
filename: The name of the binary blob.
Returns:
The list of bytes that make up the EDID.
"""
with open(filename, 'rb') as f:
chunk = f.read()
return [int(x) for x in bytes(chunk)] | 47d13dd1ea1443c53302c655d478aa4ef8773c7d | 652,477 |
import os
def get_structures(base_dir):
"""Returns a copy of the directory tree without the runtype folders for each chemical system- no need to know if the file was ran as an optimisation or hessian etc... the files with a chemical name are initial coordinates, and equil.xyz are equilibrium coordinates found aft... | 0148e99cae310da1fbe624ee847f9d4877c2ae06 | 652,478 |
import requests
import re
def pre_process_audio(url):
"""
Parsing read file, windows character set not supported in mac.
Make this more elegant.
"""
abc_music = requests.get(url).content
proc_abc_music = re.sub('\%(.*?)\\\\r\\\\n', '', str(abc_music))
proc_abc_music = re.sub('\#(.*?)\\\\r\... | ecae337260e56b54099f6275d15f04af52d387e9 | 652,479 |
def matrix_divided(matrix, div):
"""matrix """
if (not isinstance(matrix, list) or matrix == [] or
not all(isinstance(row, list) for row in matrix) or
not all((isinstance(col, int) or isinstance(col, float))
for col in [num for row in matrix for num in row])):
... | 9620c6ae25aa10cbf833ff48c8e65779140cec47 | 652,480 |
def allowed_file(filename):
"""Function checks if the file is in an acceptable format"""
return '.' in filename and \
filename.rsplit('.', 1)[1].lower() in set(['png', 'jpg', 'jpeg']) | 184cef5cfcf966dba83b4d033d8fee444c2eec74 | 652,481 |
def map_item_type(type):
"""Returns mapped type."""
item_types = {
"1": "https://ils.rero.ch/api/item_types/1",
"2": "https://ils.rero.ch/api/item_types/2",
"3": "https://ils.rero.ch/api/item_types/3",
"4": "https://ils.rero.ch/api/item_types/4",
"5": "https://ils.rero.ch... | b9b4f11feba06424ad0d08bfcde27621d5292796 | 652,482 |
import time
def create_status(connection, uid, message, **data):
"""创建状态消息散列"""
pipe = connection.pipeline(True)
pipe.hget('user:' + uid, 'login')
pipe.incr('status:id:')
login, sid = pipe.execute()
# 发布状态消息前先验证用户账号是否存在
if not login:
return None
data.update({
'message':... | a7d11b435edbde12bf1d1d07f172ce5f73acd2fe | 652,483 |
def test_1arg(x):
"""
test_1arg(x) = x
Must be called with exactly one argument "x".
"""
return x | f424bd9fe7b16a5ca94102ca8dbd622dc5f232b4 | 652,484 |
def divide_image_into_bounding_boxes(img,width_split=1,height_split=1):
"""
This splits the image into width_split x height_split bounding boxes based upon the...
width_split: how many times to split the image in the x direction
height_split: how many times to split the image in the ... | 0c85227fdcd58691b562f8a6bc61d42fe5d87310 | 652,485 |
import pathlib
def tmp_yaml(tmp_path: pathlib.Path) -> pathlib.Path:
"""Temporary copy of path.yaml."""
dest_path = tmp_path / "path.yaml"
src_path = pathlib.Path("tests/data/path.yaml")
text = src_path.read_text()
dest_path.write_text(text)
return dest_path | dfa35cd3877e72e1d51696276463c540fc8c3fef | 652,486 |
def _consume_response(response):
"""Consume content and release the original connection.
Args:
response: A requests.Response to whose connection to reuse.
Returns:
requests.PreparedRequest, a copy of the response's request.
"""
response.content
response.close()
return respo... | c5c6dbc4dbe56756156cca33c28c7a1448b3b10a | 652,487 |
def get_parameter_for_sharding(sharding_instances):
"""Return the parameter for sharding, based on the given number of
sharding instances.
Args:
sharding_instances: int. How many sharding instances to be running.
Returns:
list(str). A list of parameters to represent the sharding config... | b4d844b9248002b638be4546aba13410d1081400 | 652,488 |
def _set_default_junction_temperature(
temperature_junction: float,
temperature_case: float,
environment_active_id: int,
) -> float:
"""Set the default junction temperature for integrated circuits.
:param temperature_junction: the current junction temperature.
:param temperature_case: the curre... | 3cf1adadab18d76ed72548df4deaac0743a55e8d | 652,489 |
import os
def isDir(path):
"""
isDir(filename: string)
determine whether a path is a directory
"""
return os.path.isdir(path) | 7ec02f3a38c60fc35843c75683f56de3ea738676 | 652,490 |
import os
def get_int_environ_parameter(
name: str,
default: int = 0,
) -> int:
"""
Getting integer environment variable
"""
return int(os.environ.get(name, default)) | 1da8de81461f756ba5732ba563b5da991f975f4d | 652,491 |
def if_error(f, x, upon_error):
"""
Mimics Excel IFERROR functionality.
If you're using this, you're probably doing Python wrong.
(If you're using this with numpy/pandas, check the numpy WHERE argument
first.)
But sometimes it's useful.
Like maybe you'd like to ignore unicode errors for a wh... | 8a864c0dcb0f84936719ddb85df60ebc5d2e0f87 | 652,492 |
from typing import List
def erase_overlap_intervals_count(intervals: List[List[int]]) -> int:
"""
LeteCode 435: Non-overlapping Intervals
Given a list of intervals, find the minimum number of intervals you need to remove
to make the rest of the intervals non-overlapping.
Examples:
1. i... | 3766b368079f8bd71d51976d41f15a10b130aced | 652,493 |
import re
def check_pom(test, pom, org_name, artifact_name, version, dependencies):
"""
Check the contents of the pom. Make sure the groupId, artifactId, and version are properly set.
:param org_name: organization (group) id of the package
:param artifact_name: artifact id of package
:param versio... | f593a0af43b86d18e5507e3d680dbc0965dc28d1 | 652,494 |
def get_severity_points(severity):
"""
normal
critical
major
trivial
enhancement
minor
blocker
:param severity:
:return:
"""
points = 0
for i in severity:
if i == 'normal':
points += severity[i] * 3
elif i == 'critical':
points... | a9f93b3e728610de218192bc6bd8dfd688ba8e13 | 652,495 |
import re
def generate_tid_dict(threat_reports):
"""this will return a dictionary with TID's as keys. Values will be a list of all threat reports for that TID"""
tid_dict = {}
pattern = "t\d{4}"
for threat_report in threat_reports:
# grab all the supported OS tags
if "windows" in thre... | 458d9eb78060f304fdeecffe91f98d5a42af36c7 | 652,496 |
import os
import resource
def spareprocs():
"""
Compute the maximum number of threads we can start up according to ulimit
"""
if not os.path.exists("/proc"):
# Return a decent small value, we just want it to run, more grindy tests
# can take place on other machines.
return 10
... | 58c5e6275fecd85f34243a4eee45dae2c409e2a2 | 652,497 |
import os
import pickle
import json
def gqa_create_answers(gqa_q='data/GQA-Questions', cache='data/GQA-Cache'):
""" Create mapping from answers to labels """
# Create File Paths and Load from Disk (if cached)
dfile = os.path.join(cache, 'answers.pkl')
if os.path.exists(dfile):
with open(dfile... | c901ad99594bb59172956f8d9718a0d17f72378f | 652,498 |
def remove_title(soup):
"""Deletes the extra H1 title."""
h1 = soup.find('h1')
if h1:
h1.extract()
return soup | 3017bc18ddb8a6fe4a4be1333de9e7ff3d7150c7 | 652,499 |
import numpy
def symbolise( pitches, eps=8e-2 ):
"""
eps :: float = tan(5 degrees) default
"""
#if input pitches are all 0.0, categorise it as silent (3)
if not pitches.any():
return 3
N = len(pitches)
xs = numpy.arange(N)
ys = pitches
AA = numpy.vstack([xs, numpy.on... | 076d7c08c230b1e9eaf87878ccfcd8e3ccca65da | 652,500 |
import torch
def nosigmloss1d(a, b):
"""Get 1D sigmoid loss, WITHOUT applying the sigmoid function to the inputs beforehand.
Args:
a (torch.Tensor): Predicted output
b (torch.Tensor): True output
Returns:
torch.Tensor: Loss
"""
x = a
y = b
ret = torch.mean(-y*tor... | 4fb836f6779506cf40b1787405ab97aeb20e9902 | 652,501 |
def insert_sort(data):
"""Sort data via insertion."""
try:
idx = 0
count = 1
for x in data[1:]:
if not isinstance(x, type(data[idx])):
raise TypeError()
while x < data[idx]:
data[idx], data[idx + 1] = data[idx + 1], data[idx]
... | 9b706e3c810755d805f64a211eff6f51200903a0 | 652,502 |
import subprocess
def run_subprocess(command):
"""Run commands as a subprocess using subprocess
Args:
command: list
Returns:
result: subprocess result object
"""
result = subprocess.run(command,
capture_output=True, text=True
... | e0b83d9c2f56f32c4875ae9e7071b57e593d9c40 | 652,503 |
import re
def _convert_to_db_type(sval):
""" Detect which database type (string, int, float) is most appropriate for sval
and convert it to its corresponding database type. """
# floats: Ex. 1.23, 0.23, .23
if re.search(r'^\s*\d*\.\d+\s*$', sval):
return float(sval)
# ints: Ex. 0, 12... | acb1f0d05f6307b73c77b95f4166957bf748a6f9 | 652,504 |
def source_key(resp):
"""
Provide the timestamp of the swift http response as a floating
point value. Used as a sort key.
:param resp: httplib response object
"""
return float(resp.getheader('x-put-timestamp') or
resp.getheader('x-timestamp') or 0) | 80d56dfe1e4e0ddc9e1eeabb20a05e9b19357cb8 | 652,505 |
def calculate_c_haines_index(t700: float, t850: float, d850: float) -> float:
""" Given temperature and dew points values, calculate c-haines.
Based on original work:
Graham A. Mills and Lachlan McCaw (2010). Atmospheric Stability Environments
and Fire Weather in Australia – extending the Haines Index.
... | 153a994a5437faedfc275689f7682f426b390504 | 652,506 |
def build_initiator_target_map(connector, target_wwns, lookup_service):
"""Return a dictionary mapping server-wwns and lists of storage-wwns."""
init_targ_map = {}
initiator_wwns = connector['wwpns']
if lookup_service:
dev_map = lookup_service.get_device_mapping_from_network(
initiat... | bdf19a30d6a0f57481df70ff96b9e0a7427e43d3 | 652,507 |
def authenticate(resource_protector, scope=None, permissions=None):
"""
Used to authenticate request using CustomResourceProtector
:param resource_protector: CustomResourceProtector
:param scope: Scope with scopes string and operator (And/Or)::
Scope(scopes="resource.create resource.read", ope... | 92734b843beebf1211acc177c8a000bc16ec3539 | 652,508 |
def param_max(data, i, body, param="Ecce", fmt="hdf5", **kwargs):
"""
Checks to see if at some point Prox b got within a certain number of sigma
of its observed semimajox axis within specified age bounds.
Parameters
----------
data : Dataset Object
bigplanet hdf5 dataset wrangler... | e7c632bbce9512d9d749009ed30bf7995b34dc54 | 652,509 |
def walk(fn, obj, *args):
"""Recursively walk an object graph applying `fn`/`args` to objects."""
if type(obj) in [list, tuple]:
return list(walk(fn, o, *args) for o in obj)
if type(obj) is dict:
return dict((walk(fn, k, *args), walk(fn, v, *args)) for k, v in
obj.items()... | 7fd65a6b598375c72f7d10efb1b04c500324fcb4 | 652,510 |
def is_mol_parameter(param):
"""Identify if a parameter is a `mol` parameter."""
parts = param.split("_")
return param.startswith("mol_") \
and parts[-1].isdigit() \
and len(parts) > 2 | 5c6d3324922d393b5d17ed26f5c665f8e98a1d24 | 652,511 |
def get_word(word):
"""Return normalized contents of a word."""
return "".join([n.string.strip() for n in word.contents if n.name in [None, "s"]]) | 7625e485b66a95e53cb9d0ccea30190408d7579b | 652,513 |
import os
def generate_random_iv(iv_len):
"""Generates a random initialization vector (IV).
:returns: Initialization vector
:rtype: bytes
"""
return os.urandom(iv_len) | 44f432de8a45a98ab9321773b31ea515e90ec27c | 652,514 |
def to_str(bytes_or_string):
"""if bytes, return the decoded string (unicode here in python3). else return itself"""
if isinstance(bytes_or_string, bytes):
return bytes_or_string.decode('utf-8')
return bytes_or_string | b1fa95df710523179d08a7155c7f7c4d7e31303c | 652,515 |
def _message_format(msg, image_info, device, partition_uuids):
"""Helper method to get and populate different messages."""
message = None
result_msg = msg
root_uuid = partition_uuids.get('root uuid')
efi_system_partition_uuid = (
partition_uuids.get('efi system partition uuid'))
if (ima... | 39a5dd6da3e2b4cbc232ca5178c4503d46eff5bf | 652,517 |
from typing import Any
def dynamic_import(import_path: str) -> Any:
"""Dynamically import the specified object.
It can be a module, class, method, function, attribute,
nested arbitrarily.
Parameters:
import_path: The path of the object to import.
Raises:
ImportError: When there ... | 78ecdd95d4b0d31ff908da190a4c7842e5d2efd2 | 652,518 |
from typing import Tuple
def screen_to_world(screen_pos: tuple,
pan: tuple,
zoom: float) -> Tuple[float, float]:
""" Converts screen coordinates to world coordinates using the pan and
zoom of the screen """
result = (((screen_pos[0] - pan[0]) / zoom),
... | 3096fe18742cf4c5bbfdc629ede3eac83e6d4f74 | 652,519 |
import numpy
def visibility_shift(uvw, vis, dl, dm):
"""
Shift visibilities by the given image-space distance. This is
based on simple FFT laws. It will require kernels to be suitably
shifted as well to work correctly.
:param uvw:
:param vis: :math:`(u,v,w)` distribution of projected baseline... | 267620c6e354f05f393610e9bcb52a1992a504e1 | 652,521 |
def count_empty(index, key):
"""
Count for any key how many papers leave the value unspecified.
Note that this function only checks the first of the rows corresponding to a paper.
"""
count = 0
for paper, rows in index.items():
value = rows[0][key]
if value in {"", "none given", ... | 64b48a945fbec7ed7f219f3f541f8f27cf174f46 | 652,522 |
from typing import Tuple
def _convergent(continued_fractions: Tuple[int, ...],) -> Tuple[int, int]:
"""Get the convergent for a given continued fractions sequence of integers
:param continued_fractions: Tuple representation of continued fraction
:return: reduced continued fraction representation of conve... | c5263b5046e07fb9b19f20ede2080112013bbe4f | 652,523 |
def matches_release(allowed_releases, release):
"""
Check if the given `release` is allowed to upgrade based in `allowed_releases`.
:param allowed_releases: All supported releases
:type allowed_releases: list or dict
:param release: release name to be checked
:type release: string
:return: ... | 9555254459e56114e9544dcded66f24af9a6de32 | 652,524 |
def _neighbor_indexes(n, mesh, restrict):
"""Find the indexes of the neighbors of n"""
nz, ny, nx = mesh.shape
indexes = []
if 'above' not in restrict:
# The guy above
tmp = n - nx * ny
if tmp > 0:
indexes.append(tmp)
if 'below' not in restrict:
# The guy ... | e0ad8f2bd96f605983d2aaee7264c2f7bd679ed1 | 652,525 |
def get_near_doctor(doctors,patient):
"""Returns extra zeros from path.
Return
Dynamical model generates duplicated zeros for several graphs when obtaining partial solutions.
"""
return doctors | 968e7f990496e95a02c955ec5d4a0904845439b5 | 652,526 |
import argparse
def _parse_args(args=None):
"""Parse `args` as command line options. If `args` is None,
use sys.argv"""
desc = 'File hash indexer for duplicate file finding.'
parser = argparse.ArgumentParser(prog='dupi', description=desc)
subparsers = parser.add_subparsers(dest='command')
u... | 0a0406d2e7d39291b5438643250c43f18d9ed61f | 652,527 |
def is_valid_xml_char(char):
"""Check if a character is valid based on the XML specification."""
codepoint = ord(char)
return (0x20 <= codepoint <= 0xD7FF or
codepoint in (0x9, 0xA, 0xD) or
0xE000 <= codepoint <= 0xFFFD or
0x10000 <= codepoint <= 0x10FFFF) | 8bd5edf78246d9ba2ef4f50a48780c6a210ffdb0 | 652,528 |
def prescribe_voltage(A, b, coil_rings, voltage, v_ref, J):
"""Get the voltage coefficients :math:`c_l` with the total voltage
prescribed.
"""
# The currents must equal in all coil rings.
for k in range(len(coil_rings) - 1):
i = coil_rings[k]
i1 = coil_rings[k + 1]
A[i][:] = ... | 49532b265970bc654c6777d6f6c0058f0afbe66e | 652,529 |
import argparse
def parse_args(args):
""" Parse the arguments.
"""
parser = argparse.ArgumentParser(description='Simple training script for training a RetinaNet network.')
subparsers = parser.add_subparsers(help='Arguments for specific dataset types.', dest='dataset_type')
subparsers.required ... | d2ae0772e3a85637c14dbe496302fb881b70cc59 | 652,530 |
def endtime(x):
"""Return endtime of intervals x"""
try:
return x['endtime']
except (KeyError, ValueError, IndexError):
return x['time'] + x['length'] * x['dt'] | 345aea136b142af7f33e61622bdf3856d7561491 | 652,531 |
def get_ceph_rook_cfg(k8s_conf):
"""
Returns ceph rook enablement choice
:return true/false
"""
if k8s_conf.get('enable_ceph_rook') :
return k8s_conf['enable_ceph_rook'] | e7c94ce1a9bb63175ede4fb354e8f6ae35995ad1 | 652,532 |
def DecodeFileRecordSegmentReference(ReferenceNumber):
"""Decode a file record segment reference, return the (file_record_segment_number, sequence_number) tuple."""
file_record_segment_number = ReferenceNumber & 0xFFFFFFFFFFFF
sequence_number = ReferenceNumber >> 48
return (file_record_segment_number,... | e6f47a5e221ab5e53398c7aac55d0abcb3ad0308 | 652,533 |
import random
def sample_strategy(distrib):
""" return the index of a strategy
general util used by nature and agent oracle """
strategy_i = random.choices(list(range(len(distrib))), weights=distrib)[0]
return strategy_i | 58d1b9f04478d3571859859dea219d9bc1e50d28 | 652,534 |
def firstjulian(year):
"""Calculate the Julian date up until the first of the year."""
return ((146097*(year+4799))//400)-31738 | 782627810324ad43fa010b4f060e28af63bbfe96 | 652,535 |
def sum_non_reds(s):
"""
Sum all numbers except for those contained in a dict where a value is "red".
Parameters
----------
s : int, list, or dict
An item to extract numbers from.
Returns
-------
int
The total of all valid numbers.
"""
if isinstance(s, int):
... | 8d5ffb05b3575d9d3b34d3836b5ef7e728471ddd | 652,536 |
import typing
import struct
def read_uint32(stream: typing.BinaryIO) -> int:
"""Reads a Uint32 from stream"""
return struct.unpack("<I", stream.read(4))[0] | 8ae59153ff53076ade31374f2fad3e03859ec336 | 652,537 |
import requests
def buscar_avatar(usuario: str) -> str:
"""
Busca avatar no GitHub
Args: usuario (str): usuário no github
Return: str com o link do avatar
"""
url = f'https://api.github.com/users/{usuario}'
resp = requests.get(url)
return resp.json()['avatar_url'] | 1199336cb1f1f0774e3e159308c0a4c313ef8f6c | 652,538 |
import numpy
def min_max_scaler(saliency):
"""Normalize saliency to value 0-1"""
maxv = numpy.max(saliency)
minv = numpy.min(saliency)
if maxv == minv:
saliency = numpy.zeros_like(saliency)
else:
saliency = (saliency - minv) / (maxv - minv)
return saliency | a1f14cb7a0eeca33241a7e13e4e0229cc9f21749 | 652,539 |
def normalize_cpm(value, total):
"""Normalize by CPM."""
return value / total * 10**6 | b23e5b60663f942c780997419dda865a8a3c7dce | 652,540 |
from typing import Callable
import inspect
def cache(times: int) -> Callable:
"""Cache decorator which returns func result n times"""
cached_values = {}
def _cache(func: Callable) -> Callable:
def wrapper(*args, **kwargs):
bound = inspect.signature(func).bind(*args, **kwargs)
... | cdf3b0577fd84f0406f61de3a190bce9f48d55db | 652,541 |
def get_ftp_dir(abspath: str) -> str:
"""
Returns path within ftp site
Parameters
----------
abspath
The full ftp url
Returns
-------
str
The relative path within the ftp site
Examples
--------
>>> abspath = 'ftp://ftp.ncbi.nlm.nih.gov/genomes/all/GCF/901/1... | ca815927f16e36ca3b1e8e153ea662acb6ad8676 | 652,542 |
def cactus_stats(tools, results, timeout):
"""re-arrange the data for cactus plot"""
ret_results = {}
for bench in results.keys():
for tool in results[bench].keys():
if tool not in ret_results.keys():
ret_results[tool] = []
if float(results[bench][tool][0]) <... | 9f77603b5c3e0f5baec34df16ae8ed786f285f0a | 652,543 |
from textwrap import dedent
import re
def message(source, *args, **kwargs):
"""
:param source:
:param kwargs:
:return:
"""
out = (
dedent(source.format(*args, **kwargs).strip('\n'))
.strip()
.replace('\t', ' ')
.replace('\n', ' ')
)
return re.sub(r'\s... | 175617aa58f69413cb5139507a10976dce92f5a6 | 652,544 |
import requests
def ack_alert(host, nagios_api, comment, service=None):
"""
Acknowledge a problem in Nagios.
Specify service AND host if ack --> service.
"""
headers = {
'Content-type': 'application/json',
}
if service:
payload = {
'host': host,
's... | 8740e1ab3a15ea2cfa3707df4ef4b9ef173d5ff2 | 652,545 |
def parse_network(dyn_data: dict) -> dict:
"""
parses out network information from dynamic data dictionary
Args:
dyn_data: dictionary read from dynamic data
Returns:
network_dict: dictionary parsing the network information extracted from dyn_data
"""
if dyn_data == {}:
... | 773c91dd3db7bb25cfc7eda353e328894d13aba0 | 652,546 |
import torch
import math
def rotate(origin, point, angle):
"""
Rotate a point counterclockwise by a given angle around a given origin.
The angle should be given in radians.
"""
if(torch.is_tensor(angle)):
N=point.shape[0]
angle=angle.reshape(N)
po=(point-origin).reshape(N,... | 2fbd5c5cb64e7d967679c0e6f8f324a0295ccfc9 | 652,548 |
import argparse
def load():
"""
Description
Define and load the arguments that will be used in the moc_ET.py program.
Returns
Arguments object.
"""
parser = argparse.ArgumentParser(description="Extract and Transform data from .owl Ontology, and write data to JSON files",
... | a0b110b3944768d65d92a86f33c11b2873e7ec0f | 652,549 |
def make_graph_abcde(node):
"""
A -> B
| |
| v
+--> C -> D
|
+--> E
"""
d = node('D')
e = node('E')
c = node('C', cd=d)
b = node('B', bc=c)
a = node('A', ab=b, ac=c, ae=e)
return a, b, c, d, e | 0c234a64c9a716c5629f0b6cc757ca588210fe7c | 652,550 |
import types
def isframe(object):
"""Return true if the object is a frame object.
Frame objects provide these attributes:
f_back next outer frame object (this frame's caller)
f_builtins built-in namespace seen by this frame
f_code code object being executed in t... | 6848b9969610f7b23723f66ce506bbd5f295d350 | 652,551 |
def tag_fig_ordinal(tag):
"""
Meant for finding the position of fig tags with respect to whether
they are for a main figure or a child figure
"""
if "specific-use" not in tag.attrs:
# Look for tags with no "specific-use" attribute
return (
len(
list(
... | b0961c7244ca9b55ccc8ae3d89165c5b5d1d6606 | 652,552 |
import pathlib
def process_path(path, parent, default):
"""Convert a path to an absolute path based on its current value.
Arguments
---------
path : PathLike
The path to be processed.
parent : PathLike
The parent path that `path` will be appended to if `path` is a relative path.
... | 8e69ef8881f854e9d6016aaffb96a0210f432d20 | 652,553 |
def normalize_preferences(choices):
"""Removes duplicates and drops falsy values from a single preference order."""
new_choices = []
for choice in choices:
if choice and (choice not in new_choices):
new_choices.append(choice)
return new_choices | bde074bfdc0e690eb16ae83e42ee01e542188cec | 652,554 |
def charencode(string):
"""String.CharCode"""
encoded = ''
for char in string:
encoded = encoded + "," + str(ord(char))
return encoded[1:] | 0014366be17cb1193ad2a7408845825694f2dbfb | 652,555 |
def vels(speed, turn):
"""
Function to get current velocity (speed and heading direction)
:param speed: linear velocity (m/sec)
:param turn: heading direction (radians)
:return: typeset string useful for displaying current velocity
:rtype: string
"""
return "currently:\tspeed %s\tturn %... | c2ef82d56894b9612457a19f9b13b57a40fff6b6 | 652,556 |
def result_field_map():
"""Recent pythons have an ordered dictionary, so we can be comfortable with these columns
"count turtles": "count_turtles",
"[step]": "step",
"""
return {
"[run number]": "run_number",
"map-file": "map_file",
"People": "people",
"person... | c6afa3437dab0aa7f967ad903c01ab608f290a92 | 652,557 |
def nl_sanitize_record(record, use_case):
"""
Sanitize record to avoid translation errors
Params:
record (str): target record
Returns: the sanitized record
"""
if record:
if use_case == 'cervix':
record = record.replace('cin ii - iii', 'cin2 cin3')
record = record.replace('cin ii-iii', 'cin2 cin3')
... | 8210cd145a4548a27e058831e94b65715a30c085 | 652,559 |
import argparse
def parse_arguments():
"""Parse and return the command line arguments."""
parser = argparse.ArgumentParser()
parser.add_argument('filepath', help="Path to the data file.")
parser.add_argument('--name', help="File name to save in SharedArray. "
"De... | 30d57f5371bfc8323c466ed29fd8863c985f762f | 652,561 |
def check(wants, has):
"""
Check if a desired scope ``wants`` is part of an available scope ``has``.
Returns ``False`` if not, return ``True`` if yes.
:example:
If a list of scopes such as
::
READ = 1 << 1
WRITE = 1 << 2
READ_WRITE = READ | WRITE
SCOPES = (
... | d5edf8886d986784bf62234671e321f9ffa7aa7b | 652,562 |
import torch
def bhw_to_onehot_by_scatter_V1(bhw_tensor: torch.Tensor, num_classes: int):
"""
Args:
bhw_tensor: b,h,w
num_classes:
Returns: b,h,w,num_classes
"""
assert bhw_tensor.ndim == 3, bhw_tensor.shape
assert num_classes > bhw_tensor.max(), torch.unique(bhw_tensor)
#... | 398d38ff6f73de483b2c0c88d50861b4542e3bf7 | 652,564 |
from typing import Optional
import os
def normalize_make_env(envs=os.environ) -> Optional[str]:
"""normalize the environment variables for make
`Make` still attempts to expand environment variables in the Makefile,
so we need to redeclare them literally to avoid further expansion
See: https://stackov... | ff913097df2bf0cf1d784496d8a46e944d37689d | 652,565 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.