code stringlengths 281 23.7M |
|---|
class FakeOFTable():
def __init__(self, dp_id, num_tables=1, requires_tfm=True):
self.dp_id = dp_id
self.tables = [[] for _ in range(0, num_tables)]
self.groups = {}
self.requires_tfm = requires_tfm
self.tfm = {}
def table_state(self):
table_str = str(self.tables)... |
def bg_checks(sampler_list, timeout, t_start):
global shutdown
now = time.time()
if timeout:
pdt = (now - (mqtt_last_publish_time() or t_start))
if (pdt > timeout):
if mqtt_last_publish_time():
logger.error('MQTT message publish timeout (last %.0fs ago), exit', pd... |
class OptionPlotoptionsBulletSonificationTracksMappingRate(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.... |
class OptionPlotoptionsWordcloudSonificationContexttracksMappingTremoloSpeed(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: s... |
def test_sample_rate_undefined_by_parent(elasticapm_client):
trace_parent = TraceParent.from_string('00-0af7651916cd43dd8448eb211c80319c-b7ad6b-03')
elasticapm_client.begin_transaction('test', trace_parent=trace_parent)
with elasticapm.capture_span('x'):
pass
transaction = elasticapm_client.end_... |
def extractCottonflavouredWordpressCom(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... |
class ToggleButton(BaseButton):
DEFAULT_MIN_SIZE = (10, 28)
def _create_dom(self):
global window
node = window.document.createElement('button')
return node
def _render_dom(self):
return [self.text]
('pointer_click')
def __toggle_checked(self, *events):
self.us... |
def get_latest_release(ver, this_version, force=False):
releases_url = '
with suppress(requests.RequestException):
release = requests.get(releases_url)
if (release.status_code >= 400):
release = requests.get(releases_url, proxies=get_proxy(False))
release = release.json()
... |
class ProgressBar(JQueryUI):
def destroy(self):
return JsObjects.JsObjects.get(('%s.progressbar("destroy")' % self.component.dom.jquery.varId))
def disable(self):
return JsObjects.JsObjects.get(('%s.progressbar("disable")' % self.component.dom.jquery.varId))
def enable(self):
return ... |
class IDName(AbstractCrudObject):
def __init__(self, fbid=None, parent_id=None, api=None):
self._isIDName = True
super(IDName, self).__init__(fbid, parent_id, api)
class Field(AbstractObject.Field):
id = 'id'
name = 'name'
_field_types = {'id': 'string', 'name': 'string'}
... |
class FncFiltere():
def __init__(self, data, js_src, data_schema=None, profile: Union[(dict, bool)]=False):
(self._js_src, self._data_schema, self._data, self.profile) = (js_src, data_schema, data, profile)
fnc_name = JsFncsRecords.JsFilter.__name__
fnc_pmts = (['data'] + (list(JsFncsRecords... |
def main():
if (len(sys.argv) < 7):
sys.exit('Usage: {} [file] [samples] [first iline] [last iline] [first xline] [last xline]'.format(sys.argv[0]))
spec = segyio.spec()
filename = sys.argv[1]
spec.sorting = 2
spec.format = 1
spec.samples = range(int(sys.argv[2]))
spec.ilines = range... |
class ParFile(TBase):
def __init__(self, f, dump=None):
TBase.__init__(self, 'g', dump)
self.grad = []
self.main(f)
def main(self, f):
if (len(f.children) == 0):
return
if (f.children[0].type == 'error'):
self.error(f.children[0].leaf)
... |
def test_token_provider_dash(mocker):
mocker.patch('foundry_dev_tools.utils.token_provider.AppServiceDashTokenProvider.get_flask_request_headers', return_value={APP_SERVICE_ACCESS_TOKEN_HEADER: 'secret-token-dash'})
with PatchConfig(config_overwrite={'jwt': None}):
from foundry_dev_tools.foundry_api_cli... |
class SignedTransactionMethods(BaseTransactionMethods, SignedTransactionAPI):
type_id: Optional[int] = None
_property
def sender(self) -> Address:
return self.get_sender()
def validate(self) -> None:
if (self.gas < self.intrinsic_gas):
raise ValidationError('Insufficient gas'... |
class DangerousDelegatecall(Checker):
def __init__(self, contract_manager, account_manager):
super().__init__()
self.contract_manager = contract_manager
self.account_manager = account_manager
self.addresses = []
for contract in contract_manager.contract_dict.values():
... |
def test_modify_library(mockproject):
with mockproject._path.joinpath('contracts/FooLib.sol').open('w') as fp:
fp.write(LIBRARY.replace('true', 'false'))
mockproject.load()
assert (sorted(mockproject._compile.call_args[0][0]) == ['contracts/BaseFoo.sol', 'contracts/Foo.sol', 'contracts/FooLib.sol']) |
_app.callback(Output('sms-demand-result', 'children'), Input('ask-sms', 'n_clicks'))
def askCode(n_clicks):
ctx = callback_context
if ctx.triggered:
try:
app.myp.remote_client.get_sms_otp_code()
return dbc.Alert('SMS sent', color='success')
except Exception as e:
... |
class OptionPlotoptionsVariablepieStatesSelectHalo(Options):
def attributes(self):
return self._config_get(None)
def attributes(self, value: Any):
self._config(value, js_type=False)
def opacity(self):
return self._config_get(0.25)
def opacity(self, num: float):
self._conf... |
class TestActionClose(TestCase):
VERSION = {'version': {'number': '5.0.0'}}
def builder(self):
self.client = Mock()
self.client.info.return_value = self.VERSION
self.client.cat.indices.return_value = testvars.state_one
self.client.indices.get_settings.return_value = testvars.sett... |
class Template(object):
def __init__(self, name, code):
self.name = name
self.code = code.strip()
def compile(self, ctx):
compiled = self.code
for (key, val) in ctx.items():
compiled = compiled.replace(('{%s}' % key), str(val))
return compiled |
def example():
class Example(ft.Column):
def __init__(self):
super().__init__()
self.datepicker = ft.DatePicker(first_date=datetime.datetime(2023, 10, 1), last_date=datetime.datetime(2024, 10, 1), on_change=self.change_date)
self.selected_date = ft.Text()
self... |
def test_drop_events_in_processor(elasticapm_client, caplog):
dropping_processor = mock.MagicMock(return_value=None, event_types=[TRANSACTION], __name__='dropper')
shouldnt_be_called_processor = mock.Mock(event_types=[])
elasticapm_client._transport._processors = [dropping_processor, shouldnt_be_called_proc... |
def set_global_machine_arch(arch, binary):
binary.config.MACHINE_ARCH = arch
if (arch == 'x86'):
binary.config.REG_MAPPING = constants.REG_MAPPING_x86
binary.config.SYSCALL_TABLE = constants.SYSCALL_TABLE_x86
binary.config.ADDRESS_BYTE_SIZE = 4
binary.config.HIGH_PC =
elif (... |
class EnforcerTestCase(ForsetiTestCase):
.object(google.auth, 'default', return_value=(mock.Mock(spec_set=credentials.Credentials), TEST_PROJECT))
def setUpClass(cls, mock_google_credential):
fake_global_configs = {'compute': {'max_calls': 18, 'period': 1}}
cls.gce_api_client = compute.ComputeCl... |
def extractProjektworldwitchesCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [('Noble Witches', 'Noble Witches: 506th Joint Fighter Wing', 'translated'), ('PRC', 'PRC', 'tran... |
def test_attach_external_modules_multiple_levels_deep(module1, module2, module3, module4):
w3 = Web3(EthereumTesterProvider(), external_modules={'module1': module1, 'module2': (module2, {'submodule1': (module3, {'submodule2': module4})})})
assert w3.is_connected()
assert hasattr(w3, 'geth')
assert hasat... |
class XMLDiff(DiffBase):
def parse(self):
parser = lxml.etree.XMLParser(remove_blank_text=True, remove_comments=True)
self.config = lxml.etree.parse(self.filename, parser)
if (not self.ordered):
for parent in self.config.xpath('//*[./*]'):
parent[:] = sorted(paren... |
class CREDHIST_FILE():
def __init__(self, raw):
self.credhist_entries = {}
self.credhist_entries_list = []
self.version = unpack('<L', raw[:4])[0]
self.current_guid = unpack('16s', raw[4:20])[0]
i = 0
next_len = unpack('<L', raw[((- i) - 4):])[0]
i += 4
... |
class ServerSentEvent():
def __init__(self, html_code: Optional[str]=None, src: Optional[Union[(str, primitives.PageModel)]]=None, server: Optional[str]=False):
(self.page, self.__server) = (src, server)
self._selector = (html_code or ('sse_%s' % id(self)))
self.page.properties.js.add_builde... |
class Lighting(object):
swagger_types = {'light': 'list[str]', 'turn': 'list[str]'}
attribute_map = {'light': 'light', 'turn': 'turn'}
def __init__(self, light=None, turn=None):
self._light = None
self._turn = None
self.discriminator = None
if (light is not None):
... |
def _create_feature():
fc1 = QuarterlyFeatures(data_key='quarterly', columns=(QUARTER_COLUMNS + DEV_COLUMNS), quarter_counts=QUARTER_COUNTS, max_back_quarter=MAX_BACK_QUARTER, min_back_quarter=MIN_BACK_QUARTER, calc_stats_on_diffs=True, data_preprocessing=_preprocess, verbose=VERBOSE)
fc2 = QuarterlyDiffFeature... |
_dataloader('speech-to-speech')
class SpeechToSpeechDataloader(SpeechToTextDataloader):
def from_files(cls, source: Union[(Path, str)], target: Union[(Path, str)], tgt_lang: Union[(Path, str, None)]=None) -> SpeechToSpeechDataloader:
source_list = load_list_from_file(source)
target_list = load_list_... |
class OptionSeriesHeatmapSonificationDefaultspeechoptionsMappingPitch(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('undefined')
def mapTo(self, text: s... |
def _handle_error_while_loading_component_module_not_found(configuration: ComponentConfiguration, e: ModuleNotFoundError) -> None:
error_message = str(e)
match = re.match("No module named '([\\w.]+)'", error_message)
if (match is None):
raise e from e
import_path = match.group(1)
parts = imp... |
class OptionSeriesLineSonificationContexttracks(Options):
def activeWhen(self) -> 'OptionSeriesLineSonificationContexttracksActivewhen':
return self._config_sub_data('activeWhen', OptionSeriesLineSonificationContexttracksActivewhen)
def instrument(self):
return self._config_get('piano')
def ... |
class ColAlterType(BaseAlterType):
CHANGE_COL_DEFAULT_VAL = 'change_col_default_val'
REORDER_COL = 'reorder_col'
ADD_COL = 'add_col'
ADD_AUTO_INC_COL = 'add_auto_inc_col'
DROP_COL = 'drop_col'
CHANGE_COL_DATA_TYPE = 'change_col_data_type'
CHANGE_NULL = 'change_null'
CHANGE_ENUM = 'change... |
def SetRotationQuaternion(kwargs: dict) -> OutgoingMessage:
compulsory_params = ['id', 'quaternion']
optional_params = ['is_world']
utility.CheckKwargs(kwargs, compulsory_params)
msg = OutgoingMessage()
msg.write_int32(kwargs['id'])
msg.write_string('SetRotationQuaternion')
for i in range(4)... |
def test_get_feature_names_out(df_enc_big):
input_features = df_enc_big.columns.tolist()
tr = StringSimilarityEncoder()
tr.fit(df_enc_big)
out = ['var_A_B', 'var_A_D', 'var_A_A', 'var_A_G', 'var_A_C', 'var_A_E', 'var_A_F', 'var_B_A', 'var_B_D', 'var_B_B', 'var_B_G', 'var_B_C', 'var_B_E', 'var_B_F', 'var... |
def update_plugin_translations(plugin):
plugin_folder = current_app.pluggy.get_plugin(plugin).__path__[0]
translations_folder = os.path.join(plugin_folder, 'translations')
source_file = os.path.join(translations_folder, 'messages.pot')
if (not os.path.exists(source_file)):
return False
subpr... |
class TestIsSameOrParentPathOf():
def test_should_return_true_for_same_path(self):
assert (is_same_or_parent_path_of(['parent', 'child1'], ['parent', 'child1']) is True)
def test_should_return_true_for_parent_path_of_child(self):
assert (is_same_or_parent_path_of(['parent'], ['parent', 'child1']... |
def test_partition_of_split(loose_leaf, X):
grow_val = X[(0, 0)]
growable_vals = loose_leaf.get_growable_vals(X=X, grow_dim=0)
assert torch.isclose(torch.tensor([loose_leaf.get_partition_of_split(X=X, grow_dim=0, grow_val=grow_val)]), torch.mean((growable_vals == grow_val.item()).to(torch.float), dtype=torc... |
def merge_config_sources(user_config: dict, default_config: dict, cli_options: dict) -> dict:
for opt in CLI_ONLY_OPTS:
del cli_options[opt]
config = hierarchical_merge([default_config, user_config, cli_options])
validated_config = validate_config(config)
return validated_config |
def setup_custom_db(db, scantype, dbtype=DB_TYPE_HMM, silent=False):
if (dbtype == DB_TYPE_HMM):
(dbpath, host, idmap_file) = setup_custom_hmmdb(db, scantype, silent)
elif (dbtype == DB_TYPE_SEQ):
(dbpath, host, idmap_file) = setup_custom_seqdb(db, scantype, silent)
else:
raise Emapp... |
class TestPseudoLogicCondition():
.parametrize('condition, result', [(Condition(OperationType.equal, [var_a, constant_5]), 'a,eax#3 == 5'), (Condition(OperationType.less_or_equal, [BinaryOperation(OperationType.plus, [var_a, constant_5]), constant_5]), "a + 0x5,['eax#3'] <= 5"), (Condition(OperationType.greater_or_... |
class OptionPlotoptionsXrangeSonificationContexttracksMapping(Options):
def frequency(self) -> 'OptionPlotoptionsXrangeSonificationContexttracksMappingFrequency':
return self._config_sub_data('frequency', OptionPlotoptionsXrangeSonificationContexttracksMappingFrequency)
def gapBetweenNotes(self) -> 'Opt... |
class OptionSeriesItemSonificationContexttracksMappingVolume(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):
sel... |
.parametrize('session_type', [SessionType.POMODORO, SessionType.SHORT_BREAK, SessionType.LONG_BREAK])
def test_changes_session_when_button_is_clicked(session_type, session_button, session):
session_button.widget.emit('mode_changed', session_type.value)
refresh_gui()
session.change.assert_called_once_with(se... |
class TestSeriesRepr(TestData):
def test_repr_flights_carrier(self):
pd_s = self.pd_flights()['Carrier']
ed_s = ed.Series(ES_TEST_CLIENT, FLIGHTS_INDEX_NAME, 'Carrier')
pd_repr = repr(pd_s)
ed_repr = repr(ed_s)
assert (pd_repr == ed_repr)
def test_repr_flights_carrier_5(s... |
def calculate_message_call_gas(value: U256, gas: Uint, gas_left: Uint, memory_cost: Uint, extra_gas: Uint, call_stipend: Uint=GAS_CALL_STIPEND) -> MessageCallGas:
call_stipend = (Uint(0) if (value == 0) else call_stipend)
if (gas_left < (extra_gas + memory_cost)):
return MessageCallGas((gas + extra_gas)... |
class OptionPlotoptionsTimelineMarkerStatesSelect(Options):
def enabled(self):
return self._config_get(True)
def enabled(self, flag: bool):
self._config(flag, js_type=False)
def fillColor(self):
return self._config_get('#cccccc')
def fillColor(self, text: str):
self._conf... |
class OptionPlotoptionsWindbarbSonificationDefaultinstrumentoptionsMappingFrequency(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, ... |
def get_sensors():
import sensors
found_sensors = list()
def get_subfeature_value(feature, subfeature_type):
subfeature = chip.get_subfeature(feature, subfeature_type)
if subfeature:
return chip.get_value(subfeature.number)
for chip in sensors.get_detected_chips():
fo... |
class LoggingKafkaAdditional(ModelNormal):
allowed_values = {('compression_codec',): {'None': None, 'GZIP': 'gzip', 'SNAPPY': 'snappy', 'LZ4': 'lz4', 'NULL': 'null'}, ('required_acks',): {'one': 1, 'none': 0, 'all': (- 1)}, ('auth_method',): {'PLAIN': 'plain', 'SCRAM-SHA-256': 'scram-sha-256', 'SCRAM-SHA-512': 'scr... |
def get_arch_info():
info = idaapi.get_inf_structure()
proc = info.procName.lower()
bits = get_inf_structure_bitness(info)
instruction_set = None
instruction_mode = None
if (proc == 'metapc'):
instruction_set = CS_ARCH_X86
if (bits == 16):
instruction_mode = CS_MODE_1... |
def test_allow_deleted_event_for_admin(db, app):
obj = EventFactoryBasic(deleted_at=datetime.now())
db.session.commit()
with app.test_request_context('?get_trashed=true'):
event = safe_query(Event, 'id', obj.id, 'id')
assert (event.id == obj.id)
assert (event == obj) |
def test_mixed_expressions(mfunctions):
(f, one, two) = mfunctions
f.sub(0).assign(one.sub(0))
assert evaluate(f.dat.data, (1, 0))
f.assign(0)
f.sub(1).assign(one.sub(1))
assert evaluate(f.dat.data, (0, 1))
f.assign(0)
two.sub(0).assign(one.sub(0))
assert evaluate(two.dat.data, (1, 2... |
class TestOFPInstructionWriteMetadata(unittest.TestCase):
type_ = ofproto.OFPIT_WRITE_METADATA
len_ = ofproto.OFP_INSTRUCTION_WRITE_METADATA_SIZE
metadata =
metadata_mask =
fmt = ofproto.OFP_INSTRUCTION_WRITE_METADATA_PACK_STR
def test_init(self):
c = OFPInstructionWriteMetadata(self.m... |
def score_models(models, loader):
for model in models:
name = model.named_steps['classifier'].__class__.__name__
scores = {'model': str(model), 'name': name, 'accuracy': [], 'precision': [], 'recall': [], 'f1': [], 'time': []}
for (X_train, X_test, y_train, y_test) in loader:
sta... |
class AndOp(Node):
def forward(self, *args, **kwargs):
if ((type(args[0]) is tuple) and (len(args) == 1)):
args = args[0]
if any([(a == False) for a in args]):
return False
elif any([(a is None) for a in args]):
return None
else:
return... |
def test_selectors(additionals, utils):
for sel in additionals.ALL_SELECTORS:
with open(utils.get_info_path('selector', sel)) as f:
info = yaml.safe_load(f)
assert ('desc' in info)
assert ('args' in info)
assert isinstance(info['args'], list)
for arg in info['args... |
.parametrize('dens_fn, json_fn, ref_dpm', (('orca_ch4_sto3g_rhf_cis.densities', 'orca_ch4_sto3g_rhf_cis.json', (0.00613, 0.00867, (- 0.0))), ('orca_ch4_sto3g_uhf_cis.densities', 'orca_ch4_sto3g_uhf_cis.json', (0.0, 0.0, 0.0))))
def test_orca_es_densities(dens_fn, json_fn, ref_dpm):
dens_dict = parse_orca_densities(... |
class LFSR(Module):
def __init__(self, n_out, n_state, taps):
self.o = Signal(n_out)
state = Signal(n_state)
curval = [state[i] for i in range(n_state)]
curval += ([0] * (n_out - n_state))
for i in range(n_out):
nv = (~ reduce(xor, [curval[tap] for tap in taps]))
... |
class RedButton(DefaultObject):
desc_closed_lid = 'This is a large red button, inviting yet evil-looking. A closed glass lid protects it.'
desc_open_lid = 'This is a large red button, inviting yet evil-looking. Its glass cover is open and the button exposed.'
auto_close_msg = "The button's glass lid silentl... |
def start_command():
parser = argparse.ArgumentParser(description='EmbedChain SlackBot command line interface')
parser.add_argument('--host', default='0.0.0.0', help='Host IP to bind')
parser.add_argument('--port', default=5000, type=int, help='Port to bind')
args = parser.parse_args()
slack_bot = S... |
def get_latest_submission_ids_for_fiscal_year(fiscal_year: int):
cte = With(SubmissionAttributes.objects.filter(submission_window__submission_reveal_date__lte=now(), reporting_fiscal_year=fiscal_year).values('toptier_code').annotate(latest_fiscal_period=Max('reporting_fiscal_period')))
submission_ids = list(cte... |
class TestChoiceField(FieldValues):
valid_inputs = {'poor': 'poor', 'medium': 'medium', 'good': 'good'}
invalid_inputs = {'amazing': ['"amazing" is not a valid choice.']}
outputs = {'good': 'good', '': '', 'amazing': 'amazing'}
field = serializers.ChoiceField(choices=[('poor', 'Poor quality'), ('medium'... |
def upload_apk_to_virustotal(virustotal_apikey, packageName, apkName, hash, versionCode, **kwargs):
import requests
logging.getLogger('urllib3').setLevel(logging.WARNING)
logging.getLogger('requests').setLevel(logging.WARNING)
outputfilename = os.path.join('virustotal', (((((packageName + '_') + str(ver... |
class VideoPoll(AbstractCrudObject):
def __init__(self, fbid=None, parent_id=None, api=None):
self._isVideoPoll = True
super(VideoPoll, self).__init__(fbid, parent_id, api)
class Field(AbstractObject.Field):
close_after_voting = 'close_after_voting'
default_open = 'default_open'
... |
def default_requires():
setup_spec.extras['default'] = ['tokenizers>=0.14', 'accelerate>=0.20.3', 'protobuf==3.20.3', 'zhipuai', 'dashscope', 'chardet']
setup_spec.extras['default'] += setup_spec.extras['framework']
setup_spec.extras['default'] += setup_spec.extras['knowledge']
setup_spec.extras['defaul... |
('cuda.perm021fc_crc_bias.gen_function')
def gen_function(func_attrs, exec_cond_template, dim_info_dict):
problem_args = bmm_common.PROBLEM_ARGS_TEMPLATE.render(mm_info=_get_problem_info(alpha_value=func_attrs.get('alpha', 1)))
input_ndims = len(func_attrs['input_accessors'][0].original_shapes)
weight_ndims... |
class TestUtils(IsolatedAsyncioTestCase):
def setUp(self) -> None:
self.instance_id = 'test_instance_123'
self.server_domain = 'study123.pci.facebook.com'
self.server_key_ref_env_var_name = SERVER_PRIVATE_KEY_REF_ENV_VAR
self.server_key_region_env_var_name = SERVER_PRIVATE_KEY_REGION... |
def _compile_context_struct(configs, lib_name):
if (not configs):
return ('void', [])
ctxt_name = f'{lib_name}_Context'
ctxt_def = [f'typedef struct {ctxt_name} {{ ', f'']
seen = set()
for c in sorted(configs, key=(lambda x: x.name())):
name = c.name()
if (name in seen):
... |
class SpeedValue(object):
def __eq__(self, other):
return (self.to_native_units() == other.to_native_units())
def __ne__(self, other):
return (not self.__eq__(other))
def __lt__(self, other):
return (self.to_native_units() < other.to_native_units())
def __le__(self, other):
... |
('/get-auth', methods=['POST'])
def get_auth_cookie():
req = request.get_json()
if (req['pass'] == '1234'):
res = make_response(jsonify({'auth': str(auth)}))
res.set_cookie('auth', str(auth))
else:
res = make_response(jsonify({'erro': 'nao autorizado'}), 401)
res.set_cookie('... |
class HFConfigKeys():
def conv_multi_query(config: FalconConfig) -> bool:
return (config.layer.attention.n_query_heads != config.layer.attention.n_key_value_heads)
def conv_n_attention_query_heads(config: FalconConfig) -> int:
return config.layer.attention.n_query_heads
def conv_n_attention_... |
def test_get_latest_comparisons(backend_db, comparison_db):
before = time()
(fw_one, fw_two, _, _) = _add_comparison(comparison_db, backend_db)
result = comparison_db.page_comparison_results(limit=10)
for (comparison_id, hid, submission_date) in result:
assert (fw_one.uid in hid)
assert ... |
def extractAlicrowCom(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 tagmap:... |
def main():
if (not is_in_rootdir()):
testlog.error('Error: Please run me from the root dir of pyelftools!')
return 1
argparser = argparse.ArgumentParser(usage='usage: %(prog)s [options] [file] [file] ...', prog='run_dwarfdump_tests.py')
argparser.add_argument('files', nargs='*', help='files... |
class Strategy(Model):
def __init__(self, **kwargs: Any) -> None:
self._search_query = kwargs.pop('search_query', DEFAULT_SEARCH_QUERY)
location = kwargs.pop('location', DEFAULT_LOCATION)
self._agent_location = Location(latitude=location['latitude'], longitude=location['longitude'])
... |
def extractSupermeganetCom(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 ta... |
def clean(path):
n_cleaned = 0
for name in MOD_NAMES:
name = name.replace('.', '/')
for ext in ['so', 'html', 'cpp', 'c']:
file_path = (path / f'{name}.{ext}')
if file_path.exists():
file_path.unlink()
n_cleaned += 1
print(f'Cleaned {n_... |
class AvailabilityCmd():
_args(source=(None, dict(type=str, help='File or directory for describing a dataset or source of data with GRIB data.')), stdout=dict(action='store_true', help='Output to stdout (no file).'), yaml=dict(action='store_true', help='Output yaml format.'), keys=('--keys', dict(type=str, help=f"K... |
class DeviceForm(ModelForm):
required_css_class = 'required'
class Meta():
model = Device
fields = ['name', 'description', 'field_1', 'field_2', 'field_3', 'field_4', 'field_5', 'field_6', 'field_7', 'field_8', 'field_9', 'field_10', 'enable']
def __init__(self, *args, **kwargs):
sup... |
class GUID(ct.Structure):
_fields_ = [('Data1', DWORD), ('Data2', WORD), ('Data3', WORD), ('Data4', (BYTE * 8))]
def __init__(self, name=None):
if (name is not None):
_CLSIDFromString(str(name), ct.byref(self))
def __repr__(self):
return ('GUID("%s")' % str(self))
def __str__... |
def extractNeverlandtranslationsWordpressCom(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... |
def test_back_edges():
DG = ClassifiedGraph()
DG.add_edge(BasicEdge(v[0], v[1]))
DG.add_edge(BasicEdge(v[0], v[3]))
DG.add_edge(BasicEdge(v[1], v[2]))
DG.add_edge(BasicEdge(v[2], v[0]))
DG.add_edge(BasicEdge(v[1], v[3]))
DG.add_edge(BasicEdge(v[3], v[4]))
DG.add_edge(BasicEdge(v[2], v[4]... |
def delete_internal(sess, ids):
if ids:
print(('Doint delete. %s rows requiring update.' % (len(ids),)))
else:
print('No rows needing deletion.')
return
ctbl = version_table(db.WebPages.__table__)
chunk_size = 5000
for chunk_idx in range(0, len(ids), chunk_size):
chun... |
def create_event_sub_topics():
event_sub_topic = {'Film, Media & Entertainment': ['Comedy', 'Gaming', 'Anime'], 'Community & Culture': ['City/Town', 'Other', 'LGBT'], 'Home & Lifestyle': ['Dating', 'Home & Garden'], 'Sports & Fitness': ['Volleyball', 'Other'], 'Health & Wellness': ['Yoga', 'Medical'], 'Food & Drink... |
class AdminUserCreationForm(forms.ModelForm):
class Meta():
model = User
fields = ('username',)
field_classes = {'username': UsernameField}
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
if (self._meta.model.USERNAME_FIELD in self.fields):
... |
class Preferences(GObject.GObject):
__gsignals__ = {'preferences-changed': ((GObject.SignalFlags.RUN_FIRST | GObject.SignalFlags.NO_RECURSE), None, ()), 'image-preferences-changed': ((GObject.SignalFlags.RUN_FIRST | GObject.SignalFlags.NO_RECURSE), None, ())}
def __init__(self, config):
GObject.GObject.... |
def filter_casb_user_activity_data(json):
option_list = ['application', 'casb_name', 'category', 'control_options', 'description', 'match', 'match_strategy', 'name', 'type', 'uuid']
json = remove_invalid_fields(json)
dictionary = {}
for attribute in option_list:
if ((attribute in json) and (json... |
def SGEMM(M: size, N: size, K: size, A: f32[(M, K)], B: f32[(K, N)], C: f32[(M, N)]):
assert (M >= 1)
assert (N >= 1)
assert (K >= 1)
assert (stride(A, 1) == 1)
assert (stride(B, 1) == 1)
assert (stride(C, 1) == 1)
for k in seq(0, K):
for i in seq(0, M):
for j in seq(0, N... |
def compute_embeddings(paths: list, embedding_name: str, device: str='cpu', chunk_size: int=20):
(model, embedding_dim, transforms, metadata) = load_pretrained_model(embedding_name=embedding_name)
model.to(device)
for path in tqdm(paths):
inp = path['images']
path['embeddings'] = np.zeros((i... |
def _run_command(args: Any) -> Tuple[(str, str)]:
with Popen(args=args, stdout=PIPE, stderr=PIPE) as proc:
log.info(f"Running command: {' '.join(args)}")
(out, err) = proc.communicate()
out_str = (out.decode().strip() if (out is not None) else '')
err_str = (err.decode().strip() if (... |
class LiteSATAALIGNInserter(Module):
def __init__(self, description):
self.sink = sink = stream.Endpoint(description)
self.source = source = stream.Endpoint(description)
cnt = Signal(8)
send = Signal()
self.sync += If((source.valid & source.ready), cnt.eq((cnt + 1)))
... |
class CssInputNoBorder(CssStyle.Style):
_attrs = {'border': 'none', 'text-align': 'center', 'cursor': 'text', 'margin': 0}
_focus = {'outline': 0}
def customize(self):
self.attrs.css({'color': 'inherit', 'font-family': self.page.body.style.globals.font.family, 'line-height': ('%spx' % Defaults_html.... |
def get_spec(distgit_config):
spec_dir = distgit_config['specs']
specfiles = glob.glob(os.path.join(spec_dir, '*.spec'))
if (len(specfiles) != 1):
abs_spec_dir = os.path.join(os.getcwd(), spec_dir)
message = 'Exactly one spec file expected in {0} directory, {1} found'.format(abs_spec_dir, le... |
.parametrize('abi_type,should_match', (('bool[]', True), ('uint[]', True), ('uint[][]', True), ('uint[5][]', True), ('uint[][5]', True), ('int[]', True), ('string[]', True), ('address[]', True), ('bytes[]', True), ('string', False), ('bytes', False), ('uint[', False), ('uint]', False)))
def test_is_array_type(abi_type,... |
class OptionPlotoptionsHistogramTooltipDatetimelabelformats(Options):
def day(self):
return self._config_get('%A, %e %b %Y')
def day(self, text: str):
self._config(text, js_type=False)
def hour(self):
return self._config_get('%A, %e %b, %H:%M')
def hour(self, text: str):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.