content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def auc(y, z, round=True):
"""Compute area under the ROC curve."""
if round:
y = y.round()
if len(y) == 0 or len(np.unique(y)) < 2:
return np.nan
return skm.roc_auc_score(y, z) | 2,300 |
def test_die_init() -> None:
"""tests the use of a single die"""
die = Die()
assert die.sides == 6
assert die.max == 6
assert die.min == 1
assert die.rolls == 0
assert die.net_sides == die.sides
assert str(die) == "<d6 Die>"
assert repr(die) == "<d6 Die>"
assert not die > die
... | 2,301 |
def get_routing_attributes(obj, modify_doc=False, keys=None):
"""
Loops through the provided object (using the dir() function) and
finds any callables which match the name signature (e.g.
get_foo()) AND has a docstring beginning with a path-like char
string.
This does process things in alphabeti... | 2,302 |
def copy_jce_policy_files(cluster):
"""" Copy JCE unlimited strength policy files to all nodes. """
source_folder = cluster.get_config(KEY_JCE_POLICY_FILES_LOCATION)
if not source_folder:
raise KerberosConfigError(
'The location of JCE Unlimited Strength Policy files was not found in {}'... | 2,303 |
def get_tmp_filepath(_file):
"""生成一个针对_file的临时文件名"""
_path = os.path.dirname(_file)
_tmp_filename = os.path.basename(_file)
if not _tmp_filename.startswith('.'):
_tmp_filename = '.' + _tmp_filename
_tmp_filename += '_tmp'
_tmp_filepath = os.path.join(_path, _tmp_filename)
if os.... | 2,304 |
def upperLeftOrigin( largeSize, smallSize ):
"""
The upper left coordinate (tuple) of a small rectangle in a larger rectangle (centered)
"""
origin = tuple( map( lambda x: int( ( (x[0]-x[1])/2 ) ), zip( largeSize, smallSize )) )
return origin | 2,305 |
def get_supported_events():
"""Returns the list of available _local_ templates.
If a template exists in the local app, it will take precedence
over the default trello_webhooks template. The base assumption
for this function is that _if_ a local template exists, then this
is an event we are interest... | 2,306 |
def test_unwrap_spans() -> None:
"""It unwraps span.pre elements."""
tree = parse_html("<span class='pre'>Test</span>")
postprocess._remove_span_pre(tree)
span = tree("span")
assert len(span) == 0
assert str(tree) == "Test" | 2,307 |
def from_ext(ext: str) -> S:
"""Get a SignedObject by file extension."""
object_types: typing.List[S] = [RpkiGhostbusters,
RpkiManifest,
RouteOriginAttestation]
entry_point_name = "rpkimancer.sigobj"
entry_points = importlib.metadat... | 2,308 |
def plot_audio(audio,time,ResultPath,title):
"""Plot and save an audio file amplitude over time"""
plt.figure()
plt.plot(time,audio, linewidth=0.01)
plt.ylabel("Amplitude")
plt.xlabel("Time (s)")
plt.title(title)
pathname=ResultPath + title
plt.savefig(pathname)
plt.show()
... | 2,309 |
def dataSet():
"""
测试数据集
"""
x = [np.array([[1], [2], [3]]),
np.array([[2], [3], [4]])]
d = np.array([[1], [2]])
return x, d | 2,310 |
def config():
"""
Get the OpenAPI Document configuration
:returns: OpenAPI configuration YAML dict
"""
with open(get_test_file_path('pygeoapi-test-openapi-config.yml')) as config_file: # noqa
return yaml_load(config_file) | 2,311 |
def save_data(df, database_filename):
"""Saves Data into Database
Args:
df: cleaned dataframe
database_filename: database file name
"""
engine = create_engine('sqlite:///' + database_filename)
df.to_sql('Disasters', engine, if_exists='replace',index=False) | 2,312 |
def convert_broadcast_lesser(node, **kwargs):
"""Map MXNet's broadcast_lesser operator attributes to onnx's Less operator
and return the created node.
"""
return create_basic_op_node('Less', node, kwargs) | 2,313 |
def main(mt_input: str, panelapp_path: str, config_path: str, out_vcf: str):
"""
Read the MT from disk
Do filtering and class annotation
Export as a VCF
:param mt_input: path to the MT directory
:param panelapp_path: path to the panelapp data dump
:param config_path: path to the config json... | 2,314 |
def test_simulator_setup_space_quoted():
"""run_and_pytest() parses quoted --setup TEXT argument."""
command = (
'phmdoctest doc/setup.md --setup "import math" --teardown LAST'
" --report --outfile discarded.py"
)
simulator_status = phmdoctest.simulator.run_and_pytest(
well_forme... | 2,315 |
def sliding_window(image, step_size, window_size):
"""给定一副图像,返回一个从左向右滑动的窗口,直至覆盖整个图像"""
for y in range(0, image.shape[0], step_size):
for x in range(0, image.shape[1], step_size):
yield (x, y, image[y:y + window_size[1], x:x + window_size[0]]) | 2,316 |
def check_federated_type(
type_spec: computation_types.Type,
member: Optional[computation_types.Type] = None,
placement: Optional[placement_literals.PlacementLiteral] = None,
all_equal: Optional[bool] = None):
"""Checks that `type_spec` is a federated type with the given parameters.
Args:
type_... | 2,317 |
def randomize_examples(verbalize, path='prompts/',example_filenames="example_" , n_examples=3, onlyverbal=False):
"""
Randomizes the examples for the initial prompt.
Parameters
----------
verbalize : bool
If true, examples contain reasoning for the answer, e.g. "because I do not believe in... | 2,318 |
def histogram2d(x, y, bins_x, bins_y):
"""Histogram 2d between two continuous row vectors.
Parameters
----------
x : array_like
Vector array of shape (N,) and of type np.float32
y : array_like
Vector array of shape (N,) and of type np.float32
bins_x, bins_y : int64
Numbe... | 2,319 |
def xy2latlong(x: float, y: float, ds: Any) -> Tuple[float, float]:
"""Return lat long coordinate by x, y
>>> import gdal
>>> path = "../../../tests/data/raster_for_test.tif"
>>> ds = gdal.Open(path)
>>> xy2latlong(3715171, 2909857, ds)
(1.7036231518576481, 48.994284431891565)
"""
old_c... | 2,320 |
def relative_date(r='12m', end_date='today', date_format='%Y-%m-%d',
as_string=False, unixtimestamp=False):
"""
Relative Date function
Calculates a datetime from a given end date and a relative reference.
INPUT:
r - relative date reference as '-12d' accepts d, w, m or... | 2,321 |
def get_iexist_vdw_bond(ipt):
"""
check if a given mol pair contain any vdw bond, which exists
in the query mol. Note that input mol pairs must have cc=0.
"""
obj, mi, mj = ipt
iok = F
if np.any( [ set(b) <= set(mi.iasq+mj.iasq) for b in obj.ncbs ] ):
iok = T
return iok | 2,322 |
def getSVG(shape, opts=None, view_vector=(-0, 0, 20.0)):
"""
Export a shape to SVG
"""
d = {"width": 800, "height": 800, "marginLeft": 20, "marginTop": 20}
if opts:
d.update(opts)
# need to guess the scale and the coordinate center
uom = guessUnitOfMeasure(shape)
width = ... | 2,323 |
def test_process(ase3_code):
"""Test running a calculation
note this does not test that the expected outputs are created of output parsing"""
# Prepare input parameters
Ase3Parameters = DataFactory('ase3')
input_file = SinglefileData(
file=os.path.join(TEST_DIR, 'input_files', 'run_gpaw.py... | 2,324 |
def load_data(messages_filepath, categories_filepath):
"""Loads messages and categories data and creates a merged dataframe
Args:
messages_filepath (str): Path to the messages file
categories_filepath (str): Path to the categories file
Returns:
(pd.DataFrame): A messages and catego... | 2,325 |
def is_square_inside(row, col, rows, cols):
"""Check if row and col is square inside grid having rows and cols."""
return row not in (0, rows - 1) and col not in (0, cols - 1) | 2,326 |
def demo(ks=(1, 2, 3, 4), N=20, azimuths=(0, 20), elevations=(90, 30), colors=get_colors(), verbose=True, savefig=False,
showfig=True, elements=True):
"""
:param tuple ks : Orders of the Enneper surface
:param int N : Resolution of each plot
:param tuple azimuths : Azimuths fo... | 2,327 |
def reshapeLabel(label):
"""
Reshape 1-D [0,1,...] to 2-D [[1,-1],[-1,1],...].
"""
n = label.size(0)
y = FloatTensor(n, 2)
y[:, 0] = 2 * (0.5 - label)
y[:, 1] = - y[:, 0]
return y.long() | 2,328 |
def _coo_scipy2torch(adj, coalesce=True, use_cuda=False):
"""
convert a scipy sparse COO matrix to torch
"""
values = adj.data
indices = np.vstack((adj.row, adj.col))
i = torch.LongTensor(indices)
v = torch.FloatTensor(values)
ans = torch.sparse.FloatTensor(i, v, torch.Size(adj.s... | 2,329 |
def behavior_by_delta_temp(db_dict: dict, bins: np.ndarray):
"""
Computes frequency of behavior by delta-temperature achieved during the preceding bout
:param db_dict: Debug dictionary created during simulation run
:param bins: The bin-edges for dividing the bout delta temperature space
:return: A d... | 2,330 |
def _gen_efficientnet(channel_multiplier=1.0, depth_multiplier=1.0, num_classes=1000, **kwargs):
"""Creates an EfficientNet model.
Ref impl: https://github.com/tensorflow/tpu/blob/master/models/official/efficientnet/efficientnet_model.py
Paper: https://arxiv.org/abs/1905.11946
EfficientNet params
... | 2,331 |
def test_rescan_file(test_microvm_with_ssh, network_config):
"""Verify that rescan works with a file-backed virtio device."""
test_microvm = test_microvm_with_ssh
test_microvm.spawn()
# Set up the microVM with 1 vCPUs, 256 MiB of RAM, 0 network ifaces and
# a root file system with the rw permission... | 2,332 |
def do_add_application_type(request):
"""定义
dict_class=models.CharField(u"字典类别",max_length=255)
dict_type=models.CharField(u"字典类型",max_length=255)
dict_name=models.CharField(u"字典名称",max_length=255)
dict_value=models.CharField(u"字典值",max_length=255)
dict_status=models.IntegerField(u"字典状态")
di... | 2,333 |
def setup_app(command, conf, vars):
"""Place any commands to setup axantaddressbook here"""
conf = base_config.configure(conf.global_conf, conf.local_conf)
base_config.setup(conf)
setup_schema(command, conf, vars)
bootstrap(command, conf, vars) | 2,334 |
def eval_single_grid_node(iden, counter, phases, maxiter, start_index):
"""
Evaluating randomly generated spotty single system model.
:param iden: str; node ID
:param counter: int; current number of already calculeted nodes
:param phases: numpy.array; desired phases of observations
:param maxit... | 2,335 |
def assert_data_frame_almost_equal(left, right):
"""Raise AssertionError if ``pd.DataFrame`` objects are not "almost equal".
Wrapper of ``pd.util.testing.assert_frame_equal``. Floating point values
are considered "almost equal" if they are within a threshold defined by
``assert_frame_equal``. This wrap... | 2,336 |
def exponential_decay_function(distance: np.ndarray) -> np.ndarray:
"""Calculate exponential discount factor for action interaction weight matrix.
Parameters
-----------
distance: array-like, shape (len_list, )
Distance between two slots.
"""
if not isinstance(distance, np.ndarray) or ... | 2,337 |
def line_length(line, ellipsoid='WGS-84',shipping=True):
"""Length of a line in meters, given in geographic coordinates
Adapted from https://gis.stackexchange.com/questions/4022/looking-for-a-pythonic-way-to-calculate-the-length-of-a-wkt-linestring#answer-115285
Arguments:
line {Shapely LineString... | 2,338 |
def corr2_coeff(x, y):
"""A magic function for computing correlation between matrices and arrays.
This code is 640x+ faster on large dataset compared to np.corrcoef().
------------------------------------------------------------------
author: Divakar (https://stackoverflow.com/users/3293881/di... | 2,339 |
def get_database_url(track: str) -> Optional[URL]:
"""
Get the database URL based on the environment
How the database URL is selected:
1. If a predefined URL for the track is set, use that
2. If no predefined URL is set, generate one based on the preferred database type
"""
database_default... | 2,340 |
def create_membership_push_to_timeline(sender, instance, created, **kwargs):
"""
Creating new membership with associated user. If the user is the project owner we don't
do anything because that info will be shown in created project timeline entry
@param sender: Membership model
@param instance: Mem... | 2,341 |
def build_suite():
"""A function."""
#suite = unittest.TestSuite()
#suite.addTest(WidgetTestCase('test_default_size'))
#suite.addTest(WidgetTestCase('test_resize'))
suite = unittest.TestLoader().loadTestsFromTestCase(WidgetTestCase)
return suite | 2,342 |
def get_quantile(data, percentage, **kwargs):
"""
Assuming the dataset is loaded as type `np.array`, and has shape
(num_samples, num_features).
:param data: Provided dataset, assume each row is a data sample and \
each column is one feature.
:type data: `np.ndarray`
:param percentage: Quan... | 2,343 |
def clean_repository_clone_url( repository_clone_url ):
"""Return a URL that can be used to clone a tool shed repository, eliminating the protocol and user if either exists."""
if repository_clone_url.find( '@' ) > 0:
# We have an url that includes an authenticated user, something like:
# http:/... | 2,344 |
def calculate_uncertainty_ins_seg(logits, classes):
"""
We estimate uncerainty as L1 distance between 0.0 and the logit prediction in 'logits' for the
foreground class in `classes`.
Args:
logits (Tensor): A tensor of shape (R, C, ...) or (R, 1, ...) for class-specific or
class-a... | 2,345 |
def euclidean_distance(x, y):
"""
Compute Euclidean distance between two Variable matrices.
---
param:
x: PyTorch Variable with shape (m, d)
y: PyTorch Variable with shape (n, d)
return:
distance: PyTorch Variable with shape (m, n)
"""
m, n = x.size(0), y.size(0)
... | 2,346 |
def gsettings_set(schema, path, key, value):
"""Set value of gsettings schema"""
if path is None:
gsettings = Gio.Settings.new(schema)
else:
gsettings = Gio.Settings.new_with_path(schema, path)
if isinstance(value, list):
return gsettings.set_strv(key, value)
if isinstance(va... | 2,347 |
def _get_permutations_draw(draw):
"""Helper to get all permutations of a draw (list of letters), hint:
use itertools.permutations (order of letters matters)"""
for length in range(1, 8):
yield from itertools.permutations(draw, r=length) | 2,348 |
def test_constructor_mm2gamma(setup_mm2gamma_zarr):
"""
test that constructor parses metadata properly
no data extraction in this test
"""
src = setup_mm2gamma_zarr
mmr = ZarrReader(src)
assert(mmr.mm_meta is not None)
assert(mmr.z_step_size is not None)
assert(mmr.width is not... | 2,349 |
def initialize_parameters_deep(layer_dims):
"""
Arguments:
layer_dims -- python array (list) containing the dimensions of each layer in our network
Returns:
parameters -- python dictionary containing your parameters "W1", "b1", ..., "WL", "bL":
Wl -- weight matrix of shape (... | 2,350 |
def get_nblocks_ntraces(f,nblocks,ntraces,pts,nbheaders,dt,read_blockhead):
"""
Read n blocks from a Varian binary file which may have multiple traces
per block.
Parameters:
* f File object of Varian binary file to read from.
* nblocks Number of blocks to read.
* ... | 2,351 |
def register():
"""Run multi_pyspin constructor and register multi_pyspin destructor. Should be called once when first imported"""
multi_pyspin.register() | 2,352 |
def calcMedian(list_o_tuples):
"""Given a list of tuples (A, B), where A = category, and B = counts,
returns A that represents the median count value"""
#calc total
ct = 0
for (a, b) in list_o_tuples:
ct += float(b)
med = ct / 2
#find A
ct = 0
for (i, (a, b)) in enumerate(li... | 2,353 |
def add(n1, n2):
"""Adds the 2 given numbers"""
return n1 + n2 | 2,354 |
def kwarg_any(kwarg_functions):
"""Resolve kwarg predicates with short-circuit evaluation. This optimization
technique means we do not have to evaluate every predicate if one is already
true.
"""
return any(kwarg_function() for kwarg_function in kwarg_functions) | 2,355 |
def _behler_parrinello_cutoff_fn(dr: Array,
cutoff_distance: float=8.0) -> Array:
"""Function of pairwise distance that smoothly goes to zero at the cutoff."""
# Also returns zero if the pairwise distance is zero,
# to prevent a particle from interacting with itself.
return jnp.... | 2,356 |
def test_get_models_list():
"""Assert that the right models are returned when the parameter is a list."""
atom = ATOMClassifier(X_bin, y_bin, random_state=1)
atom.run(["LR1", "LR2", "LR3"])
assert atom._get_models(["LR1", "LR2"]) == ["LR1", "LR2"] | 2,357 |
def _get_build_to_download(build: str) -> Tuple[str, Optional[str]]:
"""Get the build version to download.
If the passed value is not an explict build number (eg. 15.0) then
the build for the current day of that major/minor will be downloaded.
:param build: The target build number.
:return: The t... | 2,358 |
def test(program, mode):
"""
function to do tests
"""
print('Program {}, mode {}'.format(program, mode))
print('Doing tests...') | 2,359 |
def label(type=None,
is_emphasis=True,
is_label_show=False,
label_pos=None,
label_text_color="#000",
label_text_size=12,
formatter=None,
**kwargs):
""" Text label of , to explain some data information about graphic item like value, name and so on... | 2,360 |
def MPC_ComputeCrc(card_type: TechnologyType, frame: bytes) -> bytes:
"""Computes frame CRC
Parameters
----------
card_type : TechnologyType
Technology type
frame : bytes
Input frame
Returns
-------
bytes
CRC bytes
"""
if not isinstance(card_type, Techno... | 2,361 |
def max_contiguous(input, value, _builder=None):
"""
Let the compiler knows that the `value` first values in :code:`input` are contiguous.
"""
value = _constexpr_to_value(value)
return semantic.max_contiguous(input, value) | 2,362 |
def kl_reverse(logu: torch.Tensor) -> torch.Tensor:
"""
Log-space Csiszar function for reverse KL-divergence D_f(p,q) = KL(q||p).
Also known as the exclusive KL-divergence and negative ELBO, minimizing
results in zero-forcing / mode-seeking behavior.
Args:
logu (torch.Tensor): ``p.log_prob... | 2,363 |
def twos_comp_to_signed(val: int, n_bits: int) -> int:
"""
Convert a "two's complement" representation (as an integer) to its signed
version.
Args:
val: positive integer representing a number in two's complement format
n_bits: number of bits (which must reflect a whole number of bytes)
... | 2,364 |
def main():
"""main entry point for module execution
"""
argument_spec = dict(
lines=dict(type='list', aliases=['commands'], required=True),
)
module = AnsibleModule(
argument_spec=argument_spec,
supports_check_mode=True
)
lines = module.params['lines']
result = {
'changed': False
... | 2,365 |
def delete_file(subject_file_id):
"""deletes a particular file
:rtype tuple
:return (subject_file_id, deleted_file_path)
"""
file_entity = SubjectFileEntity.query.filter_by(id=subject_file_id).one()
file_path = file_entity.get_full_path(app.config['REDIDROPPER_UPLOAD_SAVED_DIR'])
os.remove... | 2,366 |
def export_chart_avg_age_by_country(data_file_path):
"""
Exports a line chart with average age observed for each country.
Args:
data_file_path (str):
File path of the exported CSV file
"""
# Read csv as pandas dataframe
fight_data = pd.read_csv(data_file_path, sep=';')
fight_da... | 2,367 |
def test_command_line_slide_info_file_not_found(sample_svs):
"""Test CLI slide info file not found error."""
runner = CliRunner()
slide_info_result = runner.invoke(
cli.main,
[
"slide-info",
"--img-input",
str(sample_svs)[:-1],
"--file-types",
... | 2,368 |
def do_lint() -> str:
"""
Execute pylint
"""
check_command_exists("pylint")
with safe_cd(SRC):
lint_output_file_name = f"{PROBLEMS_FOLDER}/lint.txt"
if os.path.isfile(lint_output_file_name):
os.remove(lint_output_file_name)
if IS_DJANGO:
django_bits ... | 2,369 |
def json_configs(type, name):
"""
Base method that extracts the configuration info from the json file defined
in SETTINGS
Args:
type - the name of the type of configuration object to look in
name - the name of the object whose configs will be extracted
Returns:
a di... | 2,370 |
def reload() -> bool:
"""Gracefully reloads uWSGI.
* http://uwsgi.readthedocs.io/en/latest/Management.html#reloading-the-server
"""
return False | 2,371 |
def predict_imagen(titulo=None,
grados=None,
ano_lanzamiento=None,
paginas=None,
codbarras=None):
""" Predictor for Imagen from model/5a143f443980b50a74003699
Created using BigMLer
"""
import re
tm_tokens = 'tokens_on... | 2,372 |
def traducir_texto(texto, lenguaje_destino):
"""
Permite traducir un texto de entrada.
.. note::
Es importante tener en cuenta los siguientes aspectos al utilizar la \
función **traducir_texto**:
* La función utiliza la librería googletrans, que hace uso de la API \
de ... | 2,373 |
def euler_to_axis_angle(roll: float, pitch: float, yaw: float) -> np.ndarray:
"""Converts Euler angle to Axis-angle format.
Args:
roll: rotation angle.
pitch: up/down angle.
yaw: left/right angle.
Returns:
Equivalent Axis-angle format.
"""
r = Rotation.from_euler('xyz', [roll, pitch, yaw])
... | 2,374 |
def predict():
"""
An example of how to load a trained model and use it
to predict labels.
"""
# load the saved model
classifier = pickle.load(open('best_model.pkl'))
# compile a predictor function
predict_model = theano.function(
inputs=[classifier.input],
outputs=clas... | 2,375 |
def test_sanitize_query_params_only_month():
"""
GIVEN Empty year and correct month params.
WHEN sanitize_query_params() fun is invoked.
THEN Result is tuple with empty year and correct month.
"""
result = sanitize_query_params(year='', month='1')
assert result == ('', '01') | 2,376 |
def add_scalebar(axis, matchx=True, matchy=True, hidex=True, hidey=True, unitsx=None, unitsy=None, scalex=1.0, scaley=1.0, xmax=None, ymax=None, space=None, **kwargs):
"""
Add scalebars to axes
Adds a set of scale bars to *ax*, matching the size to the ticks of the plot and optionally hiding the x and y ax... | 2,377 |
def test_cross_validate():
"""Assert that the cross_validate method works as intended."""
atom = ATOMClassifier(X_bin, y_bin, random_state=1)
atom.run("LR")
assert isinstance(atom.lr.cross_validate(), dict)
assert isinstance(atom.lr.cross_validate(scoring="AP"), dict) | 2,378 |
def parse_args():
"""Parse and enforce command-line arguments."""
try:
options, args = getopt(sys.argv[1:], "l:dh", ["listen=", "debug", "help"])
except GetoptError as e:
print("error: %s." % e, file=sys.stderr)
print_usage()
sys.exit(1)
listen = {"host": "127.0.0.1", "... | 2,379 |
def test_status_no_total(monkeypatch):
""" Have not created a job with .set_total() yet
"""
monkeypatch.setenv('WorkTopic', 'abc123')
with patch('redis.StrictRedis', mock_strict_redis_client):
with pytest.raises(JobDoesNotExist):
RedisProgress().status('123') | 2,380 |
def create_medoids_summary(season, country, result, d, names):
"""
Create cluster based summary of medoids' description
Parameters:
season: str, season sued to cluster
country: str, used to cluster
result: cluster resutls joint to customer features
d: trajectory clustering re... | 2,381 |
def backtest(
strategy,
data, # Treated as csv path is str, and dataframe of pd.DataFrame
commission=COMMISSION_PER_TRANSACTION,
init_cash=INIT_CASH,
data_format="c",
plot=True,
verbose=True,
sort_by="rnorm",
**kwargs
):
"""
Backtest financial data with a specified trading s... | 2,382 |
def mapflatdeep(iteratee, *seqs):
"""
Map an `iteratee` to each element of each iterable in `seqs` and recurisvely flatten the
results.
Examples:
>>> list(mapflatdeep(lambda n: [[n, n]], [1, 2]))
[1, 1, 2, 2]
Args:
iteratee (object): Iteratee applied per iteration.
... | 2,383 |
def eHealthClass_getSkinConductanceVoltage():
"""eHealthClass_getSkinConductanceVoltage() -> float"""
return _ehealth.eHealthClass_getSkinConductanceVoltage() | 2,384 |
def construct_item(passage: str, labels):
"""
根据输入的passage和labels构建item,
我在巴拉巴拉...
['B-ASP', 'I-ASP', 'I-ASP', 'I-ASP', ..., 'I-OPI', 'I-OPI', 'O']
构造结果示例如下:
{
'passage': '使用一段时间才来评价,淡淡的香味,喜欢!',
'aspect': [['香味', 14, 16]],
'opinion': [['喜欢', 17, 19]]
}
:return:
... | 2,385 |
def for_b():
""" *'s printed in the Shape of Small b """
for row in range(9):
for col in range(6):
if col ==0 or row in (4,8) and col !=5 or row in (5,6,7) and col ==5:
print('*',end=' ')
else:
print(' ',end=' ')
print() | 2,386 |
def close_client(client):
"""Saves the recoded responses to a temp file if the config file allows.
This should be called in the unit test's tearDown method.
Checks to see if settings.CACHE_RESPONSES is True, to make sure we only
save sessions to repeat if the user desires.
"""
if client and settings.CAC... | 2,387 |
def getStartingAddress(packet):
"""Get the address of a modbus request"""
return ((ord(packet[8]) << 8) + ord(packet[9])) | 2,388 |
def rf_local_unequal(left_tile_col, rhs: Union[float, int, Column_type]) -> Column:
"""Cellwise inequality comparison between two tiles, or with a scalar value"""
if isinstance(rhs, (float, int)):
rhs = lit(rhs)
return _apply_column_function('rf_local_unequal', left_tile_col, rhs) | 2,389 |
def save_dump_to_file(dump):
"""
Saves dump information and activities in csv files.
"""
assert isinstance(dump, Dump)
with open("dumps.csv", "a") as dumps_file:
dumps_file.write(dump.to_csv())
dumps_file.write("\n")
print("Saved {0} activities between {1} and {2}...".format(
... | 2,390 |
def get_normalized_star_spectrum(spectral_type, magnitude, filter_name):
"""
spec_data = get_normalized_star_spectrum(spectral_type, magnitude, filter_name)
Returns a structure containing the synthetic spectrum of the star having the spectral type and magnitude
in the specified input filter. Magnitude... | 2,391 |
def header(**kwargs):
"""
Create header node and return it.
Equivalent to :code:`return Element("header", attributes...)`.
"""
return Element("header", **kwargs) | 2,392 |
def bump_func(xs_arg, low, high, btype):
"""
Setup initial displacement distribution of a bump,
either sine or triangular.
"""
# check the case of a single float as input
if isinstance(xs_arg, (int, float)):
xs_in = np.array([float(xs_arg)])
scalar = True
else:
xs_in ... | 2,393 |
def main(debug_function: bool = False):
"""
the main function for the script
"""
# region def main(...):
# region debug_function
if debug_function:
print("[def] sort_by_number_of_videos_and_size.main()")
print("{")
# endregion
current_directory_path = os.getcwd()
# region debug_func... | 2,394 |
def set_kallisto_binary_path(path):
"""Helper function to set the KALLISTO_PATH variable. Automatically finds the
full path to the executable and sets that as KALLISTO_PATH.
"""
global KALLISTO_PATH
shutil_path = shutil.which(path)
actual_path = None
# First, check if it is an executable i... | 2,395 |
def setup_session(username, password, check_url=None,
session=None, verify=True):
"""
A special call to get_cookies.setup_session that is tailored for
URS EARTHDATA at NASA credentials.
"""
if session is not None:
# URS connections cannot be kept alive at the moment.
... | 2,396 |
def is_number(item):
"""Check if the item is a number."""
return isinstance(item, numbers.Number) | 2,397 |
def from_list(commands):
"""
Given a list of tuples of form (depth, text)
that represents a DFS traversal of a command tree,
returns a dictionary representing command tree.
"""
def subtrees(commands, level):
if not commands:
return
acc = []
parent, *commands... | 2,398 |
def get_cassandra_config_options(config):
"""Parse Cassandra's Config class to get all possible config values.
Unfortunately, some are hidden from the default cassandra.yaml file, so this appears the only way to do this."""
return _get_config_options(config=config, config_class='org.apache.cassandra.config... | 2,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.