content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import numpy as np
def random(size, nulls=False):
"""Return random numpy.ndarray instance of 64 bit floats.
"""
r = np.random.random(size)
if nulls:
idx = np.random.randint(0, r.size, size=max(1, r.size//4))
r[idx] = np.nan
return r | 029fe98e3ba4c12320a20112eb721d93de44786f | 665,557 |
def comicvine_volume_id_test(expected):
"""Build a test function to assert comicvine volume ID."""
def test(metadata):
"""Ensure that the metadata instance contains the expected data."""
if metadata.identifiers:
result = metadata.identifiers.get('comicvine-volume')
else:
... | bb8ac261e1a932c200ccc83016cd80b8cfcf5472 | 665,558 |
import hashlib
def sha(data):
"""hashes data
Args:
data (bytes): the data to hash
"""
sha2 = hashlib.sha256()
sha2.update(data)
return sha2.digest() | 2eca70d990c85779de22807508ab4e3fb193213c | 665,559 |
import os
import logging
def create_dir(destination) -> str:
"""
Parameters
----------
destination: str
Het pad dat aangemaakt dient te worden.
Returns
-------
destination: str
Het pad dat is aangemaakt (zelfde als input)
"""
try:
if not os.path.exists(de... | 008b12729e6089490db6fd7ad27660cd2571d4c3 | 665,560 |
def gformat(val, length=11):
"""format a number with '%g'-like format, except that
the return will be length ``length`` (default=12)
and have at least length-6 significant digits
"""
length = max(length, 7)
fmt = '{: .%ig}' % (length-6)
if isinstance(val, int):
out = ('{: .%ig}' % (l... | d48597849087266c7a65bfd1564aedfd8f2e2cec | 665,563 |
import argparse
from pathlib import Path
def parse_args():
"""Parse CLI arguments."""
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('-o',
'--out',
type=Path,
required=True,
help='Ou... | ecac0cb9365c5b428e4be840b2292bd67d797e94 | 665,564 |
def immediate_divide_by_n(string_immediate, nb_immediate, n):
""" Convert the string representing an immediate in a string representing the number divided by n without the '#'
and with the same number of digits indicated by the parameter nb_immediate"""
return "{0:b}".format(int(string_immediate.strip('... | 999e21f555abda8a916ba26fb4eaaf971d9312b0 | 665,565 |
def build_tree(elems, root, currentkey, parentkey):
""" Constructs a hierarchic tree from a flat dictionary.
https://stackoverflow.com/questions/35452512/construct-hierarchy-tree-from-python-flat-parent-children-dict-list
:param elems: flat dictionary
:param root: root node of current recursion
:p... | 60d21e56027a2b396d5f58e466ea58786135268d | 665,566 |
def match_strings(str_in, match_list):
""" Check if any of a list of strings is found in another string.
str_in input string.
match_list list of strings to find in str_in.
returns True if a match is found and False if no match is found.
"""
for match in match_list:
if match i... | a8a977304c0f85858a7c89c75299c5630849fd53 | 665,568 |
def parse_destination(phone_number, destinations):
"""Find the matching destination for a phone number.
Args:
phone_number: a string number with no leading '+'
destinations: a list of Destination instances
Returns:
a Destination instance or None if the prefix wasn't found.
"""
# ... | bab6e6e17196a7ab5a624bb799c9bb700bff852e | 665,569 |
def bedl_matches_vcf(variant, line_split: list) -> bool:
""" Consecutive checks of whether the chromosome, start position and repeat unit
in the supplied variant and (split + stripped) bedl line match. If all matches, return True,
otherwise return False
"""
if not line_split[0] == variant.CHROM:
... | c8950677bdfab2152314acf95138662de6e373d1 | 665,570 |
def add_try_clause(code, excpt):
"""Add a try/except clause, excepting 'excpt' around code."""
code = code.replace('\t', ' ')
return ("try:\n" + '\n'.join([" " + line for line in code.split('\n')])
+ "\nexcept " + excpt.__name__ + ":\n pass") | 5863fcf0c8f8af426425c982042d3d05a0ab497e | 665,571 |
def recursive_binomial_coefficient(n, k):
"""Calculates the binomial coefficient, C(n,k), with n>=k using recursion
Time complexity is O(k), so can calculate fairly quickly for large values of k.
>>> recursive_binomial_coefficient(5,0)
1
>>> recursive_binomial_coefficient(8,2)
28
>>> recu... | 07af2d622d91228eb370d6074c43702c10fdede6 | 665,572 |
import torch
def probs_ind_backchannel(probs):
"""
Extract the probabilities associated with
A: |__|--|--|__|
B: |__|__|__|--|
"""
bc_pred = []
# Iterate over speakers
for current_speaker, backchanneler in zip([1, 0], [0, 1]):
# Between speaker diff
# ----------... | cc52791c07f0f383aa27ed93113973a10a1d9ed7 | 665,573 |
import numpy
def nasa_entropy_polynomial_value(temp, cfts):
""" NASA polynomial entropy value
"""
cf1, cf2, cf3, cf4, cf5, _, cf7 = cfts
entr_over_r = (cf1 * numpy.log(temp) +
cf2 * numpy.power(temp, 1) / 1. +
cf3 * numpy.power(temp, 2) / 2. +
c... | 2b45087131168a43e41ccafa4b8e0d259bc27f74 | 665,575 |
def check_file(df):
"""Check a file format for correct column names and structure"""
if not all(x in df.columns
for x in ["image_path", "xmin", "xmax", "ymin", "ymax", "label"]):
raise IOError(
"Input file has incorrect column names, the following columns must exist 'image_pa... | f1eb49ef1b08b4e538979897d6848b5f80e9713b | 665,576 |
def apply_discount(trigger, triggers_needed, affected, discount, when, basket):
"""Adds the given `discount` to the `basket`, if all preconditions are met,
returning the new basket with discounts present.
This is the function that all discounts are expected to call, hence the
deprecation of the ``*_ver... | d66eee47b01d9798aa52a70c09f1db19285ed838 | 665,577 |
import os
def load():
"""Display the system load over the last 1, 5 and 15 minutes."""
loaddata = []
load = os.getloadavg()
for i in load:
loaddata.append(i)
load_data = (
"\nLoad average of the system"
+ "\n"
+ " 1 min: \t"
+ str(loaddata[0])
+ "\n... | 37aca219c763c63a175e47e174eb730f81918f50 | 665,578 |
import re
def get_res():
"""
"""
candidate_terms = ['subjects', 'adults', 'children', 'users', 'patients',
'men', 'women', 'controls', 'volunteers']
cd_np = re.compile("Chunk\('([^0-9]*(\d+)[^0-9]*)/NP", re.MULTILINE|re.DOTALL)
cd_cand = re.compile(".*(\\b\d+)(.*[{0}]\\b).*... | 581d7e26e1b896feb771455083bcf354ff450a31 | 665,579 |
def sort_by_numnodes(node):
"""
Sort by number of nodes.
"""
return len(node.nodes) | 476d20c55c109faf6a3622dd598fcc1e63617293 | 665,580 |
def _get_tag_fixture():
"""Generate a simple list of test cases for optional return_tags."""
# just picked a few valid tags to try out as valid str return_tags args:
test_str_as_arg = [
"X-y-must-have-same-index",
"capability:pred_var",
"skip-inverse-transform",
]
# we can a... | 7c4bd325e404cfbf88833f94fa846555f6caea29 | 665,582 |
def MostSimilar(caseAttrib, queryValue, weight):
"""
Most similar matches using ES default (works for all attribute types). Default similarity for strings and exact match for other types.
"""
# build query string
query = {
"match": {
caseAttrib: {
"query": queryValue,
"boost": weight,
"_name": "... | 3d6b1e199208b24f7228066ffbcda89cb26aecbd | 665,583 |
import subprocess
def prettify_c_code(cCode,style):
"""
Requires clang-format 7.0+.
Use e.g. the one coming with ROCm:
/opt/rocm-<suffix>/hcc/bin/clang-format"
"""
command = "printf \"{0}\" | clang-format -style={1}".format(cCode.replace("%","%%"),style)
return subprocess.check_output... | ec3423cfeb3f0da40953c53c3f0d8d5589871b93 | 665,584 |
def split_data(dataframe):
""" Split the dataset into features and labels
Parameters
----------
dataframe : the full dataset
Returns
-------
features : the features of the dataset
labels : the attack flag label of the dataset
"""
label = ... | 99f982def66318f3ab40de5cb868cce6548f19f8 | 665,585 |
def is_instance_or_subclass(val, class_):
"""Return True if ``val`` is either a subclass or instance of ``class_``."""
try:
return issubclass(val, class_)
except TypeError:
return isinstance(val, class_) | a8b008e9fa877647a02723d950006f6123e27ec3 | 665,586 |
import logging
import re
def get_kingdom_page_urls(
first_pagination_url,
first_pagination_page,
kingdom,
cazy_home,
family_name,
):
"""Retrieve the URLs to all pages containing proteins for the current working family.
Also retrieve the total number of proteins catagloued under the family... | 4098cf8c4be5fd2298af22678e0220ebd49d2e7f | 665,588 |
def require_atlas(f):
"""Decorator that ensures a subject (the first argument) is from the ATLAS
survey.
"""
def g(subject, *args, **kwargs):
if subject['metadata']['survey'] != 'atlas':
raise ValueError('Subject not from ATLAS survey.')
return f(subject, *args, **kwargs)
... | 1fe2e88ae190ffde179e1c2f5945604f235c9382 | 665,589 |
def add2(a, b):
"""
Test coverage with docstring
>>> add2(1, 2)
3
"""
return a + b | d3060a5d7b010497557ac3a03aab9c51e75470a5 | 665,590 |
def tarjan(nodes, edge_functor):
"""
Returns a set of "Starting" non terminals which have atleast
one production containing left recursion.
"""
def strongconnect(currNode, index, indexes, lowlink, stack):
indexes[currNode] = index
lowlink[currNode] = index
index = index + 1
... | 1c400492e5582c57ef7aa0a655af61d16d4c5e2f | 665,591 |
def check_for_executable(supernova_args, env_vars):
"""
It's possible that a user might set their custom executable via an
environment variable. If we detect one, we should add it to supernova's
arguments ONLY IF an executable wasn't set on the command line. The
command line executable must take p... | 329710c73b8fed7234e54b7ceda46070435f05ab | 665,592 |
import os
def get_path():
"""Shortcut for users whose theme is next to their conf.py."""
# Theme directory is defined as our parent directory
return os.path.abspath(os.path.dirname(os.path.dirname(__file__))) | daa446c84c4aa4f481c62060d47e14b2ed36e84e | 665,593 |
def rl_decode(buf):
"""
Uncompresses the buffer by adding the correct number of 1s identified by the digit after 0
(since 0 indicates a repeated character when the original compression is performed).
"""
decoding = []
for index, char in enumerate(buf):
if char == 0:
for repeats in range(buf[index+1]):... | 9ddf93dda96f157f9fdb0d8aa05b83305f011506 | 665,594 |
def _make_choices_from_int_list(source_list):
"""
Converts a given list of Integers to tuple choices.
Returns a dictionary containing two keys:
- max_length: the maximum char length for this source list,
- choices: the list of (value, value) tuple choices.
"""
_choices = []
for value in... | 49f49946512249d6fb879fc31aac49eb55cdfc2e | 665,595 |
from typing import Sequence
import torch
from typing import Tuple
def split_into_parts(tensors: Sequence[torch.Tensor], num_parts: int) -> Tuple[torch.Tensor, ...]:
""" combines averaged_tensors into one tensor and splits them into equal chunks of size group_size """
total_size = sum(t.numel() for t in tensor... | 7ecb244fe53e7af7987f0c002a417b97103ddd53 | 665,596 |
def readlines_without_newlines(path):
"""
Read file into a list of lines, this exists because open(path).readlines() will preserve trailing newlines
"""
with open(path) as file:
return [line.strip() for line in file] | b050d61fdcde4f6f724c7089e3b947b02f6c7771 | 665,597 |
def find_role(member, key):
"""
Find and return the role to pass the message to.
:param server: The server to find the role for.
:param key: The role to select
"""
if not member:
return None
for role in member.roles:
if role.name == key:
return role
return ... | 8c016859fef7e719c242cb8f748a85690236e466 | 665,598 |
from typing import Dict
def extract_bool(arg_name: str, arguments: Dict[str, str]) -> bool:
"""
Pull a bool from a arg dict
"""
if arg_name in arguments and arguments[arg_name]:
value = arguments[arg_name]
if value == "False":
return False
if value == "True":
... | 42bd53cd238b297d63303a8e8586815ac2fd2dab | 665,599 |
def unique_elements_non_linear(first_arr, second_arr):
"""
Returns a list with common elements in order of appearance in first list -- Complexity -- O(N*N)
"""
# List of common elements in both lists
common_elements_list = list(set(first_arr).intersection(set(second_arr)))
# Init the result array
result_arr = [... | 30e426a6c150206769611b3e1059923687c035c3 | 665,600 |
def repeatsDigits(n):
"""Return True if n has repeat digits or a 0, True otherwise"""
s = str(n)
alreadySeen = [True]
for i in range(9):
alreadySeen.append(False)
for c in s:
if(alreadySeen[int(c)]):
return True
else:
alreadySeen[int(c)] = True
ret... | 1f7764e12ee75b565f7b6acbd5f546d0cb71b736 | 665,601 |
from typing import List
import json
def _parse_str_list(string: str) -> List[str]:
"""
Parse a list of string from string like "['a', 'b', 'c']" or those separated by \n
:param string: string like "['a', 'b', 'c']" or those separated by \n
:return: a list of string
"""
try:
res = json.... | 68ee3e8508b09a5d95656eedeb13af0a582f7028 | 665,602 |
def bb_iou(boxA, boxB, format="coco"):
"""
based on https://www.pyimagesearch.com/2016/11/07/intersection-over-union-iou-for-object-detection/
"""
if format == "coco":
boxA = [float(boxA[0]),\
float(boxA[1]),\
float(boxA[0]+boxA[2]),\
float(boxA[1]... | 4b9d2cdf06ffc38ab30e64adca4bc3514df52aaf | 665,603 |
from typing import Union
import uuid
def get_cache_key_for_site(site_uuid: Union[str, uuid.UUID]):
"""
Get the cache key for a site.
"""
return 'site_config_client.backend.{site_uuid}'.format(
site_uuid=site_uuid,
) | 03e24116cbafcc215e07a1c529613451953113e9 | 665,604 |
def add_node_ids(node):
"""
Adds node IDs to the tree (the recursive Python dict)
in a breadth-first fasion.
Arguments:
node -- the root node for the tree
Returns:
the same tree (Python dict), but with a new key for
each node (the ID)
"""
nodes_to_explore = [node]
counter ... | a7273edaeca3ea97b841c90142014e7ad511ed42 | 665,605 |
def format_list(list):
"""Given a list of tuples as returned by :func:`extract_tb` or
:func:`extract_stack`, return a list of strings ready for printing. Each string
in the resulting list corresponds to the item with the same index in the
argument list. Each string ends in a newline; the stri... | ca6ef7e6f15e251a1848a5e46c0045466896256e | 665,606 |
def copy_b_factor(native_pdb,designed_pdb):
""" copy the b factors from one structure to another"""
native_atoms = native_pdb.get_atoms()
designed_atoms = designed_pdb.get_atoms()
for native_atom, designed_atom in zip(native_atoms, designed_atoms):
designed_atom.set_bfactor(native_atom.get_bfactor)
return design... | 6ee3c47c33ce9e4fb2cc63ac49aa09f4811ad295 | 665,609 |
def contains_whitespace(text):
"""
Returns True if there are any whitespace characters in the string
"""
return any(x.isspace() for x in text) | 1fdd1c1c5d4f36e62365e7729e9332fed491b12e | 665,611 |
def score(score1, score2):
"""combines the scores for the two cross-validation sets
into a single score"""
return score1*score1 + score2*score2 | ce3f3c5d44b4b46d8affa12f83aec366bbee69ce | 665,612 |
def guess_content_type(name):
"""Return the content type by the extension of the filename."""
if name.endswith(".jpg"):
return "image/jpg"
elif name.endswith(".jpeg"):
return "image/jpeg"
elif name.endswith(".png"):
return "image/png"
elif name.endswith(".gif"):
retur... | 3f6681e1df2384e3fcba58eda436cb31c3e8d18c | 665,613 |
import os
def make_dir(parent_path: str, dir_name: str) -> str:
""" Make the a directory at the given parent directory's path
:param parent_path: The parent directory
:param dir_name: The name of the directory
:return: The full path of the directory
"""
dir_path = parent_path + os.sep + dir_na... | d390b00f6763d3a85b47153ee93e8acebf559295 | 665,614 |
def boundaries(w_one, w_two):
"""Returns the boundaries of a wire
>>> boundaries(["R8", "U5", "L5", "D3"])
{'top': 5, 'bottom': 0, 'left': 0, 'right': 8}
"""
top = bottom = left = right = 0
for wire in (w_one, w_two):
vert = 0
horz = 0
for move in wire:
if m... | add4d8e35e9db7e6a5e2347f6156a7c84e5dfe8b | 665,615 |
import sys
def load_wordlist(list_name):
"""
Takes the location of a wordlist file and loads it into a lst
:param list_name: (str) The name of the wordlist file to load
:return: (lst) A list containing the files lines
"""
try:
with open(list_name) as f:
f_contents = f.readl... | ee0ad6481d97c70a7c8cbd8f72739bdd8a85ef16 | 665,616 |
def yaml_keyword(request):
"""Return multiple possible styles for the bumpsemver:yaml keyword."""
return request.param | d2269be586544b7e7ba9f0837a9a7df6d1c36bbc | 665,617 |
def phone_number_hide_formatter(value,number=3,symbol='X'):
"""
Phone hiding by replacing specified number of characters by specified symbol
:param value: Currency value to be formatted
:type value: String, float or integer
:param decimals: Number of decimal positions
:type decimals: Integer
... | c63e44db9797dc83cbd21096e6d4f0bbcda37b28 | 665,618 |
def h1(text):
"""h1 tag
>>> h1('my heading')
'<h1>my heading</h1>'
"""
return '<h1>{}</h1>'.format(text) | 19bed612f8ff77146df14cff197a846cab58ff8c | 665,619 |
import os
def _get_dir_size(directory):
"""Get directory size in bytes."""
total_size = 0
for dirpath, dirnames, filenames in os.walk(directory):
for file in filenames:
filepath = os.path.join(dirpath, file)
if not os.path.islink(filepath):
total_size += os.... | d27941080c205fcda5f73a69ee098e0f94be2603 | 665,621 |
def capture_logs(process, verbose):
"""Capture logs from ruby process."""
result = ''
for line in process.stdout:
result = result + line + '\n'
return result | 4d6c58fdefa39035b5dfd7a5044a884e685ffed5 | 665,622 |
def parseRunScriptResults(in_filename, num_knobs, design_id_start_text, results_start_text):
"""
Only works for DCT, MM, Sobel, SPMV
"""
csv_text = ""
with open(in_filename, 'rt') as in_file:
csv_text += "ID,"
csv_text += ",".join(["knob_" + str(i) for i in range(num_knobs)])
... | 6729dccd167364f6a3bb895578d47d2b09a5fddf | 665,623 |
import os
def check_path(path, create=False):
"""
Check for a path on filesystem
:param path: str - path name
:param create: bool - create if do not exist
:return: bool - path exists
"""
if not os.path.exists(path):
if create:
os.makedirs(path)
return os.pa... | 2162a3d7f03386f30a0330f0b0c3d0def135ee8c | 665,624 |
import os
def get_scaler_path(run_id):
"""
Generate path for storing/loading fitted scaler
:param run_id (str): run ID to be used
:return: full file path for storing/loading fitted scaler
"""
return os.path.join('models', run_id + '.gz') | f116e52b693ccfd690365835e19d954c121c3e85 | 665,625 |
def setcols(df, fn=lambda x: x.columns.map('_'.join), cols=None):
"""Sets the column of the data frame to the passed column list.
"""
if cols:
df.columns = cols
else:
df.columns = fn(df)
return df | 05d178d6c6c4080d3380cf075c45105eff59c80e | 665,626 |
def replace_line(data, my_array):
"""
Args: data : data to replace
my_array : replace data in this array
Return: new array with new data
"""
new_list = []
for line in my_array:
for idx, value in data.items():
line = line.replace(idx, value)
new_list.append... | fba0707ae6c83faf3f1ddbb3f23d56df688301af | 665,627 |
def find_verb(sent):
"""Pick a candidate verb for the sentence."""
verb = None
for word, part_of_speech in sent.pos_tags:
if part_of_speech.startswith('VB'): # This is a verb
verb = word
break
return verb | 1d54a2d717a06176a6f53b4f8be0c27be16a4db2 | 665,629 |
import secrets
def get_secret(size):
"""
Generate a random secert token
@param size: The size of the secret token
"""
# alphapet = string.ascii_letters + string.digits
# result = []
# for _ in range(size):
# result.append(choice(alphapet))
# return ''.join(result)
return s... | 3f19ad6584c80c870395e4b96616acd0fbf9abc7 | 665,630 |
import torch
def block_diag(m):
"""
Takes a 3-dimensional tensor of shape (B, M, N) and returns a block diagonal tensor
of shape (B x M, B x N).
:param torch.Tensor m: 3-dimensional input tensor
:returns torch.Tensor: a 2-dimensional block diagonal tensor
"""
assert m.dim() == 3, "Input t... | 65724efd478da78b30662ec70e36294d11b9014a | 665,631 |
def tolist_if_not(x):
"""Convert to a list."""
if not isinstance(x, list):
x = [x]
return x | c8bc0c2a446fe5e53d2da51e36f34d6662f1db71 | 665,632 |
def get_C_second_moment(k, pc, tc):
"""
Calculate the second moments of the sum of collision
input:
k: maximum retransmission
pc:the collision probability
tc: channel busy slot number because of collision
return: the second moments of the sum of collision(M_C1)
"""
retu... | 74a5e32b552f72f6ea7159ca688d652ab8b2c448 | 665,633 |
import argparse
def create_args():
"""Create arguments for each tool
:returns: arguments
"""
parser = argparse.ArgumentParser()
parser.add_argument('-u', '--url', type=str, required=True, help='Url to scan')
parser.add_argument('-o', '--output', action='store_true', help='Output file')
# New... | ea5670a0e02244b1f7f309b3ce0007f6e353bb21 | 665,634 |
def convert_value_to_stac_type(key: str, value):
"""
Convert return type as per STAC specification
"""
# In STAC spec, "instruments" have [String] type
if key == "eo:instrument":
return [value]
else:
return value | bbcf065dbe7a4dbfbf0fc2844e9453dcb3b25828 | 665,636 |
def cat(file: str) -> str:
""" Return contents of file """
return open(file).read().rstrip() | 3412a224d210eae4b772baf5fe5ec0d5cfe218dd | 665,637 |
def deal_with_out_boundary(img):
"""
Deal with the outlier.
:param img: input image.
:return: image without outlier.
"""
img[img > 255.] = 255.
img[img < 0.] = 0.
return img | 9dc8549183adab719b7e9b557e9b99b8f91b18b8 | 665,638 |
def few_enough_underscores(current: str, match: str) -> bool:
"""Returns whether match should be shown based on current
if current is _, True if match starts with 0 or 1 underscore
if current is __, True regardless of match
otherwise True if match does not start with any underscore
"""
if curre... | a656b1af6e37f896fec789f3a2bc7dfd3f2c4d27 | 665,639 |
import os
import pickle
def load_data(path=os.path.join(os.path.dirname(__file__),"..", "data", "data_preprocessed.pkl")):
"""
load_data(path)
Utility to load data.
Arguments:
==========
path: file path
"""
with open(path, "rb") as file:
data = pickle.load(file)
... | 1363b30f139d100906d4168c69b65cb47bad9597 | 665,640 |
def calculate_position(moving_average_1, moving_average_2, moving_average_3, moving_average_4):
"""
DOCSTRING
"""
if moving_average_4 > moving_average_1 > moving_average_2 > moving_average_3:
return 1
elif moving_average_1 > moving_average_4 > moving_average_2 > moving_average_3:
ret... | bcdd0ba3e594ed8cb8c018dbf2c807c796da41be | 665,641 |
import os
def password(request):
"""Return the password form environmental variable PASSWORD"""
return os.environ['PASSWORD'] | 10f6ab78fc692d2b7112d64cdfb78fc064ebfec6 | 665,642 |
from typing import OrderedDict
def order_columns_in_row(fields, unordered_row):
"""Ensure columns appear in the same order for every row in table
:param fields:
:param unordered_row:
"""
fields_idx = {f: pos for pos, f in enumerate(fields)}
return OrderedDict(sorted(unordered_row.items(),
... | ac05b98032fba2e153d7a7afba678012d50a79d6 | 665,643 |
def create_back_points(shift, pt1xstr, pt1zstr, pt1ystr, pt2xstr, pt2zstr, pt2ystr, pt3xstr, pt3zstr, pt3ystr, pt4xstr, pt4zstr, pt4ystr, pt5xstr, pt5zstr, pt5ystr, pt6xstr, pt6zstr, pt6ystr, pt7xstr, pt7zstr, pt7ystr, pt8xstr, pt8zstr, pt8ystr, pt9xstr, pt9zstr, pt9ystr, pt10xstr, pt10zstr, pt10ystr, pt11xstr, pt11zst... | a61e029c8bf0a5d395b6f855a4aac2eaa4a01a4a | 665,644 |
import os
def get_root_dir():
"""Returns the absolute path to the work4core root directory"""
return os.path.dirname(os.path.dirname(__file__)) | 81e579c2099068b1422340858268bea1235a1576 | 665,645 |
def init_no_need_to_follow_list(api):
"""
create list for data dictionary where users that
there's no need to follow in it.
:param api: api param from data dictionary
:return: list with no need to follow users
"""
follows = []
# no need to follow user that you've alredy followed
# o... | 28acb10b8bbf49c3433397d2944117b1a07d3c50 | 665,646 |
def f(x):
"""
in this test calculation, STYBLINSKI-TANG FUNCTION is used.
https://www.sfu.ca/~ssurjano/stybtang.html
f(x) = \frac{1}{2}\sum^d_{i=1}(x^4_i-16x_i^2+5x_i)
"""
returnf = 0.0
for i in range(len(x)):
returnf += x[i]**4 - 16.0 * x[i]**2 + 5.0 * x[i]
returnf *= 0.5
re... | 03570b09f33c339ce82a45693bcd35767d59ad27 | 665,647 |
def rdist3(x, y):
"""Optimized rdist for 3D arrays."""
return (x[0] - y[0]) ** 2 + (x[1] - y[1]) ** 2 + (x[2] - y[2]) ** 2 | 931b5d425e41c8052e4bae072d2b62f3e7142970 | 665,648 |
from typing import Dict
import json
import hashlib
def calc_body_checksum_sha256(req_spec: Dict[str, str], parsed_args: Dict[str, str]) -> str:
"""
Calculates the body checksum(256)
:param req_spec: Dict[str, str]
:param parsed_args: Dict[str, str]
:return: str Calculated SHA1 checksum
"""
... | bdef0e4c9d537bd3d6fec34deab4d915200c83cd | 665,649 |
def central_image_crop(img, crop_width, crop_heigth):
"""
Crops the input PILLOW image centered in width and starting from the bottom
in height.
Arguments:
crop_width: Width of the crop
crop_heigth: Height of the crop
Returns:
Cropped image
"""
half_the_width = img.sh... | 5899172acb531994670bc8a2774f71ff3041b277 | 665,650 |
def is_this_list(lst: list, count: int) -> bool:
"""
Returns true iff the list is not empty and the last item of the list equals the 'count'
:param lst:
:param count:
:return:
"""
return len(lst) > 0 and lst[-1] == count | 542bcc31e68728e75ad6ae301ee8a7b7a9beffa8 | 665,652 |
def open_no_nl(filepath, mode="r"):
"""Open a file for reading without translating newlines."""
return open(filepath, mode, newline="") | 5412cd2f84c552a38e6d350ff81863b9176251f4 | 665,653 |
def apply_polynomial(coeff, x):
"""Given coefficients [a0, a1, ..., an] and x, compute f(x) = a0 + a1*x + ... + ai*x**i +
... + an*x**n.
Args:
coeff (list(int)): Coefficients [a0, a1, ..., an].
x (int): Point x to on which to evaluate the polynomial.
Returns:
int: f(x) = a0 + a... | 08bc04ca19b9289b726fec0b9ad832470709270d | 665,654 |
def limit_speed(speed):
"""Limit speed in range [-900,900]."""
if speed > 900:
speed = 900
elif speed < -900:
speed = -900
return speed | 5ad91ce28264e5aa127b9c8be22697a23dc8327a | 665,655 |
def get_multi_asset_mode(self, **kwargs):
"""
|
| **Get Current Multi-Assets Mode (USER_DATA)**
| *Get user's Multi-Assets mode (Multi-Assets Mode or Single-Asset Mode) on Every symbol*
:API endpoint: ``GET /fapi/v1/multiAssetsMargin``
:API doc: https://binance-docs.github.io/apidocs/futures/en... | 90e360516e5a46fd01487a2d211a96784f5a9e26 | 665,656 |
def make(move, pos):
"""Make a move in a position. NOTE: Doesn't touch original bitarray."""
pos = pos.copy()
pos[move] = 1
# NOTE: Loop over whole pos length (not just t) to ensure pos ends in 1s
for i in range(2, len(pos) - move):
if pos[i] == 0:
continue
pos[move + i] ... | b2567fd93d2a00ee51506af75caca79f122e9b66 | 665,658 |
import argparse
def parse_input_args():
"""
Parse command line argument
'config_file' is the first argument; it should be one of the YAML
files in this same directory
'k8s_release' is the second argument; provide the release version
:return: parsed argument
"""
parser = argparse.Argume... | 81fcfc8bda1015e504afccb94f19ad4a9aef6ec6 | 665,659 |
def decomposition(x):
"""
Return the decomposition of ``x``.
EXAMPLES::
sage: M = matrix([[2, 3], [3, 4]])
sage: M.decomposition()
[
(Ambient free module of rank 2 over the principal ideal domain Integer Ring, True)
]
sage: G.<a,b> = DirichletGroup(20)
... | 9ce34f0e57c2729a8ffe631230c1da71d9676cd1 | 665,660 |
def _sum_ft(tensor):
"""sum over the first and last dimention"""
return tensor.sum(dim=0).sum(dim=-1) | 5102e22efa399bfdf9e090f0a8e825fc65290fef | 665,661 |
import torch
def _get_anchor_negative_triplet_mask(labels):
"""Return a 2D mask where mask[a, n] is True iff a and n have distinct labels.
Args:
labels: torch.Tensor with shape [batch_size]
Returns:
mask: Variable with torch.ByteTensor with shape [batch_size, batch_size]
"""
# Chec... | a00bd917946886f7d8586bf6fe92f31b0c8b1891 | 665,662 |
def read_file(fname):
"""Read input file format."""
with open(fname,"r") as f:
data = f.read().split("\n")[1:-1]
return data | 74d3c0b379c5ee9b3c46144315f17024d9f3f94e | 665,663 |
import torch
def X3D(N: int, D: int) -> torch.Tensor:
"""3D input
"""
torch.manual_seed(42)
return torch.randn(N, D, D) | cfde6057eef1a9cc3e7fdd1a00eaaf661f14c390 | 665,664 |
def bool_as_int(val: object) -> str:
"""Convert a True/False value into '1' or '0'.
Valve uses these strings for True/False in editoritems and other
config files.
"""
if val:
return '1'
else:
return '0' | d931e992fbb0d4baa5dbd2d7d2643d82a74590bf | 665,665 |
import re
def pack_article(article_raw):
"""
article preprocessing, splitting paragraphs
:param article_raw: article as string
:return: list of paragraphs
"""
article = list()
article_split = re.split(r'(?<=>)(.+?)(?=<)', article_raw)
## parse articles (no tags)
for p in range(1,... | 89f811ce43ace325bb38c98b8121ab3584d0a398 | 665,666 |
import os
import argparse
def parse_args(argv):
"""
Parse and document arguments
"""
default_start_at = 0
default_max_results = 50
basename = os.path.basename(argv[0])
parser = argparse.ArgumentParser(description=f'{basename} - helper script for JIRA')
group_login = parser.add_argume... | fec179a160ae452bd5a7f6e1e9d9a5c70b532e73 | 665,667 |
def read_file(fname):
"""Read file and return the its content."""
with open(fname, "r") as f:
return f.read() | e802fbb4574b2d25c4b7d48f60e8a248c5f1f050 | 665,669 |
import unittest
import sys
def skip_from_python(*ver):
"""Skip a test on Python after (including) a certain version."""
def skip_from_python_(cls):
decorator = unittest.skipIf(
sys.version_info[:len(ver)] >= ver,
"skipped because Python %s"
% ".".join(map(str, sys.v... | f219d4b892547c5cbff110aa0c3fb7446f453a21 | 665,670 |
def clomia_network_info() -> tuple:
""" clomia Network 공식 서버 정보를 반환 한다 """
__server_ip = "112.158.160.11"
__server_input_port = 47500
__server_response_port = 47501
__secret_code = "9LK2DX"
return (__server_ip, __server_input_port, __server_response_port, __secret_code) | b11d0c21b6d5d5d9fe014d7c396c554140178702 | 665,671 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.