code stringlengths 281 23.7M |
|---|
def parse_access(register, name, write, value, byte_order, silent):
(modbus_type, address, pack_type, presenter) = re.match(REGISTER_RE, register).groups()
if (not address):
logging.warn('%r is not a known named register nor a valid register definition. Skipping it.', register)
return None
i... |
def graphs_no_ep_in_address():
x = vars('x', 6)
y = vars('y', 6)
z = vars('z', 6, aliased=True)
c = const(10)
in_n0 = BasicBlock(0, [_assign(x[0], x[2]), _assign(z[0], x[0]), _assign(y[0], _addr(z[0])), _assign(x[1], c[0]), _assign(z[1], x[1]), _assign(y[1], _add(_addr(z[1]), x[0])), _assign(y[2], _... |
class TriggerReqBody(BaseModel):
messages: str = Field(..., description='User input messages')
command: Optional[str] = Field(default='fix', description='Command name')
model: Optional[str] = Field(default='gpt-3.5-turbo', description='Model name')
stream: Optional[bool] = Field(default=False, descripti... |
_custom_acc_mapper_fn(op_and_target=('call_method', 'repeat_interleave'), arg_replacement_tuples=[('input', 'input'), ('repeats', 'repeats'), ('dim', 'dim', this_arg_is_optional), ('output_size', 'output_size', this_arg_is_optional)], skip_normalization_if_none=True)
_custom_acc_mapper_fn(op_and_target=('call_function'... |
def extractTracantranslationBlogspotCom(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, t... |
def setup_to_pass():
shutil.copy('/etc/pam.d/system-auth', '/etc/pam.d/system-auth.bak')
shutil.copy('/etc/pam.d/password-auth', '/etc/pam.d/password-auth.bak')
shellexec("sed -i '/password\\s*sufficient\\s*pam_unix.so/ s/sha512/sha512 remember=5/' /etc/pam.d/system-auth")
shellexec("sed -i '/password\\... |
.param_file((FIXTURE_PATH / 'mock_include.md'))
def test_render(file_params, tmp_path, monkeypatch):
monkeypatch.chdir(tmp_path)
tmp_path.joinpath('other.md').write_text('a\nb\nc')
tmp_path.joinpath('fmatter.md').write_text('---\na: 1\n---\nb')
doctree = publish_doctree(file_params.content, parser=Parse... |
def xls_for_macs2(macs_xls, row_limit=None, cell_char_limit=None):
if macs_xls.macs_version.startswith('1.'):
raise Exception('Only handles output from MACS 2.0*')
macs_xls.sort_on('fold_enrichment', reverse=True)
if (row_limit is None):
row_limit = Limits.MAX_NUMBER_ROWS_PER_WORKSHEET
i... |
def train(model, train_loader, val_loader, optimizer, init_lr=0.002, checkpoint_dir=None, checkpoint_interval=None, nepochs=None, clip_thresh=1.0):
if use_cuda:
model = model.cuda()
criterion = nn.CrossEntropyLoss()
criterion_reconstruction = DiscretizedMixturelogisticLoss()
global global_step, ... |
def string_to_script_template(text: str) -> ScriptTemplate:
if text.startswith(PREFIX_BIP276_SCRIPT):
(prefix, version, network, data) = bip276_decode(text, Net.BIP276_VERSION)
assert (network == Net.BIP276_VERSION), 'incompatible network'
return classify_output_script(Script(data), Net.COIN... |
def create_diagram(cnarr, segarr, threshold, min_probes, outfname, show_range=None, title=None, show_labels=True):
if (cnarr and segarr):
do_both = True
cnarr_is_seg = False
else:
if cnarr:
cnarr_is_seg = False
elif segarr:
cnarr = segarr
cnarr... |
def _create_model_start_listener(system_app: SystemApp):
from dbgpt.datasource.manages.connection_manager import ConnectManager
cfg = Config()
def startup_event(wh):
print('begin run _add_app_startup_event')
conn_manage = ConnectManager(system_app)
cfg.LOCAL_DB_MANAGE = conn_manage
... |
.django_db
def test_limit_values(client, create_idv_test_data):
_test_post(client, {'award_id': 2, 'limit': 1}, (400002, 1, 1, False, 14))
_test_post(client, {'award_id': 2, 'limit': 5}, (400002, 5, 1, False, 14, 13, 12, 11, 10))
_test_post(client, {'award_id': 2, 'limit': 0}, expected_status_code=status.HT... |
class OptionSeriesBubbleSonification(Options):
def contextTracks(self) -> 'OptionSeriesBubbleSonificationContexttracks':
return self._config_sub_data('contextTracks', OptionSeriesBubbleSonificationContexttracks)
def defaultInstrumentOptions(self) -> 'OptionSeriesBubbleSonificationDefaultinstrumentoption... |
def get_erpnext_item_code(integration: str, integration_item_code: str, variant_id: Optional[str]=None, has_variants: Optional[int]=0) -> Optional[str]:
filters = {'integration': integration, 'integration_item_code': integration_item_code}
if variant_id:
filters.update({'variant_id': variant_id})
el... |
def test_router_add_websocket_route(client):
with client.websocket_connect('/ws') as session:
text = session.receive_text()
assert (text == 'Hello, world!')
with client.websocket_connect('/ws/test') as session:
text = session.receive_text()
assert (text == 'Hello, test!') |
(scope='function')
def experience_config_tcf_overlay(db: Session) -> Generator:
config = PrivacyExperienceConfig.create(db=db, data={'accept_button_label': 'Accept all', 'acknowledge_button_label': 'Confirm', 'banner_enabled': 'enabled_where_required', 'component': 'tcf_overlay', 'description': 'On this page you ca... |
def run_trace(filename, out):
with open(filename) as trace_file:
sequence = parse_trace(trace_file, None)
with open(out, 'w') as trace_file:
for (command, out) in sequence:
trace_file.write('$ {}\n'.format(command))
(status, stdout, stderr) = run_command(command)
... |
def extractZetrotranslationWordpressCom(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, t... |
def bm25(rawMatchInfo):
match_info = _parseMatchInfo(rawMatchInfo)
K = 0.5
B = 0.75
score = 0.0
(P_O, C_O, N_O, A_O) = range(4)
term_count = match_info[P_O]
col_count = match_info[C_O]
total_docs = match_info[N_O]
L_O = (A_O + col_count)
X_O = (L_O + col_count)
weights = ([1]... |
class _InnerEnv(BaseEnv, _EnvInterfaceInner):
action_space = None
observation_space = None
reward_range = None
metadata = None
def seed(self, seed: int) -> None:
pass
def close(self) -> None:
pass
def reset(self) -> Any:
pass
def step(self, action):
pass
... |
class _BaseVenvFactory():
venvs_directory: Path
def venv(self, project: str, setup_commands: list[str]) -> Generator[(VirtualEnvironment, None, None)]:
venv_path = (self.venvs_directory / project)
old_cwd = Path.cwd()
virtual_env = VirtualEnvironment(venv_path, project)
virtual_e... |
.parametrize('host_in,port_in,expected_host_out,expected_port_out', ((None, None, 'localhost', 5432), (None, 5432, 'localhost', 5432), ('localhost', '5432', 'localhost', 5432), ('foo.bar', '5432', 'foo.bar', 5432), ('localhost,foo.bar', '5432,1234', 'localhost', 5432)))
def test_get_destination(host_in, port_in, expect... |
_converter(acc_ops.tile)
def acc_ops_tile(target: Target, args: Tuple[(Argument, ...)], kwargs: Dict[(str, Argument)], name: str) -> ConverterOutput:
input_val = kwargs['input']
if (not isinstance(input_val, AITTensor)):
raise RuntimeError(f'Unexpected input for {name}: {input_val}')
shape_dims = li... |
class DataFile(AbstractLayout):
layout = 'text'
opened_queue = []
max_queue_entries = 31
def __init__(self, textFile, textParser, variationModules):
self._record_index = RecordIndex(textFile, textParser)
self._text_parser = textParser
self._text_file = textFile
self._vari... |
class OptionPlotoptionsDependencywheelSonificationTracksMappingTime(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 OptionPlotoptionsCylinderSonificationTracksMappingLowpassFrequency(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 ViolationAttributes(BaseModel):
data_categories: List[str] = Field(description='A list of data categories which led to an evaluation violation.')
data_subjects: List[str] = Field(description='A list of data subjects which led to an evaluation violation.')
data_uses: List[str] = Field(description='A li... |
def test_periodic_interval_div_free():
m = PeriodicUnitIntervalMesh(50)
mesh = ExtrudedMesh(m, 50)
V = VectorFunctionSpace(mesh, 'CG', 3)
(x, y) = SpatialCoordinate(mesh)
u = Function(V)
u.interpolate(as_vector([sin(((2 * np.pi) * x)), ((((- 2) * np.pi) * y) * cos(((2 * np.pi) * x)))]))
asse... |
def test_sampling_array_dims():
raw = [1, 2, 3, 4, 5, 6]
dimensions = [3]
samples = sampling(raw, dimensions)
assert np.array_equal(samples[0], np.array(raw[0:3]))
assert np.array_equal(samples[1], np.array(raw[3:6]))
dimensions = [6]
samples = sampling(raw, dimensions)
assert np.array_e... |
def cfrp(agent: Agent, state: ShortDeckPokerState, i: int, t: int, c: int, locks: Dict[(str, mp.synchronize.Lock)]={}):
ph = state.player_i
player_not_in_hand = (not state.players[i].is_active)
if (state.is_terminal or player_not_in_hand):
return state.payout[i]
elif (ph == i):
this_info... |
def test_adding_a_extra_init_container_as_yaml():
config = "\nextraInitContainers:\n - name: do-something\n image: busybox\n command: ['do', 'something']\n"
r = helm_template(config)
extraInitContainer = r['statefulset'][uname]['spec']['template']['spec']['initContainers']
assert ({'name': 'do-so... |
class OptionSeriesPyramidDataDragdropGuideboxDefault(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 color(se... |
def sequential_graph_fixer(fixers: List[GraphFixer]) -> GraphFixer:
def sequential(bmg: BMGraphBuilder) -> GraphFixerResult:
made_progress = False
errors = ErrorReport()
current = bmg
for fixer in fixers:
(current, fixer_made_progress, errors) = fixer(current)
... |
def Fstiffness_k(k: int, kappa0: float, kappa1: float, innerimagelist: np.ndarray, outerimagelist: np.ndarray, Eholo_vertical: np.ndarray):
v0inner = (innerimagelist[k] - innerimagelist[(k + 1)])
tdelta0inner = np.linalg.norm(v0inner)
v0outer = (outerimagelist[k] - outerimagelist[(k + 1)])
tdelta0outer ... |
class TestBasicLazy(AllTypes):
def arg_builder(monkeypatch):
with monkeypatch.context() as m:
m.setattr(sys, 'argv', ['', '--config', './tests/conf/yaml/test.yaml'])
config = ConfigArgBuilder(TypeConfig, TypeOptConfig, lazy=True)
return config.generate() |
def on_window_new(layouts: Layouts, state: State):
def _on_window_new(i3l: Connection, e: WindowEvent):
logger.debug(f'[ipc] window new event - container:{e.container.id}:{e.container.window}')
context = state.sync_context(i3l)
if ((not layouts.exists_for(context.workspace.name)) or (context... |
class TaskStatusCondition(Condition):
def __init__(self, workflow_name: str, task_name: str, namespace: str, expect_status: TaskStatus):
key = TaskStatusChangedEvent.generate_task_status_changed_event_key(namespace, workflow_name, task_name)
super().__init__([key])
self.expect_status = expec... |
def upgrade():
op.execute('delete from users_events_roles where event_id is null or role_id is null or user_id is null')
op.alter_column('users_events_roles', 'event_id', existing_type=sa.INTEGER(), nullable=False)
op.alter_column('users_events_roles', 'role_id', existing_type=sa.INTEGER(), nullable=False)
... |
class EvaluatorStaticTest(unittest.TestCase, EvaluatorTestCases):
grammar_scopes = AttributeGrammar.from_modules(scopes, rule_extractor=Parser())
grammar_arithmetic = AttributeGrammar.from_modules(arithmetic, rule_extractor=Parser())
evaluator_scopes = StaticEvaluator(grammar_scopes)
evaluator_arithmeti... |
class Deployer(object):
def __init__(self, cloud='heroku', config_json=None, credentials_json=None):
self.cloud = cloud
self.dep = None
if (cloud == 'local'):
self.dep = Local(config_json=config_json, credentials_json=credentials_json)
if (cloud == 'heroku'):
... |
class OptionPlotoptionsPyramidSonificationDefaultinstrumentoptionsMappingVolume(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... |
def test_get_experiment(poly_example_tmp_dir, dark_storage_client):
resp: Response = dark_storage_client.get('/experiments')
answer_json = resp.json()
assert (len(answer_json) == 1)
assert ('ensemble_ids' in answer_json[0])
assert (len(answer_json[0]['ensemble_ids']) == 2)
assert ('name' in answ... |
def rotate_alphabet(text, key):
result = ''
for letter in text:
if letter.isalpha():
if letter.isupper():
result += AlPHABET[((AlPHABET.index(letter.lower()) + key) % 26)].upper()
else:
result += AlPHABET[((AlPHABET.index(letter) + key) % 26)]
... |
def test_write_long(la: LogicAnalyzer, slave: I2CSlave):
la.capture(2, block=False)
slave.write_long(WRITE_DATA, REGISTER_ADDRESS)
la.stop()
(scl, sda) = la.fetch_data()
assert (len(scl) == ((SCL_START + (SCL_WRITE * 6)) + SCL_STOP))
assert (len(sda) == ((((SDA_START + SDA_DEVICE_ADDRESS) + SDA_... |
(scope='function')
def exit_manager(manager_nospawn, monkeypatch, temp_output):
def no_op(self, *args, **kwargs):
def _():
self.is_counting = False
return _
def new_config(self, qtile, bar):
QuickExit._configure(self, qtile, bar)
self.qtile.stop = no_op(self)
monk... |
def test_data_integrity_test_all_unique_values() -> None:
test_dataset = pd.DataFrame({'feature1': [1, 1, 2, 3], 'feature2': [1, 2, np.nan, 4], 'target': ['1', '2', '3', '']})
suite = TestSuite(tests=[TestColumnAllUniqueValues(column_name='not_exists_feature')])
suite.run(current_data=test_dataset, referenc... |
def test_object_many_objects_nameonly(tmpdir_factory, merge_files_manyLR):
fpath = str(tmpdir_factory.mktemp('lf').join('same-id.dlis'))
content = ['data/chap4-7/eflr/envelope.dlis.part', 'data/chap4-7/eflr/file-header.dlis.part', 'data/chap4-7/eflr/match/T.CHANNEL-I.MATCH1-O.16-C.0.dlis.part', 'data/chap4-7/ef... |
class OptionPlotoptionsErrorbarSonificationContexttracksMappingTime(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 TreeNode():
def __init__(self, klass):
self.klass = klass
self.name = klass.__name__
self.children = []
self.parents = []
self.level = None
def add_parent(self, parent):
assert isinstance(parent, TreeNode)
if (parent not in self.parents):
... |
def output_excel_footer(worksheet, row, no_file_comments, qn, elapsed_time):
if (not no_file_comments):
worksheet.write(row, 0, f'## {qn} queries scanned')
worksheet.write((row + 1), 0, f'## Total time (seconds): {elapsed_time}')
worksheet.write((row + 2), 0, f'## Rate: {(float(qn) / elapsed... |
class RoleDetail(ResourceDetail):
def before_get_object(self, view_kwargs):
if (view_kwargs.get('role_invite_id') is not None):
role_invite = safe_query_kwargs(RoleInvite, view_kwargs, 'role_invite_id')
view_kwargs['id'] = role_invite.role_id
if (view_kwargs.get('users_events... |
def get_prices(games: Iterable['Game'], country: str) -> Iterator[Tuple[(str, Price)]]:
prices = {}
chunk = []
for game in games:
chunk.append(game)
if (len(chunk) == 50):
fetched = {nsuid: price for (nsuid, price) in fetch_prices(country=country, nsuids=[game.nsuid for game in c... |
.gui()
.parametrize(('show_on_startup', 'expected_return_code'), [(False, introduction.Choice.SHOW), (True, introduction.Choice.DONT_SHOW)])
def test_introduction_toggle_checkbox_changes_return_code(qtbot, show_on_startup, expected_return_code):
dialog = introduction.IntroductionDialog(show_on_startup=show_on_start... |
.skipif((('raspberrypi' != os.uname()[1]) and ('raspizero' != os.uname()[1])), reason='RPi only (ePhat) test')
class TestE2eRPiEphatEgress():
def get_ping_status(self, fledge_url):
conn =
conn.request('GET', '/fledge/ping')
r = conn.getresponse()
assert (200 == r.status)
r =... |
def construct_article_list(modules_and_symbols):
articles = {}
symbol_to_article = {}
for (mod_name, (module, symbols)) in modules_and_symbols.items():
if len(symbols):
article_name = mod_name.lower()
if (article_name in articles):
suffix = 1
w... |
class SnowflakeAdapterTeleport(TeleportAdapter):
def __init__(self, db_adapter: BaseAdapter, teleport_credentials: TeleportCredentials):
from dbt.adapters.fal_experimental.adapter_support import new_connection
self._db_adapter = db_adapter
self._credentials = teleport_credentials
url... |
def largest_optimized(min_factor, max_factor):
if (min_factor > max_factor):
raise ValueError('min must be <= max')
result = 0
answer = []
for number_a in range(max_factor, (min_factor - 1), (- 1)):
was_bigger = False
for number_b in range(max_factor, (number_a - 1), (- 1)):
... |
class TestRefreshingToken():
def test_repr(self):
low_token = make_token_obj('token', False)
cred = MagicMock()
auto_token = RefreshingToken(low_token, cred)
assert repr(auto_token).startswith('RefreshingToken(')
def test_fresh_token_returned(self):
low_token = make_token... |
class PKManyToManyTests(TestCase):
def setUp(self):
for idx in range(1, 4):
target = ManyToManyTarget(name=('target-%d' % idx))
target.save()
source = ManyToManySource(name=('source-%d' % idx))
source.save()
for target in ManyToManyTarget.objects.a... |
class OptionPlotoptionsLineSonificationTracksMappingLowpass(Options):
def frequency(self) -> 'OptionPlotoptionsLineSonificationTracksMappingLowpassFrequency':
return self._config_sub_data('frequency', OptionPlotoptionsLineSonificationTracksMappingLowpassFrequency)
def resonance(self) -> 'OptionPlotoptio... |
class TestCu2QuPen(unittest.TestCase, _TestPenMixin):
def __init__(self, *args, **kwargs):
super(TestCu2QuPen, self).__init__(*args, **kwargs)
self.Glyph = DummyGlyph
self.Pen = DummyPen
self.Cu2QuPen = Cu2QuPen
self.pen_getter_name = 'getPen'
self.draw_method_name = ... |
(IStatusBarManager)
class StatusBarManager(HasTraits):
message = Property
messages = List(Str)
status_bar = Any()
def create_status_bar(self, parent):
if (self.status_bar is None):
self.status_bar = wx.StatusBar(parent)
self.status_bar._pyface_control = self
i... |
class GreetingWorkflowImpl(GreetingWorkflow):
async def get_greeting(self):
global version_found_in_step_1_0, version_found_in_step_1_1
global version_found_in_step_2_0, version_found_in_step_2_1
version_found_in_step_1_0 = Workflow.get_version('first-item', DEFAULT_VERSION, 2)
versi... |
def setup_logging(verbosity: int, color_logging: bool=False, apprise_notifiers: List[str]=[]) -> None:
add_logging_level('EXTRA_DEBUG', (logging.DEBUG - 1))
add_logging_level('WEBSOCKET_DATA', (logging.DEBUG - 2))
format = '{asctime} [{levelname:^11s}] {name:<42} : {message}'
sh = create_logging_handle... |
class TestMlabNullEngineBase(unittest.TestCase):
def setUp(self):
e = Engine()
e.start()
self._non_null_engine = e
mlab.set_engine(e)
def tearDown(self):
if (not (mlab.get_engine() is self._non_null_engine)):
raise AssertionError('The NullEngine has overridden... |
class KiwoomOpenApiPlusServiceServer(Logging):
def __init__(self, control, host=None, port=None, credentials=None, **kwargs):
if (host is None):
host = config.get_string('koapy.backend.kiwoom_open_api_plus.grpc.host', 'localhost')
host = config.get_string('koapy.backend.kiwoom_open_a... |
class Arm(BaseArch):
bits = 32
gpr_registers = ['r0', 'r1', 'r2', 'r3', 'r4', 'r5', 'r6', 'r7', 'r8', 'r9', 'r10', 'r11', 'r12', 'sp', 'lr', 'pc']
gpr_key = 'general'
flag_register = 'cpsr'
flag_register_bit_masks = {'n': , 'z': , 'c': , 'v': , 'q': , 'j': , 'ge': 983040, 'e': 512, 'a': 256, 'i': 12... |
def get_curr_and_ref_df(data: InputData, min_rel_score: Optional[int]=None, no_feedback_users: bool=False, bin_data: bool=True):
target_column = data.data_definition.get_target_column()
prediction = data.data_definition.get_prediction_columns()
if ((target_column is None) or (prediction is None)):
r... |
class M12L16161A(SDRModule):
nbanks = 2
nrows = 2048
ncols = 256
technology_timings = _TechnologyTimings(tREFI=(.0 / 4096), tWTR=(2, None), tCCD=(1, None), tRRD=(None, 10))
speedgrade_timings = {'default': _SpeedgradeTimings(tRP=15, tRCD=15, tWR=15, tRFC=(None, 55), tFAW=None, tRAS=40)} |
def extractIdidmybesttranslationsWordpressCom(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, n... |
class UserDeleteView(MenuItemMixin, FormView):
form_class = UserDeletionForm
template_name = 'registration/unregister.html'
menu_parameters = 'account'
_decorator(login_required)
def dispatch(self, request, *args, **kwargs):
return super(UserDeleteView, self).dispatch(request, *args, **kwarg... |
.parametrize('ops', ALL_OPS)
.parametrize('dtype', FLOAT_TYPES)
def test_reduce_mean(ops, dtype):
X = ops.asarray2f([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0], [1.0, 2.0], [3.0, 4.0]], dtype=dtype)
lengths = ops.asarray1i([3, 2])
ops.xp.testing.assert_allclose(ops.reduce_mean(X, lengths), [[3.0, 4.0], [2.0, 3.0]])... |
class OptionPlotoptionsAreasplineSonificationContexttracksMappingFrequency(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... |
()
('--batch-size', type=int, default=0, help='Inference batch size')
('--seq-length', type=int, default=0, help='Inference sequence length')
('--activation', type=str, default='fast_gelu', help='Activation function applied on BERT, currently only support fast_gelu on Rocm. CUDA supports both gelu and fast_gelu. No eff... |
def test_alias_argument_1():
f = alias_argument()(func_x)
assert (f(1) == 1)
assert (f(x=1) == 1)
with pytest.raises(TypeError):
assert (f(unk=1) == 1)
f = alias_argument(x=['alias'])(func_x)
assert (f(alias=1) == 1)
assert (f(x=1) == 1)
f = alias_argument(x='alias')(func_x)
... |
def request_counter(metrics_name: str) -> Callable:
def wrap(f: Callable):
(f)
def wrapper_sync(self: MetricsGetter, *args, **kwargs):
if self.has_metrics():
self.get_metrics().count(metrics_name, 1)
return f(self, *args, **kwargs)
(f)
async de... |
.xfail(raises=ImageComparisonFailure, reason='Matplotlib plots for reasons a different image size.')
.skipif((MID_MEMORY > memory), reason='Travis has too less memory to run it.')
def test_hicPlotMatrix_region_region2_log1p_clearMaskedBins_and_bigwig_vmin_vmax_vertical():
outfile = NamedTemporaryFile(suffix='.png',... |
class OptionPlotoptionsTreemapSonificationContexttracks(Options):
def activeWhen(self) -> 'OptionPlotoptionsTreemapSonificationContexttracksActivewhen':
return self._config_sub_data('activeWhen', OptionPlotoptionsTreemapSonificationContexttracksActivewhen)
def instrument(self):
return self._conf... |
class TestLeakyReluConverter(AITTestCase):
def test_leaky_relu(self):
class TestModule(torch.nn.Module):
def forward(self, x: torch.Tensor) -> torch.Tensor:
return torch.nn.functional.leaky_relu(x, negative_slope=0.05)
model = TestModule().cuda().half()
inputs = [... |
.scheduler
def test_surface_init_fails_during_forward_model_callback(copy_case, monkeypatch, try_queue_and_scheduler):
copy_case('snake_oil_field')
rng = np.random.default_rng()
Path('./surface').mkdir()
nx = 5
ny = 10
surf = xtgeo.RegularSurface(ncol=nx, nrow=ny, xinc=1.0, yinc=1.0, values=rng.... |
class NotifierTest(ForsetiTestCase):
def test_can_convert_created_at_datetime_to_timestamp_string(self):
violations = [dict(created_at_datetime=datetime(1999, 12, 25, 1, 2, 3)), dict(created_at_datetime=datetime(2010, 6, 8, 4, 5, 6))]
expected_timestamps = ['1999-12-25T01:02:03Z', '2010-06-08T04:05:... |
class LinkableContract(Contract):
unlinked_references: Optional[Tuple[Dict[(str, Any)]]] = None
linked_references: Optional[Tuple[Dict[(str, Any)]]] = None
needs_bytecode_linking = None
def __init__(self, address: bytes, **kwargs: Any) -> None:
if self.needs_bytecode_linking:
raise B... |
class MsgStub(object):
def __init__(self, channel):
self.VerifyInvariant = channel.unary_unary('/cosmos.crisis.v1beta1.Msg/VerifyInvariant', request_serializer=cosmos_dot_crisis_dot_v1beta1_dot_tx__pb2.MsgVerifyInvariant.SerializeToString, response_deserializer=cosmos_dot_crisis_dot_v1beta1_dot_tx__pb2.MsgV... |
class DPSet(app_manager.RyuApp):
def __init__(self, *args, **kwargs):
super(DPSet, self).__init__(*args, **kwargs)
self.name = 'dpset'
self.dps = {}
self.port_state = {}
def _register(self, dp):
LOG.debug('DPSET: register datapath %s', dp)
assert (dp.id is not Non... |
class OefSearchDialogue(Dialogue):
INITIAL_PERFORMATIVES: FrozenSet[Message.Performative] = frozenset({OefSearchMessage.Performative.REGISTER_SERVICE, OefSearchMessage.Performative.UNREGISTER_SERVICE, OefSearchMessage.Performative.SEARCH_SERVICES})
TERMINAL_PERFORMATIVES: FrozenSet[Message.Performative] = froze... |
class TestDialogues(SimpleDataRequestTestCase):
def setup(cls):
super().setup()
cls. = cast(HttpDialogues, cls._skill.skill_context.
def test_
'Test the HttpDialogues class.'
(_, dialogue) = self. performative=HttpMessage.Performative.REQUEST, method='some_method', url='some_url'... |
class ESRolloutWorkerWrapper(Wrapper[Union[(StructuredEnv, LogStatsEnv)]]):
def __init__(self, env: Union[(StructuredEnv, LogStatsEnv)], shared_noise: SharedNoiseTable, agent_instance_seed: int):
super().__init__(env)
self.shared_noise = shared_noise
self.abort = False
self.wrapper_r... |
class Default(Plugin):
def __init__(self, parser, cfg):
super().__init__(parser, cfg)
group = parser.add_argument_group('Azure authentication options')
group.add_argument('--ad-authority', metavar='NAME', default=self.cfg('authority', type=Str, default='login.microsoftonline.com'), help='Azu... |
def test_vertical_alignment_enum():
r = ft.Row(vertical_alignment=ft.CrossAxisAlignment.STRETCH)
assert isinstance(r.vertical_alignment, ft.CrossAxisAlignment)
assert isinstance(r._get_attr('verticalAlignment'), str)
cmd = r._build_add_commands()
assert (cmd[0].attrs['verticalalignment'] == 'stretch... |
def test_prepare_transaction_replacement_gas_price_defaulting_when_strategy_higher(w3):
def higher_gas_price_strategy(w3, txn):
return 20
w3.eth.set_gas_price_strategy(higher_gas_price_strategy)
current_transaction = SIMPLE_CURRENT_TRANSACTION
new_transaction = {'value': 2}
replacement_trans... |
class LightenerConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
VERSION = 2
def __init__(self) -> None:
self.lightener_flow = LightenerFlow(self, steps={'name': 'user'})
super().__init__()
async def async_step_user(self, user_input: (dict[(str, Any)] | None)=None):
return (await... |
def test():
ind = GraphApi()
item1 = (1, 'aaaa1')
item2 = (2, 'aaaa2')
item3 = (3, 'aaaa1')
item4 = (4, 'aaaa2')
item5 = (5, 'aaaa1')
item6 = (6, 'aaaa2')
item7 = (7, 'aaaa1')
item8 = (8, 'aaaa2')
ind.insert_link(item1, item2)
ind.insert_link(item2, item3)
ind.insert_link... |
def create_data_format_readers(patch_reader, ffrom, to_size):
dfpatch_size = unpack_size(patch_reader)
if (dfpatch_size > 0):
data_format = unpack_size(patch_reader)
patch = patch_reader.decompress(dfpatch_size)
(dfdiff, ffrom) = create_readers(data_format, ffrom, patch, to_size)
... |
class ConfigLoader():
_config = {}
_config_last_modified_time = None
def _config_modified():
current_time = time.time()
modified_time = os.path.getmtime(CONFIG_FILE)
if (ConfigLoader._config_last_modified_time is None):
ConfigLoader._config_last_modified_time = modified_t... |
def optPortLongOnly(cov, mu=None):
inv = np.linalg.inv(cov)
ones = np.ones(shape=(inv.shape[0], 1))
if (mu is None):
mu = ones
w = np.dot(inv, mu)
w /= np.dot(ones.T, w)
w = w.flatten()
threshold = (w < 0)
wpluss = w.copy()
wpluss[threshold] = 0
wpluss = (wpluss / np.sum(... |
class Testing(Module):
def timeTravel(self, timestamp: int) -> None:
return self.w3.manager.request_blocking(RPC.testing_timeTravel, [timestamp])
def mine(self, num_blocks: int=1) -> None:
return self.w3.manager.request_blocking(RPC.evm_mine, [num_blocks])
def snapshot(self) -> int:
... |
def envelope_from_bytes(bytes_: bytes, separator: bytes=SEPARATOR, logger: Logger=_default_logger) -> Optional[Envelope]:
logger.debug('processing: {!r}'.format(bytes_))
envelope = None
try:
envelope = _decode(bytes_, separator=separator)
except ValueError as e:
logger.error('Bad formatt... |
def downgrade():
op.drop_index(op.f('ix_accessmanualwebhook_id'), table_name='accessmanualwebhook')
op.drop_table('accessmanualwebhook')
op.execute('alter type connectiontype rename to connectiontype_old')
op.execute("create type connectiontype as enum('postgres', 'mongodb', 'mysql', ' 'snowflake', 'red... |
.django_db
def test_program_activity_list_success(client, monkeypatch, agency_account_data, helpers):
helpers.mock_current_fiscal_year(monkeypatch)
resp = client.get(url.format(code='007', query_params=''))
expected_result = {'fiscal_year': helpers.get_mocked_current_fiscal_year(), 'toptier_code': '007', 'm... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.