code stringlengths 281 23.7M |
|---|
def forward(model: Model[(NestedT[InItemT], NestedT[OutItemT])], Xnest: NestedT[InItemT], is_train: bool) -> Tuple[(NestedT[OutItemT], Callable)]:
layer: Model[(FlatT[InItemT], FlatT[OutItemT])] = model.layers[0]
(Xflat, lens) = _flatten(Xnest)
(Yflat, backprop_layer) = layer(Xflat, is_train)
Ynest = _u... |
(('config_name', 'overrides', 'with_hydra', 'expected'), [param('select_multi', [], False, DefaultsTreeNode(node=ConfigDefault(path='select_multi'), children=[ConfigDefault(path='group1/file1'), ConfigDefault(path='group1/file2'), ConfigDefault(path='_self_')]), id='select_multi'), param('select_multi', ['group1=[file1... |
()
('f', type=click.File('rb'), default='-')
('-a', 'algorithm', default=None, type=click.Choice(ALGOS), help='Only this algorithm (Default: all)')
def cmd_crypto_hasher(f, algorithm):
data = f.read()
if (not data):
print('Empty file or string!')
return 1
if algorithm:
print(hasher(d... |
def test_different_folders(project, tmp_path):
with tmp_path.joinpath('brownie-config.yaml').open('w') as fp:
yaml.dump(structure, fp)
project.main._create_folders(Path(tmp_path))
for path in ('contracts', 'interfaces', 'scripts', 'reports', 'tests', 'build'):
assert (not Path(tmp_path).join... |
class OptionSeriesHeatmapSonificationDefaultinstrumentoptionsMappingTime(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 OptionPlotoptionsFunnel3dDatalabelsTextpath(Options):
def attributes(self):
return self._config_get(None)
def attributes(self, value: Any):
self._config(value, js_type=False)
def enabled(self):
return self._config_get(False)
def enabled(self, flag: bool):
self._conf... |
def get_msg(self):
self.loginInfo['deviceid'] = ('e' + str(random.randint(0, (.0 - 1))).rjust(15, '0'))
url = ('%s/webwxsync?sid=%s&skey=%s&pass_ticket=%s' % (self.loginInfo['url'], self.loginInfo['wxsid'], self.loginInfo['skey'], self.loginInfo['pass_ticket']))
data = {'BaseRequest': self.loginInfo['BaseRe... |
class EnumValueMixin(BaseModel):
def _to_enum_value(self, key, value):
field = self.__fields__[key]
if (not issubclass(field.type_, Enum)):
return value
if isinstance(value, list):
return [(v.value if isinstance(v, Enum) else v) for v in value]
return (value.v... |
def parse_nick_template(string, template_regex, outtemplate):
match = template_regex.match(string)
if match:
matchdict = {key: (value if (value is not None) else '') for (key, value) in match.groupdict().items()}
return (True, outtemplate.format_map(matchdict))
return (False, string) |
class Migration(migrations.Migration):
dependencies = [('manager', '0014_auto__1904')]
operations = [migrations.CreateModel(name='EventTag', fields=[('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(help_text='This name will be used as a... |
def add_errored_system_status_for_consent_reporting(db: Session, privacy_request: PrivacyRequest, connection_config: ConnectionConfig) -> None:
for pref in privacy_request.privacy_preferences:
if (pref.affected_system_status and (pref.affected_system_status.get(connection_config.system_key) == ExecutionLogS... |
class BaseRuleTest(unittest.TestCase):
RULE_LOADER_FAIL = False
RULE_LOADER_FAIL_MSG = None
RULE_LOADER_FAIL_RAISED = False
def setUpClass(cls):
global RULE_LOADER_FAIL, RULE_LOADER_FAIL_MSG
if (not RULE_LOADER_FAIL):
try:
rc = default_rules()
... |
class OptionSeriesDependencywheelSonificationDefaultspeechoptionsMappingVolume(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:... |
class ManageForum(MethodView):
decorators = [login_required, allows.requires(IsAtleastModeratorInForum(), on_fail=FlashAndRedirect(message=_('You are not allowed to manage this forum'), level='danger', endpoint=(lambda *a, **k: url_for('forum.view_forum', forum_id=k['forum_id']))))]
def get(self, forum_id, slug... |
class JaxMonitorData(MonitorData, JaxObject, ABC):
def from_monitor_data(cls, mnt_data: MonitorData) -> JaxMonitorData:
self_dict = mnt_data.dict(exclude={'type'}).copy()
for field_name in cls.get_jax_field_names():
data_array = self_dict[field_name]
if (data_array is not Non... |
class CustomAudienceDocsTestCase(DocsTestCase):
def setUp(self):
ca = self.create_custom_audience()
DocsDataStore.set('ca_id', ca.get_id_assured())
def test_add_users(self):
custom_audience = CustomAudience(DocsDataStore.get('ca_id'))
response = custom_audience.add_users(schema=C... |
('aea.cli.utils.decorators.try_to_load_agent_config')
('aea.cli.utils.decorators._validate_config_consistency')
class AddContractCommandTestCase(TestCase):
def setUp(self):
self.runner = CliRunner()
('aea.cli.add.add_item')
def test_add_contract_positive(self, *mocks):
result = self.runner.i... |
class DEP001MissingDependenciesFinder(ViolationsFinder):
def find(self) -> list[Violation]:
logging.debug('\nScanning for missing dependencies...')
missing_dependencies: list[Violation] = []
for module_with_locations in self.imported_modules_with_locations:
module = module_with_l... |
class OptionPlotoptionsColumnSonificationPointgrouping(Options):
def algorithm(self):
return self._config_get('minmax')
def algorithm(self, text: str):
self._config(text, js_type=False)
def enabled(self):
return self._config_get(True)
def enabled(self, flag: bool):
self._... |
def test_utc_to_local_is_working_properly():
from stalker.models import utc_to_local
import datetime
import pytz
local_now = datetime.datetime.now()
utc_now = datetime.datetime.now(pytz.utc)
utc_without_tz = datetime.datetime(utc_now.year, utc_now.month, utc_now.day, utc_now.hour, utc_now.minute... |
def just_load_modules(pkgs: List[str]):
for package_name in pkgs:
package = importlib.import_module(package_name)
if (not hasattr(package, '__path__')):
continue
for (_, name, _) in pkgutil.walk_packages(package.__path__, prefix=f'{package_name}.'):
importlib.import_m... |
_ordering
class RouteTargetMembershipNLRI(StringifyMixin):
ROUTE_FAMILY = RF_RTC_UC
DEFAULT_AS = '0:0'
DEFAULT_RT = '0:0'
def __init__(self, origin_as, route_target):
if (not ((origin_as is self.DEFAULT_AS) and (route_target is self.DEFAULT_RT))):
if ((not self._is_valid_asn(origin_a... |
class PeerCountReporterComponent(AsyncioIsolatedComponent):
name = 'Peer Count Reporter'
def configure_parser(cls, arg_parser: ArgumentParser, subparser: _SubParsersAction) -> None:
arg_parser.add_argument('--report-peer-count', action='store_true', help='Report peer count to console')
def is_enable... |
.future_test_attributes
def test_count0_value_bit(tmpdir, merge_files_oneLR):
path = os.path.join(str(tmpdir), 'count0-value-bit.dlis')
content = ['data/chap3/start.dlis.part', 'data/chap3/template/default.dlis.part', 'data/chap3/object/object.dlis.part', 'data/chap3/objattr/count0-value-bit.dlis.part']
mer... |
def test_rlp_encode_20_elem_byte_uint_combo() -> None:
raw_data = (([Uint(35)] * 10) + ([b'hello'] * 10))
expected = ((bytearray([248]) + b'F') + b'\x85hello\x85hello\x85hello\x85hello\x85hello\x85hello\x85hello\x85hello\x85hello\x85hello')
assert (rlp.encode_sequence(raw_data) == expected) |
def fence(node: RenderTreeNode, context: RenderContext) -> str:
info_str = node.info.strip()
lang = (info_str.split(maxsplit=1)[0] if info_str else '')
code_block = node.content
fence_char = ('~' if ('`' in info_str) else '`')
if (lang in context.options.get('codeformatters', {})):
fmt_func ... |
class CloudAssetCrawlerTest(CrawlerBase):
def setUp(self):
CrawlerBase.setUp(self)
self.inventory_config = InventoryConfig(gcp_api_mocks.ORGANIZATION_ID, '', {}, 0, {'enabled': True, 'gcs_path': 'gs://test-bucket'})
self.inventory_config.set_service_config(FakeServerConfig('mock_engine'))
... |
def test_import_export_rmsasc(tmp_path, simple_well):
t0 = xtg.timer()
wname = (tmp_path / '$random').with_suffix('.rmsasc')
wuse = simple_well.to_file(wname)
print('Time for save RMSASC: ', xtg.timer(t0))
t0 = xtg.timer()
result = xtgeo.well_from_file(wuse)
assert result.dataframe.equals(re... |
def run_queries(name: str, queries: Sequence[Query]) -> Sequence[Result]:
jsonified = []
byid = {}
for q in queries:
jsonified.append(q.as_json())
byid[id(q)] = q
path_urls = f'/tmp/kat-client-{name}-urls.json'
path_results = f'/tmp/kat-client-{name}-results.json'
path_log = f'/t... |
class CommonCrawlExtractor():
__warc_path = None
__local_download_dir_warc = './cc_download_warc/'
__filter_valid_hosts = []
__filter_start_date = None
__filter_end_date = None
__filter_strict_date = True
__reuse_previously_downloaded_files = True
__continue_after_error = False
__ign... |
def extractTaholtorfWordpressCom(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)... |
def test_gini_gain():
assert (round(gini_gain([1, 1, 1, 1, 0, 0, 0, 0], [[1, 1, 1, 1], [0, 0, 0, 0]]), 3) == 0.5)
assert (round(gini_gain([1, 1, 1, 1, 0, 0, 0, 0], [[1, 1, 1, 0], [0, 0, 0, 1]]), 3) == 0.125)
assert (round(gini_gain([1, 1, 1, 1, 0, 0, 0, 0], [[1, 0, 0, 0], [0, 1, 1, 1]]), 3) == 0.125)
as... |
class OptionSeriesPackedbubbleSonification(Options):
def contextTracks(self) -> 'OptionSeriesPackedbubbleSonificationContexttracks':
return self._config_sub_data('contextTracks', OptionSeriesPackedbubbleSonificationContexttracks)
def defaultInstrumentOptions(self) -> 'OptionSeriesPackedbubbleSonificatio... |
def test_EIP155_transaction_sender_extraction(txn_fixture):
key = keys.PrivateKey(decode_hex(txn_fixture['key']))
transaction = rlp.decode(decode_hex(txn_fixture['signed']), sedes=SpuriousDragonTransaction)
sender = extract_transaction_sender(transaction)
assert is_same_address(sender, transaction.sende... |
def process_twitter(args):
print('')
print('# Process Twitter')
print('')
op = OperatorTwitter()
data = op.readFromJson(args.data_folder, args.run_id, 'twitter.json')
data_deduped = op.dedup(data, target='toread')
data_scored = op.score(data_deduped, start_date=args.start, max_distance=args.... |
class TestFuseDuplicateFusedElementwise(unittest.TestCase):
SHAPE = [32, 64, 100]
def _count_fused_elementwise_ops(graph: List[Tensor], target_elementwise_ops: List[FuncEnum]) -> int:
fused_elementwise_ops = filter((lambda op: (op._attrs['op'] == 'fused_elementwise')), get_sorted_ops(graph))
cou... |
class MyApp(App):
def compose(self):
(yield Header())
(yield Label('[b]Sera que clicou?[/]'))
(yield Input('Digite algo!'))
with Horizontal():
(yield Button('Vermelho!', variant='error'))
(yield Button('Verde!', variant='success'))
(yield Button('A... |
def extractCyptranslationsWordpressCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [('sealed lips', 'Sealed Lips', 'translated'), ('PRC', 'PRC', 'translated'), ('Loiterous', '... |
class OptionSeriesParetoSonificationTracksMappingRate(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):
self._conf... |
def load_extensions(force=False):
global _loaded_plugins
if (force or (not _loaded_plugins)):
import pkgutil
import importlib
_loaded_plugins = True
for (module_loader, name, ispkg) in pkgutil.iter_modules():
if name.startswith(PLUGIN_PREFIX):
importli... |
def random_box():
xx = randrange((- 55), 54)
yy = randrange((- 55), 54)
zz = randrange((- 55), 54)
x = randrange(0, 21)
y = randrange(0, 21)
z = randrange(0, 21)
red = random()
green = random()
blue = random()
box(pos=(xx, yy, zz), length=x, height=y, width=z, color=(red, green, ... |
class TestStageFlow(TestCase):
def test_get_first_stage(self) -> None:
self.assertEqual(DummyStageFlow.STAGE_1, DummyStageFlow.get_first_stage())
def test_get_last_stage(self) -> None:
self.assertEqual(DummyStageFlow.STAGE_3, DummyStageFlow.get_last_stage())
def test_move_forward(self) -> No... |
def motion_notify(win, ev, c):
try:
dx = (((ev.x - win.click_x) / c.get_scale()) / 3.79)
dy = (((ev.y - win.click_y) / c.get_scale()) / 3.79)
win.click_x = ev.x
win.click_y = ev.y
(x1, y1, x2, y2) = c.get_bounds()
c.set_bounds((x1 - dx), (y1 - dy), (x2 - dx), (y2 - dy... |
def test_get_ops():
assert isinstance(get_ops('numpy'), NumpyOps)
assert isinstance(get_ops('cupy'), CupyOps)
try:
from thinc_apple_ops import AppleOps
assert isinstance(get_ops('cpu'), AppleOps)
except ImportError:
assert isinstance(get_ops('cpu'), NumpyOps)
try:
fro... |
def output_registers(bit_offset, in_use):
reg = RegisterAddress(frame_offsets=[29, 28], bit_offset=bit_offset, reverse=True)
for (idx, register) in enumerate(REGISTER_MAP):
if (register is None):
for _ in range(16):
reg.next_bit(used=False)
continue
(layou... |
def mul_polys(a, b, modulus, root_of_unity):
rootz = [1, root_of_unity]
while (rootz[(- 1)] != 1):
rootz.append(((rootz[(- 1)] * root_of_unity) % modulus))
if (len(rootz) > (len(a) + 1)):
a = (a + ([0] * ((len(rootz) - len(a)) - 1)))
if (len(rootz) > (len(b) + 1)):
b = (b + ([0] ... |
class Command(mixins.ETLMixin, BaseCommand):
help = 'Loads CGACs, FRECs, Subtier Agencies, Toptier Agencies, and Agencies. Load is all or nothing. If anything fails, nothing gets saved.'
agency_file = None
force = False
etl_logger_function = logger.info
etl_dml_sql_directory = (Path(__file__).reso... |
class FaucetLink(Link):
def __init__(self, node1, node2, port1=None, port2=None, intf_name1=None, intf_name2=None, addr1=None, addr2=None, **params):
Link.__init__(self, node1, node2, port1=port1, port2=port2, intfName1=intf_name1, intfName2=intf_name2, cls1=FaucetIntf, cls2=FaucetIntf, addr1=addr1, addr2=a... |
def display_main_menu():
handle = int(sys.argv[1])
xbmcplugin.setContent(handle, 'files')
add_menu_directory_item(string_load(30406), 'plugin://plugin.video.embycon/?mode=SHOW_ADDON_MENU&type=library')
add_menu_directory_item(string_load(30407), 'plugin://plugin.video.embycon/?mode=SHOW_ADDON_MENU&type=... |
class DefaultDialogues(Dialogues, ABC):
END_STATES = frozenset({DefaultDialogue.EndState.SUCCESSFUL, DefaultDialogue.EndState.FAILED})
_keep_terminal_state_dialogues = True
def __init__(self, self_address: Address, role_from_first_message: Callable[([Message, Address], Dialogue.Role)], dialogue_class: Type[... |
class Interpreter():
def __init__(self, proc, kwargs, use_randomization=False):
assert isinstance(proc, LoopIR.proc)
self.proc = proc
self.env = ChainMap()
self.use_randomization = use_randomization
for a in proc.args:
if (not (str(a.name) in kwargs)):
... |
def verify_json_dump(joblist, config, selected_jobs, run_id):
expected_default_env = {'_ERT_ITERATION_NUMBER': '0', '_ERT_REALIZATION_NUMBER': '0', '_ERT_RUNPATH': './'}
assert ('config_path' in config)
assert ('config_file' in config)
assert (run_id == config['run_id'])
assert (len(selected_jobs) =... |
class OptionSeriesSplineSonificationDefaultinstrumentoptionsMappingLowpassResonance(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 ClkReg1():
def __init__(self, value=0):
self.unpack(value)
def unpack(self, value):
self.low_time = ((value >> 0) & ((2 ** 6) - 1))
self.high_time = ((value >> 6) & ((2 ** 6) - 1))
self.reserved = ((value >> 12) & ((2 ** 1) - 1))
self.phase_mux = ((value >> 13) & ((... |
def test_save_image_in_tempfolder():
utils.logger.setLevel('DEBUG')
image = QtGui.QImage(20, 20, QtGui.QImage.Format.Format_RGB32)
test_id = f'_unittest_{uuid4()}'
utils.save_image_in_temp_folder(image, postfix=test_id)
png_files = list((Path(tempfile.gettempdir()) / 'normcap').glob(f'*{test_id}*'))... |
class ImgFace(RectFace):
def __init__(self, img_path, width, height, name='', padding_x=0, padding_y=0):
RectFace.__init__(self, width=width, height=height, name=name, padding_x=padding_x, padding_y=padding_y)
with open(img_path, 'rb') as handle:
img = base64.b64encode(handle.read()).dec... |
class Attachment():
def __init__(self, id: Optional[Union[(str, int, float)]]=None, kind: Optional[Union[(AttachmentKind, str)]]=None, content: Optional[Union[(AttachmentContent, Tuple[(str, Union[(str, bytes)])])]]=None, title: Optional[str]=None, raw: Any=None, get_file: Optional[Callable[(..., Awaitable)]]=None)... |
.django_db
def test_category_awarding_subagency_subawards(agency_test_data):
test_payload = {'category': 'awarding_subagency', 'subawards': True, 'page': 1, 'limit': 50}
spending_by_category_logic = AwardingSubagencyViewSet().perform_search(test_payload, {})
expected_response = {'category': 'awarding_subage... |
class SemanticDocument(SemanticMixedContentWrapper):
def __init__(self):
self.front = SemanticFront()
self.body_section = SemanticSection(section_type=SemanticSectionTypes.BODY)
self.back_section = SemanticSection(section_type=SemanticSectionTypes.BACK)
super().__init__([self.front, ... |
def generate_sample_data():
file = TemporaryFile('w+b')
writer = Writer(file)
writer.start(profile='ros2', library='test')
string_schema_id = writer.register_schema(name=String._type, encoding='ros2msg', data=String._full_text.encode())
string_channel_id = writer.register_channel(topic='/chatter', m... |
class ColumnInteractionPlot(Metric[ColumnInteractionPlotResults]):
x_column: str
y_column: str
def __init__(self, x_column: str, y_column: str, options: AnyOptions=None):
self.x_column = x_column
self.y_column = y_column
super().__init__(options=options)
def calculate(self, data:... |
def extractInnercitynovelBlogspotCom(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_t... |
class OptionSeriesScatter3dSonificationDefaultinstrumentoptionsMappingTremoloSpeed(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, t... |
def test_feeder_list_devices(client: TestClient, with_registered_device: None):
from tests.test_database_models import SAMPLE_DEVICE_HID
response = client.get('/api/v1/feeder')
assert (response.status_code == 200)
devices = response.json()
assert (len(devices) == 1)
assert (devices[0]['hid'] == ... |
class OptionPlotoptionsBulletSonificationDefaultspeechoptionsMappingVolume(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... |
def temppass(request):
handle = request.POST.get('handle', '')
if (handle != ADMIN_USER):
return error_template(request, 'Could not find signature in feed of user {}'.format(handle))
publickey_str = request.POST.get('pubkey')
if (':' not in publickey_str):
return error_template(request, ... |
class TestListPluggedDevice(object):
def test_debug_devices(self, monkeypatch):
monkeypatch.setenv('RIVALCFG_PROFILE', '1038:1702')
devices_list = list(devices.list_plugged_devices())
debug_device_found = False
for device in devices_list:
if ((device['vendor_id'] == 4152)... |
class FederalAccountCountViewSet(DisasterBase):
endpoint_doc = 'usaspending_api/api_contracts/contracts/v2/disaster/federal_account/count.md'
_response()
def post(self, request: Request) -> Response:
filters = [Q(treasury_account__federal_account_id=OuterRef('pk')), self.is_in_provided_def_codes, se... |
def initialize_network_objects() -> List[Network]:
networks_obj = []
networks_json_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '__json'))
with open(os.path.join(networks_json_path, 'eth_networks.json'), encoding='UTF-8') as open_file:
network_data = json.load(open_file)
for en... |
class NodeUpdateForm(UpdateForm):
_api_call = system_node_update
_node_hostname = None
hostnames = ArrayField(required=True, widget=forms.HiddenInput(attrs={'class': 'hide'}))
def _add_error(self, field_name, error):
if self._node_hostname:
if isinstance(error, (list, tuple)):
... |
def extractPoppyscanlationsVideoBlog(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [('A Seductive Gentleman', 'A Seductive Gentleman', 'translated'), ('PRC', 'PRC', 'translated'... |
.django_db
def test_just_fy(client, create_gtas_data):
resp = client.get('/api/v2/references/total_budgetary_resources/?fiscal_year=2020')
assert (resp.status_code == status.HTTP_200_OK)
assert (resp.data == {'results': [{'fiscal_year': 2020, 'fiscal_period': 3, 'total_budgetary_resources': Decimal(4)}, {'f... |
def test_etm_chat_conversion_group(db, slave):
group_chat = slave.get_chat_by_criteria(chat_type='GroupChat')
assert isinstance(group_chat, GroupChat)
etm_group_chat = convert_chat(db, group_chat)
assert isinstance(etm_group_chat, ETMGroupChat)
assert isinstance(etm_group_chat.self, ETMSelfChatMembe... |
def test_discard_thin_prisms():
prism_boundaries = np.array([[(- 5000.0), 5000.0, (- 5000.0), 5000.0, 0.0, 55.1], [5000.0, 15000.0, (- 5000.0), 5000.0, 0.0, 55.01], [(- 5000.0), 5000.0, 5000.0, 15000.0, 0.0, 35.0], [5000.0, 15000.0, 5000.0, 15000.0, 0.0, 84.0]])
densities = np.array([2306, 2122, 2190, 2069])
... |
class LiteralType(_common.FlyteIdlEntity):
def __init__(self, simple=None, schema=None, collection_type=None, map_value_type=None, blob=None, enum_type=None, union_type=None, structured_dataset_type=None, metadata=None, structure=None, annotation=None):
self._simple = simple
self._schema = schema
... |
class OptionSeriesTreegraphLabelStyle(Options):
def fontSize(self):
return self._config_get('0.8em')
def fontSize(self, num: float):
self._config(num, js_type=False)
def fontWeight(self):
return self._config_get('bold')
def fontWeight(self, text: str):
self._config(text, ... |
class OptionPlotoptionsArcdiagramOnpointConnectoroptions(Options):
def dashstyle(self):
return self._config_get(None)
def dashstyle(self, text: str):
self._config(text, js_type=False)
def stroke(self):
return self._config_get(None)
def stroke(self, text: str):
self._confi... |
class OptionSeriesLollipopSonificationDefaultinstrumentoptionsMappingHighpass(Options):
def frequency(self) -> 'OptionSeriesLollipopSonificationDefaultinstrumentoptionsMappingHighpassFrequency':
return self._config_sub_data('frequency', OptionSeriesLollipopSonificationDefaultinstrumentoptionsMappingHighpass... |
def test_ref_plain_two_outputs():
r1 = ReferenceEntity(TaskReference('proj', 'domain', 'some.name', 'abc'), inputs=kwtypes(a=str, b=int), outputs=kwtypes(x=bool, y=int))
ctx = context_manager.FlyteContext.current_context()
with context_manager.FlyteContextManager.with_context(ctx.with_new_compilation_state(... |
def test_cli_literals_list():
cli = Radicli()
ran = False
('test', a=Arg('--a'))
def test(a: List[Literal[('pizza', 'pasta', 'burger')]]):
assert (a == ['pasta', 'pizza'])
nonlocal ran
ran = True
cli.run(['', 'test', '--a', 'pasta', '--a', 'pizza'])
assert ran
with py... |
class ColumnComponent(JsPackage):
lib_alias = {'js': 'tabulator-tables', 'css': 'tabulator-tables'}
lib_selector = 'column'
def getElement(self):
return JsNodeDom.JsDoms(('%s.getElement()' % self.toStr()), page=self.page, component=self.component)
def getTable(self):
return JsObjects.JsO... |
class RadialGradient(Html.Html):
name = 'SVG RadialGradient'
def __init__(self, page, html_code):
super(RadialGradient, self).__init__(page, '', html_code=html_code)
self.items = []
def url(self) -> str:
return ('url(#%s)' % self.htmlCode)
def stop(self, offset, styles):
... |
class DiscreteActorCriticHead(nn.Module):
def __init__(self, input_size: int, hidden_sizes: Sequence[int], num_actions: int) -> None:
super().__init__()
self._input_size = input_size
self._hidden_sizes = hidden_sizes
self._num_actions = num_actions
self._mlp_p = MLP(input_siz... |
.parametrize('lst, n, expected', [([0], 2, [0]), ([0, 1], 2, [0, 1]), ([0, 1, 2], 2, [[0, 1], 2]), ([0, 1, 2], 3, [0, 1, 2]), ([0, 1, 2, 3], 2, [[0, 1], [2, 3]]), ([0, 1, 2, 3], 3, [[0, 1, 2], 3]), ([0, 1, 2, 3, 4], 3, [[0, 1, 2], 3, 4]), ([0, 1, 2, 3, 4, 5], 3, [[0, 1, 2], [3, 4, 5]]), (list(range(7)), 3, [[0, 1, 2], ... |
class EqlAnalytic(EqlNode):
__slots__ = ('query', 'metadata')
def __init__(self, query, metadata=None):
self.query = query
self.metadata = (metadata or {})
def id(self):
return self.metadata.get('id')
def name(self):
return self.metadata.get('name')
def __unicode__(se... |
def parse_args(argv):
parser = argparse.ArgumentParser(prog='ergo view', description='View the model struture and training statistics.', formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('path', help='Path of the project.')
parser.add_argument('--img-only', dest='img_only', default... |
class perm102_bmm_rrr(bmm):
def __init__(self):
super().__init__()
self._attrs['op'] = 'perm102_bmm_rrr'
def cal_align_ab(m, n, k):
return common.default_align_ab(k, n, self._attrs['inputs'][0].dtype())
self._attrs['f_ab_alignment'] = cal_align_ab
def _infer_shapes(se... |
(autouse=True)
def fail_from_errors_on_other_threads():
def pytest_excepthook(*args, **kwargs):
_errors.extend(args)
threading.excepthook = pytest_excepthook
(yield)
if _errors:
caught_errors_str = ', '.join([str(err) for err in _errors])
pytest.fail(f'''Caught exceptions from ot... |
def density_minmax(density, bottom, top):
(density_bounds_min, density_bounds_max) = np.sort([density(bottom), density(top)])
kwargs = dict(bounds=[bottom, top], method='bounded')
minimum = np.min((minimize_scalar(density, **kwargs).fun, density_bounds_min))
maximum = np.max(((- minimize_scalar((lambda ... |
def _get_overlay_arp_table(node, overlay_rule_name, overlay_vnics):
return {vnic.mac: {'arp': vnic.ip, 'port': vnic.node.get_overlay_port(overlay_rule_name), 'ip': vnic.node.get_overlay_ip(overlay_rule_name, remote=(vnic.node.dc_name != node.dc_name))} for vnic in overlay_vnics if (vnic.node != node)} |
class MayaviUIPlugin(Plugin):
VIEWS = 'envisage.ui.workbench.views'
PERSPECTIVES = 'envisage.ui.workbench.perspectives'
PREFERENCES_PAGES = 'envisage.ui.workbench.preferences_pages'
ACTION_SETS = 'envisage.ui.workbench.action_sets'
BANNER = 'envisage.plugins.ipython_shell.banner'
name = 'Mayavi ... |
def get_default_flags(module: ModuleConf) -> List[Parameter]:
def_flags: List[Parameter] = []
if (module.default_flags._convert_ is not None):
def_flags.append(Parameter(name='_convert_', type_str='str', default=f'"{module.default_flags._convert_.name}"'))
if (module.default_flags._recursive_ is not... |
('cuda.bmm_rcr_permute.gen_function')
def gen_function(func_attrs, exec_cond_template, dim_info_dict):
default_mm_info = bmm_common.get_default_problem_info(PROBLEM_ARGS, alpha_value=func_attrs.get('alpha', 1))
(problem_args, _, input_addr_calculator, output_addr_calculator) = bmm_common.make_function_strided_a... |
def key_601_CosSin_2009():
dlf = DigitalFilter('Key 601 CosSin (2009)', 'key_601_CosSin_2009')
dlf.base = np.array([4.e-13, 4.e-13, 5.e-13, 5.e-13, 6.e-13, 6.e-13, 7.e-13, 8.e-13, 8.e-13, 9.e-13, 1.e-12, 1.e-12, 1.e-12, 1.e-12, 1.e-12, 1.e-12, 1.e-12, 2.e-12, 2.e-12, 2.e-12, 2.e-12, 3.e-12, 3.e-12, 3.e-12, 4.e-... |
def get_rates(temperature, reactant_thermos, ts_thermo, product_thermos=None):
G_TS = ts_thermo.G
imag_wavenumber = ts_thermo.org_wavenumbers[0]
assert (imag_wavenumber < 0.0)
imag_frequency = ((imag_wavenumber * C) * 100)
kappa_wigner = wigner_corr(temperature, imag_frequency)
kappa_bell = bell... |
_validator
def validate_release(request, **kwargs):
releasename = request.validated.get('release')
if (releasename is None):
return
db = request.db
release = db.query(Release).filter(or_((Release.name == releasename), (Release.name == releasename.upper()), (Release.version == releasename))).firs... |
class IOStrategy(_common.FlyteIdlEntity):
DOWNLOAD_MODE_EAGER = _core_task.IOStrategy.DOWNLOAD_EAGER
DOWNLOAD_MODE_STREAM = _core_task.IOStrategy.DOWNLOAD_STREAM
DOWNLOAD_MODE_NO_DOWNLOAD = _core_task.IOStrategy.DO_NOT_DOWNLOAD
UPLOAD_MODE_EAGER = _core_task.IOStrategy.UPLOAD_EAGER
UPLOAD_MODE_ON_EX... |
class ScatterInspector(SelectTool):
persistent_hover = Bool(False)
hover_metadata_name = Str('hover')
selection_metadata_name = Str('selections')
inspector_event = Event(ScatterInspectorEvent)
visible = False
draw_mode = 'none'
def normal_mouse_move(self, event):
plot = self.componen... |
class ModelTest(BasePyTestCase):
klass = None
attrs = {}
_populate_db = False
def setup_method(self):
super(ModelTest, self).setup_method(self)
buildsys.setup_buildsystem({'buildsystem': 'dev'})
if (type(self) is not ModelTest):
try:
new_attrs = {}
... |
class TestActions(unittest.TestCase):
def test_output_equality(self):
action = ofp.action.output(port=1, max_len=4660)
action2 = ofp.action.output(port=1, max_len=4660)
self.assertEquals(action, action2)
action2.port = 2
self.assertNotEquals(action, action2)
action2.p... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.