id int64 0 6k | code stringlengths 4k 8k | code_compressed listlengths 0 44 |
|---|---|---|
200 | import pytest, py
import re
def exvalue():
import sys
return sys.exc_info()[1]
def f():
return 2
def test_assert():
try:
assert f() == 3
except AssertionError:
e = exvalue()
s = str(e)
assert s.startswith('assert 2 == 3\n')
def test_assert_within_finally():
e... | [
{
"body": " ### Use a custom class hierarchy with existing instances\n class Picklable(self.View):\n pass\n class Simple(Picklable):\n __view__ = object\n def pickle(self):\n return repr(self.__obj__)\n class Seq(Picklable):\n ... |
201 | from __future__ import annotations
from collections import defaultdict
from typing import Dict, Iterable, Set, Tuple, TypeVar, Union
from pharmpy.deps import sympy
from pharmpy.internals.expr.subs import subs
from pharmpy.internals.expr.tree import prune
from pharmpy.internals.graph.directed.reachability import reach... | [
{
"body": " if expr.is_Mul and expr.args[0] == -1:\n return sympy.Mul(*expr.args[1:])\n else:\n return expr",
"name": "METHOD_NAME(expr):"
},
{
"body": " \"\"\"Derive the physical unit of a variable in the model\n Unit information for the dataset needs to be available.\n ... |
202 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
#
# «recovery_xml» - Helper Class for parsing and using a bto.xml
#
# Copyright (C) 2010-2011, Dell Inc.
#
# Author:
# - Mario Limonciello <Mario_Limonciello@Dell.com>
#
# This is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Pub... | [
{
"body": " if isinstance(old, str):\n return old\n else:\n return str(bytes(old), 'utf-8', errors='ignore')",
"name": "METHOD_NAME(old):"
},
{
"body": " \"\"\"Appends a fish package\"\"\"\n elements = self.dom.getElementsByTagName('fish')\n new_element = sel... |
203 | # coding=utf-8
# Copyright 2018-2023 EvaDB
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... | [
{
"body": " numpy_array = NumpyArray(\n name=\"input\", is_nullable=False, type=NdArrayType.UINT8, dimensions=(2, 2)\n )\n catalog_entries = numpy_array.generate_catalog_entries()\n # check that there is only a single catalog entry\n self.assertEqual(len(catalog_ent... |
204 | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | [
{
"body": "\t\treturn self.get_query_params().get('TargetType')",
"name": "get_TargetType(self):ModifyReplicationJobAttributeRequest(RpcRequest):"
},
{
"body": "\t\tself.add_query_param('TargetType',TargetType)",
"name": "set_TargetType(self,TargetType):ModifyReplicationJobAttributeRequest(RpcRe... |
205 | # -*- coding: utf-8 -*-
# ------------------------------------------------------------------------------
#
# Copyright 2021-2023 Valory AG
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License... | [
{
"body": " \"\"\"Get defaults from genesis file.\"\"\"\n genesis = load_genesis()\n return dict(genesis_time=genesis.get(\"genesis_time\"))",
"name": "get_defaults()PeriodDumper:"
},
{
"body": " \"\"\"Dump tendermint run data for replay\"\"\"\n store_dir = self.dump_dir / f\"... |
206 | #!/usr/bin/python
'''
Copyright (c) 2020, dataJAR Ltd. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
... | [
{
"body": " ''' Check that we have the Install_pkg's & proceed if we do'''\n found_pkgs = 0\n print('Looking for pkgs...')\n for adobe_folder in sorted(adobe_folders):\n try:\n install_pkg = glob.glob(os.path.join(DOWNLOADS_PATH, adobe_folder, \\\n ... |
207 | import requests
from plugin import plugin, require
from colorama import Fore
from bs4 import BeautifulSoup
@require(network=True)
@plugin("food recipe")
def getChoices(jarvis, s):
"""
function gets the choice of the type of cuisine the user wants.
user must get an api key from https://spoonacular.com/foo... | [
{
"body": " url = f\"https://api.spoonacular.com/recipes/complexSearch?apiKey={apiKey}&cuisine={cuisine}&includeNutrition=true.\"\n response = requests.get(url)\n # print(response)\n if response.status_code == 200:\n content = response.json()\n # for debugging purposes, need import jso... |
208 | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | [
{
"body": "\t\treturn self.get_query_params().get('ResourceOwnerId')",
"name": "get_ResourceOwnerId(self):UpgradeDBInstanceMajorVersionRequest(RpcRequest):"
},
{
"body": "\t\tself.add_query_param('ResourceOwnerId', ResourceOwnerId)",
"name": "set_ResourceOwnerId(self,UpgradeDBInstanceMajorVersio... |
209 | # coding=utf-8
# Copyright 2023 The TensorFlow Datasets Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appl... | [
{
"body": " \"\"\"Try importing a module, with an informative error message on failure.\"\"\"\n try:\n mod = importlib.import_module(module_name)\n return mod\n except ImportError as e:\n err_msg = (\n \"Failed importing {name}. This likely means that the dataset \"\n \"requires additi... |
210 | import io
import random
import math
import IMP
import IMP.test
import IMP.atom
import IMP.core
from test_coulomb import place_xyzs
def make_test_pair_score(min_distance=9.0, max_distance=10.0):
m = IMP.Model()
p0 = m.add_particle("p0")
sph = IMP.algebra.Sphere3D(IMP.algebra.Vector3D(0, 0, 0), 1.0)
IM... | [
{
"body": " \"\"\"Check score value of LennardJonesPairScore\"\"\"\n m, sf, d0, d1, c = make_test_pair_score()\n box = IMP.algebra.Vector3D(10.0, 20.0, 30.0)\n for r0 in (2.0, 1.0):\n d0.set_radius(r0)\n for r1 in (2.0, 1.0):\n d1.set_radius(r1)\n... |
211 | #
# Copyright (c) 2018-2020 Red Hat, Inc.
#
# This file is part of nmstate
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 2.1 of the License, or
# (at your option) any l... | [
{
"body": " if not config.getoption(\"--runslow\"):\n # --runslow is not in cli: skip slow tests\n _mark_skip_slow_tests(items)\n _mark_tier2_tests(items)",
"name": "METHOD_NAME(config,"
},
{
"body": " if os.getenv(\"CI\"):\n with tempfile.TemporaryDirectory() as tmpdir... |
212 | import json
from bs4 import BeautifulSoup
from puppetboard import app
from test import MockDbQuery
def test_radiator_view(client, mocker,
mock_puppetdb_environments,
mock_puppetdb_default_nodes):
query_data = {
'nodes': [[{'count': 10}]],
'resources'... | [
{
"body": " mock_puppetdb_environments,\n mock_puppetdb_default_nodes):\n # starting with v6.9.1 they changed the metric API to v2\n # and a totally different format\n base_str = 'puppetlabs.puppetdb.population:'\n query_data = {\n 'version'... |
213 | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | [
{
"body": "\t\treturn self.get_body_params().get('Description')",
"name": "get_Description(self):UpdatePrivateAccessPolicyRequest(RpcRequest):"
},
{
"body": "\t\tself.add_body_params('Description', Description)",
"name": "set_Description(self,UpdatePrivateAccessPolicyRequest(RpcRequest):"
},
... |
214 | """Datumaro Helper."""
# Copyright (C) 2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
#
# pylint: disable=invalid-name
import os
from typing import List, Optional, Tuple, Union
import datumaro
from datumaro.components.dataset import Dataset, DatasetSubset
from datumaro.components.dataset_base import Da... | [
{
"body": " \"\"\"Returns train dataset.\"\"\"\n subsets = dataset.subsets()\n train_dataset = subsets.get(\"train\", None)\n if train_dataset is not None:\n return train_dataset\n for k, v in subsets.items():\n if \"train\" in k or \"default\" in k:\n ... |
215 | import random
from base_test import ArkoudaTest
from context import arkouda as ak
from arkouda import client_dtypes
class ClientDTypeTests(ArkoudaTest):
"""
Note: BitVector operations are not tested here because the class is
only a wrapper on a pdarray to display as such.
The class does not actually... | [
{
"body": " ip_list = ak.array([3232235777])\n ipv4 = ak.IPv4(ip_list)\n ip_as_int = ipv4.normalize(\"192.168.1.1\")\n self.assertEqual(3232235777, ip_as_int)",
"name": "METHOD_NAME(self):class"
}
] |
216 | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | [
{
"body": "\t\tself.add_query_param('OrderDirection', OrderDirection)",
"name": "set_OrderDirection(self,DescribeDtsJobsRequest(RpcRequest):"
},
{
"body": "\t\tself.add_query_param('DedicatedClusterId', DedicatedClusterId)",
"name": "METHOD_NAME(self,DescribeDtsJobsRequest(RpcRequest):"
}
] |
217 | # Copyright (c) ZenML GmbH 2022. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applic... | [
{
"body": " \"\"\"Tests the setting of the user if configured.\"\"\"\n docker_settings = DockerSettings(user=None)\n generated_dockerfile = (\n PipelineDockerImageBuilder._generate_zenml_pipeline_dockerfile(\n \"image:tag\",\n docker_settings,\n download_files=Fa... |
218 | # coding=utf-8
# Copyright 2018-2023 EvaDB
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... | [
{
"body": " self,\n evadb: EvaDBDatabase,\n query_node: Union[AbstractStatement, TableRef],\n alias: Alias = None,",
"name": "__init__(EvaDBQuery:"
},
{
"body": " \"\"\"Returns a new Relation with an alias set.\n Args:\n alias (str): an alias name... |
219 | ################################################################################
# Creme is a free/open-source Customer Relationship Management software
# Copyright (C) 2020-2022 Hybird
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General P... | [
{
"body": " \"\"\"Constructor.\n @param country: country code (e.g. 'FR').\n @param language: language code (e.g. 'fr_FR').\n @param theme: name of the theme\n \"\"\"\n self.country = country\n self.language = language\n self.theme = theme",
"name": "_... |
220 | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | [
{
"body": "\t\treturn self.get_query_params().get('DeviceLifeCycleFlag')",
"name": "get_DeviceLifeCycleFlag(self):UpdateSubscribeRelationRequest(RpcRequest):"
},
{
"body": "\t\tself.add_query_param('DeviceLifeCycleFlag',DeviceLifeCycleFlag)",
"name": "set_DeviceLifeCycleFlag(self,DeviceLifeCycle... |
221 | # Copyright 2021-2023 AIPlan4EU project
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to i... | [
{
"body": " TestCase.METHOD_NAME(self)",
"name": "METHOD_NAME(self):TestSubstituter(TestCase):"
}
] |
222 | """Tests for Action Classification Task with OTX CLI"""
# Copyright (C) 2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
#
import os
import copy
from copy import deepcopy
import pytest
import torch
from otx.api.entities.model_template import parse_model_template
from otx.cli.registry import Registry
from... | [
{
"body": " adapting_num_workers_args = deepcopy(args)\n adapting_num_workers_args[\"train_params\"].extend([\"--learning_parameters.auto_num_workers\", \"True\"])\n tmp_dir_path = tmp_dir_path / f\"action_cls_auto_adapt_num_workers\"\n otx_train_testing(template, tmp_dir_path, otx_d... |
223 | # Copyright (c) 2022 The Regents of the University of California
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met: redistributions of source code must retain the above copyright
# notice, this lis... | [
{
"body": " super().__init__()\n # There is some annoying redundancy here. The BaseCPU type already\n # defines the ISA, so here we are defining it twice. However, there\n # currently isn't a good way to get the ISA from the BaseCPU Type.\n if isa:\n requires(isa_re... |
224 | #!/usr/bin/env python3
# Copyright (c) 2013 ARM Limited
# All rights reserved
#
# The license below extends only to copyright in the software and shall
# not be construed as granting a license to any other intellectual
# property including but not limited to intellectual property relating
# to a hardware implementatio... | [
{
"body": " \"\"\"\n This opens the file passed as argument for reading using an appropriate\n function depending on if it is gzipped or not. It returns the file\n handle.\n \"\"\"\n try:\n # First see if this file is gzipped\n try:\n # Opening the file works even if i... |
225 | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | [
{
"body": "\t\treturn self.get_query_params().get('LaunchTemplateName')",
"name": "get_LaunchTemplateName(self):DescribeLaunchTemplateVersionsRequest(RpcRequest):"
},
{
"body": "\t\tself.add_query_param('LaunchTemplateName', LaunchTemplateName)",
"name": "METHOD_NAME(self,DescribeLaunchTemplateV... |
226 | import json
import logging
from types import GeneratorType
import pytest
from pypuppetdb.errors import EmptyResponseError
from requests import Response
from requests.exceptions import ConnectionError, HTTPError
from werkzeug.exceptions import InternalServerError, NotFound
from puppetboard import app
from puppetboard ... | [
{
"body": " # the downside of simplifying showing plain strings without quotes is that it's hard\n # to distinguish things that LOOK LIKE non-string but in fact are strings.\n python_not_really_array = '\"[\"foo\", \"bar\"]\"'\n python_not_really_array_as_string = '\"[\"foo\", \"bar\"]\"'\n asser... |
227 | from django.urls import NoReverseMatch
from rest_framework import exceptions as drf_exceptions
from rest_framework import versioning as drf_versioning
from rest_framework.compat import unicode_http_header
from rest_framework.utils.mediatypes import _MediaType
from distutils.version import StrictVersion
from api.base i... | [
{
"body": " super(BaseVersioning, self).__init__()",
"name": "__init__(self):BaseVersioning(drf_versioning.BaseVersioning):"
},
{
"body": " invalid_version_message = 'Invalid version in URL path.'\n version = kwargs.get(self.version_param)\n if version is None:\n ... |
228 | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | [
{
"body": "\t\treturn self.get_query_params().get('ClientToken')",
"name": "get_ClientToken(self):UpdateListenerRequest(RpcRequest):"
},
{
"body": "\t\tself.add_query_param('ClientToken', ClientToken)",
"name": "set_ClientToken(self,UpdateListenerRequest(RpcRequest):"
},
{
"body": "\t\tr... |
229 | # Copyright 2017-2020 EPAM Systems, Inc. (https://www.epam.com/)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | [
{
"body": " tool = None\n try:\n response = self.call(API_TOOL_SEARCH, params={\"image\": image_name}, http_method='GET')\n tool = self.parse_response(response=response)\n except RuntimeError as e:\n print('Tool [{image_name}] is not found.'.format(image_nam... |
230 | import calendar
from flask import make_response, Response
from flask_appbuilder import expose, has_access, permission_name
from flask_appbuilder import ModelView
from flask_appbuilder.charts.views import GroupByChartView
from flask_appbuilder.models.group import aggregate_count
from flask_appbuilder.models.mongoengine... | [
{
"body": " item = self.datamodel.get(pk)\n file = item.file.read()\n response = make_response(file)\n response.headers[\"Content-Disposition\"] = \"attachment; filename={0}\".format(\n item.file.name\n )\n return response",
"name": "METHOD_NAME(self,Cont... |
231 | import subprocess
from error_codes import *
from errors import error_info
from helpers import geninfo_lookup, find_dce
SSL_CMD = "echo | openssl s_client -connect {0}:443 -brief"
CURL_CMD = "curl -s -S -k https://{0}/ping"
GLOBAL_HANDLER_URL = "global.handler.control.monitor.azure.com"
REGION_HANDLER_URL = ... | [
{
"body": " \"\"\"\n openssl connect to specific endpoint\n \"\"\"\n try:\n ssl_output = subprocess.check_output(ssl_cmd.format(endpoint), shell=True,\\\n stderr=subprocess.STDOUT, universal_newlines=True)\n ssl_output_lines = ssl_output.split('\\n')\n (conne... |
232 | """
Use nextclade QC to produce a list of sequences to be excluded.
"""
import argparse
import numpy as np
import pandas as pd
from datetime import datetime, timedelta
def isfloat(value):
try:
float(value)
return True
except ValueError:
return False
def METHOD_NAME(x, minus_weeks=0):
... | [
{
"body": " try:\n float(value)\n return True\n except ValueError:\n return False",
"name": "isfloat(value):"
},
{
"body": " try:\n return (datetime.strptime(x,\"%Y-%m-%d\") - timedelta(weeks=minus_weeks)).toordinal()\n except:\n return np.nan",
"na... |
233 | # Copyright (c) ZenML GmbH 2022. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applic... | [
{
"body": " \"\"\"Name of the flavor.\n Returns:\n The name of the flavor.\n \"\"\"\n return S3_ARTIFACT_STORE_FLAVOR",
"name": "name(self)S3ArtifactStoreFlavor(BaseArtifactStoreFlavor):"
},
{
"body": " self,",
"name": "service_connector_requirements... |
234 | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | [
{
"body": "\t\treturn self.get_query_params().get('Environment')",
"name": "METHOD_NAME(self):ListSlotRequest(RpcRequest):"
},
{
"body": "\t\tself.add_query_param('Environment', Environment)",
"name": "set_Environment(self,ListSlotRequest(RpcRequest):"
}
] |
235 | """Constructors for concrete tool and input source objects."""
import logging
from typing import (
Callable,
Dict,
List,
Optional,
)
from yaml import safe_load
from galaxy.tool_util.loader import load_tool_with_refereces
from galaxy.util import (
ElementTree,
parse_xml_string_to_etree,
)
from... | [
{
"body": " proxy = tool_proxy(tool_object=safe_load(yaml_string))\n # regular CwlToolSource sets basename as tool id, but that's not going to cut it in production\n return CwlToolSource(tool_proxy=proxy)",
"name": "build_cwl_tool_source(yaml_string:tool_source_class"
},
{
"body": " conf... |
236 | """Test singularity{,-ce} & apptainer versions."""
from subprocess import check_output # nosec
import cwltool.singularity
from cwltool.singularity import (
get_version,
is_apptainer_1_or_newer,
is_version_2_6,
is_version_3_1_or_newer,
is_version_3_4_or_newer,
is_version_3_or_newer,
)
def res... | [
{
"body": " \"\"\"Mock out subprocess.check_output.\"\"\"\n cwltool.singularity.check_output = ( # type: ignore[attr-defined]\n lambda c, text: name + \" version \" + version\n )",
"name": "METHOD_NAME(name:"
}
] |
237 | import os
import pytest
import mock
import shutil
import tempfile
import xml
from future.moves.urllib.parse import urljoin
from scripts import generate_sitemap
from osf_tests.factories import (AuthUserFactory, ProjectFactory, RegistrationFactory, CollectionFactory,
PreprintFactory, Pr... | [
{
"body": " return AuthUserFactory()",
"name": "user_admin_project_public(self):TestGenerateSitemap:"
},
{
"body": " return UnconfirmedUserFactory()",
"name": "user_unconfirmed(self):TestGenerateSitemap:"
},
{
"body": " return AuthUserFactory()",
"name": "user_ad... |
238 | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | [
{
"body": "\t\treturn self.get_query_params().get('FullNatEntryDescription')",
"name": "get_FullNatEntryDescription(self):CreateFullNatEntryRequest(RpcRequest):"
},
{
"body": "\t\tself.add_query_param('FullNatEntryDescription', FullNatEntryDescription)",
"name": "set_FullNatEntryDescription(self... |
239 | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | [
{
"body": "\t\treturn self.get_query_params().get('MinRequestAmount')",
"name": "get_MinRequestAmount(self):CreateCircuitBreakerRuleRequest(RpcRequest):"
},
{
"body": "\t\tself.add_query_param('MinRequestAmount', MinRequestAmount)",
"name": "set_MinRequestAmount(self,CreateCircuitBreakerRuleRequ... |
240 | from lm_eval.utils import get_rolling_token_windows, make_disjoint_window
# noinspection DuplicatedCode
def test_get_rolling_token_windows_v1():
gold = [
([-100, 0, 1, 2, 3, 4, 5, 6, 7, 8], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]),
(
[9, 10, 11, 12, 13, 14, 15, 16, 17, 18],
[10, 11,... | [
{
"body": " gold = [\n ([-100, 0], [0, 1]),\n ([1, 2], [2, 3]),\n ([3, 4], [4, 5]),\n ([5, 6], [6, 7]),\n ([6, 7], [8]),\n ]\n x = list(range(9))\n generator = get_rolling_token_windows(\n token_list=x,\n prefix_token=-100,\n max_seq_len=2,\n ... |
241 | import argparse
import csv
import re
from django.core.management import BaseCommand
from pola.company.models import Brand, Company
from pola.management.command_utils import ask_yes_no
from pola.product.models import Product
def update_product(self, brand, ean_code, company, product_name):
product = Product.obje... | [
{
"body": " product = Product.objects.filter(code=ean_code).first()\n if product:\n product.brand = brand\n product.name = product_name\n product.company = company\n product.save()\n self.stdout.write(self.style.SUCCESS(f\"Successfully updated product {product_name}\"))\... |
242 | # coding=utf-8
from tests import unittest
from mock import MagicMock, patch, Mock
from aliyunsdkcore.endpoint.location_service_endpoint_resolver \
import LocationServiceEndpointResolver
from aliyunsdkcore.endpoint.resolver_endpoint_request import ResolveEndpointRequest
from aliyunsdkcore.acs_exception.exception... | [
{
"body": " resolver = LocationServiceEndpointResolver(None)\n self.assertEqual(resolver._location_service_endpoint,\n \"location-readonly.aliyuncs.com\")\n resolver.set_location_service_endpoint(\"new location endpoint\")\n self.assertEqual(resolver._location... |
243 | #
# junitxml: extensions to Python unittest to get output junitxml
# Copyright (C) 2009 Robert Collins <robertc@robertcollins.net>
#
# Copying permitted under the LGPL-3 licence, included with this library.
"""unittest compatible JUnit XML output."""
import datetime
import re
import time
import unittest
# same f... | [
{
"body": " self._offset = None",
"name": "__init__(self):JUnitXmlResult(unittest.TestResult):"
},
{
"body": " if self._offset is None:\n t = 1260423030 # arbitrary, but doesn't handle dst very well\n dt = datetime.datetime\n self._offset = (dt.fromtime... |
244 | # License: MIT
# Copyright © 2023 Frequenz Energy-as-a-Service GmbH
"""Tests for the moving window."""
import asyncio
from collections.abc import Iterator, Sequence
from datetime import datetime, timedelta, timezone
import async_solipsism
import numpy as np
import pytest
import time_machine
from frequenz.channels im... | [
{
"body": " \"\"\"Replace the loop with one that doesn't interact with the outside world.\"\"\"\n loop = async_solipsism.EventLoop()\n yield loop\n loop.close()",
"name": "event_loop()"
},
{
"body": " \"\"\"Test accessing an empty window, should throw IndexError.\"\"\"\n window, _ ... |
245 | from arm.logicnode.arm_nodes import *
class MathNode(ArmLogicTreeNode):
"""Mathematical operations on values."""
bl_idname = 'LNMathNode'
bl_label = 'Math'
arm_version = 3
@staticmethod
def METHOD_NAME(obj, prop_name, value):
return obj.bl_rna.properties[prop_name].enum_items[value].id... | [
{
"body": " return obj.bl_rna.properties[prop_name].enum_items[value].identifier",
"name": "METHOD_NAME(obj,MathNode(ArmLogicTreeNode):"
},
{
"body": " # Checking the selection of another operation\n select_current = self.METHOD_NAME(self, 'property0', value)\n select_pre... |
246 | """
@file
@brief This file contains the project file listview, used by the main window
@author Noah Figg <eggmunkee@hotmail.com>
@author Jonathan Thomas <jonathan@openshot.org>
@section LICENSE
Copyright (c) 2008-2018 OpenShot Studios, LLC
(http://www.openshotstudios.com). This file is part of
OpenShot Video ... | [
{
"body": " event.accept()\n # Set context menu mode\n app = get_app()\n app.context_menu_object = \"files\"\n index = self.indexAt(event.pos())\n # Build menu\n menu = QMenu(self)\n menu.addAction(self.win.actionImportFiles)\n menu.addAction(self.w... |
247 | """Misc. useful functions that can be used at many places in the program."""
import os
import subprocess as sp
import warnings
import proglog
OS_NAME = os.name
def cross_platform_popen_params(popen_params):
"""Wrap with this function a dictionary of ``subprocess.Popen`` kwargs and
will be ready to work wit... | [
{
"body": " \"\"\"Wrap with this function a dictionary of ``subprocess.Popen`` kwargs and\n will be ready to work without unexpected behaviours in any platform.\n Currently, the implementation will add to them:\n - ``creationflags=0x08000000``: no extra unwanted window opens on Windows\n when t... |
248 | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | [
{
"body": "\t\treturn self.get_query_params().get('QueryCondition')",
"name": "get_QueryCondition(self):DescribeDiagnosisRecordsRequest(RpcRequest):"
},
{
"body": "\t\tself.add_query_param('QueryCondition', QueryCondition)",
"name": "set_QueryCondition(self,DescribeDiagnosisRecordsRequest(RpcReq... |
249 | from typing import Any, Callable, Dict, Optional
from urllib.parse import urlparse
from django.contrib.staticfiles.testing import StaticLiveServerTestCase
from django.urls import reverse
from selenium.webdriver.common.by import By
from selenium.webdriver.firefox.webdriver import WebDriver
from selenium.webdriver.remot... | [
{
"body": " if multiple:\n return self.selenium.find_elements(By.CSS_SELECTOR, selector)\n else:\n return self.selenium.find_element(By.CSS_SELECTOR, selector)",
"name": "METHOD_NAME(self,BaseStoreTest(StaticLiveServerTestCase):"
},
{
"body": " try:\n ... |
250 | import asyncio
from typing import Any, Dict, List, Optional
from hummingbot.connector.exchange.injective_v2.injective_query_executor import BaseInjectiveQueryExecutor
class ProgrammableQueryExecutor(BaseInjectiveQueryExecutor):
def __init__(self):
self._ping_responses = asyncio.Queue()
self._spo... | [
{
"body": " self._ping_responses = asyncio.Queue()\n self._spot_markets_responses = asyncio.Queue()\n self._derivative_market_responses = asyncio.Queue()\n self._derivative_markets_responses = asyncio.Queue()\n self._spot_order_book_responses = asyncio.Queue()\n self._d... |
251 | import pytest
from api.base.settings.defaults import API_BASE
from osf_tests.factories import (
NodeFactory,
ProjectFactory,
RegistrationFactory,
AuthUserFactory,
PrivateLinkFactory,
)
@pytest.fixture()
def user():
return AuthUserFactory()
@pytest.fixture()
def registration_with_children(use... | [
{
"body": " return AuthUserFactory()",
"name": "user():"
},
{
"body": " project = ProjectFactory(creator=user)\n NodeFactory(parent=project, creator=user)\n NodeFactory(parent=project, creator=user)\n NodeFactory(parent=project, creator=user)\n NodeFactory(parent=project, creator=u... |
252 | import platform
import secrets
import signal
from pickle import PickleError
from typing import Any, Mapping
from unittest.mock import AsyncMock, MagicMock
import pytest
from aiodocker.exceptions import DockerError
from ai.backend.agent.docker.agent import DockerAgent
from ai.backend.common.docker import ImageRef
from... | [
{
"body": " behavior = AutoPullBehavior.DIGEST\n docker_mock = MagicMock()\n docker_mock.close = AsyncMock()\n docker_mock.images = MagicMock()\n inspect_mock = AsyncMock(\n side_effect=DockerError(\n status=404,\n data={\"message\": \"Simulated missing image\"},\n ... |
253 | # Copyright 2019 Camptocamp (http://www.camptocamp.com).
# @author Simone Orsi <simahawk@gmail.com>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from .common import TestMultiUserCommon
class TestMultiUserCustomer(TestMultiUserCommon):
"""Test interaction with /customer endpoint."""
def te... | [
{
"body": " self.backend.customer_multi_user = False\n self.data.update({\"external_id\": \"cust1\"})\n params = dict(self.data, company_token=\"ABCDEF\")\n res = self.service.dispatch(\"create\", params=params)[\"data\"]\n partner = self.env[\"res.partner\"].browse(res[\"id\"... |
254 | from typing import Optional
from AnyQt.QtCore import Qt, QSizeF, QRectF, QPointF
from AnyQt.QtGui import QPixmap, QTransform, QPainter
from AnyQt.QtWidgets import (
QGraphicsWidget, QGraphicsItem, QStyleOptionGraphicsItem, QWidget,
)
from Orange.widgets.utils.graphicslayoutitem import scaled
class GraphicsPixmap... | [
{
"body": " self,\n parent: Optional[QGraphicsItem] = None,\n pixmap: Optional[QPixmap] = None,\n scaleContents=False,\n aspectMode=Qt.KeepAspectRatio,\n **kwargs",
"name": "__init__(GraphicsPixmapWidget(QGraphicsWidget):"
},
{
"body"... |
255 | # Copyright (c) ZenML GmbH 2022. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applic... | [
{
"body": " # TODO [HIGH] Implement label config generator\n # refactoring out duplicated code from the various functions below\n raise NotImplementedError()",
"name": "_generate_label_config()"
},
{
"body": " labels: List[str],",
"name": "generate_text_classification_label_config("
... |
256 | '''
Copyright (C) 2017-2023 Bryant Moscon - bmoscon@gmail.com
Please see the LICENSE file for the terms and conditions
associated with this software.
'''
from collections import defaultdict
import asyncio
import logging
from typing import Optional, ByteString
from aiokafka import AIOKafkaProducer
from aiokafka.errors... | [
{
"body": " \"\"\"\n You can pass configuration options to AIOKafkaProducer as keyword arguments.\n (either individual kwargs, an unpacked dictionary `**config_dict`, or both)\n A full list of configuration parameters can be found at\n https://aiokafka.readthedocs.io/en/stable... |
257 | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | [
{
"body": "\t\treturn self.get_query_params().get('ResourceOwnerId')",
"name": "get_ResourceOwnerId(self):DescribeCommandsRequest(RpcRequest):"
},
{
"body": "\t\tself.add_query_param('ResourceOwnerId', ResourceOwnerId)",
"name": "set_ResourceOwnerId(self,DescribeCommandsRequest(RpcRequest):"
}... |
258 | import json
from json import JSONEncoder
from typing import List, Union, cast
from typeguard import typechecked
from arkouda.client import generic_msg
__all__ = [
"AllSymbols",
"RegisteredSymbols",
"information",
"list_registry",
"list_symbol_table",
"pretty_print_information",
]
AllSymbols =... | [
{
"body": " return o.__dict__",
"name": "default(self,InfoEntry:"
},
{
"body": " \"\"\"\n Returns JSON formatted string containing information about the objects in names\n Parameters\n ----------\n names : Union[List[str], str]\n names is either the name of an object or l... |
259 | import uuid
from galaxy.jobs import (
HasResourceParameters,
JobDestination,
)
from galaxy.jobs.mapper import (
ERROR_MESSAGE_NO_RULE_FUNCTION,
ERROR_MESSAGE_RULE_FUNCTION_NOT_FOUND,
JobRunnerMapper,
)
from galaxy.util import bunch
from . import (
test_rules,
test_rules_override,
)
WORKFLO... | [
{
"body": " mapper = __mapper(__dynamic_destination(dict(function=\"upload\")))\n assert mapper.get_job_destination({}) is DYNAMICALLY_GENERATED_DESTINATION\n assert mapper.job_config.rule_response == \"local_runner\"",
"name": "test_dynamic_mapping():MockJobWrapper(HasResourceParameters):"
},
... |
260 | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | [
{
"body": "\t\treturn self.get_query_params().get('Notification')",
"name": "get_Notification(self):CreateStoryRequest(RpcRequest):"
},
{
"body": "\t\tself.add_query_param(\"Notification\", json.dumps(Notification))",
"name": "set_Notification(self,CreateStoryRequest(RpcRequest):"
},
{
"... |
261 | # Copyright 2017-2022 EPAM Systems, Inc. (https://www.epam.com/)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | [
{
"body": " super(Metadata, self).__init__()",
"name": "__init__(self):Metadata(API):"
},
{
"body": " api = cls.instance()\n response_data = api.call('metadata/find?entityName={}&entityClass={}'.format(identifier,\n ... |
262 | import pytest
import env # noqa: F401
from pybind11_tests import ConstructorStats
from pybind11_tests import call_policies as m
@pytest.mark.xfail("env.PYPY", reason="sometimes comes out 1 off on PyPy", strict=False)
def test_keep_alive_argument(capture):
n_inst = ConstructorStats.detail_reg_inst()
with cap... | [
{
"body": " n_inst = ConstructorStats.detail_reg_inst()\n with capture:\n p = m.Parent()\n assert capture == \"Allocating parent.\"\n with capture:\n p.addChild(m.Child())\n assert ConstructorStats.detail_reg_inst() == n_inst + 1\n assert (\n capture\n == \"\"\"... |
263 | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | [
{
"body": "\t\treturn self.get_query_params().get('TemplateInstanceId')",
"name": "get_TemplateInstanceId(self):ModifyScalingRuleRequest(RoaRequest):"
},
{
"body": "\t\tself.add_query_param('TemplateInstanceId', TemplateInstanceId)",
"name": "set_TemplateInstanceId(self,ModifyScalingRuleRequest(... |
264 | import logging
import os
from flask_appbuilder import SQLA
from flask_appbuilder.models.sqla.interface import SQLAInterface
from .base import FABTestCase
from .const import MAX_PAGE_SIZE, PASSWORD_ADMIN, USERNAME_ADMIN
from .sqla.models import Model1
log = logging.getLogger(__name__)
class FlaskTestCase(FABTestCas... | [
{
"body": " from flask import Flask\n from flask_appbuilder import AppBuilder\n from flask_appbuilder.views import ModelView\n self.app = Flask(__name__)\n self.basedir = os.path.abspath(os.path.dirname(__file__))\n self.app.config.from_object(\"tests.config_api\")\n ... |
265 | from __future__ import print_function
import numpy as np
try:
import scipy.special
except ImportError:
scipy = None
import IMP
import IMP.test
import IMP.algebra
import pickle
class UnitSimplexDTests(IMP.test.TestCase):
types = [
(1, IMP.algebra.UnitSimplex1D, (), IMP.algebra.Vector1D),
... | [
{
"body": " alpha = (1 - tailprob) ** dim\n return sigma * np.sqrt(2) * scipy.special.erfinv(alpha)",
"name": "METHOD_NAME(tailprob,UnitSimplexDTests(IMP.test.TestCase):"
},
{
"body": " \"\"\"Check that fixed-dimension simplices are constructed correctly\"\"\"\n for d, st... |
266 | import traceback
from shared.regular.regular_api import *
from shared.connection.connectors.connectors_base import Connector, with_connection
from shared.regular import regular_log
from pymongo import MongoClient
from bson import ObjectId
def with_mongodb_exception_handler(f):
def wrapper(*args):
log = reg... | [
{
"body": " def wrapper(*args):\n log = regular_log.default()\n try:\n return f(*args)\n except Exception as e:\n log['error']['exception_details'] = str(e)\n return {'log': log}\n return wrapper",
"name": "with_mongodb_exception_handler(f):MongoDB... |
267 | """
Tool Input Translation.
"""
import logging
from galaxy.util.bunch import Bunch
log = logging.getLogger(__name__)
class ToolInputTranslator:
"""
Handles Tool input translation.
This is used for data source tools
>>> from galaxy.util import Params, XML
>>> translator = ToolInputTranslator.fr... | [
{
"body": " \"\"\"Loads the proper filter by the type attribute of elem\"\"\"\n rval = ToolInputTranslator()\n for req_param in elem.findall(\"request_param\"):\n # req_param tags must look like <request_param galaxy_name=\"dbkey\" remote_name=\"GENOME\" missing=\"\" />\n ... |
268 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
import argparse
import json
import os
import re
import shutil
import subpr... | [
{
"body": " \"\"\"\n Load configuration from CLI args and Taskcluster secrets\n \"\"\"\n parser = argparse.ArgumentParser(description=\"Run code-review integration tests\")\n parser.add_argument(\n \"-c\",\n \"--configuration\",\n help=\"Local configuration file replacing Tas... |
269 | ##########################################################################
#
# Copyright (c) 2008, Image Engine Design Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistribu... | [
{
"body": "\t\treturn self.__nodeName",
"name": "METHOD_NAME(Derived"
},
{
"body": "\t\treturn self.__attributeName",
"name": "attributeName(Derived"
}
] |
270 | import numpy as np
from sklearn.base import clone
from sklearn.base import BaseEstimator, RegressorMixin
from sklearn.ensemble import GradientBoostingRegressor
from sklearn.utils import check_random_state
from joblib import Parallel, delayed
def _parallel_fit(regressor, X, y):
return regressor.fit(X, y)
class ... | [
{
"body": " \"\"\"Fit one regressor for each quantile.\n Parameters\n ----------\n X : array-like, shape=(n_samples, n_features)\n Training vectors, where `n_samples` is the number of samples\n and `n_features` is the number of features.\n y : array-like,... |
271 | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | [
{
"body": "\t\treturn self.get_query_params().get('HealthCheckEnabled')",
"name": "get_HealthCheckEnabled(self):CreateEndpointGroupRequest(RpcRequest):"
},
{
"body": "\t\tself.add_query_param('HealthCheckEnabled', HealthCheckEnabled)",
"name": "set_HealthCheckEnabled(self,CreateEndpointGroupRequ... |
272 | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | [
{
"body": "\t\treturn self.get_query_params().get('AddressIpVersion')",
"name": "METHOD_NAME(self):ListLoadBalancersRequest(RpcRequest):"
},
{
"body": "\t\treturn self.get_query_params().get('ResourceGroupId')",
"name": "get_ResourceGroupId(self):ListLoadBalancersRequest(RpcRequest):"
},
{
... |
273 | import pytest
from django.test import RequestFactory
from osf.models import RegistrationSchema
from admin_tests.utilities import setup_view
from admin.registration_schemas import views
from django.contrib.messages.storage.fallback import FallbackStorage
from django.core.files.uploadedfile import SimpleUploadedFile
f... | [
{
"body": " req = RequestFactory().get('/fake_path')\n # django.contrib.messages has a bug which effects unittests\n # more info here -> https://code.djangoproject.com/ticket/17971\n setattr(req, 'session', 'session')\n messages = FallbackStorage(req)\n setattr(req, '_m... |
274 | """
This type stub file was generated by pyright.
"""
from django.contrib import admin
from django.utils.decorators import method_decorator
from django.views.decorators.http import require_POST
from .mixins import BaseExportMixin, BaseImportMixin
class ImportExportMixinBase:
def get_model_info(self): ...
class ... | [
{
"body": "",
"name": "METHOD_NAME(self):="
},
{
"body": " \"\"\"\n Returns whether a request has import permission.\n \"\"\"\n ...",
"name": "has_import_permission(self,="
},
{
"body": " \"\"\"\n Perform the actual import action (after the user ... |
275 | # Copyright 2022 Sony Group Corporation.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to ... | [
{
"body": " env = gym.make(env_name)\n env = NumpyFloat32Env(env)\n if render:\n # render environment if render is True\n env = ScreenRenderEnv(env)\n return env",
"name": "build_classic_control_env(env_name,ExampleQFunctionBuilder(ModelBuilder):"
},
{
"body": " supe... |
276 | # Copyright 2017,2018,2019,2020,2021 Sony Corporation.
# Copyright 2021 Sony Group Corporation.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-... | [
{
"body": " if not isinstance(value, str):\n value = str(value)\n return value.lower()",
"name": "METHOD_NAME(value):"
},
{
"body": " parser.add_argument(\"--device-id\", \"-d\", type=str, default='0',\n help='Device ID the training run on. This is only valid i... |
277 | import re
from pathlib import Path
from click.testing import CliRunner, Result
from ggshield.__main__ import cli
from ggshield.core.errors import ExitCode
from tests.conftest import (
_IAC_MULTIPLE_VULNERABILITIES,
_IAC_NO_VULNERABILITIES,
_IAC_SINGLE_VULNERABILITY,
)
from tests.unit.conftest import asser... | [
{
"body": " assert \"Error scanning. Results may be incomplete.\" not in result.stdout",
"name": "METHOD_NAME(result:"
}
] |
278 | from typing import Any, Dict, List, Optional, Tuple
from boa3.internal.model.builtin.method.builtinmethod import IBuiltinMethod
from boa3.internal.model.type.primitive.ibytestringtype import IByteStringType
from boa3.internal.model.variable import Variable
from boa3.internal.neo.vm.opcode import OpcodeHelper
from boa3... | [
{
"body": " from boa3.internal.model.type.type import Type\n if not isinstance(self_type, IByteStringType):\n self_type = Type.bytes\n identifier = 'isdigit'\n args: Dict[str, Variable] = {'self': Variable(self_type)}\n super().__init__(identifier, args, return_type... |
279 | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | [
{
"body": "\t\tself.add_query_param('Password',Password)",
"name": "METHOD_NAME(self,Password):CreateDrdsDBRequest(RpcRequest):"
}
] |
280 | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | [
{
"body": "\t\treturn self.get_query_params().get('ResourceOwnerId')",
"name": "get_ResourceOwnerId(self):DescribeRouteEntryListRequest(RpcRequest):"
},
{
"body": "\t\tself.add_query_param('ResourceOwnerId', ResourceOwnerId)",
"name": "set_ResourceOwnerId(self,DescribeRouteEntryListRequest(RpcRe... |
281 | #!/bin/python
# -*- coding: utf-8 -*-
"""
Unit tests for gluon.sqlhtml
"""
import os
import sys
import unittest
from gluon.compileapp import run_controller_in, run_view_in, compile_application, remove_compiled_application
from gluon.languages import TranslatorFactory
from gluon.storage import Storage, List
from... | [
{
"body": " return True",
"name": "fake_check_credentials(foo):TestAppAdmin(unittest.TestCase):"
},
{
"body": " from gluon.globals import Request, Response, Session, current\n from gluon.html import A, DIV, FORM, MENU, TABLE, TR, INPUT, URL, XML\n from gluon.html import ASSIG... |
282 | from itertools import chain
from math import isnan
from numbers import Real, Integral
import numpy as np
from Orange.data import Value, Unknown, DiscreteVariable
__all__ = ["Instance"]
class Instance:
def __init__(self, METHOD_NAME, data=None, id=None):
"""
Construct a new data instance.
... | [
{
"body": " \"\"\"\n Construct a new data instance.\n :param domain: domain that describes the instance's variables\n :type domain: Orange.data.Domain\n :param data: instance's values\n :type data: Orange.data.Instance or a sequence of values\n :param id: instanc... |
283 | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | [
{
"body": "\t\treturn self.get_body_params().get('ProductCode')",
"name": "get_ProductCode(self):CompareFaceVerifyRequest(RpcRequest):"
},
{
"body": "\t\tself.add_body_params('ProductCode', ProductCode)",
"name": "set_ProductCode(self,CompareFaceVerifyRequest(RpcRequest):"
},
{
"body": "... |
284 | # coding=utf-8
# Copyright 2023 The Uncertainty Baselines Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by ap... | [
{
"body": " images: jnp.ndarray,\n hidden_size: int,\n patch_size: Optional[Tuple[int, int]] = None,\n patch_grid: Optional[Tuple[int, int]] = None) -> jnp.ndarray:\n n, h, w, _ = images.shape\n if patch_size is None == patch_grid is None:\n raise V... |
285 | # coding: utf-8
"""
Generated by: https://github.com/openapi-json-schema-tools/openapi-json-schema-generator
"""
import unittest
from unittest.mock import patch
import urllib3
import typing_extensions
import unit_test_api
from unit_test_api.paths.request_body_post_oneof_complex_types_request_body.post import op... | [
{
"body": " content_type = 'application/json'\n # first oneOf valid (complex)\n with patch.object(urllib3.PoolManager, 'request') as mock_request:\n payload = (\n {\n \"bar\":\n 2,\n }\n )\n ... |
286 | # This file is part of h5py, a Python interface to the HDF5 library.
#
# http://www.h5py.org
#
# Copyright 2008-2013 Andrew Collette and contributors
#
# License: Standard 3-clause BSD; see "license.txt" for full license terms
# and contributor agreement.
import unittest as ut
from h5py import h5p, h5f, ve... | [
{
"body": " '''test get/set virtual prefix '''\n dalist = h5p.create(h5p.DATASET_ACCESS)\n self.assertEqual(dalist.get_virtual_prefix().decode(), '')\n virtual_prefix = \"path/to/virtual/dataset\"\n dalist.set_virtual_prefix(virtual_prefix.encode('utf-8'))\n self.assert... |
287 | from boa3_test.tests.boa_test import BoaTest # needs to be the first import to avoid circular imports
from boa3.internal.exception import CompilerError
from boa3.internal.neo.vm.type.String import String
from boa3.internal.neo3.vm import VMState
from boa3_test.test_drive.testrunner.neo_test_runner import NeoTestRunne... | [
{
"body": " path, _ = self.get_deploy_file_paths('ReversedListBool.py')\n runner = NeoTestRunner(runner_id=self.method_name())\n invokes = []\n expected_results = []\n list_bool = [True, True, False]\n invokes.append(runner.call_contract(path, 'main'))\n reversed... |
288 | """Implementation of the CNN Decoder part of
"Convolutional Sequence to Sequence Learning"
"""
import torch
import torch.nn as nn
from onmt.modules import ConvMultiStepAttention, GlobalAttention
from onmt.utils.cnn_factory import shape_transform, GatedConv
from onmt.decoders.decoder import DecoderBase
SCALE_WEIGHT = ... | [
{
"body": " self,\n num_layers,\n hidden_size,\n attn_type,\n copy_attn,\n cnn_kernel_width,\n dropout,\n embeddings,\n copy_attn_type,",
"name": "__init__(CNNDecoder(DecoderBase):"
},
{
"body": " \"\"\"Alternate constructor.\"\"\... |
289 | from boa3_test.tests.boa_test import BoaTest # needs to be the first import to avoid circular imports
from boa3.internal.exception import CompilerError
from boa3.internal.neo.vm.opcode.Opcode import Opcode
from boa3.internal.neo3.vm import VMState
from boa3_test.test_drive.testrunner.neo_test_runner import NeoTestRun... | [
{
"body": " expected_output = (\n Opcode.INITSLOT # function signature\n + b'\\x01'\n + b'\\x00'\n + Opcode.PUSHNULL\n + Opcode.STLOC0\n + Opcode.RET # return\n )\n path = self.get_contract_path('VariableNone.py')\... |
290 | """
Copyright (c) 2023, NVIDIA CORPORATION.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in ... | [
{
"body": " self._stop = False",
"name": "__init__(self):NullStrategy(object):"
},
{
"body": " self._stop = True\n self._stop_reason = message",
"name": "set_stop(self,NullStrategy(object):"
},
{
"body": " return self._stop_reason",
"name": "stop_reason(se... |
291 | # Downloaded from https://github.com/HazyResearch/state-spaces/blob/06dbbdfd0876501a7f12bf3262121badbc7658af/src/models/functional/toeplitz.py
""" Utilities for computing convolutions.
There are 3 equivalent views:
1. causal convolution
2. multiplication of (lower) triangular Toeplitz matrices
3. polynomial... | [
{
"body": " if not pad and not fast:\n return triangular_toeplitz_multiply(u, v)\n if not pad and fast:\n return triangular_toeplitz_multiply_fast(u, v)\n if pad and not fast:\n return triangular_toeplitz_multiply_padded(u, v)\n if pad and fast:\n return triangular_toepli... |
292 | """
Adapted from a code editor component created
for Enki editor as replacement for QScintilla.
Copyright (C) 2020 Andrei Kopats
Originally licensed under the terms of GNU Lesser General Public License
as published by the Free Software Foundation, version 2.1 of the license.
This is compatible with Orange3's GPL-3.0 ... | [
{
"body": " # (Un)indent multiline with Space\n self.qpart.indentUseTabs = False\n self.qpart.text = ' ab\\n cd'\n self.qpart.selectedPosition = ((0, 2), (1, 3))\n QTest.keyClick(self.qpart, Qt.Key_Space, Qt.ShiftModifier | Qt.ControlModifier)\n self.assertEqual(self.... |
293 | ##########################################################################
#
# Copyright (c) 2008-2009, Image Engine Design Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redis... | [
{
"body": "\t\tl = IECore.LineSegment3f( imath.V3f( 0 ), imath.V3f( 1 ) )\n\t\tself.assertEqual( l( 0 ), imath.V3f( 0 ) )\n\t\tself.assertEqual( l( 1 ), imath.V3f( 1 ) )\n\t\tself.assertEqual( l( 0.5 ), imath.V3f( 0.5 ) )\n\t\tself.assertEqual( l( -1 ), imath.V3f( -1 ) )\n\t\tself.assertEqual( l( 2 ), imath.V3f... |
294 | # Copyright 2019,2020,2021 Sony Corporation.
# Copyright 2021 Sony Group Corporation.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Un... | [
{
"body": " for i in range(0, num_units):\n with nn.parameter_scope(\"unit_\"+str(i+1)):\n x = unit(x, depth_list, stride, end_point, act_fn=act_fn, atrous_conv=atrous_conv,\n atrous_rate=atrous_rate, last_block=last_block, test=test, fix_params=fix_params)\n ... |
295 | # coding=utf-8
# Copyright 2023 The TensorFlow Datasets Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appl... | [
{
"body": " \"\"\"Prepares examples for 1 day.\"\"\"\n # Read raw data\n raw_texts = _read_texts_file(texts_file_path)\n annotations = _read_annot_file(annot_file_path)\n # Construct replies graph\n idx_to_parents = {idx: [] for idx in range(len(raw_texts))}\n for parent_msg_idx, msg_idx in annotations:\... |
296 | """osf/management/commands/metrics_backfill_user_domains.py
Usage:
$ dc-manage metrics_backfill_user_domains --source=$path_to_csv
$ dc-manage metrics_backfill_user_domains --source=$path_to_csv --dry # dry run
$ dc-manage metrics_backfill_user_domains --source=$path_to_csv --resume-from 1264 # start from rec... | [
{
"body": " if not source:\n logger.info('No source file detected, exiting.')\n return\n # new user domains report is weird, b/c old data needs to be aggregated by date & domain\n count = 0\n reader = csv.DictReader(source)\n tally = {}\n this_year = None\n for row in reader:\... |
297 | import asyncio
import functools
from decimal import Decimal
from typing import Awaitable, Callable, Optional
from unittest import TestCase
from unittest.mock import AsyncMock
from hummingbot.client.config.client_config_map import ClientConfigMap
from hummingbot.client.config.config_helpers import ClientConfigAdapter
f... | [
{
"body": " super().setUp()\n self.log_records = []\n self.test_task: Optional[asyncio.Task] = None\n self.resume_test_event = asyncio.Event()\n self.client_config_map = ClientConfigAdapter(ClientConfigMap())\n self.exchange = CoinbaseProExchange(\n client_co... |
298 | # Wrapper module for waagent
#
# waagent is not written as a module. This wrapper module is created
# to use the waagent code as a module.
#
# Copyright 2014 Microsoft Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# Yo... | [
{
"body": " pass",
"name": "_AddExtensionEvent(*args,_WALAEventOperation:"
},
{
"body": " \"\"\"\n Get http_proxy and https_proxy from waagent config.\n Username and password is not supported now.\n This code is adopted from /usr/sbin/waagent\n \"\"\"\n host = None\n port... |
299 | ######################################################################
# BioSimSpace: Making biomolecular simulation a breeze!
#
# Copyright: 2017-2023
#
# Authors: Lester Hedges <lester.hedges@gmail.com>
#
# BioSimSpace is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Pub... | [
{
"body": " \"\"\"Return a string representation of the parameters.\"\"\"\n return \", \".join(\n [_Production.METHOD_NAME(self), _FreeEnergyMixin.METHOD_NAME(self)]\n )",
"name": "METHOD_NAME(self):Call"
},
{
"body": " \"\"\"Return a human readable string repr... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.