code stringlengths 281 23.7M |
|---|
class ifcfg():
def __init__(self, filename):
self._config = {}
self._deleted = []
self.filename = filename
self.clear()
def clear(self):
self._config = {}
self._deleted = []
def cleanup(self):
self._config.clear()
def get(self, key):
return... |
class ChoiceTypeLikeFilter(FilterLike):
def __init__(self, column, name, options=None, **kwargs):
super(ChoiceTypeLikeFilter, self).__init__(column, name, options, **kwargs)
def apply(self, query, user_query, alias=None):
column = self.get_column(alias)
choice_types = []
if user_... |
def test_gauss_tet3():
print('3rd Order Polynomial')
print('Tetrahedron')
gaussTetrahedron.setOrder(1)
int0_f3 = dot(f3(gaussTetrahedron.points), gaussTetrahedron.weights)
print(int0_f3)
gaussTetrahedron.setOrder(2)
int1_f3 = dot(f3(gaussTetrahedron.points), gaussTetrahedron.weights)
pri... |
class HiddenMarkovModel():
def __init__(self, N: int, K: int, concentration: float, mu_loc: float, mu_scale: float, sigma_shape: float, sigma_rate: float) -> None:
self.N = N
self.K = K
self.concentration = concentration
self.mu_loc = mu_loc
self.mu_scale = mu_scale
s... |
def prepare_file_offset_table(data_file_path):
file_offset_table = FileOffsetTable.create_for_data_file(data_file_path)
if (not file_offset_table.is_valid()):
console.info(('Preparing file offset table for [%s] ... ' % data_file_path), end='', flush=True)
line_number = 0
with file_offset... |
class AbstractPopStatsByEthosDataContainer(AbstractPopStatsDataContainer, abc.ABC):
def _iterate_popstats(self, cd: datamodel.CountryData) -> Iterable[datamodel.PopStatsByEthos]:
return iter(cd.pop_stats_ethos)
def _get_key_from_popstats(self, ps: PopStatsType) -> str:
assert isinstance(ps, data... |
class SqliteInterface(SqlInterfaceCursor, AbsSqliteInterface):
target = sqlite
def __init__(self, filename=None, print_sql=False):
self._filename = filename
super().__init__(print_sql)
def _create_connection(self):
import sqlite3
try:
conn = sqlite3.connect((self.... |
class PluginLoader():
def load_plugins(self, generator: PluginPromptGenerator, my_plugins: List[str]) -> PluginPromptGenerator:
logger.info(f'load_select_plugin:{my_plugins}')
for plugin in self.plugins:
if (plugin._name in my_plugins):
if (not plugin.can_handle_post_prom... |
class TestASGCriterion(unittest.TestCase):
def setUp(self):
self.device = torch.device('cpu')
if (torch.cuda.device_count() > 0):
self.device = torch.device('cuda')
def test_fwd_bwd(self):
T = 5
N = 6
B = 3
labels = [[2, 1, 5, 1, 3], [4, 3, 5], [3, 2, ... |
def compile_controlnet(pt_mod, batch_size=2, height=512, width=512, clip_chunks=1, dim=320, hidden_dim=768, use_fp16_acc=False, convert_conv_to_gemm=False, model_name='ControlNetModel', constants=False):
batch_size = (batch_size * 2)
ait_mod = ait_ControlNetModel()
ait_mod.name_parameter_tensor()
pt_mod... |
class SimpleEditor(Editor):
def init(self, parent):
self.control = QtGui.QDateEdit()
if hasattr(self.factory, 'qt_date_format'):
self.control.setDisplayFormat(self.factory.qt_date_format)
if (not self.factory.allow_future):
self.control.setMaximumDate(QtCore.QDate.cur... |
def get_dcs(request, sr=(), pr=(), order_by=('name',), annotate=None, extra=None):
if sr:
qs = Dc.objects.distinct().select_related(*sr)
else:
qs = Dc.objects.distinct()
if pr:
qs = qs.prefetch_related(*pr)
if request.user.is_staff:
qs = qs.exclude(access=Dc.DELETED).orde... |
def test_working_hours_argument_value_is_dictionary_of_other_formatted_data():
with pytest.raises(TypeError) as cm:
WorkingHours(working_hours={'not': 'properly valued'})
assert (str(cm.value) == 'WorkingHours.working_hours should be a dictionary with keys "mon, tue, wed, thu, fri, sat, sun" and the val... |
_unknown_type()
class OptionDataUnknown(Option):
def __init__(self, buf, option_class=None, type_=None, length=0):
super(OptionDataUnknown, self).__init__(option_class=option_class, type_=type_, length=length)
self.buf = buf
def parse_value(cls, buf):
return {'buf': buf}
def serializ... |
def extractLagoontranslationsWordpressCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [('S Rank Girl', 'My Daughter who Left for the Capital to Become an Adventurer Reached S ... |
def get_or_create_fides_user_device_id_provided_identity(db: Session, identity_data: Optional[Identity]) -> ProvidedIdentity:
if ((not identity_data) or (not identity_data.fides_user_device_id)):
raise HTTPException(HTTP_422_UNPROCESSABLE_ENTITY, detail='Fides user device id not found in identity data')
... |
class JSON():
classes: Dict[(Any, Any)] = {}
def register(cls, *classes):
for klass in classes:
cls.classes[klass.__name__] = klass
def dumps(cls, obj, **kwargs):
def encode_obj(obj):
class_name = obj.__class__.__name__
if (class_name not in cls.classes):
... |
def banner():
banner = "\n _____ _____ _ _ _____\n / ___/ ___| | | / ___|\n \\ `--.\\ `--.| |_| \\ `--. ___ __ _ _ __\n `--. \\`--. | _ |`--. \\/ __/ _` | '_ \\\n /\\__/ /\\__/ | | | /\\__/ | (_| (_| | | | |\n \\____/\\____/\\_| |_\\____/ \\___\\__,_|_| |_|\n ... |
def edit_default_save_file_path(_: Any) -> None:
locale_manager = locale_handler.LocalManager.from_config()
default_save_file_path = get_config_value('DEFAULT_SAVE_FILE_PATH')
default_save_file_path = helper.select_dir(locale_manager.search_key('select_default_save_path'), default_save_file_path)
set_co... |
class OptionPlotoptionsArearangeSonificationContexttracksMappingTremolo(Options):
def depth(self) -> 'OptionPlotoptionsArearangeSonificationContexttracksMappingTremoloDepth':
return self._config_sub_data('depth', OptionPlotoptionsArearangeSonificationContexttracksMappingTremoloDepth)
def speed(self) -> ... |
class OptionPlotoptionsAreaSonificationDefaultinstrumentoptionsMappingLowpassResonance(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(sel... |
class TestCredentialsOnline():
def test_request_client_token(self, app_env):
c = Credentials(app_env[0], app_env[1])
token = c.request_client_token()
assert (token.refresh_token is None)
assert (str(token.scope) == '')
c.close()
.asyncio
async def test_async_request_c... |
class DatasetDownload(APIView):
permission_classes = [IsAuthenticated]
def get_object(self, pk):
try:
data = Dataset.objects.filter(pk=pk, user=self.request.user)
if (not data):
data = Dataset.objects.filter(pk=pk, purchased__id__exact=self.request.user.id)
... |
def load_overrides(path, custom=False):
try:
if custom:
sys.path.append(path)
from overrides import overrides
log.debug('Imported overrides: %s', repr(overrides))
for provider in overrides:
update_definitions(provider, overrides[provider])
... |
class Downloader(QtCore.QObject):
def __init__(self, parent: Optional[QtCore.QObject]=None) -> None:
super().__init__(parent=parent)
self.com = Communicate()
self.threadpool = QtCore.QThreadPool()
self.worker: Optional[Worker] = None
def get(self, url: str, timeout: float=30) -> ... |
class EndpointFactory(ModelFactory):
class Meta():
model = Endpoint
name = factory.LazyFunction((lambda : str(uuid.uuid4())))
monitor_level = 1
time_added = factory.LazyFunction((lambda : (datetime.utcnow() - timedelta(days=1))))
version_added = '1.0'
last_requested = factory.LazyFunctio... |
def example():
return ft.Column([ft.TextButton(width=150, content=ft.Row([ft.Icon(name=ft.icons.FAVORITE, color='pink'), ft.Icon(name=ft.icons.AUDIOTRACK, color='green'), ft.Icon(name=ft.icons.BEACH_ACCESS, color='blue')], alignment=ft.MainAxisAlignment.SPACE_AROUND)), ft.TextButton(content=ft.Container(content=ft.... |
class PexpectWrapper(PopenSpawn):
def __init__(self, *args, **kwargs):
if (platform.system() != 'Windows'):
kwargs['preexec_fn'] = os.setsid
super().__init__(*args, **kwargs)
def control_c(self) -> None:
time.sleep(0.1)
send_control_c(self.proc, True)
def returnco... |
def test_mia_analyses_raises_exception_at_init_if_partitions_is_none_and_value_gt_than_255():
d = scared.MIADistinguisher()
with pytest.raises(ValueError):
d.update(traces=np.random.randint(0, 255, (500, 200), dtype='int16'), data=np.random.randint(0, 3000, (500, 16), dtype='uint16')) |
def source_metrics(user_statuses):
total = len(user_statuses)
if (total == 0):
return (0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
adv = 0
android = 0
blackberry = 0
ipad = 0
iphone = 0
mac = 0
websites = 0
windows = 0
non_std = 0
sources = Counter()
for status in user_stat... |
def init_db(sqlite_conn, data_factory, dates):
sqlite_conn.executescript(SCHEMA_SQL)
import_dates(sqlite_conn, dates)
practice_codes = _get_active_practice_codes(data_factory, dates)
sqlite_conn.executemany('INSERT INTO practice (offset, code) VALUES (?, ?)', enumerate(practice_codes)) |
class TaskTreeView(QtWidgets.QTreeView):
def __init__(self, parent=None, tasks=None, allow_multi_selection=False, allow_drag=False, allow_editing=False, context_menu_handler_class=None, horizontal_labels=None, show_asset_and_shot_children=True, show_takes=False, show_dependency_info=False):
super(TaskTreeVi... |
def filter_firewall_internet_service_custom_group_data(json):
option_list = ['comment', 'member', 'name']
json = remove_invalid_fields(json)
dictionary = {}
for attribute in option_list:
if ((attribute in json) and (json[attribute] is not None)):
dictionary[attribute] = json[attribut... |
class MediaFileTranslation(Translation(MediaFile)):
caption = models.CharField(_('caption'), max_length=1000)
description = models.TextField(_('description'), blank=True)
class Meta():
verbose_name = _('media file translation')
verbose_name_plural = _('media file translations')
uniqu... |
class OptionPlotoptionsArcdiagramSonificationContexttracksMappingFrequency(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 Surprise(Skill):
associated_action = SurpriseAction
skill_category = ['character', 'active']
target = t_OtherOne()
no_reveal = True
no_drop = True
usage = 'handover'
def check(self):
cl = self.associated_cards
if (not (len(cl) == 1)):
return False
(c... |
class LocalTaskExecutor(TaskExecutorBase):
def __init__(self, parallelism: int=LOCAL_TASK_EXECUTOR_PARALLELISM, registry_path: str=PID_REGISTRY_PATH):
self.manager: Optional[SyncManager] = None
self.task_queue: Optional['Queue[TaskExecutionCommandType]'] = None
self.parallelism = parallelism... |
def link(scatters: Union[(List[Scatter], List[Tuple[(Scatter, str)]])], match_by: Union[(str, List[str])]='index', rows: Optional[int]=1, row_height: int=320, cols: Optional[int]=None):
return compose(scatters, match_by=match_by, rows=rows, row_height=row_height, cols=cols, sync_view=True, sync_selection=True, sync... |
class OverworldTiles():
_cached_dict = None
Mountains = Tile(name='Mountains', symbol='', room_prototype='wilderness_mountains')
Water = Tile(name='Water', symbol='', room_prototype='wilderness_water')
Swamp = Tile(name='Swamp', symbol='', room_prototype='wilderness_swamp')
Desert = Tile(name='Deser... |
class CreateInitialRevisionsDbTest(TestModelMixin, TestBase):
databases = {'default', 'mysql', 'postgres'}
def testCreateInitialRevisionsDb(self):
obj = TestModel.objects.create()
self.callCommand('createinitialrevisions', using='postgres')
self.assertNoRevision()
self.assertSing... |
class CmdUnban(COMMAND_DEFAULT_CLASS):
key = 'unban'
locks = 'cmd:perm(unban) or perm(Developer)'
help_category = 'Admin'
def func(self):
banlist = ServerConfig.objects.conf('server_bans')
if (not self.args):
self.msg(list_bans(self, banlist))
return
try:
... |
class TaskBase():
__name__: ClassVar[str]
def __init__(self, get_main_session: Callable[(..., contextlib.AbstractAsyncContextManager[AsyncSession])]=get_single_main_async_session, get_workspace_session: Callable[(..., contextlib.AbstractAsyncContextManager[AsyncSession])]=get_workspace_session_task, email_provi... |
class Normalizer():
def __init__(self, in_domain, out_domain=(0, 1)):
(self.in_min, self.in_max) = (in_domain[0], in_domain[1])
(self.out_min, self.out_max) = (out_domain[0], out_domain[1])
self.slope = ((self.out_max - self.out_min) / (self.in_max - self.in_min))
def normalize(self, v):... |
class OptionSeriesHistogramSonificationDefaultinstrumentoptionsMappingHighpassFrequency(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(se... |
.filterwarnings('ignore:Default values*')
def test_default_surface_statistics(default_surface):
small = xtgeo.RegularSurface(**default_surface)
so2 = xtgeo.Surfaces()
for _ in range(10):
tmp = small.copy()
tmp.values += 8.76543
so2.append([tmp])
res2 = so2.statistics(percentiles=... |
def downgrade():
op.drop_index(op.f('ix_servednoticehistory_vendor_legitimate_interests'), table_name='servednoticehistory')
op.drop_index(op.f('ix_servednoticehistory_vendor_consent'), table_name='servednoticehistory')
op.drop_index(op.f('ix_servednoticehistory_system_legitimate_interests'), table_name='se... |
class TestAsyncExecutor():
class NoopContextManager():
def __init__(self, mock):
self.mock = mock
async def __aenter__(self):
return self
async def __call__(self, *args):
return (await self.mock(*args))
async def __aexit__(self, exc_type, exc_val, ... |
def subviewsOfView(view):
views = [(view, 0)]
(yield views[0])
while views:
(view, level) = views.pop(0)
subviews = fb.evaluateExpression(('(id)[%s subviews]' % view))
subviewsCount = int(fb.evaluateExpression(('(int)[(id)%s count]' % subviews)))
for i in range(subviewsCount)... |
def extractFlyingsaucertranslatesBlogspotCom(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, na... |
_converter(torch.ops.aten._adaptive_avg_pool2d.default)
def aten_ops_adaptive_avg_pool2d(target: Target, args: Tuple[(Argument, ...)], kwargs: Dict[(str, Argument)], name: str) -> ConverterOutput:
input_val = args[0]
if (not isinstance(input_val, AITTensor)):
raise RuntimeError(f'Non-tensor inputs for {... |
class TestMaps():
def test_return_raise(self, monkeypatch, tmp_path):
with monkeypatch.context() as m:
m.setattr(sys, 'argv', [''])
with pytest.raises(_SpockInstantiationError):
class FailReturnConfig():
val_1: float = 0.5
def _... |
(scope='function')
def shopify_erasure_data(shopify_connection_config, shopify_erasure_identity_email, shopify_secrets) -> Generator:
base_url = f"
faker = Faker()
firstName = faker.first_name()
lastName = faker.last_name()
body = {'customer': {'first_name': firstName, 'last_name': lastName, 'email'... |
class Enum(RawType):
def __init__(self, cstruct, name, type_, values):
self.type = type_
self.values = values
self.reverse = {}
for (k, v) in values.items():
self.reverse[v] = k
super().__init__(cstruct, name, len(self.type))
def __call__(self, value):
... |
class LinearScalingStrategy(TimeGasStrategy):
def __init__(self, initial_gas_price: Wei, max_gas_price: Wei, increment: float=1.125, time_duration: int=30):
super().__init__(time_duration)
self.initial_gas_price = Wei(initial_gas_price)
self.max_gas_price = Wei(max_gas_price)
self.in... |
class EchoAction(UserAction):
def __init__(self, source, target, card):
(self.source, self.target, self.card) = (source, target, card)
def apply_action(self):
(src, tgt, c) = (self.target, self.target, self.card)
g = self.game
assert c.detached
shadow = Echo(src)
... |
class OptionSeriesTreemapSonificationContexttracksMappingTremolo(Options):
def depth(self) -> 'OptionSeriesTreemapSonificationContexttracksMappingTremoloDepth':
return self._config_sub_data('depth', OptionSeriesTreemapSonificationContexttracksMappingTremoloDepth)
def speed(self) -> 'OptionSeriesTreemapS... |
class MonitorSubscribe(object):
swagger_types = {'batch_notify': 'MonitorSubscribeBatchNotify', 'callback': 'MonitorWebhook', 'refresh_event': 'float', 'retry_policy': 'MonitorSubscribeRetryPolicy'}
attribute_map = {'batch_notify': 'batchNotify', 'callback': 'callback', 'refresh_event': 'refreshEvent', 'retry_p... |
def process_value(setting_info, value, selected_preset=None):
dpis = []
if isinstance(value, (int, float)):
dpis = [int(value)]
elif isinstance(value, (list, tuple)):
dpis = [int(dpi) for dpi in value]
else:
dpis = [int(dpi) for dpi in value.replace(' ', '').split(',')]
if (s... |
class TestLang(util.TestCase):
def test_lang(self):
markup = '\n <div lang="de-DE">\n <p id="1"></p>\n </div>\n <div lang="de-DE-1996">\n <p id="2"></p>\n </div>\n <div lang="de-Latn-DE">\n <p id="3"></p>\n </div>\n <div lang=... |
def test_array_type_spark_to_foundry(spark_session):
foundry_schema = spark_schema_to_foundry_schema(StructType([StructField('purple_alias', ArrayType(StringType()), True, {})]))
assert (foundry_schema == {'fieldSchemaList': [{'type': 'ARRAY', 'name': 'purple_alias', 'nullable': True, 'customMetadata': {}, 'arr... |
class Unparser(_unparse.Unparser):
boolops = {'And': 'and', 'Or': 'or'}
def _Interactive(self, tree):
for stmt in tree.body:
self.dispatch(stmt)
def _Expression(self, tree):
self.dispatch(tree.body)
def _ClassDef(self, tree):
self.write('\n')
for deco in tree.... |
class FixedColumns(Options):
def activate(self):
self.leftColumns = 2
return self
def heightMatch(self):
return self._config_get()
def heightMatch(self, val):
self._config(val)
def leftColumns(self):
return self._config_get()
def leftColumns(self, val):
... |
class MaxPool3d(Module):
def __init__(self, kernel_size, stride=None, padding=0):
super().__init__()
self.kernel_size = kernel_size
self.stride = (stride if (stride is not None) else kernel_size)
self.padding = padding
def forward(self, *args):
assert (len(args) == 1)
... |
def save_data(data):
aux = []
for item in data:
number = item.get('number')
title = item.get('title')
guest = item.get('guest')
like = randint(80, 2000)
unlike = (random() * like)
if guest:
user = User.objects.create_user(username=slugify(guest), first... |
class EventVRRPConfigChangeRequest(event.EventRequestBase):
def __init__(self, instance_name, priority=None, advertisement_interval=None, preempt_mode=None, preempt_delay=None, accept_mode=None):
super(EventVRRPConfigChangeRequest, self).__init__()
self.instance_name = instance_name
self.pri... |
class Once():
def __init__(self):
self._lock = asyncio.Lock()
self._done = False
async def do(self, func, *args, **kwargs):
if (not self._done):
async with self._lock:
if (not self._done):
(await func(*args, **kwargs))
s... |
def test_search_path_expansion(workdir):
paths = set_up(workdir)
os.symlink(paths['repo2'], paths['link1'])
with push_dir('projectA'):
status = mu_repo.main(config_file='.bar_file', args=['register', '--recursive'])
assert status.succeeded
_compare_repos(status.config.repos, ['sectionX/repo1... |
def delV3User(snmpEngine, userName, securityEngineId=None):
(securityEngineId, usmUserEntry, tblIdx1, pysnmpUsmSecretEntry, tblIdx2) = __cookV3UserInfo(snmpEngine, userName, securityEngineId)
snmpEngine.msgAndPduDsp.mibInstrumController.writeMibObjects((((usmUserEntry.name + (13,)) + tblIdx1), 'destroy'), snmpE... |
(scope='function')
def emerse_system(db: Session) -> System:
system = System.create(db=db, data={'fides_key': f'emerse{uuid.uuid4()}', 'vendor_id': 'gvl.8', 'name': f'Emerse', 'description': 'Emerse Sverige AB is a provider of programmatic advertising solutions, offering advertisers and publishers tools to manage a... |
def test_plugin_versions_in_cli_help(monkeypatch, capsys):
monkeypatch.setitem(PARSER_EXTENSIONS, 'table', ExampleTablePlugin)
with pytest.raises(SystemExit) as exc_info:
run(['--help'])
assert (exc_info.value.code == 0)
captured = capsys.readouterr()
assert ('Installed plugins:' in captured... |
(scope='function')
def stravawidget(monkeypatch):
monkeypatch.setattr('qtile_extras.resources.stravadata.sync.get_client', fake_client)
monkeypatch.setattr('qtile_extras.resources.stravadata.sync.APP_ID', True)
monkeypatch.setattr('qtile_extras.resources.stravadata.sync.SECRET', True)
monkeypatch.setatt... |
class OptionPlotoptionsScatterSonificationDefaultspeechoptionsMappingTime(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 apps_urlconf(*, apps=None):
if (apps is None):
apps = getattr(_apps_urlconf_cache, 'cache', None)
if (apps is None):
apps = _APPS_MODEL._default_manager.active().applications()
_apps_urlconf_cache.cache = apps
if (not apps):
return settings.ROOT_URLCONF
re... |
def test_hexary_trie_missing_node():
db = {}
trie = HexaryTrie(db, prune=True)
key1 = to_bytes(291)
trie.set(key1, b'use a value long enough that it must be hashed according to trie spec')
key2 = to_bytes(4660)
trie.set(key2, b'val2')
trie_root_hash = trie.root_hash
root_node = trie.root... |
class TreeNodeModelAdmin(admin.ModelAdmin):
TREENODE_DISPLAY_MODE_ACCORDION = 'accordion'
TREENODE_DISPLAY_MODE_BREADCRUMBS = 'breadcrumbs'
TREENODE_DISPLAY_MODE_INDENTATION = 'indentation'
treenode_display_mode = TREENODE_DISPLAY_MODE_INDENTATION
form = TreeNodeForm
list_per_page = 1000
ord... |
class RetentionFilterTestCase(TestCase):
REF_TIME = datetime.datetime(2019, 5, 9, 0, 0, 0, 0, tzinfo=None)
versions: Set[Version]
def _make_version(uid: str, date: datetime.datetime) -> Version:
version = MagicMock(spec=('uid', 'date', '__repr__'))
version.uid = VersionUid(uid)
versi... |
def extractMidnightmoontranslationWordpressCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [("the silly wizard's courtship method", "the silly wizard's courtship method", 'tra... |
.django_db(transaction=True)
.skip(reason='Test based on pre-databricks loader code. Remove when fully cut over.')
def test_delete_fabs_success(monkeypatch):
baker.make(AwardSearch, award_id=1, generated_unique_award_id='TEST_AWARD_1')
baker.make(TransactionSearch, transaction_id=1, award_id=1, generated_unique... |
def sha3(computation: ComputationAPI) -> None:
(start_position, size) = computation.stack_pop_ints(2)
computation.extend_memory(start_position, size)
sha3_bytes = computation.memory_read_bytes(start_position, size)
word_count = (ceil32(len(sha3_bytes)) // 32)
gas_cost = (constants.GAS_SHA3WORD * wor... |
class Diagnostics(BaseDiagnostics):
def __init__(self, samples: MonteCarloSamples):
super().__init__(samples)
self.mean = self.summaryfn(common_stats.mean, display_names=['avg'])
self.std = self.summaryfn(common_stats.std, display_names=['std'])
self.confidence_interval = self.summar... |
()
('search_root')
('--project', help='only render project matches the given name')
_log.simple_verbosity_option(logger)
def render(search_root, project):
template_paths = []
matrix_dirs = []
for (cur_dir, dirs, files) in os.walk(search_root):
for f in files:
if (f == 'matrix.yml'):
... |
class OptionSeriesSunburstSonificationContexttracksMappingFrequency(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 ModelRunSchema(ExtendedBaseModel):
unique_id: str
invocation_id: str
name: str
schema_name: Optional[str] = Field(alias='schema', default=None)
status: str
execution_time: float
compiled_code: Optional[str] = None
full_refresh: Optional[bool] = None
materialization: Optional[st... |
def search_nswlib_jaccard_topk(index_data, query_data, index_params, k):
import nmslib
(index_sets, index_keys, _, index_cache) = index_data
(query_sets, query_keys, _) = query_data
cache_key = json.dumps(index_params)
if (cache_key not in index_cache):
print('Building HNSW Index.')
... |
class OptionSeriesBubbleSonificationDefaultinstrumentoptions(Options):
def activeWhen(self) -> 'OptionSeriesBubbleSonificationDefaultinstrumentoptionsActivewhen':
return self._config_sub_data('activeWhen', OptionSeriesBubbleSonificationDefaultinstrumentoptionsActivewhen)
def instrument(self):
re... |
def test_details_view():
(app, db, admin) = setup()
(Model1, Model2) = create_models(db)
view_no_details = CustomModelView(Model1)
admin.add_view(view_no_details)
view_w_details = CustomModelView(Model2, can_view_details=True)
admin.add_view(view_w_details)
string_field_view = CustomModelVie... |
def _dropout_array(model: Model[(InT, InT)], X: ArrayXd, is_train: bool) -> Tuple[(ArrayXd, Callable)]:
rate = model.attrs['dropout_rate']
mask = model.ops.get_dropout_mask(X.shape, rate)
def backprop(dY: ArrayXd) -> ArrayXd:
return (dY * mask)
return (cast(ArrayXd, (X * mask)), backprop) |
def test_chain_adapter_insertion(chain: Chain):
parent = chain
adaptee = parent.Chain
adapter = DummyChainAdapter(adaptee)
assert (adaptee.parent == parent)
adapter.inject()
assert (adapter.parent == parent)
assert (adaptee.parent == adapter)
assert (adapter in iter(parent))
assert (... |
class MPCGameService():
def __init__(self, mpc_game_repository: MPCGameRepository) -> None:
self.logger: logging.Logger = logging.getLogger(__name__)
self.mpc_game_repository: MPCGameRepository = mpc_game_repository
def build_onedocker_args(self, game_name: str, mpc_party: MPCParty, server_ip: O... |
class FaucetDisconnectTest(FaucetUntaggedTest):
def update_config(self, dpid):
conf = self._get_faucet_conf()
conf['dps'][self.DP_NAME]['dp_id'] = int(dpid)
self.reload_conf(conf, self.faucet_config_path, restart=True, cold_start=False, change_expected=False)
def test_untagged(self):
... |
def add_profiler(file_pairs, workdir, op_type, output_name, code):
prefix = os.path.join(workdir, 'profiler', op_type)
if (not os.path.exists(prefix)):
os.makedirs(prefix)
obj_path = os.path.join(prefix, output_name)
if os.path.exists(obj_path):
return
if isinstance(code, dict):
... |
class OptionSeriesArcdiagramSonificationTracksMappingPlaydelay(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... |
def cli_get_output_printer(output_format, fields, list_command=False):
if (output_format == 'json'):
if list_command:
return JsonPrinterListCommand(fields)
return JsonPrinter(fields)
if (output_format == 'text'):
return ColumnTextPrinter(fields)
return RowTextPrinter(fiel... |
def crop(self, context, distort=False, selection=None):
selection_mode = bpy.context.scene.tool_settings.uv_select_mode
selected_obs = [ob for ob in bpy.context.selected_objects if (ob.type == 'MESH')]
bpy.ops.uv.select_split()
if (len(selected_obs) <= 1):
bm = bmesh.from_edit_mesh(bpy.context.a... |
def get_datasets_and_modules(tree: Union[(eql.ast.BaseNode, kql.ast.BaseNode)]) -> tuple:
modules = set()
datasets = set()
for node in tree:
if (isinstance(node, eql.ast.Comparison) and (node.comparator == node.EQ) and isinstance(node.right, eql.ast.String)):
if (node.left == eql.ast.Fie... |
class CdsRetriever(FileSource):
sphinxdoc = '\n CdsRetriever\n '
def __init__(self, dataset, *args, **kwargs):
super().__init__()
assert isinstance(dataset, str)
if len(args):
assert (len(args) == 1)
assert isinstance(args[0], dict)
assert (not k... |
def test_traverse_args():
provider1 = providers.Object('bar')
provider2 = providers.Object('baz')
provider = providers.List('foo', provider1, provider2)
all_providers = list(provider.traverse())
assert (len(all_providers) == 2)
assert (provider1 in all_providers)
assert (provider2 in all_pro... |
class guessCardManager():
def __init__(self) -> None:
try:
self.path = str(Path(nonebot.get_driver().config.ocg_bot_guess_cfg_path, 'ocg_bot_guess_cfg.json'))
except:
self.path = 'data/ocg_bot/ocg_bot_guess_cfg.json'
self.guess_cd = 20
self.guess_cd = (self.gu... |
def initialize_variation_modules(variation_modules, mode):
log.info('Initializing variation modules...')
for (name, modules_contexts) in variation_modules.items():
body = modules_contexts[0]
for handler in ('init', 'variate', 'shutdown'):
if (handler not in body):
log... |
class Config():
stakeholders = ['development', 'management', 'users', 'customers']
inventors = ['flonatel']
reqs_spec = {'directory': 'doc/requirements', 'commit_interval': ['FILES', 'FILES'], 'default_language': 'en_GB', 'dependency_notation': set(['Solved by'])}
topic_specs = {'ts_common': ['doc/topic... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.