code stringlengths 281 23.7M |
|---|
def test_two_exits_to_one_case_depend_on_switch(task):
var_0 = Variable('var_0', Integer(32, True), None, True, Variable('var_10', Integer(32, True), 0, True, None))
var_1 = Variable('var_1', Pointer(Integer(32, True), 32), None, False, Variable('var_28', Pointer(Integer(32, True), 32), 1, False, None))
tas... |
class ListObjects(SimpleDirectiveMixin, Directive):
optional_arguments = 1
option_spec = {'baseclass': directives.unchanged}
def make_rst(self):
module = importlib.import_module(self.arguments[0])
base_class = None
if ('baseclass' in self.options):
base_class = import_cla... |
('urllib3.poolmanager.PoolManager.urlopen')
def test_timeout(mock_urlopen, elasticapm_client):
elasticapm_client.server_version = (8, 0, 0)
transport = Transport(' timeout=5, client=elasticapm_client)
transport.start_thread()
mock_urlopen.side_effect = MaxRetryError(None, None, reason=TimeoutError())
... |
('selector_type', ['empty'])
def test_call_with_context_args(selector, switch):
selector.set_selector(switch)
selector.set_providers(one=providers.Callable((lambda *args, **kwargs: (args, kwargs))))
with switch.override('one'):
(args, kwargs) = selector(1, 2, three=3, four=4)
assert (args == (1,... |
class DisableParametersUpdate(ErtScript):
def run(self, disable_parameters: str) -> None:
ert_config = self.ert().ert_config
altered_update_step = [UpdateStep(name='DISABLED_PARAMETERS', observations=list(ert_config.observations.keys()), parameters=[key for key in ert_config.ensemble_config.paramete... |
class CategoricalTest(unittest.TestCase):
def test_categorical_trivial(self) -> None:
self.maxDiff = None
queries = [c_trivial_simplex()]
observations = {}
observed = BMGInference().to_dot(queries, observations)
expected = '\ndigraph "graph" {\n N0[label="[1.0]"];\n N1[labe... |
def test_query(base_bot):
query = 'Test query'
config = BaseLlmConfig()
with patch.object(base_bot.app, 'query') as mock_query:
mock_query.return_value = 'Query result'
result = base_bot.query(query, config)
assert isinstance(result, str)
assert (result == 'Query result') |
def _completions_for_options(options):
output = []
should_suffix = int(os.getenv('NUBIA_SUFFIX_ENABLED', '1'))
def __suffix(key, expects_argument=True):
if (should_suffix and expects_argument):
return (key + '=')
else:
return _space_suffix(key)
for option in optio... |
class DT(Options):
def allowMultidate(self):
return self._config_get()
def allowMultidate(self, flag):
self._config(flag)
if flag:
self.multidateSeparator = ','
def daysOfWeekDisabled(self):
return self._config_get()
def daysOfWeekDisabled(self, values):
... |
.django_db
class TestDecreasePostsCountAfterPostDeletionReceiver(object):
def test_can_decrease_the_posts_count_of_the_post_being_deleted(self):
u1 = UserFactory.create()
top_level_forum = create_forum()
topic = create_topic(forum=top_level_forum, poster=u1)
PostFactory.create(topic=... |
def test_arg_cursor(golden):
def scal(n: size, alpha: R, x: [R][(n, n)]):
for i in seq(0, n):
x[(i, i)] = (alpha * x[(i, i)])
args = scal.args()
output = ''
for arg in args:
output += f'{arg.name()}, {arg.is_tensor()}'
if arg.is_tensor():
for dim in arg.sh... |
class TestFetchTestCases(BaseTaskTestCase):
(config.config, {'query_wiki_test_cases': True})
('bodhi.server.models.Build.update_test_cases')
def test_update_nonexistent(self, fetch):
with pytest.raises(BodhiException) as exc:
fetch_test_cases_main('foo')
assert (str(exc.value) ==... |
class ShareLinkBaseFile(DatClass):
type: BaseFileType = None
file_id: str = None
name: str = None
parent_file_id: str = field(default=None, repr=False)
category: BaseFileCategory = field(default=None, repr=False)
size: int = field(default=None, repr=False)
created_at: str = field(default=Non... |
class TestCombatCommands(AinneveTestMixin, EvenniaCommandTest):
def setUp(self):
super().setUp()
self.target = create_object(Mob, key='rat', location=self.room1)
def tearDown(self):
super().tearDown()
self.target.delete()
def test_engage(self):
self.call(combat.CmdIni... |
def generate_choices(item, id=id):
query = None
if (item == 'Ticket'):
query = FlicketTicket.query.filter_by(id=id).first()
elif (item == 'Post'):
query = FlicketPost.query.filter_by(id=id).first()
if query:
upload = []
for u in query.uploads:
upload.append((u... |
class OptionSeriesFunnel3dSonificationDefaultinstrumentoptionsMappingGapbetweennotes(Options):
def mapFunction(self):
return self._config_get(None)
def mapFunction(self, value: Any):
self._config(value, js_type=False)
def mapTo(self):
return self._config_get(None)
def mapTo(self,... |
class Engine():
def __init__(self, name: str, typ, process_pool: int=None) -> None:
self.exited = False
self.server_id: str = uuid.uuid4().hex
self.sid: bytes = self.server_id.encode()
self.name: str = name
self.server_type: int = typ
self.ip = '127.0.0.1'
sel... |
class BsBreadcrumb(Component):
name = 'Bootstrap Breadcrumb'
str_repr = '<nav aria-label="breadcrumb" {attrs}><ol class="breadcrumb">{sub_items}</ol></nav>'
dyn_repr = '{sub_item}'
def add_item(self, component: primitives.HtmlModel, active: bool=False):
if (not hasattr(component, 'options')):
... |
def build_data_drift_report(reference_data: pd.DataFrame, current_data: pd.DataFrame, column_mapping: ColumnMapping, drift_share=0.4) -> Report:
data_drift_report = Report(metrics=[DataDriftPreset(drift_share=drift_share)])
data_drift_report.run(reference_data=reference_data, current_data=current_data, column_m... |
class GlobalAttrs():
env_prometheus_server = '??'
env_basic_auth_enabled = False
env_prometheus_username = None
env_prometheus_password = None
env_insecure = False
log_dir = '/tmp/'
log_file = 'kptop.log'
exceptions_num = 0
session = None
node_exporter_node_label = 'node'
kub... |
class GaugeThreadPoller(GaugePoller):
def __init__(self, conf, logname, prom_client):
super().__init__(conf, logname, prom_client)
self.thread = None
self.interval = self.conf.interval
self.ryudp = None
def start(self, ryudp, active):
self.stop()
super().start(ryu... |
class OptionSeriesAreasplinerangeSonificationTracksMappingTime(Options):
def mapFunction(self):
return self._config_get(None)
def mapFunction(self, value: Any):
self._config(value, js_type=False)
def mapTo(self):
return self._config_get(None)
def mapTo(self, text: str):
s... |
class IPv6Dscp(MatchTest):
def runTest(self):
match = ofp.match([ofp.oxm.eth_type(34525), ofp.oxm.ip_dscp(4)])
matching = {'dscp=4 ecn=0': simple_tcpv6_packet(ipv6_tc=16), 'dscp=4 ecn=3': simple_tcpv6_packet(ipv6_tc=19)}
nonmatching = {'dscp=5 ecn=0': simple_tcpv6_packet(ipv6_tc=20)}
... |
('image-caption.diff')
def image_caption_diff(dataset, source_dataset):
db = connect()
examples = db.get_dataset(source_dataset)
counts = Counter()
blocks = [{'view_id': 'html', 'html_template': "<div style='opacity: 0.5'>{{orig_caption}}</div>"}, {'view_id': 'html', 'html_template': '{{caption}}'}, {'v... |
def construct_event_topic_set(event_abi: ABIEvent, abi_codec: ABICodec, arguments: Optional[Union[(Sequence[Any], Dict[(str, Any)])]]=None) -> List[HexStr]:
if (arguments is None):
arguments = {}
if isinstance(arguments, (list, tuple)):
if (len(arguments) != len(event_abi['inputs'])):
... |
class OptionSeriesOrganizationLevelsStatesInactive(Options):
def animation(self) -> 'OptionSeriesOrganizationLevelsStatesInactiveAnimation':
return self._config_sub_data('animation', OptionSeriesOrganizationLevelsStatesInactiveAnimation)
def enabled(self):
return self._config_get(True)
def e... |
def downgrade():
op.create_table('notification_actions', sa.Column('id', sa.INTEGER(), autoincrement=True, nullable=False), sa.Column('action_type', sa.VARCHAR(), autoincrement=False, nullable=True), sa.Column('subject', sa.VARCHAR(), autoincrement=False, nullable=True), sa.Column('link', sa.VARCHAR(), autoincremen... |
.skipif(sys.platform.startswith('darwin'), reason='No flock on MacOS')
def test_optional_job_id_namespace(tmpdir, monkeypatch):
monkeypatch.chdir(tmpdir)
Path(PROXYFILE_FOR_TESTS).write_text(EXAMPLE_QSTAT_CONTENT, encoding='utf-8')
assert ('15399.s034' in EXAMPLE_QSTAT_CONTENT)
result_job_with_namespace... |
class ArgCursorA(CursorArgumentProcessor):
def _cursor_call(self, arg_pattern, all_args):
if isinstance(arg_pattern, PC.ArgCursor):
return arg_pattern
elif isinstance(arg_pattern, str):
name = arg_pattern
proc = all_args['proc']
for arg in proc.args():... |
class UpgradeThread(QThread):
upgrade_signal = pyqtSignal('PyQt_PyObject')
progress_signal = pyqtSignal('int')
def __init__(self):
QThread.__init__(self)
def run(self):
self.progress_signal.emit(5)
upgrade_generator = Updater.apply_updates(vms=['dom0'], progress_start=5, progress... |
class OptionPlotoptionsTreegraphStates(Options):
def hover(self) -> 'OptionPlotoptionsTreegraphStatesHover':
return self._config_sub_data('hover', OptionPlotoptionsTreegraphStatesHover)
def inactive(self) -> 'OptionPlotoptionsTreegraphStatesInactive':
return self._config_sub_data('inactive', Opt... |
class TransformerLayer(fl.Chain):
def __init__(self, embedding_dim: int, num_heads: int, norm_eps: float, mlp_ratio: int, device: ((torch.device | str) | None)=None, dtype: (torch.dtype | None)=None) -> None:
self.embedding_dim = embedding_dim
self.num_heads = num_heads
self.norm_eps = norm_... |
class TestRenderedTag(object):
(autouse=True)
def setup(self):
self.loadstatement = '{% load forum_markup_tags %}'
self.request_factory = RequestFactory()
def test_can_render_a_formatted_text_on_the_fly(self):
def get_rendered(value):
request = self.request_factory.get('/... |
.django_db
def test_alternate_year(client, bureau_data):
resp = client.get(url.format(toptier_code='001', filter='?fiscal_year=2018'))
assert (resp.status_code == status.HTTP_200_OK)
expected_results = [{'name': 'Test Bureau 1', 'id': 'test-bureau-1', 'total_obligations': 20.0, 'total_outlays': 200.0, 'tota... |
def get_question_list(file_list: List[bytes]) -> list:
questions_list = []
temp = []
after_summary_tag = False
for line in file_list:
if line.startswith(b'<details>'):
temp.append(line)
after_summary_tag = True
elif (after_summary_tag and (line != b'') and (b'</de... |
class OptionSeriesWaterfallDatalabelsFilter(Options):
def operator(self):
return self._config_get(None)
def operator(self, value: Any):
self._config(value, js_type=False)
def property(self):
return self._config_get(None)
def property(self, text: str):
self._config(text, j... |
class BaseSensor(AsyncAgentExecutorMixin, PythonTask):
def __init__(self, name: str, sensor_config: Optional[T]=None, task_type: str='sensor', **kwargs):
type_hints = get_type_hints(self.poke, include_extras=True)
signature = inspect.signature(self.poke)
inputs = collections.OrderedDict()
... |
def normalize_string(string, charset=None, replacing=False):
if (not isinstance(string, unicode)):
try:
if re.search(u'=[0-9a-fA-F]{2}', string):
string = py2_decode(string, 'Quoted-printable')
string = json.loads((u'%s' % string), encoding=charset)
except Val... |
class Sent140Dataset(Dataset):
def __init__(self, data_root, max_seq_len):
self.data_root = data_root
self.max_seq_len = max_seq_len
self.all_letters = {c: i for (i, c) in enumerate(string.printable)}
self.num_letters = len(self.all_letters)
self.UNK = self.num_letters
... |
class UnicommercePackageType(Document):
def validate(self):
self.__update_title()
self.__validate_sizes()
def __update_title(self):
self.title = f'{self.package_type}: {self.length}x{self.width}x{self.height}'
def __validate_sizes(self):
fields = ['length', 'width', 'height']... |
class ExcelMathModel(object):
def __init__(self):
pass
def sum(self, elems):
sum_val = (('(' + ' + '.join(elems)) + ')')
if (sum_val == '()'):
return '0'
else:
return sum_val
def product(self, elems):
sum_val = (('(' + ' * '.join(elems)) + ')')... |
class TensorOperation(enum.Enum):
PassThrough = auto()
Add = auto()
AddAdd = auto()
AddMul = auto()
AddMulTanh = auto()
AlphaBetaAdd = auto()
AddRelu = auto()
AddFastGelu = auto()
AddTanh = auto()
AddHardswish = auto()
AddSwish = auto()
AddSigmoid = auto()
AddReluAdd ... |
def update_internals(new_coords3d, old_internals, primitives, dihedral_inds, rotation_inds, bend_inds, check_dihedrals=False, check_bends=False, bend_min_deg=BEND_MIN_DEG, bend_max_deg=LB_MIN_DEG, rotation_thresh=0.9, logger=None):
prim_internals = eval_primitives(new_coords3d, primitives)
new_internals = np.ar... |
def get_first_mouse():
if (('RIVALCFG_PROFILE' in os.environ) and (os.environ['RIVALCFG_PROFILE'] == '0000:0000')):
return None
plugged_devices = list(devices.list_plugged_devices())
if (not plugged_devices):
return None
return mouse.get_mouse(vendor_id=plugged_devices[0]['vendor_id'], p... |
def test_cube_thinning(tmpdir, loadsfile1):
logger.info('Import SEGY format via SEGYIO')
incube = loadsfile1
logger.info(incube)
incube.do_thinning(2, 2, 1)
logger.info(incube)
incube.to_file(join(tmpdir, 'cube_thinned.segy'))
incube2 = xtgeo.cube_from_file(join(tmpdir, 'cube_thinned.segy'))... |
def new_user_record_list() -> List[auth.UserRecord]:
(uid1, email1) = _random_id()
(uid2, email2) = _random_id()
(uid3, email3) = _random_id()
users = [auth.create_user(uid=uid1, email=email1, password='password', phone_number=_random_phone()), auth.create_user(uid=uid2, email=email2, password='password... |
def extractTaniandrisWordpressCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [('PRC', 'PRC', 'translated'), ('Loiterous', 'Loiterous', 'oel')]
for (tagname, name, tl_type... |
class ToneSandhi():
def __init__(self):
self.must_neural_tone_words = {'', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '... |
def cd_to_project_root():
project_root = os.path.split(os.path.realpath(__file__))[0]
class CwdContext():
def __enter__(self):
self.old_path = os.getcwd()
os.chdir(project_root)
sys.path.insert(0, project_root)
def __exit__(self, *args):
del sys.pa... |
def upgrade():
op.execute('ALTER TABLE email_notifications ALTER after_ticket_purchase TYPE boolean USING CASE after_ticket_purchase WHEN 1 THEN TRUE ELSE FALSE END', execution_options=None)
op.execute('ALTER TABLE email_notifications ALTER new_paper TYPE boolean USING CASE new_paper WHEN 1 THEN ... |
class TestSerializerValidationWithCompiledRegexField():
def setup_method(self):
class ExampleSerializer(serializers.Serializer):
name = serializers.RegexField(re.compile('\\d'), required=True)
self.Serializer = ExampleSerializer
def test_validation_success(self):
serializer =... |
.flaky(reruns=MAX_FLAKY_RERUNS)
class TestSearchSkillsLocal():
def setup_class(cls):
cls.runner = CliRunner()
('aea.cli.search.format_items', return_value=FORMAT_ITEMS_SAMPLE_OUTPUT)
def test_correct_output_default_registry(self, _):
self.result = self.runner.invoke(cli, [*CLI_LOG_OPTION, 's... |
def clean_up_queue(upload_queue_files):
try:
os.remove(upload_queue_files.image_output)
except OSError:
logger.exception('Error removing upload queue image')
try:
os.remove(upload_queue_files.thumbnail_output)
except OSError:
logger.exception('Error removing upload queue ... |
class DatasetMissingValues(MetricResult):
different_missing_values: Dict[(MissingValue, int)]
number_of_different_missing_values: int
different_missing_values_by_column: Dict[(str, Dict[(MissingValue, int)])]
number_of_different_missing_values_by_column: Dict[(str, int)]
number_of_missing_values: in... |
class TestConfig(unittest.TestCase):
pwd = os.path.dirname(os.path.abspath(__file__))
module = browsepy.appconfig
def test_case_insensitivity(self):
cfg = self.module.Config(self.pwd, defaults={'prop': 2})
self.assertEqual(cfg['prop'], cfg['PROP'])
self.assertEqual(cfg['pRoP'], cfg.p... |
def run(client_args, other_args, action_file, dry_run=False):
logger = logging.getLogger(__name__)
logger.debug('action_file: %s', action_file)
all_actions = ActionsFile(action_file)
for idx in sorted(list(all_actions.actions.keys())):
action_def = all_actions.actions[idx]
if action_def.... |
def serialize_and_package(pkgs: typing.List[str], settings: SerializationSettings, source: str='.', output: str='./flyte-package.tgz', fast: bool=False, deref_symlinks: bool=False, options: typing.Optional[Options]=None):
serializable_entities = serialize(pkgs, settings, source, options=options)
package(seriali... |
class ValveDot1xACLSmokeTestCase(ValveDot1xSmokeTestCase):
ACL_CONFIG = '\nacls:\n auth_acl:\n - rule:\n actions:\n allow: 1\n noauth_acl:\n - rule:\n actions:\n allow: 0\n'
CONFIG = '\n{}\ndps:\n s1:\n{}\n interfaces:\n ... |
class CmdIC(COMMAND_DEFAULT_CLASS):
key = 'ic'
locks = 'cmd:all()'
aliases = 'puppet'
help_category = 'General'
account_caller = True
def func(self):
account = self.account
session = self.session
new_character = None
character_candidates = []
if (not self.... |
class Packetizer(LiteXModule):
def __init__(self, sink_description, source_description, header):
self.sink = sink = stream.Endpoint(sink_description)
self.source = source = stream.Endpoint(source_description)
self.header = Signal((header.length * 8))
data_width = len(self.sink.data)
... |
.skipif((not hasattr(_writer, 'CYTHON_MODULE')), reason='Cython-specific test')
def test_regular_vs_ordered_dict_record_typeerror():
schema = {'type': 'record', 'name': 'Test', 'namespace': 'test', 'fields': [{'name': 'field', 'type': {'type': 'int'}}]}
test_records = [{'field': 'foobar'}]
record = OrderedD... |
class MarkdownRenderer():
def __init__(self, no_emoji: bool=False):
self.data: List = []
self.no_emoji = no_emoji
def text(self) -> str:
return '\n\n'.join(self.data)
def add(self, content: str):
self.data.append(content)
def table(self, data: Iterable[Iterable[str]], hea... |
_db(transaction=True)
def test_load_table_to_from_delta_for_transaction_search(spark, s3_unittest_data_bucket, populate_usas_data_and_recipients_from_broker, hive_unittest_metastore_db):
tables_to_load = ['awards', 'financial_accounts_by_awards', 'recipient_lookup', 'recipient_profile', 'sam_recipient', 'transactio... |
class ConfigLoader(Generic[T], BaseConfigLoader):
def __init__(self, schema_filename: str, configuration_class: Type[T], skip_aea_validation: bool=True) -> None:
super().__init__(schema_filename)
self._configuration_class = configuration_class
self._skip_aea_validation = skip_aea_validation
... |
class JsCountAll():
params = ('keys',)
value = '\n var temp = {}; var order= [];\n data.forEach(function(rec){ \n keys.forEach(function(k){\n var aggKey = k +"#"+ rec[k]; if(!(aggKey in temp)){order.push(aggKey); temp[aggKey] = 1} else{temp[aggKey] += 1}})}); \n order.forEach(function(label... |
def test_overflow_uint():
assert (to_int((((2 ** 256) // 2) - 1)) == (((2 ** 256) // 2) - 1))
with pytest.raises(OverflowError):
to_int(((2 ** 256) // 2))
assert (to_int((((2 ** 256) // 2) - 1), 'int') == (((2 ** 256) // 2) - 1))
with pytest.raises(OverflowError):
to_int(((2 ** 256) // 2... |
class SGETracker(IntervalModule):
interval = 60
settings = (('ssh', 'The SSH connection address. Can be or user: or -p PORT etc.'), 'color', 'format')
required = ('ssh',)
format = 'SGE qw: {queued} / r: {running} / Eqw: {error}'
on_leftclick = None
color = '#ffffff'
def parse_qstat_xml(sel... |
def generate_html(offers: Sequence[Offer], file: Path, author_name: str, author_mail: str, author_web: str, feed_id_prefix: str, source: (Source | None)=None, type_: (OfferType | None)=None, duration: (OfferDuration | None)=None) -> None:
latest_date: (datetime | None) = None
entries = []
for offer in offer... |
class OptionSeriesVariablepieDataDragdropGuideboxDefault(Options):
def className(self):
return self._config_get('highcharts-drag-box-default')
def className(self, text: str):
self._config(text, js_type=False)
def color(self):
return self._config_get('rgba(0, 0, 0, 0.1)')
def colo... |
def write_ram_ext_tags(segmk, tile_param):
for param in ['RAM_EXTENSION_A', 'RAM_EXTENSION_B']:
set_val = tile_param[param]
for opt in ['LOWER']:
segmk.add_site_tag(tile_param['site'], '{}_{}'.format(param, opt), (set_val == opt))
segmk.add_site_tag(tile_param['site'], '{}_NONE_O... |
def test_msgpack_custom_encoder_decoder():
class CustomObject():
def __init__(self, value):
self.value = value
def serialize_obj(obj, chain=None):
if isinstance(obj, CustomObject):
return {'__custom__': obj.value}
return (obj if (chain is None) else chain(obj))
... |
class TestInfraConfig(unittest.TestCase):
def test_stage_flow(self) -> None:
pass
def test_is_stage_flow_completed(self) -> None:
pass
def test_is_tls_enabled_when_flag_missing(self):
config = self._create_config(PrivateComputationGameType.LIFT, set())
is_tls_enabled = config... |
def admin_daily_update(location):
today = timezone.localtime(timezone.now()).date()
arriving_today = Use.objects.filter(location=location).filter(arrive=today).filter(status='confirmed')
maybe_arriving_today = Use.objects.filter(location=location).filter(arrive=today).filter(status='approved')
pending_n... |
class CLISerializer(AbstractSerializer):
regex_keys_with_values = '-+\\w+(?=\\s[^\\s-])'
regex_all_keys = '-+\\w+'
def __init__(self):
super().__init__(extensions=['cli'])
def parse_keys(regex, string):
results = [match.group(0) for match in finditer(regex, string)]
return result... |
class OptionPlotoptionsAreaZones(Options):
def className(self):
return self._config_get(None)
def className(self, text: str):
self._config(text, js_type=False)
def color(self):
return self._config_get(None)
def color(self, text: str):
self._config(text, js_type=False)
... |
def is_hidden(path: AnyStr) -> bool:
hidden = False
f = os.path.basename(path)
if (f[:1] in ('.', b'.')):
hidden = True
elif (sys.platform == 'win32'):
results = os.lstat(path)
FILE_ATTRIBUTE_HIDDEN = 2
hidden = bool((results.st_file_attributes & FILE_ATTRIBUTE_HIDDEN))
... |
class WebSocketRPCClient(RPCClient):
def __init__(self, ws):
self.ws = ws
self.queue = hub.Queue()
super().__init__(JSONRPCProtocol(), WebSocketClientTransport(ws, self.queue))
def serve_forever(self):
while True:
msg = self.ws.wait()
if (msg is None):
... |
class TestProxyEnv(GymTestCase):
is_agent_to_agent_messages = False
def test__init__(self):
assert (self.proxy_env._is_rl_agent_trained is False)
assert (self.proxy_env._step_count == 0)
assert (self.proxy_env._active_dialogue is None)
def test_properties(self):
assert (self.... |
(params=[2, 3], ids=['Rectangle', 'Box'])
def tp_mesh(request):
nx = 4
distribution = {'overlap_type': (DistributedMeshOverlapType.VERTEX, 1)}
m = UnitSquareMesh(nx, nx, quadrilateral=True, distribution_parameters=distribution)
if (request.param == 3):
m = ExtrudedMesh(m, nx)
x = SpatialCoor... |
class Card(ft.GestureDetector):
def __init__(self, solitaire, color):
super().__init__()
self.slot = None
self.mouse_cursor = ft.MouseCursor.MOVE
self.drag_interval = 5
self.on_pan_start = self.start_drag
self.on_pan_update = self.drag
self.on_pan_end = self.d... |
def encode_sequence(raw_sequence: Sequence[RLP]) -> Bytes:
joined_encodings = get_joined_encodings(raw_sequence)
len_joined_encodings = Uint(len(joined_encodings))
if (len_joined_encodings < 56):
return (Bytes([(192 + len_joined_encodings)]) + joined_encodings)
else:
len_joined_encodings... |
class SpotifyAudiobook(SpotifyBase):
()
_and_process(single(FullAudiobook))
def audiobook(self, audiobook_id: str, market: str=None) -> FullAudiobook:
return self._get(('audiobooks/' + audiobook_id), market=market)
()
('audiobook_ids', 1, 50, join_lists)
_and_process(model_list(FullAudio... |
()
('type_', metavar='TYPE', type=click.Choice(list(crypto_registry.supported_ids)), required=True)
_option()
_context
_aea_project
def get_address(click_context: click.Context, type_: str, password: Optional[str]) -> None:
ctx = cast(Context, click_context.obj)
address = _try_get_address(ctx, type_, password)
... |
class Geoform():
def __init__(self, hexes, geotype):
self.type = geotype
self.hexes = hexes
self.size = len(hexes)
self.id = uuid.uuid4()
self.neighbors = set()
self.to_delete = False
for h in hexes:
h.geoform = self
def to_dict(self):
... |
class Lock(Base, ReprMixIn):
__tablename__ = 'locks'
REPR_SQL_ATTR_SORT_FIRST = ['lock_name', 'host', 'process_id', 'date']
lock_name = sqlalchemy.Column(sqlalchemy.String(255), nullable=False, primary_key=True)
host = sqlalchemy.Column(sqlalchemy.String(255), nullable=False)
process_id = sqlalchemy... |
_test_windows
.asyncio
class TestAEAHelperPosixNamedPipeChannel():
.asyncio
async def test_connection_communication(self):
pipe = PosixNamedPipeChannel()
assert ((pipe.in_path is not None) and (pipe.out_path is not None)), 'PosixNamedPipeChannel not properly setup'
connected = asyncio.en... |
def get_pdf_notes_last_added_first(limit: int=None) -> List[SiacNote]:
if limit:
limit = f'limit {limit}'
else:
limit = ''
conn = _get_connection()
res = conn.execute(f"select * from notes where lower(source) like '%.pdf' order by id desc {limit}").fetchall()
conn.close()
return ... |
def import_roff(filelike: Union[(TextIO, BinaryIO, _PathLike)], name: Optional[str]=None) -> np.ma.MaskedArray[(Any, np.dtype[np.float32])]:
looking_for = {'dimensions': {'nX': None, 'nY': None, 'nZ': None}, 'parameter': {'name': None, 'data': None}}
def reset_parameter() -> None:
looking_for['parameter... |
def write_until_byte_equals(offset, byte):
current = None
before = time()
while (current != byte):
bb = time()
set_key((('B' * offset) + '\x00'))
encrypt_message(('A' * 256))
current = leak_offset_byte(offset)
print(('attempt: ' + str((time() - bb))))
print(('FINA... |
def extractCrazymoonlightCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [("i'm just this 'sue'", 'Im Just This Sue', 'translated'), ('PRC', 'PRC', 'translated'), ('Loiterous'... |
class HighlightTreeprocessor(Treeprocessor):
def __init__(self, md, ext):
self.ext = ext
super().__init__(md)
def code_unescape(self, text):
text = text.replace('<', '<')
text = text.replace('>', '>')
text = text.replace('&', '&')
return text
def run... |
class OptionSeriesTreegraphSonificationTracksMappingHighpassResonance(Options):
def mapFunction(self):
return self._config_get(None)
def mapFunction(self, value: Any):
self._config(value, js_type=False)
def mapTo(self):
return self._config_get(None)
def mapTo(self, text: str):
... |
class TestSkillDocs():
def setup_class(cls):
markdown_parser = mistune.create_markdown(renderer=mistune.AstRenderer())
skill_doc_file = Path(ROOT_DIR, 'docs', 'skill.md')
doc = markdown_parser(skill_doc_file.read_text())
cls.code_blocks = list(filter((lambda x: (x['type'] == 'block_c... |
class FipaDialogues(Model, BaseFipaDialogues):
def __init__(self, **kwargs: Any) -> None:
Model.__init__(self, **kwargs)
def role_from_first_message(message: Message, receiver_address: Address) -> Dialogue.Role:
fipa_message = cast(FipaMessage, message)
if (fipa_message.perfo... |
class TestDifferenceToFetchedAgent(BaseAEATestCase):
_mock_called = False
original_function = yaml.safe_load_all
test_agent_name: str
def setup_class(cls) -> None:
super().setup_class()
cls.test_agent_name = 'test_agent'
cls.fetch_agent(str(MY_FIRST_AEA_PUBLIC_ID), cls.test_agent... |
def test_interference_graph_of_group_first_graph_c():
interference_graph = construct_graph(1)
sub_graph = interference_graph.get_subgraph_of(InsertionOrderedSet([v_1, v_2, x_1]))
assert (InsertionOrderedSet(sub_graph.nodes) == InsertionOrderedSet([v_1, v_2, x_1]))
assert (sub_graph.are_interfering(v_1, ... |
class VRRPInterfaceMonitor(app_manager.RyuApp):
_CONSTRUCTORS = {}
def register(interface_cls):
def _register(cls):
VRRPInterfaceMonitor._CONSTRUCTORS[interface_cls] = cls
return cls
return _register
def factory(interface, config, router_name, statistics, *args, **kwa... |
class LiteEthPHYXGMIICRG(Module, AutoCSR):
def __init__(self, clock_pads, model=False):
self._reset = CSRStorage()
self.clock_domains.cd_eth_rx = ClockDomain()
self.clock_domains.cd_eth_tx = ClockDomain()
if model:
self.comb += [self.cd_eth_rx.clk.eq(ClockSignal()), self.... |
class DatasetGraph():
def __init__(self, *datasets: GraphDataset) -> None:
nodes = [Node(dr, ds) for dr in datasets for ds in dr.collections]
self.nodes: dict[(CollectionAddress, Node)] = {node.address: node for node in nodes}
self.edges: Set[Edge] = set()
for (node_address, node) in... |
class filenamesDataset(object):
def __init__(self, fnames):
self.fnames = fnames
self.fnames_array = []
f = open(self.fnames)
for line in f:
line = line.split('\n')[0]
self.fnames_array.append(line)
def __getitem__(self, idx):
return self.fnames_ar... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.