content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import random
import collections
def load_papertext(train_rate=0.8, dev_rate=0.1, test_rate=0.1, max_length=50, download_from_label_studio=True):
"""
Aspect Base sentiment analysis
:param kind: 是加载papertext数据,还是dem8的数据
:return:
:rtype:
"""
export_dir = "/opt/nlp/data/papertext/"
if dow... | b0c4747aaf61dce82612162652218ce001a7f17e | 3,649,800 |
import logging
def set_log_level_for_all_handlers(logger, level=logging.DEBUG):
"""
Set a log level for all the handlers on the provided logger.
"""
logger.setLevel(level)
handlers = logger.handlers
for handler in handlers:
handler.setLevel(level)
return logger | c217284e813f46b16d29de5aa2393e06f26981b7 | 3,649,801 |
import json
def _load_cmake_spec():
"""Load and return the CMake spec from disk"""
try:
with open(CMAKE_SPEC_FILE()) as fp:
return json.load(fp)
except (OSError, IOError, ValueError):
return None | 32d239ec667aa6f24da6f426d0c2dbf1984f3409 | 3,649,802 |
import openai
def compare_ask_ai_question():
"""
compare_ask_ai_question(): Ask a one questions to many product (GPT-3)
"""
try:
id_token = request.headers['Authorization']
claims = auth.verify_id_token(id_token)
uid = claims['uid']
data = request.json['data']
... | 097f7161fded9b5452b7373d0bcbc1b18ceb6590 | 3,649,803 |
def read():
"""
Read temperature
:return: temperature
"""
# global ds18b20
location = '/sys/bus/w1/devices/' + ds18b20 + '/w1_slave'
tfile = open(location)
text = tfile.read()
tfile.close()
secondline = text.split("\n")[1]
temperaturedata = secondline.split(" ")[9]
temper... | 7e4c689d5cce6b28c28314eb7e1773e9af1a5061 | 3,649,804 |
import time
def wine(root):
"""Title of Database: Wine recognition data
Updated Sept 21, 1998 by C.Blake : Added attribute information
These data are the results of a chemical analysis of
wines grown in the same region in Italy but derived from three
different cultivars.
The analysis dete... | f2a9a3b66b276b563dc03919becc326f35d77b3a | 3,649,805 |
def initialize_scenario_data():
"""Will initialize the Scenario Data.
:return an empty ScenarioData named tuple
:rtype ScenarioData
"""
actors = {}
companies = {}
scenario_data = ScenarioData(actors, companies)
return scenario_data | 4bbb26b84abef89fc6636bd382d0308cbc8e7573 | 3,649,806 |
def dynamicMass(bulk_density, lat, lon, height, jd, velocity, decel, gamma=1.0, shape_factor=1.21):
""" Calculate dynamic mass at the given point on meteor's trajectory.
Either a single set of values can be given (i.e. every argument is a float number), or all arguments
must be numpy arrays.
... | 48920ecaef4c039672a387f4da45297861b6da56 | 3,649,807 |
def input_fn_tfrecords(files_name_pattern, num_epochs, batch_size, mode):
"""
Input functions which parses TFRecords.
:param files_name_pattern: File name to TFRecords.
:param num_epochs: Number of epochs.
:param batch_size: Batch size.
:param mode: Input function mode.
:return: features and... | bd2b5bf41c2ea9fbb28d7e2cdc5c8f22e8bbac93 | 3,649,808 |
def validate(number):
"""Check if the number provided is a valid RUC number. This checks the
length, formatting, check digit and check sum."""
number = compact(number)
if len(number) != 13:
raise InvalidLength()
if not number.isdigit():
raise InvalidFormat()
if number[:2] < '01' ... | c09602c8b3301c6f1d4d467a1b7bfd607656c436 | 3,649,809 |
def parse_raw(data: bytes) -> dict:
"""
Parse the contents of an environment retrieved from flash or memory
and provide an equivalent dictionary.
The provided *data* should being at the start of the variable definitions.
It **must not** contain the ``env_t`` metadata, such as the CRC32 word
and... | c40c08a099d7468a4ec19da90ce9062d8ddd6ed1 | 3,649,810 |
from typing import List
def _list_registered_paths() -> List[str]:
"""List available paths registered to this service."""
paths = []
for rule in application.url_map.iter_rules():
rule = str(rule)
if rule.startswith("/api/v1"):
paths.append(rule)
return paths | 56f27aa4b33191cbd779e0e173295431670d26ab | 3,649,811 |
def input_fn(request_body, request_content_type):
"""An input_fn that loads a pickled numpy array"""
if request_content_type == "application/python-pickle":
array = np.load(BytesIO(request_body), allow_pickle=True)
return array
else:
raise Exception("Please provide 'application/pytho... | 0f6387dffc3ade2097888a92ef1af99f4d367ef8 | 3,649,812 |
def game(x_train, x_test, y_train, y_test, algo='rf', show_train_scores=True):
"""Standard Alogrithms fit and return scores.
* Default Random State is set as 192 when posible.
* Available models - dc, rf, gb, knn, mc_ovo_rf, mc_ova_rf
"""
if algo is 'dc':
clf = clf = DummyClassifier(strateg... | 9a225f04d5d883bc70c4f4f9036ddfee7b206dbc | 3,649,813 |
def get_convolutional_model(vocab_size: int,
input_length: int,
num_classes: int,
embedding_size: int=300,
model_size: str='small'
) -> Model:
"""Create a character convolution... | aafd9fe6141a05c433508ff0a9583d9c42a7de5b | 3,649,814 |
def parse_test_config(doc):
""" Get the configuration element. """
test_config = doc.documentElement
if test_config.tagName != 'configuration':
raise RuntimeError('expected configuration tag at root')
return test_config | c61c2f4e43c5501c461bb92b63609162b2918860 | 3,649,815 |
import textwrap
def _get_control_vars(control_vars):
"""
Create the section of control variables
Parameters
----------
control_vars: str
Functions to define control variables.
Returns
-------
text: str
Control variables section and header of model variables section.
... | 614a6ca5bc8ac7354f63bfceabaff4eb4b93208a | 3,649,816 |
def echo():
"""Echo data"""
return request.get_data() + '\n' | 75aad93e46925ed086be87b18a96d756fa1c6425 | 3,649,817 |
import os
import csv
def get_ids():
"""
Get all SALAMI IDs related to RWC
"""
# Filename for SALAMI RWC metadata
metadata_file = os.path.join(
dpath.SALAMI, 'metadata', 'id_index_rwc.csv')
ids = []
with open(metadata_file, "r") as rwc_file:
reader = csv.reader(rwc_file)
... | ad55be00b1a43f62c51b9ce6bb025bda9bdb1756 | 3,649,818 |
import logging
def _get_signature_def(signature_def_key, export_dir, tags):
"""Construct a `SignatureDef` proto."""
signature_def_key = (
signature_def_key or
signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY)
metagraph_def = saved_model_cli.get_meta_graph_def(export_dir, tags)
try:
sign... | d0bedd323fb68ad41553034a08b64dc73f85faf3 | 3,649,819 |
def illuminance_to_exposure_value(E, S, c=250):
"""
Computes the exposure value :math:`EV` from given scene illuminance
:math:`E` in :math:`Lux`, *ISO* arithmetic speed :math:`S` and
*incident light calibration constant* :math:`c`.
Parameters
----------
E : array_like
Scene illumina... | 7c03f816e801f04735687a2a2adb6f4969877bb2 | 3,649,820 |
from typing import Counter
def feedback(code, guess):
"""
Return a namedtuple Feedback(blacks, whites) where
blacks is the number of pegs from the guess that
are correct in both color and position and
whites is the number of pegs of the right color but wrong position.
"""
blacks = sum(g ==... | bab57da2d7c60869988d6c24b69b8eab1c7da173 | 3,649,821 |
import os
import logging
import functools
def Logging(logfile=None):
"""Custom logging function.
Args:
logfile: The name of log files. Log will be stored in logs_dir.
Returns:
The same output of the call function with logging information.
"""
# Create logs_dir if the dire... | cbb89ce22a2f1d8234dcb30430fd2f9a80421a5c | 3,649,822 |
from datetime import date
from .models import PlacedDateBet
def find_winning_dates(placed_bets, winning_date):
"""
Finds the placed bets with the dates closest to the winning date
:param placed_bets: iterable of PlacedDateBet
:param winning_date: datetime.date
:return: list of winning PlacedDateBe... | 73315f2bebfcc0290f9372af935ded78011c7d4b | 3,649,823 |
def create_greedy_policy(Q):
"""
Creates a greedy policy based on Q values.
Args:
Q: A dictionary that maps from state -> action values
Returns:
A function that takes an observation as input and returns a vector
of action probabilities.
"""
def policy_fn(observation):
... | 01966964034504454e3be9926236706371c626c8 | 3,649,824 |
def get_tags(rule, method, **options):
"""
gets the valid tags for given rule.
:param pyrin.api.router.handlers.base.RouteBase rule: rule instance to be processed.
:param str method: http method name.
:rtype: list[str]
"""
return get_component(SwaggerPackage.COMPONENT_NAME).get_tags(rule,... | 4671d1d9c66934d6b22bee74801d07b30635b3b6 | 3,649,825 |
def get_paybc_transaction_request():
"""Return a stub payment transaction request."""
return {
'clientSystemUrl': 'http://localhost:8080/abcd',
'payReturnUrl': 'http://localhost:8081/xyz'
} | b913438562d4f2b0883e340b48843f9954faa8a4 | 3,649,826 |
def dropout_forward(x, dropout_param):
"""
Performs the forward pass for (inverted) dropout.
Inputs:
- x: Input data, of any shape
- dropout_param: A dictionary with the following keys:
- p: Dropout parameter. We drop each neuron output with probability p.
- mode: 'test' or 'train'. If the mode is tr... | 4d4442ab5e612888628f43574e60b53342873d83 | 3,649,827 |
def pretreatment(filename):
"""pretreatment"""
poems = []
file = open(filename, "r")
for line in file: #every line is a poem
#print(line)
title, poem = line.strip().split(":") #get title and poem
poem = poem.replace(' ','')
if '_' in poem or '《' in poem or '[' in poem o... | 5aa85b3bda72d3efb3067ebcc06d7f4038d9990e | 3,649,828 |
def forward_fdm(order, deriv, adapt=1, **kw_args):
"""Construct a forward finite difference method.
Further takes in keyword arguments of the constructor of :class:`.fdm.FDM`.
Args:
order (int): Order of the method.
deriv (int): Order of the derivative to estimate.
adapt (int, opti... | 7b5c46fcdfc1a186079b2a4f94a129b8f79dbfde | 3,649,829 |
import torch
def lrp_linear_torch(hin, w, b, hout, Rout, bias_nb_units, eps, bias_factor=0.0, debug=False):
"""
LRP for a linear layer with input dim D and output dim M.
Args:
- hin: forward pass input, of shape (D,)
- w: connection weights, of shape (D, M)
- b: ... | 1939ef92f3c06a79148e41397f0a3668b273d716 | 3,649,830 |
import requests
def get_list_by_ingredient(ingredient):
""" this should return data for filtered recipes by ingredient """
res = requests.get(f'{API_URL}/{API_KEY}/filter.php', params={"i":ingredient})
return res.json() | 5bb34ffe635499a93decc5d4c080c638ee92c1b5 | 3,649,831 |
def chk_sudo():
"""\
Type: decorator.
The command will only be able to be executed by the author if the author is owner or have permissions.
"""
async def predicate(ctx):
if is_sudoers(ctx.author):
return True
await ctx.message.add_reaction("🛑")
raise excepts.Not... | 45ddad31e761c9cf227a19fb78e3b3f52414c966 | 3,649,832 |
def have_same_items(list1, list2):
""" Проверяет состоят ли массивы list1 и list2 из одинакового
числа одних и тех же элементов
Parameters
----------
list1 : list[int]
отсортированный по возрастанию массив уникальных элементов
list2 : list[int]
массив... | 2973a1961e25686fcbd2003dd366429cbd4c67eb | 3,649,833 |
def analyze(geometry_filenames, mode='global', training_info=None, stride=None,
box_size=None, configs=None, descriptor=None, model=None,
format_=None, descriptors=None, save_descriptors=False,
save_path_descriptors=None, nb_jobs=-1, **kwargs):
"""
Apply ARISE to given list ... | eeec9ac33a91b41b8a90f825aef0fc7605bdbf58 | 3,649,834 |
def get_params(name, seed):
"""Some default parameters.
Note that this will initially include training parameters that you won't need for metalearning since we have our own training loop."""
configs = []
overrides = {}
overrides["dataset_reader"] = {"lazy": True}
configs.append(Params(override... | 02d70be07a2d7afe793e657d6fb38fefe99171ce | 3,649,835 |
def rgb2hex(rgb):
"""Converts an RGB 3-tuple to a hexadeximal color string.
EXAMPLE
-------
>>> rgb2hex((0,0,255))
'#0000FF'
"""
return ('#%02x%02x%02x' % tuple(rgb)).upper() | 4c3323e34fcd2c1b4402ebe5f433c5fd9320cce9 | 3,649,836 |
from typing import Union
import re
from typing import Optional
def path_regex(
path_regex: Union[str, re.Pattern], *, disable_stage_removal: Optional[bool] = False
):
"""Validate the path in the event against the given path pattern.
The following APIErrorResponse subclasses are used:
PathNotFound... | 5c54d71a20fa7795b9e6eefa508de5b8516378a6 | 3,649,837 |
async def root():
"""Health check"""
return {"status": "OK"} | 80c3c7ff9e1abebbb9f38dc11a5ecd5a7fe5414a | 3,649,838 |
from typing import Dict
from typing import List
def build_foreign_keys(
resources: Dict[str, dict],
prune: bool = True,
) -> Dict[str, List[dict]]:
"""Build foreign keys for each resource.
A resource's `foreign_key_rules` (if present) determines which other resources will
be assigned a foreign ke... | 96cb032a03445400eeee57a23a4024ae06f62573 | 3,649,839 |
import ipaddress
def port_scan(ip):
"""Run a scan to determine what services are responding.
Returns nmap output in JSON format.
"""
# validate input
valid_ip = ipaddress.ip_address(ip)
# nnap requires a `-6` option if the target is IPv6
v6_flag = '-6 ' if valid_ip.version == 6 else ''
... | c33cd56635338d3476e4ce5348376a1f6b2cfd68 | 3,649,840 |
def create_table(p, table_name, schema):
"""Create a new Prism table.
Parameters
----------
p : Prism
Instantiated Prism class from prism.Prism()
table_name : str
The name of the table to obtain details about. If the default value
of None is specified, details regarding fir... | 43c8c789d4e212d2d98d68f4f22e3f0fb0a97552 | 3,649,841 |
def get_args():
"""
Parses and processes args, returning the modified arguments as a dict.
This is to maintain backwards compatibility with the old of parsing
arguments.
"""
parser = make_parser()
args = parser.parse_args()
process_args(args)
return vars(args) | 8a6f31bd0c9547a007bdd7644d148e8ba0e126d1 | 3,649,842 |
from typing import Iterable
def run_asm_pprinter(ir: gtirb.IR, args: Iterable[str] = ()) -> str:
"""
Runs the pretty-printer to generate an assembly output.
:param ir: The IR object to print.
:param args: Any additional arguments for the pretty printer.
:returns: The assembly string.
"""
a... | 8d71a4b91f90cb449f65d5c95ec740d78836a071 | 3,649,843 |
import re
def fix_ccdsec(hdu):
""" Fix CCDSEC keywords in image extensions """
section_regexp = re.compile(SECTION_STRING)
# In unbinned space
ccdsec = _get_key_value(hdu, 'CCDSEC')
detsec = _get_key_value(hdu, 'DETSEC')
if None in [ccdsec, detsec]:
raise ValueError("CCDSEC {}; detse... | 1ce3e7e519f47f63f8894c3a29e269ca77d7cf5d | 3,649,844 |
def reload(hdf):
"""Reload a hdf file, hdf = reload(hdf)"""
filename = hdf.filename
return load(filename) | 6eb17d171b1181ac4ed974de6c36f83c00e72c57 | 3,649,845 |
def read_image(im_name, n_channel, data_dir='', batch_size=1, rescale=None):
""" function for create a Dataflow for reading images from a folder
This function returns a Dataflow object for images with file
name containing 'im_name' in directory 'data_dir'.
Args:
im_name (str): ... | 017878c8afce1be73160b338407a920c4f01a286 | 3,649,846 |
def build_optimizer(config, model):
"""
Build optimizer, set weight decay of normalization to 0 by default.
"""
skip = {}
skip_keywords = {}
if hasattr(model, 'no_weight_decay'):
skip = model.no_weight_decay()
if hasattr(model, 'no_weight_decay_keywords'):
skip_keywords = mod... | 83a09ed34c24caff7367ba1e43e051f362dfa85c | 3,649,847 |
def ising2d_worm(T_range, mcsteps, L):
"""T = temperature [K]; L = Length of grid."""
def new_head_position(worm, lattice):
"""
Extract current worm head position indices,
then randomly set new worm head position index.
lattice.occupied points to either lattice.bonds_x or latti... | 6fba36aceb70f19605e20a460db7054b81264224 | 3,649,848 |
def valid_chapter_name(chapter_name):
"""
判断目录名称是否合理
Args:
chapter_name ([type]): [description]
"""
for each in ["目录"]:
if each in chapter_name:
return False
return True | 9ec71837503f969808a6a666a3bf999ee3290f03 | 3,649,849 |
from typing import Iterable
from typing import Tuple
def lex_min(perms: Iterable[Perm]) -> Tuple[Perm, ...]:
"""Find the lexicographical minimum of the sets of all symmetries."""
return min(all_symmetry_sets(perms)) | 4cbb7e78de32c46684c9e621db90708934bb5e33 | 3,649,850 |
def subfield(string, delim, occurrence):
"""
function to extract specified occurence of subfield from string
using specified field delimiter
eg select subfield('abc/123/xyz','/',0) returns 'abc'
eg select subfield('abc/123/xyz','/',1) returns '123'
eg select subfield('abc/123/xyz','/',2) retu... | ef022d0ca05e969e8ad69e4644cd24d1b7f47cb8 | 3,649,851 |
def in_hull(points, hull):
"""
Test if points in `p` are in `hull`
`p` should be a `NxK` coordinates of `N` points in `K` dimensions
`hull` is either a scipy.spatial.Delaunay object or the `MxK` array of the
coordinates of `M` points in `K`dimensions for which Delaunay triangulation
will be computed
"""
... | ab116c17b42c26648b02930824dd0ae591b32eef | 3,649,852 |
def sample_random(X_all, N):
"""Given an array of (x,t) points, sample N points from this."""
set_seed(0) # this can be fixed for all N_f
idx = np.random.choice(X_all.shape[0], N, replace=False)
X_sampled = X_all[idx, :]
return X_sampled | b2297c13cf7cf40dcdf82ea97e2029a96d7554ef | 3,649,853 |
from typing import Optional
def read(db,
query: Optional[dict] = None,
pql: any = None,
order_by: Optional[str] = None,
limit: Optional[int] = None,
offset: Optional[int] = None,
disable_count_total: bool = False,
**kwargs):
"""Read data from DB.
... | b2153ce1b83de7f3f7dd5311a619a0623aedc01b | 3,649,854 |
def check_horizontal(board: list) -> bool:
"""
Function check if in each line are unique elements.
It there are function return True. False otherwise.
>>> check_horizontal(["**** ****",\
"***1 ****",\
"** 3****",\
"* 4 1****"... | 0769f0821637c78c1a18e387eb64d6234a0ced5c | 3,649,855 |
import os
def IsDir(msg=None):
"""Verify the directory exists."""
def f(v):
if os.path.isdir(v):
return v
else:
raise Invalid(msg or 'not a directory')
return f | 415e5c8f5a3f1414640fa298b07b5cb64b0293d4 | 3,649,856 |
import math
def update_events(dt: float, pos_x: float, pos_y: float, dir_x: float, dir_y: float, plane_x: float, plane_y: float):
""" Updates player position in response to user input.
"""
for e in pygame.event.get():
if e.type == pygame.KEYDOWN:
if e.key == pygame.K_ESCAPE:
... | e43cc7a2e6ab3f35637bf4ab37baefed96279656 | 3,649,857 |
def deg_to_xyz(lat_deg, lon_deg, altitude):
"""
http://www.oc.nps.edu/oc2902w/coord/geodesy.js
lat,lon,altitude to xyz vector
input:
lat_deg geodetic latitude in deg
lon_deg longitude in deg
altitude altitude in km
output:
returns vector x 3 long ECEF in... | 0493132eb0658026727d7a292862fcf2d5d6d48b | 3,649,858 |
def remove_unused_colours(ip, line_colours):
"""
>>> remove_unused_colours(np.array([[0,0,3], [1,5,1], [2,0,6], [2,2,2],[4,4,0]]), {2, 4})
array([[0, 0, 0],
[0, 0, 0],
[2, 0, 0],
[2, 2, 2],
[4, 4, 0]])
"""
#get a list of all unique colours
all_colours... | 7e80cbb2e3e9ac86da4cf7d6e99a6d9bf2edeead | 3,649,859 |
def extract_info(spec):
"""Extract information from the instance SPEC."""
info = {}
info['name'] = spec.get('InstanceTypeId')
info['cpu'] = spec.get('CpuCoreCount')
info['memory'] = spec.get('MemorySize')
info['nic_count'] = spec.get('EniQuantity')
info['disk_quantity'] = spec.get('DiskQuan... | 7f93dcad1a8d99743a30d441dad64c2b9af08037 | 3,649,860 |
def sum_values(**d):
# doc string 예제. git commit 메시지 쓰듯이 쓰면 된다
"""dict의 values를 더한 값을 리턴
key는 뭐가 들어오던지 말던지 신경 안 쓴다.
"""
return sum_func(*d.values()) | 29b90a04760376d2b8f6844994a7341fa742f05d | 3,649,861 |
def parse_title(title):
"""Parse strings from lineageos json
:param title: format should be `code - brand phone`
"""
split_datum = title.split(' - ')
split_name = split_datum[1].split(' ')
device = split_datum[0]
brand = split_name[0]
name = ' '.join(split_name[1:])
return [brand,... | c3783ab36f4f7e021bdd5f0f781bb289ab2d458f | 3,649,862 |
def addCountersTransactions(b):
"""Step 2 : The above list with count as the last element should be
[
[1, 1, 0, 1],
[0, 0, 0, 4],
[1, 1, 1, 3]
]
converted to the following way
[
[1, 1, 0, 1, 0],
[1, 1, 1, 3, 4]
]
with cnt 1 and cnt 2 for anti-mirroring tec... | 44fb81280fc7540c796e6f8308219147993c6b7a | 3,649,863 |
import typing
import torch
def aggregate_layers(
hidden_states: dict, mode: typing.Union[str, typing.Callable]
) -> np.ndarray:
"""Input a hidden states dictionary (key = layer, value = 2D array of n_tokens x emb_dim)
Args:
hidden_states (dict): key = layer (int), value = 2D PyTorch tensor of sha... | 21c91a4c031c561b6776a604aa653c3880d69b15 | 3,649,864 |
def get_bg_stat_info(int_faces, adj_list, face_inds, face_inds_new):
"""
Out put list of faces and list of verts for each stat.
"""
stat_faces = []
stat_verts = []
for k in range(len(int_faces)):
# Check if face already exists.
if int_faces[k] != 0:
continue
... | 262130ffcb4fe474ece01ed6a63705efdaac360c | 3,649,865 |
import socket
import sys
def _build_server_data():
"""
Returns a dictionary containing information about the server environment.
"""
# server environment
server_data = {
'host': socket.gethostname(),
'argv': sys.argv
}
for key in ['branch', 'root']:
if SETTINGS.get... | 55eda8203b527952aea8f8682b980d7c3cb12ce5 | 3,649,866 |
def config_data() -> dict:
"""Dummy config data."""
return {
"rabbit_connection": {
"user": "guest",
"passwd": "guest",
"host": "localhost",
"port": 5672,
"vhost": "/",
},
"queues": {"my_queue": {"settings": {"durable": True}, "... | cbbed3baf79b5928be47d3d00c747ac6be625ae5 | 3,649,867 |
def copy_linear(net, net_old_dict):
"""
Copy linear layers stored within net_old_dict to net.
"""
net.linear.weight.data = net_old_dict["linears.0.weight"].data
net.linear.bias.data = net_old_dict["linears.0.bias"].data
return net | 8ba7f40e72b65ebef9948025b3404cbc5a660960 | 3,649,868 |
async def read_book(request: Request) -> dict:
"""Read single book."""
data = await request.json()
query = readers_books.insert().values(**data)
last_record_id = await database.execute(query)
return {"id": last_record_id} | e2ec15df60e2e8a5974c16688a9e5caa8c4452d8 | 3,649,869 |
def setup_dev():
"""Runs the set-up needed for local development."""
return setup_general() | 889153114ffecd74c50530e867a03128279fc26f | 3,649,870 |
def countAllAnnotationLines(
mpqa_dir="mpqa_dataprocessing\\database.mpqa.cleaned", doclist_filename='doclist.2.0'
):
"""
It counts all annotation lines available in all documents of a corpus.
:return: an integer
"""
m2d = mpqa2_to_dict(mpqa_dir=mpqa_dir)
mpqadict = m2d.corpus_to_dict(doclis... | 2a1c981db125db163e072eb495144be2b004a096 | 3,649,871 |
def convergence(report: Report, **kwargs):
"""
Function that displays the convergence using a antco.report.Report object.
Parameters
----------
report: antco.report.Report
antco.report.Report instance returned by the antco.run() function.
**kwargs
figsize: tuple, default=(8, 5)... | 523e64b68d88d705f22a5c31faecee51e5e59b2d | 3,649,872 |
def scene():
""" Check that the scene is valid for submission and creates a report """
xrs.validation_report.new_report()
valid = True
# Start by getting into object mode with nothing selected
bpy.ops.object.mode_set(mode="OBJECT")
bpy.ops.object.select_all(action='DESELECT')
if (xrs.collection.collecti... | 6885509d95868c64666d63d9f0daa738e6a40269 | 3,649,873 |
def ca_set_container_policies(h_session, h_container, policies):
"""
Set multiple container policies.
:param int h_session: Session handle
:param h_container: target container handle
:param policies: dict of policy ID ints and value ints
:return: result code
"""
h_sess = CK_SESSION_HAND... | b4c56108d137d8caa6fa65f6ffcfd8c649af1840 | 3,649,874 |
def run_trial(benchmark):
"""Runs the benchmark once and returns the elapsed time."""
args = ['.build/debug/slox', join('test', 'benchmark', benchmark + '.lox')]
proc = Popen(args, stdin=PIPE, stdout=PIPE, stderr=PIPE)
out, err = proc.communicate()
out = out.decode("utf-8").replace('\r\n', '\n')
# Remove... | 6c92e09134d4e12a022a5a7ae4bb4951f878be37 | 3,649,875 |
def extend(arr, num=1, log=True, append=False):
"""Extend the given array by extraplation.
Arguments
---------
arr <flt>[N] : array to extend
num <int> : number of points to add (on each side, if ``both``)
log <bool> : extrapolate in log-space
append <bool> :... | e5f8b7fea74b1a92dba19aed527be1c823c058f9 | 3,649,876 |
import sys
import logging
import os
def to_relative(path, root, relative):
"""Converts any absolute path to a relative path, only if under root."""
if sys.platform == 'win32':
path = path.lower()
root = root.lower()
relative = relative.lower()
if path.startswith(root):
logging.info('%s starts wi... | 50911c6cec942e9be0d694f95213053e23d2707a | 3,649,877 |
def do_associate_favorite(parser, token):
"""
@object - object to return the favorite count for
"""
try:
tag, node, user = token.split_contents()
except ValueError:
raise template.TemplateSyntaxError, "%r tag requires one argument" % token.contents.split()[0]
return AssociateFa... | 90ed604936a0b7639adf356911a803ae755a9653 | 3,649,878 |
from typing import Type
from pydantic import BaseModel # noqa: E0611
from typing import Tuple
from typing import List
def parse_cookie(cookie: Type[BaseModel]) -> Tuple[List[Parameter], dict]:
"""Parse cookie model"""
schema = get_schema(cookie)
parameters = []
components_schemas = dict()
propert... | 797c876676b1e002b4e54a7943f77301ed82efb1 | 3,649,879 |
def bdev_nvme_add_error_injection(client, name, opc, cmd_type, do_not_submit, timeout_in_us,
err_count, sct, sc):
"""Add error injection
Args:
name: Name of the operating NVMe controller
opc: Opcode of the NVMe command
cmd_type: Type of NVMe command. Va... | 3833256e71f47a49eef2643bf8c244308795a0b1 | 3,649,880 |
def tetheredYN(L0, KxStar, Rtot, Kav, fully=True):
""" Compare tethered (bispecific) vs monovalent """
if fully:
return polyc(L0, KxStar, Rtot, [[1, 1]], [1.0], Kav)[2][0] / \
polyfc(L0 * 2, KxStar, 1, Rtot, [0.5, 0.5], Kav)[0]
else:
return polyc(L0, KxStar, Rtot, [[1, 1]], [1.0... | a8a4be3c7b217164d690eed29eb8ab1acca45e05 | 3,649,881 |
def valid_payload(request):
"""
Fixture that yields valid data payload values.
"""
return request.param | 0c02e52a02b9089e4832ccf2e9c37fc2d355e893 | 3,649,882 |
import os
def lookup_content(path, source_id):
"""
Look for a filename in the form of:
ARCHIVE_SOURCEID.[extension]
"""
content_filename = None
files = [f for f in os.listdir(path) if not f.endswith(".xml")]
for f in files:
tokens = os.path.splitext(f)[0].split("_")
if len(... | f356a3d522a5c79f615c20b46cc9a3738b211417 | 3,649,883 |
import os
import time
import signal
def external(pgm, inp, out, cor, tim=5):
"""
The external checker is used to check for outputs using an external
program that reads the input and the generated output and writes
to stdout the veredict. If the program runs for more than tim seconds,
... | 17ca353623b5094ac9158671cefcb82e7a44c235 | 3,649,884 |
def prune_deg_one_nodes(sampled_graph):
""" prune out degree one nodes from graph """
deg_one_nodes = []
for v in sampled_graph.nodes():
if sampled_graph.degree(v) == 1:
deg_one_nodes.append(v)
for v in deg_one_nodes:
sampled_graph.remove_node(v)
return sampled_graph | c4df72a66c6fb57d5d42a1b877a846338f32f42a | 3,649,885 |
def reduce_clauses(clauses):
"""
Reduce a clause set by eliminating redundant clauses
"""
used = []
unexplored = clauses
while unexplored:
cl, unexplored = unexplored[0], unexplored[1:]
if not subsume(used, cl) and not subsume(unexplored,cl):
used.append(cl)
return ... | d28fc08f214a04aac433827560251143204fa290 | 3,649,886 |
import os
def get_pretrained_t2v(name, model_dir=MODEL_DIR):
"""
It is a good idea if you want to switch token list to vector earily.
Parameters
----------
name:str
select the pretrained model
e.g.:
d2v_all_256,
d2v_sci_256,
d2v_eng_256,
d2v_lit_256... | 369def1a01a5ffa132db484a3340de2738f4b6c9 | 3,649,887 |
import numpy as np
def get_np_io(arr, **kwargs) -> BytesIO:
"""Get the numpy object as bytes.
:param arr: Array-like
:param kwargs: Additional kwargs to pass to :func:`numpy.save`.
:return: A bytes object that can be used as a file.
"""
bio = BytesIO()
np.save(bio, arr, **kwargs)
bio... | 278a452dc97d8ca74398771bd34545c7505c191f | 3,649,888 |
from typing import Mapping
def get_deep_attr(obj, keys):
""" Helper for DeepKey"""
cur = obj
for k in keys:
if isinstance(cur, Mapping) and k in cur:
cur = cur[k]
continue
else:
try:
cur = getattr(cur, k)
continue
... | f7e3af73c2e45a5448e882136811b6898cc45e29 | 3,649,889 |
def fork_node_item_inline_editor(item, view, pos=None) -> bool:
"""Text edit support for Named items."""
@transactional
def update_text(text):
item.subject.joinSpec = text
return True
def escape():
item.subject.joinSpec = join_spec
subject = item.subject
if not subject... | 7c4b0bdbe321bab427e22440e7225539262806f2 | 3,649,890 |
def get_selfies_alphabet(smiles_list):
"""Returns a sorted list of all SELFIES tokens required to build a
SELFIES string for each molecule."""
selfies_list = list(map(sf.encoder, smiles_list))
all_selfies_symbols = sf.get_alphabet_from_selfies(selfies_list)
all_selfies_symbols.add('[nop]')
self... | f18206e0c4c03ab75db3efd693655a1a1cacb9e2 | 3,649,891 |
import datasets
import random
def get_face_angular_dataloader(dataset_path, input_size, batch_size, num_workers, train_portion=1):
""" Prepare dataset for training and evaluating pipeline
Args:
dataset_path (str)
input_size (int)
batch_size (int)
num_workers (int)
trai... | 5aa6d62c98ca942e79bbfaca192b11353a0a2fe1 | 3,649,892 |
def compile_sql_numericize(element, compiler, **kw):
"""
Turn common number formatting into a number. use metric abbreviations, remove stuff like $, etc.
"""
arg, = list(element.clauses)
def sql_only_numeric(text):
# Returns substring of numeric values only (-, ., numbers, scientific notati... | ef8631e98cd74b276ad00731c75a5c1c907eb303 | 3,649,893 |
def run_sgd(model, epochs):
"""
Runs SGD for a predefined number of epochs and saves the resulting model.
"""
print("Training full network")
weights_rand_init = model.optimize(epochs=epochs)
# weights_rand_init = model.optimize(epochs=epochs, batch_size=55000, learning_rate=0.1)
print("M... | 14c6fd1ffa8aab3a783b5738093d69771d036411 | 3,649,894 |
def get_all_outcome_links_for_context_courses(request_ctx, course_id, outcome_style=None, outcome_group_style=None, per_page=None, **request_kwargs):
"""
:param request_ctx: The request context
:type request_ctx: :class:RequestContext
:param course_id: (required) ID
:type course_id:... | 78026eff6aef5a486d920a888d4dfdabc94bfc00 | 3,649,895 |
def GetContentResourceSpec():
"""Gets Content resource spec."""
return concepts.ResourceSpec(
'dataplex.projects.locations.lakes.content',
resource_name='content',
projectsId=concepts.DEFAULT_PROJECT_ATTRIBUTE_CONFIG,
locationsId=LocationAttributeConfig(),
lakesId=LakeAttributeConfig()... | 434cb149fdeff6154928a4514d1f6241d44c85a7 | 3,649,896 |
from typing import Optional
def softplus(
x: oneflow._oneflow_internal.BlobDesc, name: Optional[str] = None
) -> oneflow._oneflow_internal.BlobDesc:
"""This operator computes the softplus value of Blob.
The equation is:
.. math::
out = log(e^x+1)
Args:
x (oneflow._oneflow_inter... | 2bef1db640e0e5b3e9971b1d9b4fbe23e4eba808 | 3,649,897 |
from typing import Tuple
from typing import List
def diff_gcs_directories(
base_directory_url: str, target_directory_url: str
) -> Tuple[List[str], List[str], List[str]]:
"""
Compare objects under different GCS prefixes.
:param base_directory_url: URL for base directory
:param target_directory_ur... | 1e7727fb352d320c79de16d6efdd6f46120e89d7 | 3,649,898 |
from typing import List
def load_compatible_apps(file_name: str) -> List[Product]:
"""Loads from file and from github and merges results"""
local_list = load_installable_apps_from_file(file_name)
try:
github_list = load_compatible_apps_from_github()
except (URLError, IOError):
github_... | efbde4a2c2f4589bc73497017d89631e0333081c | 3,649,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.