content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def buyholdsell(n):
"""
Param n is a number.
Function will decide if the number is worth buying, holding, or selling.
"""
if (n) in range(1, 30):
return "I'm buying"
elif (n) in range(30, 71):
return "I'm holding"
elif (n) in range(70, 101):
return "I'm selling"
... | c8f545fe2c0b8d13ddf5000070c62e2da8ffabb4 | 645,619 |
from typing import List
def opt_filter_string(filter_string: str, id_list: List[int]):
""" Generate string for option-based filter.
Generates a filter for filtering for specific rows based on the unique
element ID that will be added to the main SQL query.
Args:
filter_string: Start of the fi... | 6ef5680d95bc2ac3e894002e599b11ba2c634366 | 645,620 |
def miroir2(s : str) -> str:
""" ... cf. ci-dessus ...
"""
# Chaîne inversée
r : str = ''
i : int # Position du caractère courant
for i in range(1,len(s)+1):
r = r + s[-i]
return s + r | 9ee2e0c6f3a1e8816e55d2e343e26a70d944d0b0 | 645,621 |
def get_group(self, group_number):
"""Define an Element object as submesh of parent mesh object
Parameters
----------
self : ElementMat
an ElementMat object
group_number : int
a group number which define the elements which constitute the submesh
Returns
-------
... | e9c327b6416e4900cc4182363beee2844ff2106d | 645,622 |
from typing import Callable
import sys
def export(func: Callable):
"""Decorate function or class to export to __all__."""
mod = sys.modules[func.__module__]
if hasattr(mod, "__all__"):
all_list = getattr(mod, "__all__")
all_list.append(func.__name__)
else:
all_list = [func.__na... | 580854783c723ec54bf866d3c12d40baebf81205 | 645,623 |
import torch
def clip_by_value(x, tensor_min, tensor_max):
"""
Tensor extenstion to torch.clamp
https://github.com/pytorch/pytorch/issues/2793#issuecomment-428784713
"""
clipped = torch.max(torch.min(x, tensor_max), tensor_min)
return clipped | 4bb945fe9ec0e49ba8db7aa65e1f6b16ff690b8a | 645,624 |
def index():
"""Serve the client-side application."""
return "App running and working hard to emit events." | e954d3cad0d01a705c4fa83bf3381ad22d8bcbc8 | 645,625 |
def load_dico_as_dict(dico_path):
"""
Load a dico as a dict
:param: dico_path: path of the dict
:return: a dict
"""
id = 0
dico = dict()
with open(dico_path, 'r') as fd:
for word in fd:
dico[id] = word.strip()
id += 1
return dico | 7f4f4c4ea0d5cd78a98531454b2d79f892a1084c | 645,626 |
def seconds_converter(duration):
"""
This is a function that process a strig and convert it to a more workable format
It is used to extract the duration from yt requests in a more approachable way
@:param duration:
A string in a yt format that represent the duration of a video
@:return:
... | cce264045d6aca9c32ea39931b0aa43f603f98f6 | 645,627 |
def build_os_environment_string(env):
""" Creates a string of the form export key0=value0;export key1=value1;... for use in
running commands with the specified environment
:Parameter variables: a dictionay of environmental variables
:Returns string: a string that can be prepended to a command to run the comman... | c622b532b4a497c4af854e88236584abc9802e12 | 645,628 |
def remove_prefixes_of_others(values):
"""
Removes strings that are prefixes of other strings and returns the result.
"""
to_remove = set()
for value in values:
for other_value in values:
if other_value != value and other_value.startswith(value):
to_remove.add(va... | cd4c943ed46b564639041b22e69e5c3fd4d0aa8b | 645,629 |
def diff_mic(pos1, pos2, cell):
"""Minimum image convention relative vector (orthorhombic cell only)"""
diff = pos2 - pos1
for i in range(3):
diff[i] -= round(diff[i]/cell[i])*cell[i]
return diff | ea63817262321024bff29439354efeaaf8c58bb4 | 645,630 |
def int2name(i):
""" Convert integer to Excel column name. """
div = i + 1
name = ""
while div > 0:
mod = (div - 1) % 26
name = chr(65 + mod) + name
div = (div - mod) // 26
return name | 1a7a0a1f3f580a034a170029ee8e66fc30a33ab8 | 645,631 |
def get_word_freq_per_utt_from_rttm(rttm_f):
""" Get word frequency per utterance from RTTM file """
# nested dict {key_word_1: {utt_id_1: count, utt_id_2: count, ...},
# key_word_2: {utt_id_1: count, utt_id_2: count, ...},
# ...
# }
w_rttm_freq = {}
wi... | a4b49ea35899afa16e5c15e953a436dd4e613174 | 645,632 |
import json
def get_all_tunables():
"""
Query Autotune API for the application_name, direction, hpo_algo_impl, id, objective_function, tunables and
value_type, and return them.
Returns:
application_name (str): The name of the application that is being optimized.
direction (str): Direc... | acc7ca6cb7ddeeccf1cec2eb4ac4954efde55d5a | 645,633 |
def search_parse(search_results):
""" Return a simplified version of the json object returned from the USDA API.
This deletes extraneous pieces of information that are not important for providing
context on the search results.
"""
if 'errors' in search_results.keys():
return None
# Store... | cd481c26d3ca279ab0a4878a99d4387ada4c3277 | 645,634 |
import re
def option_engine(request):
"""
Движок. pdflatex|xelatex|lualatex
"""
file_engine = request.config.getoption("--engine")
if file_engine is None:
filename = request.config.getoption("--pdf")
for name in [r"pdflatex", r"xelatex", r"lualatex"]:
if re.search(name,... | c7cce142b48bac5557b90fb2910f42e7b061ea07 | 645,635 |
import os
def get_base_dirs(pkudir):
"""
-----------------------------------------------------
this function returns our base directories
-----------------------------------------------------
"""
directory_to_use = pkudir
source_dir = os.path.join(directory_to_use, 'source') #source directory to be u... | c87e26122db26d97292d46939417b00b501de514 | 645,636 |
def capital_case(v):
"""
permet de passer la première lettre en majuscule
"""
return v.capitalize() | 1433d41864cf042f4f0c5189440fbe5dc2eca443 | 645,637 |
def _state_diff(state, previous_state):
"""A dict to show the new, changed and removed attributes between two states
Parameters
----------
state : dict
previous_state : dict
Returns
-------
dict
with keys 'new', 'changed' and 'removed' for each of those with content
"""
... | d9bb207beab1362ffc1d096e0cb4b7c0c54e124a | 645,638 |
from typing import Dict
from typing import Optional
def compose_custom_response(
resp: Dict,
success_message: str = "Operation successful.",
fail_message: str = "Operation failed.",
) -> Dict:
"""Enhances a dictionarised Misty2pyResponse with `success_message` in case of success and with `fail_message... | 9dfd6fb1be5f4a8d1306ce13d059b3987e9bd551 | 645,639 |
import math
def pixels_per_degree(display_diagonal_mm, height_pix, width_pix, viewing_distance_m):
"""
computer pixels per degree given display parameters and viewing distance
This is a convenience function that can be used to provide angular
resolution of input images for the HDR-VDP-2.
Note th... | c448df9bc921ac88ef1fabe6cb0978a54821cf41 | 645,640 |
def get_defects(defects, n):
"""
Provides the exact type of defect by using target class predicted and defect dictinary provided.
Arguments:
defects : This is the defect dictionary contianing all possible types of defects
target_class : This is the target class predicted using the 'get_predictions'... | 75f4707dd64c86307fb844193a561b0b63555e8e | 645,641 |
def tee(f, *args, **kwargs):
"""When used in pipe, calls function but does not use the return value.
For example, for logging or printing.
Pipe argument is passed first, before args and kwargs, similar to pipe.call.
Resulting value is not used, pipe argument is passed along further instead.
Note:... | 2950f6d8e9bb990de1a25c157726a8e5f8828d58 | 645,642 |
def extract_request_body(requests_text: str):
"""
Parse change requests, a text of RPSL objects along with metadata like
passwords or deletion requests.
Returns a dict suitable as a JSON HTTP POST payload.
"""
passwords = []
overrides = []
rpsl_texts = []
delete_reason = ""
requ... | a14d9b016294c7b2b777f872a6b45394f58e76c4 | 645,643 |
def from_ms(time: int) -> str:
"""
Convert millisconds into a string in format mm:ss.ms
"""
minute = time // 60_000
second = time // 1000 - minute * 60
millisecond = time - minute * 60_000 - second * 1000
if second < 10:
second = "0" + str(second)
else:
second = str(se... | 83e5ac96a1aa2502636f6e375339b9bdd06b08a8 | 645,644 |
def output_file(out):
"""Convert file path to writeable file object."""
try:
return open(out, 'w')
except IOError as exc:
print('Error opening output file at path: {}.\n\n{}'.format(out, exc))
exit(1) | 854db5dc754e88aee2d76d9e06d636f00058a33b | 645,645 |
from typing import Optional
from typing import List
def get_class_selector(config_name: str) -> Optional[List[str]]:
"""Determines the class selector, based on the config name. This enables support for configs,
which train a model only on a subset of classes.
:param config_name: Name of the config used f... | 883d629f76cdbf8a9fd7e2433c7541dc136d9844 | 645,646 |
def import_m(module):
"""Will simply import a module into a var
Usage : pygame = import_m("pygame")"""
return __import__(module) | 78c417ba3a3bff2a45a1c09d52743a46e952c74c | 645,647 |
def file_typer(mediapath):
""" Take the source mediapath and return type as: text, audio, video, image
Required function as this is a historical quirk of development
param:
mediapath: String containing the mediapath
"""
if mediapath is None:
return "text"
if len(mediapath) < 3:
... | bafb87b34e653d13942ae9933a927926ef8020c2 | 645,648 |
def format_time(time):
"""Format the time for the player info"""
formatted_time = ''
if time['hours'] > 0:
formatted_time += str(time['hours']) + ':'
if time['minutes'] == 0:
formatted_time += '00:'
formatted_time += '%0*d' % (2, time['minutes']) + ':'
formatted_time +... | cca97f70ba48b917b77b902b43681234e5188483 | 645,649 |
def update_dict_from_params_using_path(keys_to_update: dict, params: dict, data: dict) -> dict:
"""Update a dictionary using a path given in a list [nest1, nest2] and update it.
For example: some_dict[nest1][nest2] = some_value
Args:
keys_to_update (dict): The keys names with the path to update... | 6c59dab1765190298d48a822e024c267c3070ed3 | 645,650 |
def checksum16(payload):
"""
Calculates checksum of packet.
:param payload: Bytearray, data to which the checksum is going
to be applied.
:return: Int, checksum result given as a number.
"""
chk_32b = 0 # accumulates short integers to calculate checksum
j = 1 # iterates through p... | 5a3e68cbb2310cdb872c22eba1424bef99a4136e | 645,651 |
import torch
def R_transform_th(R_src, R_delta, rot_coord="CAMERA"):
"""transform R_src use R_delta.
:param R_src: matrix
:param R_delta:
:param rot_coord:
:return:
"""
if rot_coord.lower() == "model":
R_output = torch.matmul(R_src, R_delta)
elif rot_coord.lower() == "camera" o... | 3154a4bdf2920c3957a0d92657a9f0394370eddd | 645,652 |
def cir_RsC_fit(params, w):
"""
Fit Function: -Rs-C-
"""
Rs = params["Rs"]
C = params["C"]
return Rs + 1 / (C * (w * 1j)) | da444240d9b2956e8814c626f32e020feb7c380b | 645,653 |
def read_from_8bit_eeprom(bus, address, count, bs=16):
"""
Reads from an 8-bit EEPROM. Only supports starting from 0x00, for now.
(to add other start addresses, you'll want to improve the address counting mechanism)
Default read block size is 16 bytes per read.
"""
data = [] # We'll add our read... | 782dbc4f17144881fcd66e5f5fb51126070dc634 | 645,654 |
def mk_list(n):
""" int -> list[int] """
return [k for k in range(1, n+1)] | e3af3d221bad970698588b5ef0b417556fde0110 | 645,655 |
import pathlib
import lzma
import tempfile
def extract_lzma(path):
"""Extract an lzma file and return the temporary file name"""
tlfile = pathlib.Path(path)
# open lzma file
with tlfile.open("rb") as td:
data = lzma.decompress(td.read())
# write temporary tar file
fd, tmpname = tempfil... | 9444eca8456e113a70841427444e3fd305a88862 | 645,656 |
def is_iterable(x):
"""Checks if an object x is iterable.
It checks only for the presence of __iter__, which must exist for
container objects.
Note: we do not consider non-containers such as string and unicode as
`iterable'; this behavior is intended.
"""
return hasattr(x, "__iter__") | a848ebe577a0ead3eb55262bff7b63e2720e0473 | 645,658 |
def check_ipv6_rule_exists(rules, address, port):
""" Check if the rule currently exists """
for rule in rules:
for ip_range in rule['Ipv6Ranges']:
if ip_range['CidrIpv6'] == address and rule['FromPort'] == port:
return True
return False | c81e7d77b7b66bb6209918348a62ac2ec1cd9fd9 | 645,659 |
import os
def absolute_file_path(cwd, filename):
"""
Join a filename in the same directory as this function with the current working directory for the absolute path.
"""
return os.path.join(cwd, filename) | 01bc503cd4b841b687be22cf4dd719d75a6b958b | 645,660 |
import requests
def ngrok_url():
"""
If ngrok is running, it exposes an API on port 4040. We can use that
to figure out what URL it has assigned, and suggest that to the user.
https://ngrok.com/docs#list-tunnels
"""
try:
ngrok_resp = requests.get("http://localhost:4040/api/tunnels")
... | 34a34bdb73000805670979c85f57be7b11d9ba64 | 645,661 |
from typing import Dict
from typing import Any
def slider_handle_label(is_numerical: bool, is_ten_pow: bool = False) -> Dict[str, Any]:
"""Get the slider handle label dict."""
if is_numerical:
label = "BINS"
if is_ten_pow:
label = "SMART BINS"
else:
label = "CATEGORIES"... | e841509cf5c4077b6977aedc8abbcdbb2338985f | 645,662 |
def read_from(filename):
"""
function to read from file; lines are lists
"""
fl = open(filename, "r")
raw = fl.readlines()
fl.close()
return raw | ee32caaa04a2e060ebdd4fce9fad8bad1f6776a8 | 645,663 |
def get_integer(prompt):
"""
Get an integer from Standard Input (stdin).
The function will continue looping, and prompting
the user, until a valid `int` is entered.
:param prompt: The String that the user will see, when
they're prompted to enter the value
:return: The integer that the... | 42f246e54a1fa6ef48c28d796d84010c0d5fd9e3 | 645,664 |
def is_tuple(obj):
"""Helper method to see if the object is a Python tuple.
>>> is_tuple((1,))
True
"""
return type(obj) is tuple | 79dc59e5166e88d9dda627b6bf36682cbd75b169 | 645,665 |
import select
def _can_allocate(struct):
""" Checks that select structs can be allocated by the underlying
operating system, not just advertised by the select module. We don't
check select() because we'll be hopeful that most platforms that
don't have it available will not advertise it. (ie: GAE) """
... | 61c8ca2c1305f13339beefcc326ba4ac171dd9ed | 645,666 |
def escape_register(register):
"""Escape register names suitable rust module and variable names."""
return register.replace("[", "").replace("]", "") | 81d6fb55a69e6054ed71483f0935453180b88d31 | 645,667 |
import math
def pts2bins(pts, prec=0.25):
"""
:param pts: List of 2d points
:param prec: Width of each bin
:return: A dictionary of bin centers and points in the bin
"""
# for pt in pts:
# def val2bin_int(val):
# return math.ceil(val / prec) if val > 0 else math.floor(pt[1]... | 731e894d85b9546cc8b1f8b622ade7402bf33b7a | 645,668 |
def serial_listen_ports(migrate_data):
"""Returns ports serial from a LibvirtLiveMigrateData"""
ports = []
if migrate_data.obj_attr_is_set('serial_listen_ports'):
ports = migrate_data.serial_listen_ports
return ports | 2d28f32f8afbd4082d811de909a361f93bc1e379 | 645,669 |
from typing import List
def splitStrToList(
string: str,
separator: str = ',',
ignores: str = '\\'
) -> List[str]:
"""Split the given string into a list, using a separator
@type string: str
@param string: The string to be splited
@type separator: str
@param separator: A separator to s... | d9fc4ca5d2a680a4fde32897250a80883ff47a90 | 645,670 |
import re
import sys
def filename_data(fname, ext=None, skip=2, delimiter='_', exclude='imf'):
"""
return a dictionary of key and values from a filename.
E.g, ssp_imf4.85_bf0.3_dav0.0.fdat
returns bf: 0.3, dav: 0.0
NB: imf is excluded because it's already included in the file.
Parameters
... | e554f20d8fbd00bc47f403a8e26351ee50c032f0 | 645,671 |
def generate_config(context):
"""Creates private PyPi."""
resources = [
{
'name': 'pypi-run',
'type': 'run-template.py',
'properties': {
'region': context.properties['region'],
},
},
{
'name': 'pypi-secret',
... | 46f3dcb972f3a062c034ece8f719e42e03f3fb06 | 645,672 |
import binascii
import hashlib
def convert_str2digest(data):
"""Convert byte string to digest
Args:
data (str):
"""
string = binascii.b2a_hex(bytes(data.encode()))
str_digest = hashlib.sha1(string).digest()
return binascii.b2a_hex(str_digest).decode() | e5dfd26e37cf36109781f793ed32191292fbe4fa | 645,673 |
import base64
import struct
def _decode_linear_biases(linear_string, nodelist):
"""Inverse of _serialize_linear_biases.
Args:
linear_string (str): base 64 encoded string of little endian
8 byte floats, one for each of the nodes in nodelist.
nodelist (list): list of the form [node1... | 823c4759d90d28fb0c2b3cdaf2a6f0d1de96d4f5 | 645,675 |
def validate_list_of_numbers_from_csv(data):
"""
Converts a comma separated string of numeric values to a list of sorted unique integers.
The values that do not match are skipped.
:param (str, iterable) data: - str | iterable
:return: - list(int)
"""
if isinstance(data, str):
... | e1c49eae266d074bda44a2699c1ccddd578a77ae | 645,676 |
import os
from os import path
def get_bids_subjs_list(bids_path):
"""Given a BIDS compliant dataset, return the list of all the subjects available."""
return [d for d in os.listdir(bids_path) if os.path.isdir(path.join(bids_path, d))] | 8260cfbab313b54cbb353d608e12808ef7f1179b | 645,677 |
def find_new(initials, finals):
"""Finds if new cores/crashes in any of the nodes in test setup.
"""
new = {}
for node, final in finals.items():
if node in initials.keys():
initial = initials[node]
diff = list(set(final).difference(set(initial)))
if not diff:
... | 99921c69e2787117f3a22b27e9570dc2ee28c2fb | 645,678 |
def get_degree(rg, v):
"""Find the degree of a vertex"""
query = f"MATCH (m1:Member {{name:{v}}})-[:Friend]->(m2:Member) WITH m1, count(m2) as degree RETURN m1, degree"
result = rg.query(query).result_set
if len(result) > 0:
_, degree = result[0]
return degree
query = f"MATCH (m1:Me... | 7e9aa50f7a1fcb3a946625204716ba02f64128bd | 645,679 |
def sizeof_fmt(num, suffix='B'):
"""Returns human-readable file size
Supports:
* all currently known binary prefixes
* negative and positive numbers
* numbers larger than 1000 Yobibytes
* arbitrary units (maybe you like to count in Gibibits!)
Example:
--------
>>> sizeof_fmt(16... | ba1b6cc8b7121a87ccee00bc333d77e4b251dd61 | 645,680 |
import os
def get_config_basepath(add_extension=""):
"""Return the path to the current script without extension"""
return os.path.splitext(os.path.realpath(__file__))[0] + add_extension | 1e002efaad695592f43a91ec0e832229d4da4c30 | 645,681 |
def cvtBitLstToInt(bLst, base=10):
"""
bLst: int-list or str-list: [bm, bm-1, ..., b0] representing number
(bm bm-1 ... b0)base
NOTE: May use np.array to handle int/str differences
See:
https://docs.scipy.org/doc/numpy/reference/generated/numpy.fromstring.html
"""
result = 0
for ... | d7708599c320d1960bdaebb00fe21c704d9ae039 | 645,682 |
def compute_reduced_cost(column, duals):
"""Compute and return the reduced cost of 'column'."""
return (column.objective_coefficient -
sum(duals[index] * coef
for index, coef in zip(column.row_indices,
column.row_coefficients))) | 14b02864f9a9ca10584b3436f1e33e14ffd90fc9 | 645,684 |
import re
def split_expression(expression):
"""
Split the given expression into atomic statements.
:param expression:
:return: statements
"""
if "-" in expression:
statements = re.compile(r'[-]').split(expression)
elif "+" in expression:
statements = re.compile(r'[+]').spl... | ae2b6248e9ce2d96ca9409cfc0922e999e377ca1 | 645,685 |
import os
def build_local_host_path(local_data_directory):
""" Build the path to the local host data file.
:param local_data_directory: The base local data path.
:type local_data_directory: str
:return: The path to the local host data file.
:rtype: str
"""
return os.path.join(local_dat... | 70b95f07cfd692b166c36bf5994b797e4fa5a091 | 645,686 |
def extract_array(line):
"""
Return the array on the RHS of the line
>>> extract_array("toto = ['one', 'two']\n")
['one', 'two']
>>> extract_array('toto = ["one", 0.2]\n')
['one', 0.2]
"""
# Recover RHS of the equal sign, and remove surrounding spaces
rhs = line.split('=')[-1].stri... | 9156cab7e4a12df858da9189b90fab355f5a97ed | 645,687 |
def get_Z(model):
"""
Parameters
----------
model : trained neural network model
Returns
-------
pi: activation level of each layer
z: latent neural network architecture sampled from Beta-Bernoulli processes
threshold: number of layers learnt
"""
Z, threshold, pi = model.ar... | a8402fc9eab37cc143920ff868b64d20f139d70c | 645,688 |
import os
def datapath(filename):
"""Return path to a file in the data directory."""
p = os.path.dirname(__file__)
gp = os.path.dirname(p)
return os.path.join(gp, 'data', filename) | c4b8cb155ca4089778f23dc44811a4b645f0e891 | 645,689 |
def check_hold_time_in_range(hold_time):
"""RFC 4271 compliant."""
if hold_time is None or hold_time == 0 or 2 < hold_time < 65536:
return True, ''
return (False, 'BGPaaS: Hold Time MUST be either zero '
'or at least three seconds') | 2824d2c367ad9bdc508e7a9f8fc36db310764da4 | 645,690 |
def get_bs_dims(bands_array):
"""
Get the dimensions from the bands array of a BandsData node.
:param numpy.array bands_array:
an array with bands as stored in an array.bands data node
:return: a tuple containing num_bands, num_kp, num_spins.
if the array is only 2d, num_spins = 0
:... | c7e92d6f90d45d5cfdf7ef50285c88fc57d55ca6 | 645,691 |
from typing import Optional
def comment(c: str, inner: str, units: Optional[str] = None):
"""Add 'Begin c' and 'End c' comments around an inner block.
Optionally add another 'units' comment before the inner block.
"""
units_str = "" if units is None else f"# {units}\n"
return units_str + f"# Beg... | 385f4566f9aa6f20fc3fa8b4d77fd7f8a0a9a580 | 645,692 |
def get_ods_by_race_wide(xml):
"""
ワイド のページを読み込み、オッズを得る
"""
ods_wide = []
tag_tables = xml.find_all('table',
attrs={'class': 'ozWideUmaINTable'})
for tag_table in tag_tables:
tag_th_uma1 = tag_table.find('th', attrs={'class': 'title'})
# 最初の馬番
uma1 = int(tag_th_u... | 3810570a455efa31152743f15fd7d9f6df98e7bf | 645,693 |
import string
def prompt_labels():
"""Prompt user for class labels and map them to keys for gathering training data
:return: tuple of labels and key press their mapped to
"""
n_class = int(input(f'Number of classes to input: '))
if n_class > 26:
raise ValueError('Only supports up to 26 c... | e2c30f0e033151aa5858b3210106a58f034f7252 | 645,694 |
def parse_position(string):
"""
>>> parse_position('3,000,000')
3000000
>>> parse_position('3M')
3000000
>>> parse_position('3kk')
3000000
"""
units = ''
for index, char in enumerate(string):
if char.lower() in ['k', 'm']:
units = string[index:]
st... | 893aef37ab347bcab81f1ced2019ce29f5d29bd4 | 645,695 |
import pandas
import os
def load_results(directory_name):
"""
Input : path to the results files (generated with merge-files.sh)
Output : pandas table with all the results
Side-effect : none
DataFrame format :
query & baseline, nof dataflows, window id, window latency, avg latency
"""
... | dc349aa5503af4040d333a59241c254b8fc62a35 | 645,696 |
import argparse
def getArguments():
"""Use argparse to get the command-line arguments"""
parser = argparse.ArgumentParser(description='A simple raytracer')
parser.add_argument('infile', help='The input file path. The input file describes the scene to be raytraced.')
parser.add_argument('-o', help='The output ... | b3dc701b75a97f8c8380c6b113d5961d91590bba | 645,697 |
import re
def validate_replication_tags(replication_tags):
"""
Returns validated replication tags or raises an error.
- 'replication_tags' should be a list of 'tag's.
- a 'tag' should be dictionary with Keys 'Key' and 'Value'
- the 'Key' Values should be a string with length between 0 and 127
... | 5a665fe2c9eaa4ab8fbfd1dda64b2d0ead65b953 | 645,698 |
from typing import Dict
from typing import Any
def abi_input_signature(input_abi: Dict[str, Any]) -> str:
"""
Stringifies a function ABI input object according to the ABI specification:
https://docs.soliditylang.org/en/v0.5.3/abi-spec.html
"""
input_type = input_abi["type"]
if input_type.start... | e2ed8b9587066b1edcbd3563c8c45ceb64dc1442 | 645,699 |
from typing import Union
import argparse
def int_or_none(string: str) -> Union[int, str]:
"""
Only allows a positive integer or a string containing "none".
:param string: The parameter to be checked
:return: The positive integer (incl. 0) or the string "none"
"""
if string == "none":
... | 9f02bbe48a8c650974687a7c39e604dc0483a818 | 645,700 |
def hsl2rgb(hsl):
"""Convert an HSL color value into RGB.
>>> hsl2rgb((0, 1, 0.5))
(255, 0, 0)
"""
try:
h, s, l = hsl
except TypeError:
raise ValueError(hsl)
try:
h /= 360
q = l * (1 + s) if l < 0.5 else l + s - l * s
p = 2 * l - q
except TypeErro... | aa61b37cfbc017c60ca990cb9399a654bc105121 | 645,701 |
import importlib
def get_class_from_qualname(name):
"""
Resolve a fully qualified class name to a class, attempting any imports
that need to be done along the way.
:raises: ImportError or AttributeError if we can't figure out how to import it
"""
tokens = name.split(".")
module_name = ".".... | 5ee7ff2113ce9bcd6951b7f6a6906879b42444c2 | 645,702 |
def getstub_connaddr(pack):
"""
get stub from connaddr
"""
return (pack >> 32) & 0xffff | 3a0f63d6d030c09e4135eae5c4b93b938289accf | 645,703 |
def format_template_dictionary(headers, values):
"""
:param headers, list, first line of legend spreadsheet
:param values: list, content of legend spreadsheet for sheet template
:return: list, template formatted content
"""
template = dict(zip(headers, values))
del template['level']
for... | a0e6e940341422e5467012f491d9c0fac9bb62db | 645,704 |
import boto
from typing import Optional
def get_aws_zone_from_boto() -> Optional[str]:
"""
Get the AWS zone from the Boto config file, if it is configured and the
boto module is available.
"""
try:
zone = boto.config.get('Boto', 'ec2_region_name')
if zone is not None:
z... | eebbe2bb15f9c95def8e1e68f95c08c5a7a29137 | 645,705 |
def to_text_string(obj, encoding=None):
"""Convert `obj` to (unicode) text string"""
if encoding is None:
return str(obj)
elif isinstance(obj, str):
# In case this function is not used properly, this could happen
return obj
else:
return str(obj, encoding) | 353d742832ca9f6cc9e3c5ad06020083e75a58fb | 645,706 |
def decorator_trace_env_name():
"""Environment variable name where decorator traces are stored."""
return "DECORATOR_TRACE" | b81b1e3b1dade805a4c5c04502668c4c20ad8ef8 | 645,707 |
def restrict_to_setting(df, setting, run='eval'):
"""Restrict an experiment dataframe to one hyperparameter setting."""
setting_df = df[df['run'] == run]
for k, v in setting.items():
if k in df.columns.values:
setting_df = setting_df[setting_df[k] == v]
return setting_df | 820f0eae187d872e231c5e688575ef05d500b607 | 645,708 |
def normpath(path):
"""Normalize path, eliminating double slashes, etc."""
# Preserve unicode (if path is unicode)
#slash, dot = (u'/', u'.') if isinstance(path, _unicode) else ('/', '.')
slash, dot = ('/', '.')
if path == '':
return dot
initial_slashes = path.startswith('/')
# POSIX... | 0c04d36d21f727c7c2f0ecf608d5e02092c07376 | 645,710 |
import inspect
def get_attributes(cls):
"""Get available RPCs via attrs"""
boring = dir(type('dummy', (object,), {}))
return [item for item in inspect.getmembers(cls) if item[0] not in boring] | db9ce97bae95298dcc481a4d5fbe1fba609f09a4 | 645,711 |
import argparse
def _parser():
"""Take care of all the argparse stuff.
:returns: the args
"""
parser = argparse.ArgumentParser(description='Telluric Removal')
parser.add_argument('fname', help='Input fits file')
# parser.add_argument('-x', '--export', default=False,
# h... | 6231cb9d5286414a406b6c61a6d293bc77cb8c52 | 645,713 |
import functools
def synchronized(lock):
"""
Synchronizes a function call access on the given lock object. `lock` must have an `acquire()` and a `release()`
method. Function call cannot proceed until the lock is acquired. Deadlocks are possible be careful
Args:
lock: the lock upon which to syn... | 14ded2891347a72bbbc51e2fcf74410ddf616dc4 | 645,714 |
def insertion_sort(array):
"""This solution uses one `for` and one `while`."""
for i in range(1, len(array)):
key = i
j = i - 1
while j >= 0 and key < array[j]:
array[j + 1] = array[j]
j -= 1
array[j + 1] = key
return array | 7dea6dac4a3450960ef27849a1d5417e1e51e3cb | 645,716 |
def nlhist(self, key="", name="", item="", comp="", node="", elem="",
shell="", layer="", stop_value="", stop_cond="", **kwargs):
"""Specify result items to track during solution.
APDL Command: NLHIST
Parameters
----------
key
Specifies the command operation:
NSOL - Nod... | 08a9b378f99e2236de826e5d312a2dbbe700b19e | 645,718 |
def simple_value(row):
"""
:param row: {'count(*)': 3}
:return: 3
"""
if not row:
return None
if len(row.keys()) == 1:
# print(row.keys())
key = list(row.keys())[0]
return row[key]
return row | e3ddd4210f7d1c2f82418672dd3b687f21be62fe | 645,719 |
import struct
def gatt_dec_svc_attr(data):
"""Decodes Service Attribute data from Discovery Response data.
BTP Single Service Attribute
0 16 32 40
+--------------+------------+-------------+------+
| Start Handle | End Handle | UUID Length | UUID |
+----------... | 868e46ae7cc4e8fdd492919d1930b46ff86eeb26 | 645,720 |
import logging
def get_log_level(name="cleverhans"):
"""
Gets the current threshold for the cleverhans logger
:param name: the name used for the cleverhans logger
"""
return logging.getLogger(name).getEffectiveLevel() | 8d95cf9b3b2d6a8663e3aab8efada09b548569c2 | 645,721 |
import torch
def abs_density_error(decoded_pc, original_pc, side_cells):
"""
arguments:
decoded_pc: the array, size: (num_point, num_feature)
original_pc: the samples, size: (num_point, num_feature)
returns:
sum( 1/(1+sqrt(n_points_ith_cell(original_pc))*abs(n_points_ith_cell(decod... | c97fd123e1f2ea23658508a681f1e0b342af55c0 | 645,722 |
def calc_labor_restriction(x_0,l_0,l_t):
"""
A function to compute sector output with the available labor force.
Parameters
----------
x_0 : np.array
sector output under business-as-usual (in M€/d)
l_0 : np.array
number of employees per sector under business-as-usual
l_t : n... | 9d28b9125d254dfb6f66dd857388c9924b7a04d4 | 645,724 |
def embed_forward(inputs, W):
"""Inputs: inputs (N,T), with values in [0,V), W (V, D). Outputs: x (N, T, D), cache.
May work with N=1 as well"""
x = W[inputs]
return x, (inputs, W) | 40e4c15de3a1b3462649475eba2206fd17500fc2 | 645,725 |
def hash_object(x):
"""Given a variable or object x, returns an object suitable for
hashing. Equivalent variables should return equivalent objects."""
if hasattr(x, 'hash_object'):
return x.hash_object()
else:
return x | b3a0a8c2accbfcd0e17839345e4e3c4e9d620810 | 645,726 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.