code stringlengths 281 23.7M |
|---|
def gazeSampleCallback(sample=POINTER(ELGazeSample)):
if (g_api is None):
return
g_api.sampleLock.acquire()
scaleX = (g_api.dispsize[0] / g_api.rawResolution[0])
scaleY = (g_api.dispsize[1] / g_api.rawResolution[1])
g_api.lastSample = ELGazeSample()
g_api.lastSample.timestampMicroSec = s... |
class ssh_config_loading():
_system_path = join(support, 'ssh_config', 'system.conf')
_user_path = join(support, 'ssh_config', 'user.conf')
_runtime_path = join(support, 'ssh_config', 'runtime.conf')
_empty_kwargs = dict(system_ssh_path='nope/nope/nope', user_ssh_path='nope/noway/nuhuh')
def default... |
def test():
import spacy.tokens
import spacy.lang.en
assert isinstance(nlp, spacy.lang.en.English), 'El objeto nlp deberia ser un instance de la clase de ingles.'
assert isinstance(doc, spacy.tokens.Doc), 'Procesaste el texto con el objeto nlp para crear un doc?'
assert ('print(doc.text)' in __solut... |
class RelationshipsForTlsPrivateKey(ModelComposed):
allowed_values = {}
validations = {}
_property
def additional_properties_type():
lazy_import()
return (bool, date, datetime, dict, float, int, list, str, none_type)
_nullable = False
_property
def openapi_types():
la... |
def test_metadata(hound, cve):
meta = hound.get_rule_metadata(cve)
assert ('files' in meta), 'no "Files:" tag in the rule'
assert ('fix' in meta), 'no "Fix:" tag in the rule'
assert ('fixes' in meta), 'no "Fixes:" or "Detect-To:" tag in the rule'
rule = hound.get_rule(cve)
if rule.endswith('.gre... |
class OptionPlotoptionsScatterClusterMarker(Options):
def enabled(self):
return self._config_get(None)
def enabled(self, flag: bool):
self._config(flag, js_type=False)
def fillColor(self):
return self._config_get(None)
def fillColor(self, text: str):
self._config(text, js... |
class ConstantVelocityGaussian2D():
def __init__(self, sigma=(1.0 / 8.0), b=[1.0, 0.0], xc=0.25, yc=0.5):
self.sigma = sigma
self.xc = xc
self.yc = yc
self.b = b
def uOfXT(self, x, t):
centerX = ((self.xc + (self.b[0] * t)) % 1.0)
centerY = ((self.yc + (self.b[1] ... |
def write_mode_tags(segmk, ps, site):
for param in ['WRITE_MODE_A', 'WRITE_MODE_B']:
set_val = verilog.unquote(ps[param])
segmk.add_site_tag(site, ('%s_READ_FIRST' % param), (set_val == 'READ_FIRST'))
segmk.add_site_tag(site, ('%s_NO_CHANGE' % param), (set_val == 'NO_CHANGE')) |
def extractNightowlwalkerWordpressCom(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 _handle_binary(p: Pattern, s: str) -> PatternRule:
op = ast.Attribute(value=ast.Name('operator', ctx=ast.Load()), attr=s, ctx=ast.Load())
return PatternRule(assign(value=binop(op=p)), (lambda a: ast.Assign(a.targets, _make_bmg_call('handle_function', [op, ast.List(elts=[a.value.left, a.value.right], ctx=ast... |
class sFlowV5FlowRecord(object):
_PACK_STR = '!II'
MIN_LEN = struct.calcsize(_PACK_STR)
def __init__(self, enterprise, flow_data_format, flow_data_length, flow_data):
super(sFlowV5FlowRecord, self).__init__()
self.enterprise = enterprise
self.flow_data_format = flow_data_format
... |
class MetaData():
def __init__(self):
self.tables: Dict[(str, MetaTable)] = {}
def __getitem__(self, key):
return self.tables[key]
def __getattr__(self, name):
return self.tables[name]
def where(self, *args, **kwargs) -> MetaDataSet:
return MetaDataSet(*args, **kwargs)
... |
def check_not_null(tensor: Tensor, tensor_idx: Optional[int]=None, skip_if_lower_bound_is_zero: bool=False) -> str:
name = tensor._attrs['name']
if (tensor_idx is None):
check = name
else:
check = f'params_[{tensor_idx}].ptr'
shape = ['1']
lower_bound_is_zero = False
for dim in t... |
def extractArvelhurstWordpressCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
if ('WATTT' in item['tags']):
return buildReleaseMessageWithType(item, 'WATTT', vol, chp, frag=fra... |
def mock_get_info(monkeypatch, set_api_key):
responses.add(responses.GET, f'{Env.current.web_api_endpoint}/tidy3d/tasks/{TASK_ID}/detail', json={'data': {'taskId': TASK_ID, 'taskName': TASK_NAME, 'createdAt': CREATED_AT, 'realFlexUnit': FLEX_UNIT, 'estFlexUnit': EST_FLEX_UNIT, 'taskType': TaskType.FDTD.name, 'metad... |
class ETHPeer(BaseChainPeer):
max_headers_fetch = MAX_HEADERS_FETCH
supported_sub_protocols: Tuple[(Type[BaseETHProtocol], ...)] = (ETHProtocolV63, ETHProtocolV64, ETHProtocolV65)
sub_proto: BaseETHProtocol = None
eth_api: AnyETHAPI
wit_api: WitnessAPI
def get_behaviors(self) -> Tuple[(BehaviorA... |
(name='api.node.vm.tasks.harvest_vm_cb', base=MgmtCallbackTask, bind=True)
()
def harvest_vm_cb(result, task_id, node_uuid=None):
node = Node.objects.get(uuid=node_uuid)
dc = Dc.objects.get_by_id(dc_id_from_task_id(task_id))
err = result.pop('stderr', None)
vms = []
vms_err = []
jsons = []
i... |
class QueryRewrite(BaseChat):
chat_scene: str = ChatScene.QueryRewrite.value()
def __init__(self, chat_param: Dict):
chat_param['chat_mode'] = ChatScene.QueryRewrite
super().__init__(chat_param=chat_param)
self.nums = chat_param['select_param']
self.current_user_input = chat_para... |
def transaction_search_1():
dsws = baker.make('submissions.DABSSubmissionWindowSchedule', submission_reveal_date='2021-04-09', submission_fiscal_year=2021, submission_fiscal_month=7, submission_fiscal_quarter=3, is_quarter=False, period_start_date='2021-03-01', period_end_date='2021-04-01')
baker.make('submissi... |
(CONSENT_REQUEST_PREFERENCES_WITH_ID, status_code=HTTP_200_OK, response_model=ConsentPreferences)
def set_consent_preferences(*, consent_request_id: str, db: Session=Depends(get_db), data: ConsentPreferencesWithVerificationCode) -> ConsentPreferences:
(consent_request, provided_identity) = _get_consent_request_and_... |
class OptionSeriesPolygonSonificationTracksMappingPan(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 extractInchoateOeuvre(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
if ('WATTT' in item['tags']):
return buildReleaseMessageWithType(item, 'WATTT', vol, chp, frag=frag, postf... |
class LESProxyPeer(BaseProxyPeer):
def __init__(self, session: SessionAPI, event_bus: EndpointAPI, les_api: ProxyLESAPI):
super().__init__(session, event_bus)
self.les_api = les_api
def from_session(cls, session: SessionAPI, event_bus: EndpointAPI, broadcast_config: BroadcastConfig) -> 'LESProxy... |
def _get_element_type(element_property: typing.Dict[(str, str)]) -> Type:
element_type = ([e_property['type'] for e_property in element_property['anyOf']] if element_property.get('anyOf') else element_property['type'])
element_format = (element_property['format'] if ('format' in element_property) else None)
... |
class GlobalGenerator(nn.Module):
def __init__(self, input_nc, output_nc, ngf=64, bottleneck='2d', n_downsampling=3, n_blocks=9, max_mult=16, norm_layer=nn.BatchNorm2d, padding_type='reflect', vaeLike=False):
assert (n_blocks >= 0)
super(GlobalGenerator, self).__init__()
self.vaeLike = vaeLi... |
def acSubmit(board, dom):
idsAndValues = dom.getValues(FIELDS)
if (not idsAndValues['Name'].strip()):
dom.alert('The name field can not be empty!')
else:
board.state = State.DISPLAY
contacts.append(idsAndValues)
displayContact(None, dom)
displayContacts(dom)
u... |
def set_brightness(brightness):
global _brightness
setup()
if ((not isinstance(brightness, int)) and (not isinstance(brightness, float))):
raise ValueError('Brightness should be an int or float')
if ((brightness < 0.0) or (brightness > 1.0)):
raise ValueError('Brightness should be betwee... |
def test_index_file_path_redirected(finder_static_files, finder_server):
directory_path = (finder_static_files.index_path.rpartition('/')[0] + '/')
index_url = (settings.STATIC_URL + finder_static_files.index_path)
response = finder_server.get(index_url, allow_redirects=False)
location = get_url_path(re... |
class MetadataIndex(McapRecord):
offset: int
length: int
name: str
def write(self, stream: RecordBuilder) -> None:
stream.start_record(Opcode.METADATA_INDEX)
stream.write8(self.offset)
stream.write8(self.length)
stream.write_prefixed_string(self.name)
stream.finis... |
_bad_request
def all_england(request):
if (request.method == 'POST'):
return _handle_bookmark_post(request, OrgBookmark)
form = _build_bookmark_form(OrgBookmark, {})
tag_filter = _get_measure_tag_filter(request.GET)
entity_type = request.GET.get('entity_type', 'CCG')
date = _specified_or_las... |
def _get_members(field_prefix: str, definitions: Dict, skip: Set[str]) -> Dict[(str, Member)]:
result = {}
required = definitions.get('required', [])
for (prop, prop_def) in definitions.get('properties', {}).items():
if ('$ref' in prop_def):
continue
full_name = (field_prefix + p... |
def sanity_test():
from argparse import ArgumentParser
import traceback
ap = ArgumentParser()
ap.add_argument('item', metavar='FILE|DIR')
ap.add_argument('--no-tb', action='store_true', default=False, help='Do not show debug-style backtrace')
options = ap.parse_args()
mh = Message_Handler('d... |
class OptionPlotoptionsBellcurveSonificationPointgrouping(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):
sel... |
class OptionPlotoptionsWindbarbSonificationTracksMappingPitch(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('y')
def mapTo(self, text: str):
sel... |
def render_create_module(copr, form, profiles=2):
components_rpms = []
built_packages = []
for build in filter(None, [p.last_build(successful=True) for p in copr.packages]):
components_rpms.append((build.package.name, build))
for package in build.built_packages.split('\n'):
built... |
def random_proxy(func):
(func)
def wrapper(*args, **kwargs):
for request in func(*args, **kwargs):
proxy_df = get_checked_proxy()
if (proxy_df is not None):
request._meta['proxy'] = proxy_df.at[(random.choice(proxy_df.index), 'url')]
(yield request)
... |
def downgrade():
op.execute('alter type connectiontype rename to connectiontype_old')
op.execute("create type connectiontype as enum('postgres', 'mongodb', 'mysql', ' 'snowflake', 'redshift', 'mssql', 'mariadb', 'bigquery', 'saas', 'manual', 'email', 'manual_webhook', 'timescale')")
op.execute('alter table ... |
class Migration(migrations.Migration):
dependencies = [('admin_interface', '0010_add_localization')]
operations = [migrations.RenameField(model_name='theme', old_name='env', new_name='env_name'), migrations.AlterField(model_name='theme', name='env_name', field=models.CharField(blank=True, max_length=50, verbose... |
def run_sample(target_fname, antitarget_fname, ref_probes, diploid_parx_genome):
tgt_raw = cnvlib.read(target_fname)
anti_raw = cnvlib.read(antitarget_fname)
cnr = commands.do_fix(tgt_raw, anti_raw, ref_probes, diploid_parx_genome=diploid_parx_genome)
cns = commands.do_segmentation(cnr, method='cbs', di... |
class MegaFiles():
def __init__(self):
self.files_collection = MegaDB().db['files']
async def insert_new_files(self, file_name: str, msg_id: int, chat_id: int, url: str, file_type: str):
self.files_collection.insert_one({'file_name': file_name, 'msg_id': msg_id, 'chat_id': chat_id, 'url': url, '... |
def test_basic_create_transaction(chain, basic_transaction):
transaction = chain.create_transaction(nonce=basic_transaction.nonce, gas_price=basic_transaction.gas_price, gas=basic_transaction.gas, to=basic_transaction.to, value=basic_transaction.value, data=basic_transaction.data, v=basic_transaction.v, r=basic_tra... |
class MacOSVPNApplication(DesktopVPNApplication):
def __init__(self, app_path, device, config):
super().__init__(app_path, device, config)
self._dns_servers_before_connect = device['dns_tool'].known_servers()
def dns_server_ips(self):
info = self._vpn_info()
if ((info is not None... |
def test_cache_does_not_close_session_before_a_call_when_multithreading():
session_cache_default = request._session_cache
timeout_default = request.DEFAULT_TIMEOUT
request._session_cache = SimpleCache(1)
_timeout_for_testing = 0.01
request.DEFAULT_TIMEOUT = _timeout_for_testing
with ThreadPoolEx... |
class OptionPlotoptionsColumnpyramidSonificationContexttracksMappingLowpass(Options):
def frequency(self) -> 'OptionPlotoptionsColumnpyramidSonificationContexttracksMappingLowpassFrequency':
return self._config_sub_data('frequency', OptionPlotoptionsColumnpyramidSonificationContexttracksMappingLowpassFreque... |
def get_arguments_for_inspection(inspection, kwargs):
names_to_args = {transform_name(arg_obj.name, to_char='_'): arg_obj.arg for (arg, arg_obj) in inspection.arguments.items()}
names_to_args.update({transform_name(extra_name, to_char='_'): arg_obj.arg for (arg, arg_obj) in inspection.arguments.items() for extr... |
class OptionPlotoptionsSplineSonificationTracksMappingHighpass(Options):
def frequency(self) -> 'OptionPlotoptionsSplineSonificationTracksMappingHighpassFrequency':
return self._config_sub_data('frequency', OptionPlotoptionsSplineSonificationTracksMappingHighpassFrequency)
def resonance(self) -> 'Option... |
class ArtistInfoPane(GObject.GObject):
__gsignals__ = {'selected': (GObject.SIGNAL_RUN_LAST, None, (GObject.TYPE_STRING, GObject.TYPE_STRING))}
paned_pos = GObject.property(type=str)
min_paned_pos = 100
def __init__(self, button_box, stack, info_paned, source):
GObject.GObject.__init__(self)
... |
.parametrize('wlogs, expected_output', [({}, {'wlogtypes': {}, 'wlogrecords': {}}), ({'X_UTME': ('CONT', None)}, {'wlogtypes': {'X_UTME': 'CONT'}, 'wlogrecords': {'X_UTME': None}}), ({'ZONELOG': ('DISC', {'0': 'ZONE00'})}, {'wlogtypes': {'ZONELOG': 'DISC'}, 'wlogrecords': {'ZONELOG': {'0': 'ZONE00'}}})])
def test_impor... |
def extractGaochaoTranslations(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol or frag)) or ('preview' in item['title'].lower())):
return None
if ('Otherworldly Evil Monarch' in item['tags']):
return buildReleaseMessageWithType(item, 'O... |
def _getPatternTemplate(pattern, key=None):
if (key is None):
key = pattern
if ('%' not in pattern):
key = pattern.upper()
template = DD_patternCache.get(key)
if (not template):
if ('EPOCH' in key):
if RE_EPOCH_PATTERN.search(pattern):
template... |
def init_state_resets(ns, state_inputs, trigger, scheduler, tp_scheduler, node):
if (len(state_inputs) > 0):
channels = []
for s in state_inputs:
d = s['done'].pipe(ops.scan((lambda acc, x: (x if x else acc)), False))
c = s['msg'].pipe(convert(s['space'], s['processor'], s['n... |
def repr_message(msg):
from ..api.chats import Group
text = str((msg.text or '')).replace('\n', ' ')
text += (' ' if text else '')
if (msg.sender == msg.bot.self):
ret = ' {self.receiver.name}'
elif (isinstance(msg.chat, Group) and (msg.member != msg.receiver)):
ret = '{self.sender.... |
class TD3BCTest(absltest.TestCase):
def test_td3(self):
environment = fakes.ContinuousEnvironment(action_dim=2, observation_dim=3, episode_length=10, bounded=True)
spec = specs.make_environment_spec(environment)
agent_networks = td3.make_networks(spec, (10,), (10,))
dataset = fakes.t... |
_trigger_tests.post(schema=bodhi.server.schemas.TriggerTestsSchema(), validators=(colander_body_validator, validate_update_id, validate_qa_acls), permission='edit', renderer='json', error_handler=bodhi.server.services.errors.json_handler)
def trigger_tests(request):
update = request.validated['update']
if (upda... |
class BaseTestExecTimeout(TestCase):
EXEC_TIMEOUT_CLASS = BaseExecTimeout
def setUpClass(cls):
if (cls is BaseTestExecTimeout):
raise unittest.SkipTest("Skip BaseTest tests, it's a base class")
def test_cancel_by_timeout(self):
slow_function_time = 0.4
timeout = 0.1
... |
class EventLoop():
active = True
queue = Queue()
freeable = []
callbackExecutor = EventExecutorThread()
callbacks = WeakValueDictionary()
threads = []
outbound = []
requests = {}
responses = {}
def __init__(self):
connection.start()
self.callbackExecutor.start()
... |
def output(outputable):
if ((format.get_selected() == 'html') or (format.get_selected() == 'htmlembedded')):
outputable.output_html()
elif (format.get_selected() == 'json'):
outputable.output_json()
elif (format.get_selected() == 'text'):
outputable.output_text()
else:
ou... |
class _ComputeDisksRepository(repository_mixins.AggregatedListQueryMixin, repository_mixins.ListQueryMixin, _base_repository.GCPRepository):
def __init__(self, **kwargs):
super(_ComputeDisksRepository, self).__init__(component='disks', **kwargs)
def list(self, resource, zone, **kwargs):
kwargs['... |
.asyncio
.workspace_host
class TestGetClient():
async def test_unauthorized(self, unauthorized_api_assertions: HTTPXResponseAssertion, test_client_api: test_data: TestData):
client = test_data['clients']['default_tenant']
response = (await test_client_api.get(f'/clients/{client.id}'))
unaut... |
def test_oef_serialization_query():
query = Query([Constraint('foo', ConstraintType('==', 'bar'))], model=None)
msg = OefSearchMessage(performative=OefSearchMessage.Performative.SEARCH_SERVICES, dialogue_reference=(str(1), ''), query=query)
msg_bytes = OefSearchMessage.serializer.encode(msg)
assert (len... |
_os(*metadata.platforms)
def main():
common.log('Clearing Windows Event Logs')
common.log('WARNING - About to clear logs from Windows Event Viewer', log_type='!')
time.sleep(3)
wevtutil = 'wevtutil.exe'
for log in ['security', 'application', 'system']:
common.execute([wevtutil, 'cl', log]) |
.parametrize('_input_vars', [['var1', 'var2', 'var2', 'var3'], [0, 1, 1, 2]])
def test_raises_error_when_duplicated_var_names(_input_vars):
with pytest.raises(ValueError) as record:
assert _check_variables_input_value(_input_vars)
msg = 'The list entered in `variables` contains duplicated variable names... |
class OptionPlotoptionsPackedbubbleStatesSelectHalo(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._con... |
def pre_process_repo_url(chroot, repo_url):
parsed_url = urlparse(repo_url)
query = parse_qs(parsed_url.query)
if (parsed_url.scheme == 'copr'):
user = parsed_url.netloc
prj = parsed_url.path.split('/')[1]
repo_url = ('/'.join([flask.current_app.config['BACKEND_BASE_URL'], 'results',... |
def run_migrations_online():
engine = create_engine(get_url())
connection = engine.connect()
context.configure(connection=connection, target_metadata=target_metadata, version_table='alembic_ziggurat_foundations_version', transaction_per_migration=True)
try:
with context.begin_transaction():
... |
class OptunaSweeper(Sweeper):
def __init__(self, sampler: SamplerConfig, direction: Any, storage: Optional[Any], study_name: Optional[str], n_trials: int, n_jobs: int, max_failure_rate: float, search_space: Optional[DictConfig], custom_search_space: Optional[str], params: Optional[DictConfig]) -> None:
from... |
class OptionPlotoptionsBarLabelStyle(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, j... |
class TestPrecisionTopK(BaseTopkRecsysTest):
name: ClassVar = 'Precision (top-k)'
header: str = 'Precision'
def get_metric(self, k, min_rel_score, no_feedback_users) -> BaseTopKRecsysType:
return PrecisionTopKMetric(k=k, min_rel_score=min_rel_score, no_feedback_users=no_feedback_users) |
def convert_to_jstree_node(node: FileTreeNode):
if node.virtual:
jstree_node = _get_directory_jstree_node(node)
elif node.not_analyzed:
jstree_node = _get_not_analyzed_jstree_node(node)
else:
jstree_node = _get_file_jstree_node(node)
if node.has_children:
jstree_node['chi... |
def usage_doc_files() -> List[str]:
usage_docs_dir: str = os.path.join(os.path.dirname(__file__), '../../docs/fields/usage')
usage_docs_path: pathlib.PosixPath = pathlib.Path(usage_docs_dir)
if usage_docs_path.is_dir():
return [x.name for x in usage_docs_path.glob('*.asciidoc') if x.is_file()]
r... |
(autouse=True, scope='function')
def privacy_request_complete_email_notification_disabled(db):
original_value = CONFIG.notifications.send_request_completion_notification
CONFIG.notifications.send_request_completion_notification = False
ApplicationConfig.update_config_set(db, CONFIG)
db.commit()
(yie... |
class bsn_vlan_counter_stats_reply(bsn_stats_reply):
version = 5
type = 19
stats_type = 65535
experimenter = 6035143
subtype = 9
def __init__(self, xid=None, flags=None, entries=None):
if (xid != None):
self.xid = xid
else:
self.xid = None
if (flag... |
def concatenate_fastq_files(merged_fastq, fastq_files, bufsize=10240, overwrite=False, verbose=True):
if verbose:
print(("Creating merged fastq file '%s'" % merged_fastq))
if (os.path.exists(merged_fastq) and (not overwrite)):
raise OSError(("Target file '%s' already exists, stopping" % merged_f... |
class TaskOutputMetaData():
def __init__(self, output_sequence, output_label, output_type: elmdpenum.TaskOutputMetaDataTypes):
self.output_sequence = output_sequence
self.output_label = output_label
self.output_type = output_type
def to_dict(self):
return {'output_sequence': self... |
class LifeEvent(AbstractCrudObject):
def __init__(self, fbid=None, parent_id=None, api=None):
self._isLifeEvent = True
super(LifeEvent, self).__init__(fbid, parent_id, api)
class Field(AbstractObject.Field):
description = 'description'
end_time = 'end_time'
field_from = '... |
def f2p_word(word, max_word_size=15, cutoff=3):
original_word = word
word = word.lower()
c = dictionary.get(word)
if c:
return [(c, 1.0)]
if (word == ''):
return []
elif (len(word) > max_word_size):
return [(original_word, 1.0)]
results = []
for w in variations(wo... |
_module()
class NaiveVOCODERDataset(NaiveDataset):
processing_pipeline = [dict(type='PickKeys', keys=['path', 'audio', 'pitches', 'sampling_rate'])]
collating_pipeline = [dict(type='ListToDict'), dict(type='PadStack', keys=[('audio', (- 1)), ('pitches', (- 1))])]
def __init__(self, path='dataset', segment_s... |
.integration_saas
.integration_mailchimp_transactional
def test_build_consent_dataset_graph(postgres_example_test_dataset_config_read_access, mysql_example_test_dataset_config, mailchimp_transactional_dataset_config):
dataset_graph: DatasetGraph = build_consent_dataset_graph([postgres_example_test_dataset_config_re... |
class OptionPlotoptionsBoxplotSonificationContexttracksMappingVolume(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 AmdGpuSensor(BaseSensor):
name = 'amdgpu'
desc = _('If CPU isnot AMD, this your eGPU')
def get_value(self, sensor):
if (sensor == 'amdgpu'):
return '{:02.0f}%'.format(self._fetch_gpu())
def _fetch_gpu(self):
result = subprocess.check_output(['cat', '/sys/class/drm/card0... |
class TestMultiHeadAttentionConverter(AITTestCase):
def test_multihead_attention_cross_attenytion(self):
class TestModule(torch.nn.Module):
def __init__(self, dim, nheads):
super().__init__()
self.attn = torch.nn.modules.activation.MultiheadAttention(embed_dim=dim... |
class BaseClassConditionAwareRefinement():
def __init__(self, asforest: AbstractSyntaxForest, options: RestructuringOptions):
self.asforest: AbstractSyntaxForest = asforest
self.condition_handler: ConditionHandler = asforest.condition_handler
self.options: RestructuringOptions = options
... |
class MultiLinear(Chain):
def __init__(self, input_dim: int, output_dim: int, inner_dim: int, num_layers: int, device: ((Device | str) | None)=None, dtype: (DType | None)=None) -> None:
layers: list[Module] = []
for i in range((num_layers - 1)):
layers.append(Linear((input_dim if (i == 0... |
class TestEjectCommandCliConfigNotAvailable(AEATestCaseEmpty):
IS_EMPTY = True
def setup_class(cls):
super().setup_class()
cls.add_item('protocol', str(DefaultMessage.protocol_id))
('aea.cli.utils.config.get_or_create_cli_config', return_value={})
def test_error(self, *_mocks):
w... |
def propagate_deletions(db, batch, path):
for i in reversed(range(len(path))):
current_node = deserialize(db_get(db, path[:i]))
print(path[:i], current_node)
assert isinstance(current_node, BranchNode)
if (current_node.values.count(ZERO) == 255):
print('one nonzero; conti... |
def forward(model: Model[(InT, OutT)], Xp: InT, is_train: bool) -> Tuple[(OutT, Callable[([OutT], InT)])]:
Ys = cast(OutT, model.ops.padded2list(Xp))
def backprop(dYs: OutT) -> InT:
dYp = model.ops.list2padded(dYs)
assert isinstance(dYp, Padded)
return dYp
return (Ys, backprop) |
def build_srpm(srcdir, destdir):
cmd = ['rpmbuild', '-bs', '--define', ('_sourcedir ' + srcdir), '--define', ('_rpmdir ' + srcdir), '--define', ('_builddir ' + srcdir), '--define', ('_specdir ' + srcdir), '--define', ('_srcrpmdir ' + destdir)]
specfiles = glob.glob(os.path.join(srcdir, '*.spec'))
if (len(sp... |
class SourceUnit(AstNode):
nodes: List[TopLevelNode]
stage1_context = synthesized()
stage2_context = synthesized()
_cache(None)
def ast_nodes_by_id(self):
return {d.id: d for d in self.descendants() if (d is not None)}
def push_cfgs(self, nodes: ContractDefinition.contract_cfg_unlinked) ... |
class Command(BaseCommand):
help = 'Deterministically generate File B and C DEF code records for the fiscal year and period provided.'
fiscal_year = None
fiscal_period = None
allow_rds = False
vacuum = False
clone_factors = [('I', 0.2, 13), ('F', 0.1, 11), ('L', 0.3, 10), ('M', 0.25, 8), ('N', 0... |
class Manager():
def __init__(self, config_dir=DATA_DIR, htpasswd_file=HTPASSWD_FILE, creds_file=CREDS_FILE):
if (not os.path.exists(config_dir)):
if os.path.exists(LEGACY_CONFIG_DIR):
import shutil
shutil.move(LEGACY_CONFIG_DIR, DATA_DIR)
else:
... |
class AIFlowConsole(Console):
def print_as_json(self, data: Dict):
json_content = json.dumps(data)
self.print(Syntax(json_content, 'json', theme='ansi_dark'), soft_wrap=True)
def print_as_yaml(self, data: Dict):
yaml_content = yaml.dump(data)
self.print(Syntax(yaml_content, 'yaml... |
def _log_calibration(calibration):
values = ' '.join((format((x / 10), '5') for x in VOLT_RANGES))
_log('# VOLTBASE: %s', values)
for (i, name) in enumerate(('GAIN', 'AMPL', 'COMP')):
for chl in range(CHANNELS):
values = ' '.join((format(x, '5') for x in calibration[i][chl]))
... |
class table_feature_prop_table_sync_from(table_feature_prop):
type = 16
def __init__(self, table_ids=None):
if (table_ids != None):
self.table_ids = table_ids
else:
self.table_ids = []
return
def pack(self):
packed = []
packed.append(struct.pac... |
def fortios_firewall(data, fos, check_mode):
fos.do_member_operation('firewall', 'vipgrp64')
if data['firewall_vipgrp64']:
resp = firewall_vipgrp64(data, fos, check_mode)
else:
fos._module.fail_json(msg=('missing task body: %s' % 'firewall_vipgrp64'))
if check_mode:
return resp
... |
def extractNanotranslationsWordpressCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [('PRC', 'PRC', 'translated'), ('Loiterous', 'Loiterous', 'oel')]
for (tagname, name, t... |
def test_default_bytes_serialization():
expected_msg = DefaultMessage(dialogue_reference=('', ''), message_id=1, target=0, performative=DefaultMessage.Performative.BYTES, content=b'hello')
msg_bytes = DefaultMessage.serializer.encode(expected_msg)
actual_msg = DefaultMessage.serializer.decode(msg_bytes)
... |
class CorefClusterer(nn.Module):
def __init__(self, dim: int, dist_emb_size: int, hidden_size: int, n_layers: int, dropout: float, rough_k: int, batch_size: int):
super().__init__()
self.dropout = torch.nn.Dropout(dropout)
self.batch_size = batch_size
self.pairwise = DistancePairwise... |
.parametrize('function, value', (('reflect', Decimal('12.8')), ('reflect', (Decimal(((2 ** 256) - 1)) / 10)), ('reflect', Decimal('-0.1')), ('reflect', Decimal('-12.8')), ('reflect', (Decimal(((2 ** 256) - 1)) / (10 ** 80))), ('reflect', (Decimal(1) / (10 ** 80))), ('reflect_short_u', 0), ('reflect_short_u', Decimal('2... |
def deploy(w3, Factory, from_address, args=None):
args = (args or [])
factory = Factory(w3)
deploy_txn = factory.constructor(*args).transact({'from': from_address})
deploy_receipt = w3.eth.wait_for_transaction_receipt(deploy_txn)
assert (deploy_receipt is not None)
return factory(address=deploy_... |
def test_regression_ignore_format(df_enc_numeric):
random = np.random.RandomState(42)
y = random.normal(0, 0.1, len(df_enc_numeric))
encoder = DecisionTreeEncoder(regression=True, random_state=random, ignore_format=True)
encoder.fit(df_enc_numeric[['var_A', 'var_B']], y)
X = encoder.transform(df_enc... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.