code stringlengths 281 23.7M |
|---|
.parametrize('degree', [1, 2, 12])
.parametrize('value, expected', [(0, 0), (16, 0), (1, 1)])
def test_FQ_sgn0(degree, value, expected):
if (degree == 1):
x = FQ(value)
elif (degree == 2):
x = FQ2([value, 0])
elif (degree == 12):
x = FQ12(([value] + ([0] * 11)))
assert (x.sgn0 ==... |
class SqlInterface():
_conn: object
supports_foreign_key = True
requires_subquery_name = False
id_type_decl = 'INTEGER'
max_rows_per_query = 1024
offset_before_limit = False
def __init__(self, print_sql=False):
self._print_sql = print_sql
def query(self, sql, subqueries=None, qar... |
class Solution():
def diameterOfBinaryTree(self, root: TreeNode) -> int:
def find_diameter(node, mm):
if (node is None):
return 0
l = find_diameter(node.left, mm)
r = find_diameter(node.right, mm)
c = (l + r)
if (c > mm[0]):
... |
class GraphAccumulationTests(unittest.TestCase):
def test_accumulate_simple_distributions(self) -> None:
self.maxDiff = None
queries = [flip_straight_constant(), flip_logit_constant(), standard_normal(), flip_logit_normal(), beta_constant(), hc(1), hc(2), beta_hc(), student_t(), bin_constant(), gamm... |
class TestFromGraph():
def setup_method(self):
DBusTestCase.start_session_bus()
def teardown_method(self):
DBusTestCase.tearDownClass()
def test_create_app_instance_when_it_is_not_registered_in_dbus(self, graph, window, plugin_engine):
graph.register_instance('tomate.ui.view', window... |
(Output('playlist-settings', 'style'), [Input('spotify-playlists-switch', 'on')])
def set_playlist_settings(spotify_playlists_switch):
athlete_info = app.session.query(athlete).filter((athlete.athlete_id == 1)).first()
if spotify_playlists_switch:
style = {}
else:
style = {'display': 'none'}... |
def run():
print('\nmodule top();\n ')
params = {}
sites = list(gen_sites())
for (gtp_int_tile, site_name) in sites:
isone = random.randint(0, 1)
params[gtp_int_tile] = (site_name, isone)
print('\nwire PLL0LOCKEN_{site};\n\n(* KEEP, DONT_TOUCH *)\nLUT1 lut_{site} (.O(PLL0LOCKE... |
class Ui_dlgJog(object):
def setupUi(self, dlgJog):
dlgJog.setObjectName('dlgJog')
dlgJog.setWindowModality(QtCore.Qt.ApplicationModal)
dlgJog.resize(345, 260)
icon = QtGui.QIcon()
icon.addPixmap(QtGui.QPixmap(':/cn5X/images/XYZAB.svg'), QtGui.QIcon.Normal, QtGui.QIcon.Off)
... |
_required
_required
_required(DnsAdminPermission)
_required('DNS_ENABLED')
def dc_domain_record_list(request):
context = collect_view_data(request, 'dc_domain_list', dc_dns_only=True)
context['is_staff'] = is_staff = request.user.is_staff
qs = request.GET.copy()
name = qs.get('flt-domain', None)
con... |
def test_incremental_load_into_award_index(award_data_fixture, elasticsearch_award_index, monkeypatch):
original_db_awards_count = Award.objects.count()
elasticsearch_award_index.update_index()
client = elasticsearch_award_index.client
assert client.indices.exists(elasticsearch_award_index.index_name)
... |
class EdgeOSTrafficData():
direction: str
rate: float
total: float
dropped: (float | None)
errors: (float | None)
packets: (float | None)
last_activity: float
def __init__(self, direction: str):
self.direction = direction
self.rate = 0
self.total = 0
self.... |
class DummyInstance(InstanceBase):
instance_id: str = field(metadata={**DataclassHookMixin.get_metadata(name_update_hook), **MutabilityMetadata.MUTABLE.value})
input_path: str = field(metadata={**DataclassHookMixin.get_metadata(ouput_update_hook, storage_update_hook), **MutabilityMetadata.MUTABLE.value})
na... |
class LoopWeight(enum.Enum):
UNIFORM = 1
COTAN = 2
MVC = 3
def create_cache(self):
if (self is LoopWeight.UNIFORM):
return Cache((lambda l: 1))
elif (self is LoopWeight.MVC):
return Cache(geometry.calc_mvc_loop_weight)
elif (self is LoopWeight.COTAN):
... |
def test_filter_with_contract_address(w3, emitter, emitter_contract_event_ids, wait_for_transaction):
event_filter = w3.eth.filter(filter_params={'address': emitter.address})
txn_hash = emitter.functions.logNoArgs(emitter_contract_event_ids.LogNoArguments).transact()
wait_for_transaction(w3, txn_hash)
s... |
def extractActivatedseriesWordpressCom(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... |
def builder_specific_actions(result, builder, output_path, cmd_type, page_name=None, print_func=print):
from sphinx.util.osutil import cd
from jupyter_book.pdf import html_to_pdf
from jupyter_book.sphinx import REDIRECT_TEXT
if isinstance(result, Exception):
msg = f'There was an error in buildin... |
class TestLinkResource():
def setup_method(self):
self.base_url = '
self.api_key = 'super_secret_api_key'
self.user_agent = 'fintoc-python/test'
self.params = {'first_param': 'first_value', 'second_param': 'second_value'}
self.client = Client(self.base_url, self.api_key, self... |
def CreateBmmRRRBillinearOperator(manifest, c_element_op):
operation_kind = library.GemmKind.BatchGemm
a_element_desc = library.TensorDesc(library.DataType.f16, library.LayoutType.RowMajor)
b_element_desc = library.TensorDesc(library.DataType.f16, library.LayoutType.RowMajor)
c_element_desc = library.Te... |
def eckart_corr(fw_barrier_height: float, bw_barrier_height: float, temperature: float, imag_frequency: float) -> float:
kBT = (KBAU * temperature)
two_pi = (2 * np.pi)
imag_frequency = (abs(imag_frequency) * AU2SEC)
hnu = (PLANCKAU * imag_frequency)
u = (hnu / kBT)
v1 = (fw_barrier_height / kBT... |
def lambda_handler(event, context):
print(event)
response = event.get('response')
request = event.get('request')
if (request.get('userNotFound') is True):
response.update({'issueTokens': False, 'failAuthentication': True, 'msg': 'User does not exist'})
else:
session = request.get('se... |
('job_name,expected', [(None, 'test_compose'), ('test_job', 'test_job')])
def test_jobname_override_initialize_ctx(hydra_restore_singletons: Any, job_name: Optional[str], expected: str) -> None:
with initialize(version_base=None, config_path='../examples/jupyter_notebooks/cloud_app/conf', job_name=job_name):
... |
def cmd_compare(jobs: Jobs, res1: str, others: List[str], *, meanonly: bool=False, pyston: bool=False) -> None:
suites = (['pyston'] if pyston else ['pyperformance'])
matched = list(jobs.match_results(res1, suites=suites))
if (not matched):
logger.error(f'no results matched {res1!r}')
sys.ex... |
class FileEditorDemo(HasTraits):
file_name = File()
file_group = Group(Item('file_name', style='simple', label='Simple', id='simple_file'), Item('_'), Item('file_name', style='custom', label='Custom'), Item('_'), Item('file_name', style='text', label='Text'), Item('_'), Item('file_name', style='readonly', label... |
_page.route('/table/column_order', methods=['POST'])
def column_order():
res = check_uuid(all_data['uuid'], request.json['uuid'])
if (res != None):
return jsonify(res)
column_order = request.json['column_order']
all_data['column_order'] = column_order
return jsonify(status='success', msg='') |
class lockdown_whitelist_ContentHandler(IO_Object_ContentHandler):
def __init__(self, item):
IO_Object_ContentHandler.__init__(self, item)
self.whitelist = False
def startElement(self, name, attrs):
IO_Object_ContentHandler.startElement(self, name, attrs)
self.item.parser_check_e... |
class DummyWorkflow():
_method
def method_annotated_plain(self):
pass
_method()
def method_annotated_decorator_call(self):
pass
_method(name='NAME', workflow_id='WORKFLOW_ID', workflow_id_reuse_policy=WorkflowIdReusePolicy.AllowDuplicate, execution_start_to_close_timeout_seconds=9999... |
class Integrator():
def __init__(self, name, dx_max, value=0.0):
self.name = name
self._last_x = math.nan
self._last_y = math.nan
self._integrator = value
self.dx_max = dx_max
def __iadd__(self, other):
assert isinstance(other, tuple)
self.add_linear(*othe... |
def filter_firewall_proxy_addrgrp_data(json):
option_list = ['color', 'comment', 'member', 'name', 'tagging', 'type', 'uuid', 'visibility']
json = remove_invalid_fields(json)
dictionary = {}
for attribute in option_list:
if ((attribute in json) and (json[attribute] is not None)):
dic... |
def self_ovlp3d_44(ax, da, A, bx, db, B):
result = numpy.zeros((15, 15), dtype=float)
x0 = (0.5 / (ax + bx))
x1 = ((ax + bx) ** (- 1.0))
x2 = (((x1 * (ax + bx)) - 1.0) * A[0])
x3 = (1. * numpy.sqrt(x1))
x4 = ((x2 ** 2) * x3)
x5 = (x0 * x3)
x6 = (3.0 * x5)
x7 = (x0 * ((3.0 * x4) + x6)... |
.django_db
def test_category_state_territory(geo_test_data, monkeypatch, elasticsearch_transaction_index):
setup_elasticsearch_test(monkeypatch, elasticsearch_transaction_index)
test_payload = {'category': 'state_territory', 'subawards': False, 'page': 1, 'limit': 50}
spending_by_category_logic = StateTerri... |
('msg.ui', relto=__file__)
class BPMAutodetectResponse(Gtk.Dialog):
__gtype_name__ = 'BPMAutodetectResponse'
(q_label, r1, r2, r3) = GtkTemplate.Child.widgets(4)
def __init__(self, parent_window, bpm, track):
Gtk.Dialog.__init__(self, parent=parent_window)
self.init_template()
self.q... |
class _IndexedNotebookEditor(BaseSourceWithLocation):
source_class = NotebookEditor
locator_class = Index
handlers = [(MouseClick, (lambda wrapper, _: _interaction_helpers.mouse_click_tab_index(tab_widget=wrapper._target.source.control, index=wrapper._target.location.index, delay=wrapper.delay)))]
def r... |
def dipole3d_41(ax, da, A, bx, db, B, R):
result = numpy.zeros((3, 15, 3), dtype=float)
x0 = (0.5 / (ax + bx))
x1 = ((ax + bx) ** (- 1.0))
x2 = ((ax * bx) * x1)
x3 = numpy.exp(((- x2) * ((A[0] - B[0]) ** 2)))
x4 = (1. * numpy.sqrt(x1))
x5 = (x3 * x4)
x6 = (x0 * x5)
x7 = (3.0 * x6)
... |
class Ui_SpawnAttachDialog(object):
def setupUi(self, Dialog):
Dialog.setObjectName('Dialog')
Dialog.resize(326, 297)
self.gridLayout = QtWidgets.QGridLayout(Dialog)
self.gridLayout.setObjectName('gridLayout')
self.label = QtWidgets.QLabel(Dialog)
self.label.setObject... |
class LFUCache2():
def __init__(self, capacity: int):
self.capacity = capacity
self.map = {}
self.head = ListNode(None)
self.tail = ListNode(None)
self.head.next = self.tail
self.tail.prev = self.head
def get(self, key: int) -> int:
if (key not in self.map... |
def get_and_store_user(request: 'pyramid.request.Request', access_token: str, response: 'pyramid.response.Response'):
userinfo = request.registry.oidc.fedora.userinfo(token={'access_token': access_token})
if ('error' in userinfo):
raise InvalidTokenError(description=userinfo['error_description'])
us... |
.django_db
def test_program_activity_list_pagination(client, agency_account_data, helpers):
query_params = f'?fiscal_year={helpers.get_mocked_current_fiscal_year()}&limit=2&page=1'
resp = client.get(url.format(code='007', query_params=query_params))
expected_result = {'fiscal_year': helpers.get_mocked_curre... |
class XmlProcessor(ProcessorBase.PageProcessor):
wanted_mimetypes = ['text/xml', 'application/xml']
want_priority = 40
loggerPath = 'Main.Text.XmlProcessor'
def __init__(self, baseUrls, pageUrl, pgContent, loggerPath, relinkable, **kwargs):
self.loggerPath = ((loggerPath + '.XmlProcessor') if (n... |
class Command(BaseCommand):
help = 'Updates the fiscal year for all transactions based on their individual action dates'
logger = logging.getLogger('script')
def handle(self, *args, **options):
all_transactions = TransactionNormalized.objects.all()
for transaction in all_transactions:
... |
def non_strict_arrays_contract(w3_non_strict_abi, address_conversion_func):
non_strict_arrays_contract_factory = w3_non_strict_abi.eth.contract(**ARRAYS_CONTRACT_DATA)
return deploy(w3_non_strict_abi, non_strict_arrays_contract_factory, address_conversion_func, args=[BYTES32_ARRAY, BYTES1_ARRAY]) |
class SlackIntegration(BaseIntegration):
def __init__(self, config: Config, tracking: Optional[Tracking]=None, override_config_defaults=False, *args, **kwargs) -> None:
self.config = config
self.tracking = tracking
self.override_config_defaults = override_config_defaults
self.message... |
class TestObserverChangeNotifierWeakrefTarget(unittest.TestCase):
def test_target_can_be_garbage_collected(self):
target = mock.Mock()
target_ref = weakref.ref(target)
notifier = create_notifier(target=target)
del target
self.assertIsNone(target_ref())
def test_deleted_ta... |
def build_ait_module(*, batch_sizes, input_nonbatch_shapes, start_indices, end_indices, n_normalize_over_last_dims, gamma_is_none, beta_is_none, fuse_sigmoid_mul, eps, test_id, ait_dtype='float16', workdir='./tmp', test_name='strided_group_layernorm'):
target = detect_target()
inputs = [Tensor(shape=[shape_util... |
class StageFlow(Enum, metaclass=StageFlowMeta):
def __init_subclass__(cls: Type[C]) -> None:
super().__init_subclass__()
cls._stage_flow_initialized_statuses = set()
cls._stage_flow_started_statuses = set()
cls._stage_flow_completed_statuses = set()
cls._stage_flow_failed_sta... |
class Plugin(plugin.PluginProto):
PLUGIN_ID = 512
PLUGIN_NAME = 'Environment - BLE Xiaomi Mijia Temperature&Humidity (TESTING)'
PLUGIN_VALUENAME1 = 'Temperature'
PLUGIN_VALUENAME2 = 'Humidity'
PLUGIN_VALUENAME3 = 'Battery'
def __init__(self, taskindex):
plugin.PluginProto.__init__(self, ... |
def describe_CFI_instructions(entry):
def _assert_FDE_instruction(instr):
dwarf_assert(isinstance(entry, FDE), ('Unexpected instruction "%s" for a CIE' % instr))
def _full_reg_name(regnum):
regname = describe_reg_name(regnum, _MACHINE_ARCH, False)
if regname:
return ('r%s (%s... |
def test_simbench_code_conversion():
all_ = sb.collect_all_simbench_codes()
for input_code in all_:
sb_code_parameters = sb.get_parameters_from_simbench_code(input_code)
output_code = sb.get_simbench_code_from_parameters(sb_code_parameters)
assert (input_code == output_code) |
('src,expected', [param({'value': 99, 'obj': {'_target_': 'tests.instantiate.SimpleDataClass', 'a': {'_target_': 'tests.instantiate.SimpleDataClass', 'a': {'foo': '${value}'}, 'b': [1, '${value}']}, 'b': None}}, (SimpleDataClass(a=SimpleDataClass(a=OmegaConf.create({'foo': 99}), b=OmegaConf.create([1, 99])), b=None), S... |
class _Group(click.Group):
def get_help(self, ctx: click.Context) -> str:
self._maybe_import_app()
return super().get_help(ctx)
def get_usage(self, ctx: click.Context) -> str:
self._maybe_import_app()
return super().get_usage(ctx)
def _maybe_import_app(self, argv: Sequence[st... |
class MyModelToolOperator(MixinLLMOperator, MapOperator[(TriggerReqBody, Dict[(str, Any)])]):
def __init__(self, llm_client: Optional[LLMClient]=None, **kwargs):
super().__init__(llm_client)
MapOperator.__init__(self, llm_client, **kwargs)
async def map(self, input_value: TriggerReqBody) -> Dict... |
.parametrize('should_sign_tx', (True, False))
.parametrize('data, gas_estimator, to, on_pending, vm_cls, expected', (pytest.param(b'', None, ADDR_1010, True, FrontierVM, 21000, id='simple default pending for FrontierVM'), pytest.param(b'', None, ADDR_1010, False, FrontierVM, 21000, id='simple default for FrontierVM'), ... |
def test_generate_gpu_of_a_look_dev_of_a_building(create_test_data, store_local_session, create_pymel, create_maya_env):
data = create_test_data
pm = create_pymel
maya_env = create_maya_env
gen = RepresentationGenerator(version=data['building1_yapi_model_main_v003'])
gen.generate_gpu()
gen.versi... |
class conv3d_bias(conv3d):
def __init__(self, stride, pad, dilate=1, group=1) -> None:
super().__init__(stride, pad, dilate=dilate, group=group)
self._attrs['op'] = 'conv3d_bias'
def __call__(self, x: Tensor, w: Tensor, b: Tensor) -> List[Tensor]:
self._attrs['inputs'] = [x, w, b]
... |
def get_maze_centers(maze_path, maze_verts):
link_centers = []
for edge in maze_path:
(x_co, y_co, z_co) = zip(*[edge.verts[poi].co for poi in [0, 1]])
(x_av, y_av, z_av) = ((sum(x_co) / len(x_co)), (sum(y_co) / len(y_co)), (sum(z_co) / len(z_co)))
link_centers.append((x_av, y_av, z_av))... |
class DumpSecrets():
def __init__(self, remoteName, username='', password='', domain='', options=None):
self.__useVSSMethod = options.use_vss
self.__useKeyListMethod = options.use_keylist
self.__remoteName = remoteName
self.__remoteHost = options.target_ip
self.__username = u... |
class IPAddress(FancyValidator):
messages = dict(badFormat=_('Please enter a valid IP address (a.b.c.d)'), leadingZeros=_('The octets must not have leading zeros'), illegalOctets=_('The octets must be within the range of 0-255 (not %(octet)r)'))
leading_zeros = False
def _validate_python(self, value, state=... |
def query_cpu() -> int:
cpu_quota = (- 1)
if os.path.isfile('/sys/fs/cgroup/cpu/cpu.cfs_quota_us'):
cpu_quota = int(open('/sys/fs/cgroup/cpu/cpu.cfs_quota_us').read().rstrip())
if ((cpu_quota != (- 1)) and os.path.isfile('/sys/fs/cgroup/cpu/cpu.cfs_period_us')):
cpu_period = int(open('/sys/f... |
class PluginRoutes(ComponentBase):
def _init_component(self):
plugin_list = _find_plugins()
self._register_all_plugin_endpoints(plugin_list)
def _register_all_plugin_endpoints(self, plugins_by_category):
for (plugin_type, plugin_list) in plugins_by_category:
for plugin in plu... |
def extractOracledutchessCom(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) in ... |
def to_pickle(data):
def process_item(item):
dtype = type(item)
if (dtype in (str, int, float, bool, bytes, SafeString)):
return item
elif (dtype == tuple):
return tuple((process_item(val) for val in item))
elif (dtype in (list, _SaverList)):
retur... |
def test_decoding_unknown_performative():
msg = LedgerApiMessage(performative=LedgerApiMessage.Performative.GET_BALANCE, ledger_id='some_ledger_id', address='some_address')
encoded_msg = LedgerApiMessage.serializer.encode(msg)
with pytest.raises(ValueError, match='Performative not valid:'):
with moc... |
def prepare_non_justification_slash(prepare_msg: (bytes <= 1024)) -> num:
sighash = extract32(raw_call(self.sighasher, prepare_msg, gas=200000, outsize=32), 0)
values = RLPList(prepare_msg, [num, num, bytes32, bytes32, num, bytes32, bytes])
validator_index = values[0]
epoch = values[1]
hash = values... |
class XYZExit(DefaultExit):
objects = XYZExitManager()
def __str__(self):
return repr(self)
def __repr__(self):
(x, y, z) = self.xyz
(xd, yd, zd) = self.xyz_destination
return f"<XYZExit '{self.db_key}', XYZ=({x},{y},{z})->({xd},{yd},{zd})>"
def xyzgrid(self):
glo... |
def updateCommandBox(args=None):
cmd = widgets['Command'].get()
widgets['helpPane']['state'] = 'normal'
widgets['helpPane'].delete(0.0, 'end')
widgets['helpPane'].insert(0.0, cmdHelp[cmd])
widgets['helpPane']['state'] = 'disabled'
for widget in widgets['req'].winfo_children():
widget.gri... |
class OptionSeriesNetworkgraphSonificationContexttracksMappingTime(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 DeprecatedMethod():
def __init__(self, method: Method[Callable[(..., Any)]], old_name: str, new_name: str) -> None:
self.method = method
self.old_name = old_name
self.new_name = new_name
def __get__(self, obj: Optional['Module']=None, obj_type: Optional[Type['Module']]=None) -> Any... |
class Actor(hk.Module):
def __init__(self, action_size: int, latent_size: int=50, hidden_sizes: Sequence[int]=(256, 256), log_std_min: float=(- 10.0), log_std_max: float=2.0, name: Optional[str]=None):
super().__init__(name=name)
self.latent_size = latent_size
self.action_size = action_size
... |
def test_consolidate_query_matches():
input_data = {'B': 55}
target_path = FieldPath('B')
assert (consolidate_query_matches(input_data, target_path) == [55])
input_data = {'A': [1, 2, 3]}
target_path = FieldPath('A')
assert (consolidate_query_matches(input_data, target_path) == [1, 2, 3])
fi... |
.parametrize('current_data, reference_data, data_mapping, metric, expected_error', ((pd.DataFrame({'col': [1, 2, 3]}), None, None, ColumnDriftMetric(column_name='col'), 'Reference dataset should be present'), (pd.DataFrame({'feature': [1, 2, 3]}), pd.DataFrame({'col': [1, 2, 3]}), None, ColumnDriftMetric(column_name='c... |
class Func(Statement):
_CAPITALIZE = False
def get_args(self):
args = []
for arg in self.args:
if isinstance(arg, (Pypher, Partial)):
arg.parent = self.parent
value = str(arg)
else:
param = self.bind_param(arg)
... |
class AdAssetFeedSpecDescription(AbstractObject):
def __init__(self, api=None):
super(AdAssetFeedSpecDescription, self).__init__()
self._isAdAssetFeedSpecDescription = True
self._api = api
class Field(AbstractObject.Field):
adlabels = 'adlabels'
text = 'text'
url_... |
class _SortFilterProxyModel(QSortFilterProxyModel):
def lessThan(self, source_left: QModelIndex, source_right: QModelIndex) -> bool:
value_left = self.sourceModel().data(source_left, QT_SORT_ROLE)
value_right = self.sourceModel().data(source_right, QT_SORT_ROLE)
return (value_left < value_ri... |
def flatten_feature_to_parse_trace_feature(feature: Dict[(str, Any)]) -> Iterable[ParseTraceFeature]:
for (key, value) in feature.items():
if (isinstance(value, str) and value):
(yield ParseTraceFeature(((key + ':') + value), []))
else:
(yield ParseTraceFeature(key, [])) |
class MultiCutTestCase(unittest.TestCase):
def setUp(self):
self.inputs = [seqrecord('Sequence 1', 'ACGT--TCAGA')]
def test_multicut(self):
actual = list(transform.multi_cut_sequences(self.inputs, [slice(None, 2), slice(8, None)]))
self.assertEqual(['ACAGA'], [str(s.seq) for s in actual]... |
def convert_dinov2_facebook(weights: dict[(str, torch.Tensor)]) -> None:
depth = (max([int(k.split('.')[1]) for k in weights.keys() if k.startswith('blocks.')]) + 1)
del weights['mask_token']
weights['cls_token'] = weights['cls_token'].squeeze(0)
weights['pos_embed'] = weights['pos_embed'].squeeze(0)
... |
def _form_loopy_kernel(kernel_domains, instructions, measure, args, **kwargs):
kargs = []
for (var, (func, intent)) in args.items():
is_input = (intent in [INC, READ, RW, MAX, MIN])
is_output = (intent in [INC, RW, WRITE, MAX, MIN])
if isinstance(func, constant.Constant):
if ... |
('fides.api.service.privacy_request.request_runner_service.dispatch_message')
('fides.api.service.privacy_request.request_runner_service.upload')
def test_start_processing_sets_started_processing_at(upload_mock: Mock, mock_email_dispatch: Mock, db: Session, privacy_request_status_pending: PrivacyRequest, run_privacy_re... |
class DummyTransportTestCase():
def setup_method(self, _):
self.client = Elasticsearch(' transport_class=DummyTransport)
def assert_call_count_equals(self, count):
assert (count == self.client.transport.call_count)
def assert_url_called(self, method, url, count=1):
assert ((method, u... |
def _omor2ftc(omorstring):
anals = dict()
ftc = ''
omors = omorstring.split('][')
for omor in omors:
kv = omor.split('=')
k = kv[0].lstrip('[')
v = kv[1].rstrip(']')
if (k in anals):
anals[k] = (anals[k] + [v])
else:
anals[k] = [v]
for ... |
class MockFixedJump(Mock):
def __init__(self, address: int):
super().__init__(spec=MediumLevelILJumpTo)
self.ssa_memory_version = 0
self.function = None
self.dest = Mock(spec=MediumLevelILConstPtr)
self.dest.constant = address
self.dest.function = MockFunction([]) |
class Solution(object):
def mincostToHireWorkers(self, quality, wage, K):
from fractions import Fraction
workers = sorted(((Fraction(w, q), q, w) for (q, w) in zip(quality, wage)))
ans = float('inf')
pool = []
sumq = 0
for (ratio, q, w) in workers:
heapq.h... |
(frozen=True, repr=True, eq=False, order=False, hash=False)
class ChangeUserDetails(MethodView):
form = attr.ib(factory=change_details_form_factory)
details_update_handler = attr.ib(factory=details_update_factory)
decorators = [login_required]
def get(self):
return self.render()
def post(sel... |
def _requires_dev_packages(f: Callable[(P, R)]) -> Callable[(P, R)]:
(f)
def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
try:
return f(*args, **kwargs)
except ModuleNotFoundError as e:
raise ModuleNotFoundError("Dev packages are required for the diagnostic widgets, w... |
class OptionPlotoptionsScatterStatesInactive(Options):
def animation(self) -> 'OptionPlotoptionsScatterStatesInactiveAnimation':
return self._config_sub_data('animation', OptionPlotoptionsScatterStatesInactiveAnimation)
def enabled(self):
return self._config_get(True)
def enabled(self, flag:... |
class MyWebSocketHandler():
class Application():
pass
class IOLoop():
def __init__(self, loop):
self._loop = loop
def spawn_callback(self, func, *args):
self._loop.call_soon_threadsafe(func, *args)
def __init__(self, ws):
self._ws = ws
self.app... |
def do_metrics(cnarrs, segments=None, skip_low=False):
from .cnary import CopyNumArray as CNA
if isinstance(cnarrs, CNA):
cnarrs = [cnarrs]
if isinstance(segments, CNA):
segments = [segments]
elif (segments is None):
segments = [None]
else:
segments = list(segments)
... |
class RelaxationZone():
def __cinit__(self, zone_type, center, orientation, epsFact_porous, waves=None, shape=None, wind_speed=np.array([0.0, 0.0, 0.0]), dragAlpha=old_div(0.5, 1.005e-06), dragBeta=0.0, porosity=1.0, vert_axis=None, smoothing=0.0, vof_water=0.0, vof_air=1.0):
self.Shape = shape
self... |
class TestCostExplorerGateway(unittest.TestCase):
TEST_ACCESS_KEY_ID = 'test-access-key-id'
TEST_ACCESS_KEY_DATA = 'test-access-key-data'
('boto3.client')
def setUp(self, BotoClient):
self.gw = CostExplorerGateway(self.TEST_ACCESS_KEY_ID, self.TEST_ACCESS_KEY_DATA)
self.gw.client = BotoC... |
class ImageWriter():
def __init__(self, outdir):
self.outdir = outdir
if (not os.path.exists(self.outdir)):
os.makedirs(self.outdir)
return
def export_image(self, image):
stream = image.stream
filters = stream.get_filters()
(width, height) = image.srcs... |
def sde64():
sde = (distutils.spawn.find_executable('sde64', os.getenv('SDE_PATH')) or distutils.spawn.find_executable('sde64'))
if (not sde):
pytest.skip('could not find SDE')
def run(cmd, **kwargs):
if (not isinstance(cmd, list)):
cmd = shlex.split(str(cmd))
return subp... |
def _process_external_references(db: Session, graph_list: List[GraphDataset], connection_config_list: List[ConnectionConfig]):
connection_config = connection_config_list[0]
if connection_config.saas_config.get('external_references'):
connector_type = connection_config.saas_config['type']
externa... |
def run_statistical_tests(pInteractionFilesList, pArgs, pViewpointObject, pQueue=None):
accepted_list = []
rejected_list = []
all_results_list = []
try:
for interactionFile in pInteractionFilesList:
(line_content1, data1) = pViewpointObject.readAggregatedFileHDF(pArgs.aggregatedFile,... |
class isFloat(_is):
def __init__(self, dot='.', message=None):
super().__init__(message=message)
self.dot = dot
def check(self, value):
try:
v = float(str(value).replace(self.dot, '.'))
return (v, None)
except (ValueError, TypeError):
pass
... |
class ThreadedProducer(ServiceThread):
_producer: Optional[aiokafka.AIOKafkaProducer] = None
event_queue: Optional[asyncio.Queue] = None
_default_producer: Optional[aiokafka.AIOKafkaProducer] = None
_push_events_task: Optional[asyncio.Task] = None
app: None
stopped: bool
def __init__(self, d... |
(name=REFRESH_STALEPATH_TIME)
def validate_refresh_stalepath_time(rst):
if (not isinstance(rst, numbers.Integral)):
raise ConfigTypeError(desc=('Configuration value for %s has to be integral type' % REFRESH_STALEPATH_TIME))
if (rst < 0):
raise ConfigValueError(desc=('Invalid refresh stalepath ti... |
_deserializable
class QnaPairChunker(BaseChunker):
def __init__(self, config: Optional[ChunkerConfig]=None):
if (config is None):
config = ChunkerConfig(chunk_size=300, chunk_overlap=0, length_function=len)
text_splitter = RecursiveCharacterTextSplitter(chunk_size=config.chunk_size, chun... |
def save_withings_token(credentials: CredentialsType) -> None:
app.server.logger.debug('***** ATTEMPTING TO SAVE TOKENS *****')
app.session.execute(delete(apiTokens).where((apiTokens.service == 'Withings')))
app.session.add(apiTokens(date_utc=datetime.utcnow(), service='Withings', tokens=pickle.dumps(creden... |
class TestTwilioSmsDispatcher():
def test_dispatch_no_to(self, messaging_config_twilio_sms):
with pytest.raises(MessageDispatchException) as exc:
_twilio_sms_dispatcher(messaging_config_twilio_sms, 'test', None)
assert ('No phone identity' in str(exc.value))
def test_dispatch_no_secr... |
def extractMadaoTranslations(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
if ('My Death Flags Show No Sign of Ending' in item['tags']):
(chp, frag) = (frag, chp)
return ... |
def _generate_system_manager_header(oauth_system_client, app_encryption_key) -> Callable[([Any], Dict[(str, str)])]:
client_id = oauth_system_client.id
def _build_jwt(systems: List[str]) -> Dict[(str, str)]:
payload = {JWE_PAYLOAD_ROLES: [], JWE_PAYLOAD_CLIENT_ID: client_id, JWE_ISSUED_AT: datetime.now(... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.