content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def split_multibody(beam, tstep, mb_data_dict, ts):
"""
split_multibody
This functions splits a structure at a certain time step in its different bodies
Args:
beam (:class:`~sharpy.structure.models.beam.Beam`): structural information of the multibody system
tstep (:class:`~sharpy.utils.datas... | 25d3d3496bdf0882e732ddfb14d3651d54167adc | 819 |
def hook_name_to_env_name(name, prefix='HOOKS'):
"""
>>> hook_name_to_env_name('foo.bar_baz')
HOOKS_FOO_BAR_BAZ
>>> hook_name_to_env_name('foo.bar_baz', 'PREFIX')
PREFIX_FOO_BAR_BAZ
"""
return '_'.join([prefix, name.upper().replace('.', '_')]) | b0dabce88da8ddf8695303ac4a22379baa4ddffa | 822 |
def readline_skip_comments(f):
"""
Read a new line while skipping comments.
"""
l = f.readline().strip()
while len(l) > 0 and l[0] == '#':
l = f.readline().strip()
return l | c4b36af14cc48b1ed4cd72b06845e131015da6c6 | 823 |
def _verify_weight_parameters(weight_parameters):
"""Verifies that the format of the input `weight_parameters`.
Checks that the input parameters is a 2-tuple of tensors of equal shape.
Args:
weight_parameters: The parameters to check.
Raises:
RuntimeError: If the input is not a 2-tuple of tensors wit... | 9ec018c66d48e830250fd299cd50f370118132cc | 824 |
def _crc16_checksum(bytes):
"""Returns the CRC-16 checksum of bytearray bytes
Ported from Java implementation at: http://introcs.cs.princeton.edu/java/61data/CRC16CCITT.java.html
Initial value changed to 0x0000 to match Stellar configuration.
"""
crc = 0x0000
polynomial = 0x1021
for byte ... | 2b00d11f1b451f3b8a4d2f42180f6f68d2fbb615 | 825 |
def reverse(segment):
"""Reverses the track"""
return segment.reverse() | 74632b8a8a192970187a89744b2e8c6fa77fb2cf | 826 |
def is_bond_member(yaml, ifname):
"""Returns True if this interface is a member of a BondEthernet."""
if not "bondethernets" in yaml:
return False
for _bond, iface in yaml["bondethernets"].items():
if not "interfaces" in iface:
continue
if ifname in iface["interfaces"]:
... | 521186221f2d0135ebcf1edad8c002945a56da26 | 827 |
def lift2(f, a, b):
"""Apply f => (a -> b -> c) -> f a -> f b -> f c"""
return a.map(f).apply_to(b) | 6b54cacf23ac4acb9bf9620cd259aa6f9630bbc3 | 831 |
def short_whitelist(whitelist):
"""A condensed version of the whitelist."""
for x in ["guid-4", "guid-5"]:
whitelist.remove(x)
return whitelist | e0de5f4f8c86df301af03c9362b095f330bffc14 | 832 |
def extract_paths(actions):
"""
<Purpose>
Given a list of actions, it extracts all the absolute and relative paths
from all the actions.
<Arguments>
actions: A list of actions from a parsed trace
<Returns>
absolute_paths: a list with all absolute paths extracted from the actions
... | 94aaf8fef1a7c6d3efd8b04c980c9e87ee7ab4ff | 833 |
def str2int(s):
"""converts a string to an integer with the same bit pattern (little endian!!!)"""
r = 0
for c in s:
r <<= 8
r += ord(c)
return r | 0dd190b8711e29e12be8cc85a641d9a68251205b | 834 |
def count_infected(pop):
"""
counts number of infected
"""
return sum(p.is_infected() for p in pop) | 03b3b96994cf4156dcbe352b9dafdd027de82d41 | 837 |
def _prompt(func, prompt):
"""Prompts user for data. This is for testing."""
return func(prompt) | c5e8964e5b3a3d0a222e167341a44d8953d1e0c1 | 838 |
def to_percent__xy(x, y):
"""
To percent with 2 decimal places by diving inputs.
:param x:
:param y:
:return:
"""
return '{:.2%}'.format(x / y) | 3d5cfcde6f1dbd65b99a4081790e03efb669ee02 | 839 |
import re
def only_letters(answer):
"""Checks if the string contains alpha-numeric characters
Args:
answer (string):
Returns:
bool:
"""
match = re.match("^[a-z0-9]*$", answer)
return bool(match) | 32c8905294f6794f09bb7ea81ed7dd4b6bab6dc5 | 841 |
def _InUse(resource):
"""All the secret names (local names & remote aliases) in use.
Args:
resource: Revision
Returns:
List of local names and remote aliases.
"""
return ([
source.secretName
for source in resource.template.volumes.secrets.values()
] + [
source.secretKeyRef.name
... | cf13ccf1d0fffcd64ac8b3a40ac19fdb2b1d12c5 | 842 |
import re
def re_identify_image_metadata(filename, image_names_pattern):
"""
Apply a regular expression to the *filename* and return metadata
:param filename:
:param image_names_pattern:
:return: a list with metadata derived from the image filename
"""
match = re.match(image_names_pattern,... | 1730620682f2457537e3f59360d998b251f5067f | 843 |
import yaml
import sys
def load_config(config_file: str) -> dict:
"""
Function to load yaml configuration file
:param config_file: name of config file in directory
"""
try:
with open(config_file) as file:
config = yaml.safe_load(file)
except IOError as e:
print(e)
... | f811aa4d6a16d8a5e56d14b91d616f9f8b3ad492 | 844 |
def mark_task(func):
"""Mark function as a defacto task (for documenting purpose)"""
func._is_task = True
return func | 9f0156fff2a2a6dcb64e79420022b78d1c254490 | 846 |
def make_slack_message_divider() -> dict:
"""Generates a simple divider for a Slack message.
Returns:
The generated divider.
"""
return {'type': 'divider'} | 9d0243c091065056a29d9fa05c62fadde5dcf6f6 | 847 |
import os
def username():
""" Return username from env. """
return os.environ["USER"] | adcb6da63823d78203d02b2a3910f92e3ae97724 | 848 |
def get_batch(source, i, cnf):
"""
Gets a batch shifted over by shift length
"""
seq_len = min(cnf.batch_size, len(source) - cnf.forecast_window - i)
data = source[i : i + seq_len]
target = source[
i + cnf.forecast_window : i + cnf.forecast_window + seq_len
].reshape(-1)
return d... | 8f4bbfca44bed498dc22d52706389378bf03f7e0 | 851 |
def _stringify(item):
"""
Private funtion which wraps all items in quotes to protect from paths
being broken up. It will also unpack lists into strings
:param item: Item to stringify.
:return: string
"""
if isinstance(item, (list, tuple)):
return '"' + '" "'.join(item) + '"'
i... | 7187b33dccce66cb81b53ed8e8c395b74e125633 | 853 |
def _get_tree_filter(attrs, vecvars):
"""
Pull attributes and input/output vector variables out of a tree System.
Parameters
----------
attrs : list of str
Names of attributes (may contain dots).
vecvars : list of str
Names of variables contained in the input or output vectors.
... | fb96025a075cfc3c56011f937d901d1b87be4f03 | 854 |
import re
import copy
def _filter(dict_packages, expression):
"""Filter the dict_packages with expression.
Returns:
dict(rst): Filtered dict with that matches the expression.
"""
expression_list = ['(' + item + ')' for item in expression.split(',')]
expression_str = '|'.join(expression_l... | 866bca2847b9d3c8220319f4b394f932931fc076 | 856 |
def similarity(item, user, sim_dict):
"""
similarity between an item and a user (a set of items)
"""
if user not in sim_dict or item not in sim_dict[user]:
return 0
else:
return sim_dict[user][item] | e63eec781f7ed9fa72d21d1119daf9ce89d39b1b | 857 |
def menu(function_text):
"""
Decorator for plain-text handler
:param function_text: function which set as handle in bot class
:return:
"""
def wrapper(self, bot, update):
self.text_menu(bot, update)
function_text(self, bot, update)
return wrapper | dc68a46aaf402cd5ce3bd832a0f2a661b5cbc71b | 859 |
from typing import Dict
from typing import List
def generate_markdown_metadata(metadata_obj: Dict[str, str]) -> List[str]:
"""generate_markdown_metadata
Add some basic metadata to the top of the file
in HTML tags.
"""
metadata: List[str] = ["<!---"]
passed_metadata: List[str] = [
f"... | 02ef3952c265276f4e666f060be6cb1d4a150cca | 860 |
def replace_string(original, start, end, replacement):
"""Replaces the specified range of |original| with |replacement|"""
return original[0:start] + replacement + original[end:] | c71badb26287d340170cecdbae8d913f4bdc14c6 | 861 |
def dictionarify_recpat_data(recpat_data):
"""
Covert a list of flat dictionaries (single-record dicts) into a dictionary.
If the given data structure is already a dictionary, it is left unchanged.
"""
return {track_id[0]: patterns[0] for track_id, patterns in \
[zip(*item.items()) for ... | d1cdab68ab7445aebe1bbcce2f220c73d6db308f | 862 |
def pre_process_data(full_data):
"""
pre process data- dump invalid values
"""
clean_data = full_data[(full_data["Temp"] > -10)]
return clean_data | 6172d4a77f5805c60ae9e4f146da2bd8283beef0 | 863 |
def user_exists(keystone, user):
"""" Return True if user already exists"""
return user in [x.name for x in keystone.users.list()] | 17d99e12c0fc128607a815f0b4ab9897c5d45578 | 864 |
def text_split(in_text, insert_points, char_set):
""" Returns: Input Text Split into Text and Nonce Strings. """
nonce_key = []
encrypted_nonce = ""
in_list = list(in_text)
for pos in range(3967):
if insert_points[pos] >= len(in_list) - 1: point = len(in_list) - 2
else: point = inser... | 15f496513e63236b0df7e2d8a8949a8b2e632af4 | 867 |
def _module_exists(module_name):
"""
Checks if a module exists.
:param str module_name: module to check existance of
:returns: **True** if module exists and **False** otherwise
"""
try:
__import__(module_name)
return True
except ImportError:
return False | 8f3ed2e97ee6dbb41d6e84e9e5595ec8b6f9b339 | 868 |
def check_cstr(solver, indiv):
"""Check the number of constraints violations of the individual
Parameters
----------
solver : Solver
Global optimization problem solver
indiv : individual
Individual of the population
Returns
-------
... | 2aa52d2badfb45d8e289f8314700648ddc621252 | 869 |
def normal_shock_pressure_ratio(M, gamma):
"""Gives the normal shock static pressure ratio as a function of upstream Mach number."""
return 1.0+2.0*gamma/(gamma+1.0)*(M**2.0-1.0) | 30d0a339b17bab2b662fecd5b19073ec6478a1ec | 871 |
from typing import Tuple
import numpy
def _lorentz_berthelot(
epsilon_1: float, epsilon_2: float, sigma_1: float, sigma_2: float
) -> Tuple[float, float]:
"""Apply Lorentz-Berthelot mixing rules to a pair of LJ parameters."""
return numpy.sqrt(epsilon_1 * epsilon_2), 0.5 * (sigma_1 + sigma_2) | b27c282cec9f880442be4e83f4965c0ad79dfb1e | 872 |
def get_ical_file_name(zip_file):
"""Gets the name of the ical file within the zip file."""
ical_file_names = zip_file.namelist()
if len(ical_file_names) != 1:
raise Exception(
"ZIP archive had %i files; expected 1."
% len(ical_file_names)
)
return ical_file_names... | 7013840891844358f0b4a16c7cefd31a602d9eae | 873 |
def circular_mask_string(centre_ra_dec_posns, aperture_radius="1arcmin"):
"""Get a mask string representing circular apertures about (x,y) tuples"""
mask = ''
if centre_ra_dec_posns is None:
return mask
for coords in centre_ra_dec_posns:
mask += 'circle [ [ {x} , {y}] , {r} ]\n'.format(
... | 04e66d160eb908f543990adf896e494226674c71 | 875 |
def dataset_hdf5(dataset, tmp_path):
"""Make an HDF5 dataset and write it to disk."""
path = str(tmp_path / 'test.h5')
dataset.write_hdf5(path, object_id_itemsize=10)
return path | 4a7920adf7715797561513fbb87593abf95f0bca | 876 |
def actions(__INPUT):
"""
Regresamos una lista de los posibles movimientos de la matriz
"""
MOVIMIENTOS = []
m = eval(__INPUT)
i = 0
while 0 not in m[i]:
i += 1
# Espacio en blanco (#0)
j = m[i].index(0);
if i > 0:
#ACCION MOVER ARRIBA
m[i][j], m[i-1][j] = m[i-... | 46875f83d7f50bbd107be8ad5d926397960ca513 | 879 |
from shutil import which as shwhich
import os
def which(program, mode=os.F_OK | os.X_OK, path=None):
"""
Mimics the Unix utility which.
For python3.3+, shutil.which provides all of the required functionality.
An implementation is provided in case shutil.which does
not exist.
:param program: (... | fbba58ba489db2c2813e4aadf9781c35d6955f0f | 880 |
def choose_string(g1, g2):
"""Function used by merge_similar_guesses to choose between 2 possible
properties when they are strings.
If the 2 strings are similar, or one is contained in the other, the latter is returned
with an increased confidence.
If the 2 strings are dissimilar, the one with the... | e39a66c9f3f941b12225dde879bc92956694d2d0 | 881 |
import argparse
def get_parser():
"""Return base parser for scripts.
"""
parser = argparse.ArgumentParser()
parser.add_argument('config', help='Tuning configuration file (examples: configs/tuning)')
return parser | 6f394f836fae278b659a0612a088f53563c8f34b | 882 |
import os
def cd(path):
"""Context manager to switch working directory"""
def normpath(path):
"""Normalize UNIX path to a native path."""
normalized = os.path.join(*path.split('/'))
if os.path.isabs(path):
return os.path.abspath('/') + normalized
return normalized
path = normpath(path)
c... | f1664765e26e3ff4ec8a70d16d6beca5a23f4d68 | 883 |
from datetime import datetime
def add_filter(field, bind, criteria):
"""Generate a filter."""
if 'values' in criteria:
return '{0}=any(:{1})'.format(field, bind), criteria['values']
if 'date' in criteria:
return '{0}::date=:{1}'.format(field, bind), datetime.strptime(criteria['date'], '%Y-... | 2358cab297b2a2cbc42af02b3b6d14ac134c8b71 | 884 |
def decode_field(value):
"""Decodes a field as defined in the 'Field Specification' of the actions
man page: http://www.openvswitch.org/support/dist-docs/ovs-actions.7.txt
"""
parts = value.strip("]\n\r").split("[")
result = {
"field": parts[0],
}
if len(parts) > 1 and parts[1]:
... | 1a1659e69127ddd3c63eb7d4118ceb4e53a28ca0 | 885 |
def _nonempty_line_count(src: str) -> int:
"""Count the number of non-empty lines present in the provided source string."""
return sum(1 for line in src.splitlines() if line.strip()) | ad2ac0723f9b3e1f36b331175dc32a8591c67893 | 886 |
import os
def _validate_source(source):
"""
Check that the entered data source paths are valid
"""
# acceptable inputs (for now) are a single file or directory
assert type(source) == str, "You must enter your input as a string."
assert (
os.path.isdir(source) == True or os.path.isfile... | 45e1f88f6c246713f85d83cf6a9753ec67799774 | 887 |
def recursion_detected(frame, keys):
"""Detect if we have a recursion by finding if we have already seen a
call to this function with the same locals. Comparison is done
only for the provided set of keys.
"""
current = frame
current_filename = current.f_code.co_filename
current_function = c... | ebf30e715d2901169095bc920e8af6c715f2a1de | 888 |
def _dump_multipoint(obj, fmt):
"""
Dump a GeoJSON-like MultiPoint object to WKT.
Input parameters and return value are the MULTIPOINT equivalent to
:func:`_dump_point`.
"""
coords = obj['coordinates']
mp = 'MULTIPOINT (%s)'
points = (' '.join(fmt % c for c in pt) for pt in coords)
... | cdea05b91c251b655e08650807e3f74d3bb5e77b | 889 |
def binary_distance(label1, label2):
"""Simple equality test.
0.0 if the labels are identical, 1.0 if they are different.
>>> from nltk.metrics import binary_distance
>>> binary_distance(1,1)
0.0
>>> binary_distance(1,3)
1.0
"""
return 0.0 if label1 == label2 else 1.0 | 2c4eaebda2d6955a5012cc513857aed66df60194 | 890 |
def calc_commission_futures_global(trade_cnt, price):
"""
国际期货:差别很大,最好外部自定义自己的计算方法,这里只简单按照0.002计算
:param trade_cnt: 交易的股数(int)
:param price: 每股的价格(美元)
:return: 计算结果手续费
"""
cost = trade_cnt * price
# 国际期货各个券商以及代理方式差别很大,最好外部自定义计算方法,这里只简单按照0.002计算
commission = cost * 0.002
return co... | ddd2c4571abfcdf7021a28b6cc78fe6441da2bd3 | 891 |
def make_collector(entries):
""" Creates a function that collects the location data from openLCA. """
def fn(loc):
entry = [loc.getCode(), loc.getName(), loc.getRefId()]
entries.append(entry)
return fn | 83fb167c38626fde79262a32f500b33a72ab8308 | 892 |
def apiname(funcname):
""" Define what name the API uses, the short or the gl version.
"""
if funcname.startswith('gl'):
return funcname
else:
if funcname.startswith('_'):
return '_gl' + funcname[1].upper() + funcname[2:]
else:
return 'gl' + funcname[0].up... | 06575fce76ac02990c973a6dd17ff177ae5e3ddc | 893 |
import argparse
from pathlib import Path
def _parse_args() -> argparse.Namespace:
"""Registers the script's arguments on an argument parser."""
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--source-root',
type=Path,
required=T... | cda37a6282b95fca4db51e91bfe98cc44f46fd07 | 896 |
def filter_marker_y_padding(markers_y_indexes, padding_y_top, padding_y_bottom):
"""
Filter the markers indexes for padding space in the top and bottom of answer sheet
:param markers_y_indexes:
:param padding_y_top:
:param padding_y_bottom:
:return:
"""
return markers_y_indexes[(markers... | b1eed0ac24bd6a6354072427be4375ad188572a5 | 897 |
def apply_function(f, *args, **kwargs):
""" Apply a function or staticmethod/classmethod to the given arguments.
"""
if callable(f):
return f(*args, **kwargs)
elif len(args) and hasattr(f, '__get__'):
# support staticmethod/classmethod
return f.__get__(None, args[0])(*args, **kwa... | 374be0283a234d4121435dbd3fa873640f2b9ad1 | 898 |
import sys
def read_lines_from_input(file):
"""
Reads the provided file line by line to provide a list representation of the contained names.
:param file: A text file containing one name per line. If it's None, the input is read from the standard input.
:return: A list of the names contained in the pr... | 4a653979ee51afea8e7199772199c1a93dbfecc3 | 899 |
import os
def installDirectory():
"""
Return the software installation directory, by looking at location of this
method.
"""
#path = os.path.abspath(os.path.join(os.path.realpath(__file__), os.pardir))
path = os.path.abspath(os.path.realpath(__file__))
path = os.path.abspath(os.path.join(... | d79d57eea1eb38ec56a864246ac2388d7320a0fa | 901 |
def make_file_iterator(filename):
"""Return an iterator over the contents of the given file name."""
# pylint: disable=C0103
with open(filename) as f:
contents = f.read()
return iter(contents.splitlines()) | e7b612465717dafc3155d9df9fd007f7aa9af509 | 902 |
def little_endian_bytes_to_int(little_endian_byte_seq):
"""Converts a pair of bytes into an integer.
The `little_endian_byte_seq` input must be a 2 bytes sequence defined
according to the little-endian notation (i.e. the less significant byte
first).
For instance, if the `little_endian_byte_seq` i... | d8d0c6d4ebb70ea541e479b21deb913053886748 | 903 |
def higher_follower_count(A, B):
""" Compares follower count key between two dictionaries"""
if A['follower_count'] >= B['follower_count']: return "A"
return "B" | d4d182ca5a3c5bff2bc7229802603a82d44a4d67 | 904 |
import os
def make_non_absolute(path):
"""
Make a path non-absolute (so it can be joined to a base directory)
@param path: The file path
"""
drive, path = os.path.splitdrive(path)
index = 0
while os.path.isabs(path[index:]):
index = index + 1
return path[index:] | 51eefa84423077273931a3a4c77b4e53669a6599 | 905 |
def pad_in(string: str, space: int) -> str:
"""
>>> pad_in('abc', 0)
'abc'
>>> pad_in('abc', 2)
' abc'
"""
return "".join([" "] * space) + string | 325c0751da34982e33e8fae580af6f439a2dcac0 | 908 |
import time
def confirm_channel(bitcoind, n1, n2):
"""
Confirm that a channel is open between two nodes
"""
assert n1.id() in [p.pub_key for p in n2.list_peers()]
assert n2.id() in [p.pub_key for p in n1.list_peers()]
for i in range(10):
time.sleep(0.5)
if n1.check_channel(n2) ... | bcbf895b286b446f7bb0ad2d7890a0fa902cdbd1 | 909 |
def extend_params(params, more_params):
"""Extends dictionary with new values.
Args:
params: A dictionary
more_params: A dictionary
Returns:
A dictionary which combines keys from both dictionaries.
Raises:
ValueError: if dicts have the same key.
"""
for yak in more_params:
if yak in p... | 626db0ae8d8a249b8c0b1721b7a2e0f1d4c084b8 | 910 |
def _AccumulatorResultToDict(partition, feature, grads, hessians):
"""Converts the inputs to a dictionary since the ordering changes."""
return {(partition[i], feature[i, 0], feature[i, 1]): (grads[i], hessians[i])
for i in range(len(partition))} | 20cc895cf936749a35c42a1158c9ea6645019e7d | 911 |
def _evolve_cx(base_pauli, qctrl, qtrgt):
"""Update P -> CX.P.CX"""
base_pauli._x[:, qtrgt] ^= base_pauli._x[:, qctrl]
base_pauli._z[:, qctrl] ^= base_pauli._z[:, qtrgt]
return base_pauli | 5d0529bc4bfe74a122c24069eccb20fa2b69f153 | 912 |
def get_block_devices(bdms=None):
"""
@type bdms: list
"""
ret = ""
if bdms:
for bdm in bdms:
ret += "{0}\n".format(bdm.get('DeviceName', '-'))
ebs = bdm.get('Ebs')
if ebs:
ret += " Status: {0}\n".format(ebs.get('Status', '-'))
... | bd375f988b13d8fe5949ebdc994210136acc3405 | 914 |
def config_section_data():
"""Produce the default configuration section for app.config,
when called by `resilient-circuits config [-c|-u]`
"""
config_data = u"""[fn_grpc_interface]
interface_dir=<<path to the parent directory of your Protocol Buffer (pb2) files>>
#<<package_name>>=<<communication_ty... | cb26012ff6ad1a2dbccbbcc5ef81c7a91def7906 | 916 |
import multiprocessing
import os
def get_workers_count_based_on_cpu_count():
"""
Returns the number of workers based available virtual or physical CPUs on this system.
"""
# Python 2.6+
try:
return multiprocessing.cpu_count() * 2 + 1
except (ImportError, NotImplementedError):
... | 0f42840196e596a371a78f16443b4bc22a89c460 | 917 |
def get_rdf_lables(obj_list):
"""Get rdf:labels from a given list of objects."""
rdf_labels = []
for obj in obj_list:
rdf_labels.append(obj['rdf:label'])
return rdf_labels | 2bcf6a6e8922e622de602f5956747955ea39eeda | 919 |
def _identifier(name):
"""
:param name: string
:return: name in lower case and with '_' instead of '-'
:rtype: string
"""
if name.isidentifier():
return name
return name.lower().lstrip('0123456789. ').replace('-', '_') | fbbbc9dd3f2bc5b6e43520c0685f63a10ee95f0a | 921 |
def get_request_list(flow_list: list) -> list:
"""
将flow list转换为request list。在mitmproxy中,flow是对request和response的总称,这个功能只获取request。
:param flow_list: flow的列表
:return: request的列表
"""
req_list = []
for flow in flow_list:
request = flow.get("request")
req_list.append(request)
... | a70e0120ef2be88bd0644b82317a2a0748352c6c | 922 |
def _get_resource(span):
"""Get resource name for span"""
if "http.method" in span.attributes:
route = span.attributes.get("http.route")
return (
span.attributes["http.method"] + " " + route
if route
else span.attributes["http.method"]
)
return sp... | 71b4d2e568350ccfb436bbff6e7a2cff1f3cb251 | 924 |
def _B(slot):
"""Convert slot to Byte boundary"""
return slot*2 | 97f13e9fd99989a83e32f635193a0058656df68b | 925 |
import torch
def nll(perm, true):
"""
perm: (n, n) or (s, n, n)
true: (n)
"""
n = true.size(-1)
# i = torch.arange(n, device=perm.device)
# j = true.to(perm.device)
# print("perm.nll:", perm.size(), true.size())
elements = perm.cpu()[..., torch.arange(n), true]
# elements = per... | a63c95e814529539ecd964f4309ea96f78cfcbb1 | 926 |
import pathlib
import json
def load_towns():
"""Sample of Wikipedia dataset that contains informations about Toulouse, Paris, Lyon and
Bordeaux.
Examples
--------
>>> from pprint import pprint as print
>>> from cherche import data
>>> towns = data.load_towns()
>>> print(towns[:3])
... | 72aa393cfc40db5f254059d78679ea5615f494d2 | 927 |
import numpy as np
def minimum_distance(object_1, object_2):
""" Takes two lists as input
A list of numpy arrays of coordinates that make up object 1 and object 2
Measures the distances between each of the coordinates
Returns the minimum distance between the two objects, as calculated using a vector n... | e61fbb1ab83c5147f69351022f59ebab3295cb5a | 930 |
def union(l1, l2):
""" return the union of two lists """
return list(set(l1) | set(l2)) | 573e3b0e475b7b33209c4a477ce9cab53ec849d4 | 931 |
def k1(f, t, y, paso):
"""
f : funcion a integrar. Retorna un np.ndarray
t : tiempo en el cual evaluar la funcion f
y : para evaluar la funcion f
paso : tamano del paso a usar.
"""
output = paso * f(t, y)
return output | 55a358a5d099111bd399bf1a0e0211d6616ab3d0 | 932 |
def get_start_end(sequence, skiplist=['-','?']):
"""Return position of first and last character which is not in skiplist.
Skiplist defaults to ['-','?'])."""
length=len(sequence)
if length==0:
return None,None
end=length-1
while end>=0 and (sequence[end] in skiplist):
end-=1
... | b67e0355516f5aa5d7f7fad380d262cf0509bcdb | 934 |
def workerfunc(prob, *args, **kwargs):
""" Helper function for wrapping class methods to allow for use
of the multiprocessing package """
return prob.run_simulation(*args, **kwargs) | 620799615b60784e754385fac31e5a7f1db37ed3 | 936 |
def test_curve_plot(curve):
"""
Tests mpl image of curve.
"""
fig = curve.plot().get_figure()
return fig | 033ee4ce5f5fa14c60914c34d54af4c39f6f84b3 | 937 |
def simplifiedview(av_data: dict, filehash: str) -> str:
"""Builds and returns a simplified string containing basic information about the analysis"""
neg_detections = 0
pos_detections = 0
error_detections = 0
for engine in av_data:
if av_data[engine]['category'] == 'malicious' or av_data[e... | c6aecf6c12794453dd8809d53f20f6152ac6d5a3 | 938 |
def quote_key(key):
"""特殊字符'/'转义处理
"""
return key.replace('/', '%2F') | ce1978ca23ed3c00489c134a35ae8d04370b49dd | 939 |
def middle(word):
"""Returns all but the first and last characters of a string."""
return word[1:-1] | 257a159c46633d3c3987437cb3395ea2be7fad70 | 940 |
import argparse
def _validate_int(value, min, max, type):
"""Validates a constrained integer value.
"""
try:
ivalue = int(value)
if min and max:
if ivalue < min or ivalue > max:
raise ValueError()
except ValueError:
err = f"{type} index must be an i... | 6e85ea9d97a4c906cad410847de6f21eace33afd | 941 |
import re
from pathlib import Path
import json
def load_stdlib_public_names(version: str) -> dict[str, frozenset[str]]:
"""Load stdlib public names data from JSON file"""
if not re.fullmatch(r"\d+\.\d+", version):
raise ValueError(f"{version} is not a valid version")
try:
json_file = Pat... | 02775d96c8a923fc0380fe6976872a7ed2cf953a | 942 |
def readlines(filepath):
"""
read lines from a textfile
:param filepath:
:return: list[line]
"""
with open(filepath, 'rt') as f:
lines = f.readlines()
lines = map(str.strip, lines)
lines = [l for l in lines if l]
return lines | 1aa16c944947be026223b5976000ac38556983c3 | 944 |
def n_tuple(n):
"""Factory for n-tuples."""
def custom_tuple(data):
if len(data) != n:
raise TypeError(
f'{n}-tuple requires exactly {n} items '
f'({len(data)} received).'
)
return tuple(data)
return custom_tuple | 0c5d8f0f277e07f73c4909895c8215427fb5e705 | 946 |
def calc_dof(model):
"""
Calculate degrees of freedom.
Parameters
----------
model : Model
Model.
Returns
-------
int
DoF.
"""
p = len(model.vars['observed'])
return p * (p + 1) // 2 - len(model.param_vals) | ccff8f5a7624b75141400747ec7444ec55eb492d | 947 |
def _level2partition(A, j):
"""Return views into A used by the unblocked algorithms"""
# diagonal element d is A[j,j]
# we access [j, j:j+1] to get a view instead of a copy.
rr = A[j, :j] # row
dd = A[j, j:j+1] # scalar on diagonal / \
B = A[j+1:, :j] # Block in corner | ... | 16ba7715cc28c69ad35cdf3ce6b542c14d5aa195 | 948 |
def bisect_jump_time(tween, value, b, c, d):
"""
**** Not working yet
return t for given value using bisect
does not work for whacky curves
"""
max_iter = 20
resolution = 0.01
iter = 1
lower = 0
upper = d
while iter < max_iter:
t = (upper - lower) / 2
if twee... | f7e1dbeb000ef60a5bd79567dc88d66be9235a75 | 950 |
import math
def getDist_P2L(PointP,Pointa,Pointb):
"""计算点到直线的距离
PointP:定点坐标
Pointa:直线a点坐标
Pointb:直线b点坐标
"""
#求直线方程
A=0
B=0
C=0
A=Pointa[1]-Pointb[1]
B=Pointb[0]-Pointa[0]
C=Pointa[0]*Pointb[1]-Pointa[1]*Pointb[0]
#代入点到直线距离公式
distance=0
distance=(... | ca0ec1fc25183a240179faef7473d7b86758a92b | 953 |
import functools
def skip_if_disabled(func):
"""Decorator that skips a test if test case is disabled."""
@functools.wraps(func)
def wrapped(*a, **kwargs):
func.__test__ = False
test_obj = a[0]
message = getattr(test_obj, 'disabled_message',
'Test disabled'... | 56d42a1e0418f4edf3d4e8478358495b1353f57a | 956 |
from typing import Any
import itertools
def _compare_keys(target: Any, key: Any) -> bool:
"""
Compare `key` to `target`.
Return True if each value in `key` == corresponding value in `target`.
If any value in `key` is slice(None), it is considered equal
to the corresponding value in `target`.
... | ff5c60fab8ac0cbfe02a816ec78ec4142e32cfbf | 957 |
import inspect
def filter_safe_dict(data, attrs=None, exclude=None):
"""
Returns current names and values for valid writeable attributes. If ``attrs`` is given, the
returned dict will contain only items named in that iterable.
"""
def is_member(cls, k):
v = getattr(cls, k)
checks ... | ce457615ba8e360243912c3bba532e8327b8def4 | 959 |
def fixture_loqus_exe():
"""Return the path to a loqus executable"""
return "a/path/to/loqusdb" | 647b31e37854a5cbc8fd066c982e67f976100c03 | 960 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.