code stringlengths 281 23.7M |
|---|
class OptionPlotoptionsAreasplineMarkerStatesSelect(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._co... |
def select_zero(context):
selection_mode = bpy.context.scene.tool_settings.uv_select_mode
bm = bmesh.from_edit_mesh(bpy.context.active_object.data)
uv_layers = bm.loops.layers.uv.verify()
bpy.ops.uv.select_all(action='DESELECT')
for face in bm.faces:
if face.select:
tris = (len(f... |
_exception
def _delete_oldest(model, define, view_function, view_item, task_id, msg):
vm = define.vm
total = model.objects.filter(vm=vm, disk_id=define.disk_id, define=define, status=model.OK).count()
to_delete = (total - define.retention)
if (to_delete < 1):
return None
oldest = model.objec... |
('model {model_name} fails with message "{msg}"')
def invoke_command_error(context, model_name: str, msg: str):
results = _load_dbt_result_file(context)
model_result = [i for i in results if (model_name in i['unique_id'])][0]
print(model_result)
assert (model_result['status'] == 'error')
assert (mod... |
def play_action(params):
log.debug('== ENTER: PLAY ==')
log.debug('PLAY ACTION PARAMS: {0}', params)
item_id = params.get('item_id')
auto_resume = int(params.get('auto_resume', '-1'))
log.debug('AUTO_RESUME: {0}', auto_resume)
force_transcode = (params.get('force_transcode', None) is not None)
... |
class VariableHandler(Handler):
def register(self):
self._lifter.HANDLERS.update({bVariable: self.lift_variable, SSAVariable: self.lift_variable_ssa, FunctionParameter: self.lift_function_parameter, MediumLevelILVar: self.lift_variable_operation, MediumLevelILVarSsa: self.lift_variable_operation_ssa, Medium... |
def example():
async def on_column_scroll(e: ft.OnScrollEvent):
notification = f'Type: {e.event_type}, pixels: {e.pixels}, min_scroll_extent: {e.min_scroll_extent}, max_scroll_extent: {e.max_scroll_extent}'
notification_text.value = notification
(await notification_text.update_async())
c... |
class AutocompleteTests(PreqlTests):
uri = SQLITE_URI
optimized = True
def test_basic(self):
p = self.Preql()
state = p._interp.state
assert ('item' in autocomplete(state, 'func d(){ [1]{'))
assert ('item' in autocomplete(state, 'func d(){ [1]['))
assert ('item' not i... |
def test_properties(cfg: ControlFlowGraph):
assert (len(cfg) == len(cfg.nodes) == len(list(cfg)) == 7)
assert all([(node in cfg) for node in cfg])
assert (cfg.root.address == 65536)
assert (cfg.root == cfg[65536])
assert ({node.address for node in cfg} == {65536, 131072, 192512, 195072, 196352, 1966... |
def get_client():
global client
if (client is not None):
return client
client = Elasticsearch(hosts=HOST, request_timeout=300)
for _ in range(100):
time.sleep(0.1)
try:
client.cluster.health(wait_for_status='yellow')
return client
except ESConnecti... |
def main():
module_spec = schema_to_module_spec(versioned_schema)
mkeyname = None
fields = {'access_token': {'required': False, 'type': 'str', 'no_log': True}, 'enable_log': {'required': False, 'type': 'bool', 'default': False}, 'vdom': {'required': False, 'type': 'str', 'default': 'root'}, 'member_path': {... |
class SingleFlowStats(base_tests.SimpleDataPlane):
def verifyStats(self, flow_mod_msg, match, out_port, test_timeout, packet_count):
stat_req = ofp.message.flow_stats_request()
stat_req.match = match
stat_req.table_id = 255
stat_req.out_port = out_port
all_packets_received = ... |
class BaseSoC(SoCCore):
def __init__(self, sys_clk_freq=int(.0), mode=mode.DOUBLE, **kwargs):
platform = arty.Platform(variant='a7-35', toolchain='vivado')
from litex.build.generic_platform import Pins, IOStandard
platform.add_extension([('do', 0, Pins('B7'), IOStandard('LVCMOS33'))])
... |
class FinetuningDataFormatterTests(unittest.TestCase):
def setUp(self) -> None:
super().setUp()
def create_most_conservative_formatter_configs(agent_type_to_check: AgentType) -> FormatterConfigs:
return FormatterConfigs(guidelines=Guidelines(categories=[Category(name='cat V', description='cat V ... |
class CssButtonBasic(CssStyle.Style):
_attrs = {'font-weight': 'bold', 'padding': '4px', 'margin': '2px 0 2px 0', 'text-decoration': 'none', 'border-radius': '4px', 'white-space': 'nowrap', 'display': 'inline-block', '-webkit-appearance': 'none', '-moz-appearance': 'none'}
_hover = {'text-decoration': 'none', '... |
def esrgan_inference(exe_module: Model, input_pixels: np.ndarray, scale=4) -> torch.Tensor:
if (np.max(input_pixels) > 256):
max_range = 65535
else:
max_range = 255
input_pixels = (input_pixels / max_range)
(height, width, _) = input_pixels.shape
inputs = {'input_pixels': torch.from_... |
class JobManager(HasTraits):
jobs = List(Instance(Job))
start = Button()
def populate(self):
self.jobs = [Job(name=('job %02d' % i), percent_complete=0) for i in range(1, 25)]
def process(self):
for job in self.jobs:
job.percent_complete = min((job.percent_complete + random.r... |
class Solution(object):
def rotatedDigits(self, N):
def rotate_single(d):
if (d in set([0, 1, 8])):
return d
elif (d == 2):
return 5
elif (d == 5):
return 2
elif (d == 6):
return 9
eli... |
class UnbanUser(MethodView):
decorators = [allows.requires(IsAtleastModerator, on_fail=FlashAndRedirect(message=_('You are not allowed to manage users'), level='danger', endpoint='management.overview'))]
def post(self, user_id=None):
if (not Permission(CanBanUser, identity=current_user)):
fl... |
def widgets(decorations=list()):
return [widget.TextBox('This is a test of widget decorations...', name='red', background='ff0000', padding=10, font='Noto Sans', decorations=decorations), widget.TextBox('...in qtile-extras.', name='blue', background='0000ff', padding=10, font='Noto Sans', decorations=decorations)] |
class OptionPlotoptionsDependencywheelDatalabelsTextpath(Options):
def attributes(self) -> 'OptionPlotoptionsDependencywheelDatalabelsTextpathAttributes':
return self._config_sub_data('attributes', OptionPlotoptionsDependencywheelDatalabelsTextpathAttributes)
def enabled(self):
return self._conf... |
class OptionPlotoptionsWindbarbSonificationContexttracksMappingTremoloDepth(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: st... |
_router.post('/item/fetch_updates/', response_model=CollectionItemListResponse, dependencies=PERMISSIONS_READ)
def fetch_updates(data: t.List[CollectionItemBulkGetIn], stoken: t.Optional[str]=None, prefetch: Prefetch=PrefetchQuery, user: UserType=Depends(get_authenticated_user), queryset: CollectionItemQuerySet=Depends... |
_op([ExprCursorA, ConfigA, ConfigFieldA])
def bind_config(proc, var_cursor, config, field):
e = var_cursor._impl._node
cfg_f_type = config.lookup(field)[1]
if (not isinstance(e, LoopIR.Read)):
raise ValueError('expected a cursor to a single variable Read')
elif (e.type != cfg_f_type):
ra... |
_converter(torch.ops.aten.expand.default)
def aten_ops_expand(target: Target, args: Tuple[(Argument, ...)], kwargs: Dict[(str, Argument)], name: str) -> ConverterOutput:
input_val = args[0]
if (not isinstance(input_val, AITTensor)):
raise ValueError(f'Non-tensor inputs for {name}: {input_val}')
size... |
def summarize_results(remote_functionality_passed, local_functionality_passed, cli_options, tmp_proj_dir):
if remote_functionality_passed:
msg_remote = dedent('The deployment was successful.')
else:
msg_remote = dedent('Some or all of the remote functionality tests failed.\n \n ... |
def to_png_sprite(index, shortname, alias, uc, alt, title, category, options, md):
attributes = {'class': ('%(class)s-%(size)s-%(category)s _%(unicode)s' % {'class': options.get('classes', index), 'size': options.get('size', '64'), 'category': (category if category else ''), 'unicode': uc})}
if title:
a... |
class SubstArgs(LoopIR_Rewrite):
def __init__(self, nodes, binding):
assert isinstance(nodes, list)
assert isinstance(binding, dict)
assert all((isinstance(v, LoopIR.expr) for v in binding.values()))
assert (not any((isinstance(v, LoopIR.WindowExpr) for v in binding.values())))
... |
class TestVariable():
def test_requirements(self):
v = Variable('v', no_type, 0)
assert (v.requirements == [v])
def test_complexity(self):
assert (Variable('v1', no_type, 0).complexity == 1)
def test_str(self):
assert (str(Variable('v1', no_type, 0)) == 'v1#0')
assert... |
def improved_guess(geom, bond_func, bend_func, dihedral_func):
H_guess = simple_guess(geom)
for (i, (pt, *indices)) in enumerate(geom.internal.typed_prims):
if (pt in Bonds):
f_func = bond_func
elif (pt in Bends):
f_func = bend_func
elif (pt in Dihedrals):
... |
def test():
assert (len(pattern1) == 2), 'Le nombre de tokens de pattern1 ne correspond pas au veritable nombre de tokens dans la chaine.'
assert (len(pattern2) == 2), 'Le nombre de tokens de pattern2 ne correspond pas au veritable nombre de tokens dans la chaine.'
assert (len(pattern1[0]) == 1), 'Le premie... |
.skipif(('pandas' not in sys.modules), reason='Pandas is not installed.')
def test_structured_dataset_type():
import pandas as pd
from pandas._testing import assert_frame_equal
name = 'Name'
age = 'Age'
data = {name: ['Tom', 'Joseph'], age: [20, 22]}
superset_cols = kwtypes(Name=str, Age=int)
... |
def dp_parser(config_file, logname, meta_dp_state=None):
(conf, _) = config_parser_util.read_config(config_file, logname)
config_hashes = None
dps = None
test_config_condition((conf is None), 'Config file is empty')
test_config_condition((not isinstance(conf, dict)), 'Config file does not have valid... |
class TestOFPStatsReply(unittest.TestCase):
c = OFPStatsReply(_Datapath)
def test_parser_single_struct_true(self):
version = ofproto.OFP_VERSION
msg_type = ofproto.OFPT_STATS_REPLY
msg_len = (ofproto.OFP_STATS_REPLY_SIZE + ofproto.OFP_AGGREGATE_STATS_REPLY_SIZE)
xid =
fm... |
def feedback_todo(context, tasks, subcontexts, highlight=None):
if (len(tasks) != 0):
id_width = max((len(utils.to_hex(task['id'])) for task in tasks))
else:
id_width = 1
for task in tasks:
task_string_builder = functools.partial(get_basic_task_string, context, id_width, task, highli... |
def test_cli_version_multiple_commands(capsys):
version = '1.2.3'
cli = Radicli(version=version)
ran1 = False
ran2 = False
('test1', a=Arg('--a'))
def test1(a: str):
nonlocal ran1
ran1 = True
('test2', a=Arg('--a'))
def test2(a: str):
nonlocal ran2
ran2 = ... |
class ForwardModelJobStatus():
def __init__(self, name: str, start_time: Optional[datetime.datetime]=None, end_time: Optional[datetime.datetime]=None, status: str='Waiting', error: Optional[str]=None, std_out_file: str='', std_err_file: str='', current_memory_usage: int=0, max_memory_usage: int=0):
self.sta... |
def test_simple_gitignore(simple_gitignore):
gitignore = GitIgnore(simple_gitignore)
assert gitignore.is_ignored(str((simple_gitignore / 'test.foo')))
assert gitignore.is_ignored(str((simple_gitignore / 'sub')))
assert gitignore.is_ignored(str(((simple_gitignore / 'sub') / 'some.bar')))
assert (not ... |
def find_gamut_intersection(a: float, b: float, l1: float, c1: float, l0: float, lms_to_rgb: Matrix, ok_coeff: list[Matrix], cusp: (Vector | None)=None) -> float:
if (cusp is None):
cusp = find_cusp(a, b, lms_to_rgb, ok_coeff)
if ((((l1 - l0) * cusp[1]) - ((cusp[0] - l0) * c1)) <= 0.0):
t = ((cu... |
class TestStubClient(TestCase):
def setUp(self):
self.client = StubClient()
def test_init_with_action_map(self):
get_foo_body = {'foo': {'id': 1}}
get_bar_error = {'code': 'invalid', 'message': 'Invalid value for bar.id', 'field': 'id'}
client = StubClient(service_action_map={'fo... |
class TemplateSource():
collect_parts_re = re.compile('{{\\ +?rally\\.collect\\(parts=\\"(.+?(?=\\"))\\"\\)\\ +?}}')
def __init__(self, base_path, template_file_name, source=io.FileSource, fileglobber=glob.glob):
self.base_path = base_path
self.template_file_name = template_file_name
sel... |
class ContributorsRankingMbmReportAction(Action):
params = (Action.params + (ActionParam(name='company', short_name='c', type=str, required=True),))
def name(cls):
return 'get-contributors-ranking-mbm-report'
def help_text(cls) -> str:
return 'Prepared Contributors month by month report'
... |
()
class _LiteDRAMPatternGenerator(Module):
def __init__(self, dram_port, init=[]):
(ashift, awidth) = get_ashift_awidth(dram_port)
self.start = Signal()
self.done = Signal()
self.ticks = Signal(32)
self.run_cascade_in = Signal(reset=1)
self.run_cascade_out = Signal()... |
class OptionSeriesSolidgaugeSonificationDefaultinstrumentoptionsMappingPitch(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: st... |
.asyncio
.workspace_host
class TestGetWebhook():
async def test_unauthorized(self, unauthorized_api_assertions: HTTPXResponseAssertion, test_client_api: test_data: TestData):
webhook = test_data['webhooks']['all']
response = (await test_client_api.get(f'/webhooks/{webhook.id}'))
unauthorize... |
def send_registration_sms(doc):
if frappe.db.get_single_value('Healthcare Settings', 'send_registration_msg'):
if doc.mobile:
context = {'doc': doc, 'alert': doc, 'comments': None}
if doc.get('_comments'):
context['comments'] = json.loads(doc.get('_comments'))
... |
.parametrize('invalide_key,if_error', ((b'\x124V', False), (b'\x124Vw', False), (b'\x124Vx\x9a', True), (b'\x124Vy\xab', True), (b'\xab\xcd\xef', False)))
def test_bin_trie_invalid_key(invalide_key, if_error):
trie = BinaryTrie(db={})
trie.set(b'\x124Vx', b'78')
trie.set(b'\x124Vy', b'79')
assert (trie.... |
.parametrize('name,expected', ((f"{('a' * 63)}.{('b' * 63)}.{('c' * 63)}.{('d' * 63)}.{('e' * 63)}.{('f' * 63)}.{('g' * 63)}", (b''.join([(b'?' + (to_bytes(text=label) * 63)) for label in 'abcdefg']) + b'\x00')), (f"{('a-1' * 21)}.{('b-2' * 21)}.{('c-3' * 21)}.{('d-4' * 21)}.{('e-5' * 21)}.{('f-6' * 21)}", (b''.join([(... |
def test_download_folder(setup_dropbox_loader, mocker):
(loader, mock_dbx) = setup_dropbox_loader
mocker.patch('os.makedirs')
mocker.patch('os.path.join', return_value='mock/path')
mock_file_metadata = mocker.MagicMock(spec=FileMetadata)
mock_dbx.files_list_folder.return_value.entries = [mock_file_m... |
class ThriftFunctionCall(ThriftArgScheme):
service: Optional[str]
method_name: str
thrift_payload: bytes
tchannel_headers: Optional[dict]
application_headers: Dict[(str, str)]
ttl: int
def create(cls, service: str, method_name: str, thrift_payload: bytes):
o = cls()
o.service... |
class desc_stats_request(stats_request):
version = 2
type = 18
stats_type = 0
def __init__(self, xid=None, flags=None):
if (xid != None):
self.xid = xid
else:
self.xid = None
if (flags != None):
self.flags = flags
else:
self... |
class MysqlConnectionPool():
dummy_table_sql = "CREATE TEMPORARY TABLE test_table\n (\n row_id INTEGER PRIMARY KEY AUTO_INCREMENT,\n value_int INTEGER,\n value_float FLOAT,\n value_string VARCHAR(200),\n value_uuid CHAR(36),\n value_binary BLOB,\n value_binary... |
def _str_to_python_value(val):
if (not isinstance(val, (str,))):
return val
elif ((val == 'true') or (val == 'True') or (val == 'on')):
return True
elif ((val == 'false') or (val == 'False') or (val == 'off')):
return False
elif INT_REGEX.match(val):
return int(val)
r... |
class OptionSeriesVectorSonificationTracksMappingHighpassFrequency(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 JqAccordion(Component):
name = 'Jquery Accordion'
_option_cls = OptJqWiidgets.OptAccordion
str_repr = '<div {attrs}>{sub_items}</div>'
dyn_repr = '{header}{content}'
_js__builder__ = ('%s.accordion(options)' % JsQuery.decorate_var('htmlObj', convert_var=False))
def var(self):
retur... |
class AbstractSyntaxTreeNodeSerializer(Serializer, ABC):
def __init__(self, serializer_group: AstNodeSerializer):
self._group = serializer_group
self._pseudo = PseudoSerializer()
def serialize(self, node: AbstractSyntaxTreeNode) -> Dict:
return {'id': self._group.get_id(node), 'type': no... |
class TestPtrUtilities(unittest.TestCase):
(base_path=st.builds(Path), exclude_patterns=st.sets(st.text()), follow_symlinks=st.booleans())
def test_fuzz_find_setup_pys(self, base_path, exclude_patterns, follow_symlinks):
ptr.find_setup_pys(base_path=base_path, exclude_patterns=exclude_patterns, follow_s... |
.parametrize('input_points, expected_points', [(range(10), [0, 4, 8]), ([1, 10, 11, 12, 13, 14, 100, 10000], [1, 13])])
def test_downsample_not_keeplast(string_to_well, input_points, expected_points):
well_definition = '1.01\n Unknown\n custom_name 0 0 0\n 1\n Zonelog DIS... |
def test_slice_will_set_the_data_attributes_on_camera(prepare_scene, create_pymel):
camera = prepare_scene
pm = create_pymel
dres = pm.PyNode('defaultResolution')
dres.width.set(960)
dres.height.set(540)
rs = RenderSlicer(camera=camera)
rs.slice(10, 20)
assert (rs.camera.isSliced.get() i... |
def helmholtz(V):
u = TrialFunction(V)
v = TestFunction(V)
f = Function(V)
x = SpatialCoordinate(V.mesh())
f.project(np.prod([cos(((2 * pi) * xi)) for xi in x]))
a = ((inner(grad(u), grad(v)) + inner(u, v)) * dx)
L = (inner(f, v) * dx)
x = Function(V)
solve((a == L), x, solver_parame... |
def test_step_one_create_table(app):
db = Database(app, auto_migrate=False)
db.define_models(StepOneThing)
ops = _make_ops(db)
diffs = ops.as_diffs()
assert ((len(diffs) == 1) and (diffs[0][0] == 'add_table'))
op = ops.ops[0]
sql = _make_sql(db, op)
assert (sql == _step_one_sql) |
class TestOFPBarrierRequest(unittest.TestCase):
class Datapath(object):
ofproto = ofproto
ofproto_parser = ofproto_v1_0_parser
c = OFPBarrierRequest(Datapath)
def setUp(self):
pass
def tearDown(self):
pass
def test_init(self):
pass
def test_parser(self):
... |
class Policy(ABC):
def seed(self, seed: int) -> None:
def needs_state(self) -> bool:
def needs_env(self) -> bool:
return False
def compute_action(self, observation: ObservationType, maze_state: Optional[MazeStateType], env: Optional[BaseEnv], actor_id: Optional[ActorID]=None, deterministic: bool... |
def remove_empty_trailing_paragraphs(html):
from bs4 import BeautifulSoup
soup = BeautifulSoup(html, 'html.parser')
all_tags = soup.find_all(True)
all_tags.reverse()
for tag in all_tags:
if ((tag.name in ['br', 'p']) and (not tag.contents)):
tag.extract()
else:
... |
def write_candidates(working_dir, candidates):
(int_duplication_candidates, inversion_candidates, tan_duplication_candidates, deletion_candidates, novel_insertion_candidates, breakend_candidates) = candidates
if (not os.path.exists((working_dir + '/candidates'))):
os.mkdir((working_dir + '/candidates'))... |
def save_key_to_pem(pfx_data, pfx_password):
(private_key, certificate) = pkcs12.load_key_and_certificates(pfx_data, pfx_password, default_backend())[:2]
try:
os.mkdir('certs')
except FileExistsError:
pass
with open('certs/public.pem', 'wb') as f:
f.write(certificate.public_bytes... |
class AbstractAuthenticationService(object):
SERVICE_ID = None
def hashPassphrase(self, authKey):
raise error.ProtocolError(errind.noAuthentication)
def localizeKey(self, authKey, snmpEngineID):
raise error.ProtocolError(errind.noAuthentication)
def digestLength(self):
raise erro... |
class Annotations(Options):
def drawTime(self):
return self._config_get('afterDraw')
def drawTime(self, value):
self._config(value)
def type(self):
return self._config_get('line')
def type(self, value):
self._config(value)
def mode(self):
return self._config_g... |
class OptionSeriesBubbleSonificationDefaultinstrumentoptionsMappingGapbetweennotes(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, t... |
def fortios_configuration_fact(params, fos):
(isValid, result) = validate_mkey(params)
if (not isValid):
return (True, False, result)
selector = params['selector']
selector_params = params['params']
mkey_name = MODULE_MKEY_DEFINITONS[selector]['mkey']
mkey_value = (selector_params.get(mk... |
def map_points_to_perimeter(mesh: PyEITMesh, points: List[Tuple[(float, float)]], output_obj: Optional[dict]=None, map_to_nodes: Optional[bool]=True) -> List[Point]:
if (output_obj is None):
output_obj = {}
trimesh_obj = trimesh.Trimesh(mesh.node, mesh.element)
exterior_polygon = create_exterior_pol... |
class Solution():
def divide(self, dividend: int, divisor: int) -> int:
is_negative = False
if (((dividend > 0) and (divisor < 0)) or ((dividend < 0) and (divisor > 0))):
is_negative = True
dividend = abs(dividend)
divisor = abs(divisor)
(runner, index) = (divisor... |
def firewall_mms_profile(data, fos):
vdom = data['vdom']
state = data['state']
firewall_mms_profile_data = data['firewall_mms_profile']
firewall_mms_profile_data = flatten_multilists_attributes(firewall_mms_profile_data)
filtered_data = underscore_to_hyphen(filter_firewall_mms_profile_data(firewall_... |
def get_project_url_name():
output = make_sp_call('fly info', capture_output=True).stdout.decode().strip()
re_app_name = '.*Hostname = (.*)\\.fly\\.dev'
app_name = re.search(re_app_name, output).group(1)
print(f' Found app name: {app_name}')
project_url = f'
print(f' Project URL: {project_url}... |
def docker(cfg, car, ip, target_root, node_name):
distribution_version = cfg.opts('mechanic', 'distribution.version', mandatory=False)
cluster_name = cfg.opts('mechanic', 'cluster.name')
rally_root = cfg.opts('node', 'rally.root')
node_root_dir = os.path.join(target_root, node_name)
return DockerPr... |
def test_staticfiles_with_package(test_client_factory):
app = StaticFiles(packages=['tests'])
client = test_client_factory(app)
response = client.get('/example.txt')
assert (response.status_code == 200)
assert (response.text == '123\n')
app = StaticFiles(packages=[('tests', 'statics')])
clie... |
class OptionPlotoptionsItemSonificationTracksMappingHighpassFrequency(Options):
def mapFunction(self):
return self._config_get(None)
def mapFunction(self, value: Any):
self._config(value, js_type=False)
def mapTo(self):
return self._config_get(None)
def mapTo(self, text: str):
... |
def make_gemm_exec_key(op_keys: str) -> str:
if (';' in op_keys):
raise RuntimeError("invalid op_keys for gemm: '{}'".format(op_keys))
values = [int(v) for v in op_keys.split('x')]
if (len(values) != 3):
raise RuntimeError("invalid op_keys for gemm: '{}'".format(op_keys))
name_values = [... |
class OptionSeriesPackedbubbleSonificationContexttracksMappingGapbetweennotes(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: ... |
class ESP32C3StubLoader(ESP32C3ROM):
FLASH_WRITE_SIZE = 16384
STATUS_BYTES_LENGTH = 2
IS_STUB = True
def __init__(self, rom_loader):
self.secure_download_mode = rom_loader.secure_download_mode
self._port = rom_loader._port
self._trace_enabled = rom_loader._trace_enabled
s... |
_os(*metadata.platforms)
def main():
temp_path = (Path(tempfile.gettempdir()) / os.urandom(16).encode('hex'))
sdelete_path = common.get_path('bin', 'sdelete.exe')
try:
with open(temp_path, 'wb') as f_out:
f_out.write('A')
subprocess.check_call([sdelete_path, '/accepteula', temp_p... |
class MyArmSocket(CommandGenerator):
_write = write
_read = read
def __init__(self, ip, netport=9000, debug=False):
super(MyArmSocket, self).__init__(debug)
self.calibration_parameters = calibration_parameters
self.SERVER_IP = ip
self.SERVER_PORT = netport
self.sock =... |
class OptionsMapbox(Options):
def accessToken(self):
return self._config_get(None)
def accessToken(self, value: str):
self._config(value)
def antialias(self):
return self._config_get(False)
def antialias(self, flag: bool):
self._config(flag)
def attributionControl(sel... |
class CommunityData(object):
mpModel = 1
securityModel = (mpModel + 1)
securityLevel = 'noAuthNoPriv'
contextName = null
tag = null
def __init__(self, communityIndex, communityName=None, mpModel=None, contextEngineId=None, contextName=None, tag=None, securityName=None):
if (mpModel is no... |
class OptionSeriesArearangeSonificationTracksPointgrouping(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):
se... |
class LiteEthPHYRGMIIRX(LiteXModule):
def __init__(self, pads, rx_delay=2e-09):
self.source = source = stream.Endpoint(eth_phy_description(8))
rx_delay_taps = int((rx_delay / 5e-11))
assert (rx_delay_taps < 256)
rx_ctl_ibuf = Signal()
rx_ctl_idelay = Signal()
rx_ctl =... |
class ExpireTokenAuthentication(TokenAuthentication):
def authenticate(self, request):
auth = super(ExpireTokenAuthentication, self).authenticate(request)
if (not auth):
return None
delta = (timezone.now() - auth[1].created)
if (delta.total_seconds() > settings.AUTHTOKEN_... |
def bump_version(v: version.Version, level: str) -> str:
release: List[int] = list(v.release)
stage: Optional[str]
pre: Optional[int]
(stage, pre) = (v.pre if v.pre else (None, None))
dev: Optional[int] = v.dev
post: Optional[int] = v.post
if (level in ('major', 'minor', 'patch')):
s... |
.parallel(nprocs=2)
.parametrize('infotype', ['local', 'sum', 'max'])
def test_get_info(a, bcs, infotype):
A = assemble(a, mat_type='matfree')
ctx = A.petscmat.getPythonContext()
itype = {'local': A.petscmat.InfoType.LOCAL, 'sum': A.petscmat.InfoType.GLOBAL_SUM, 'max': A.petscmat.InfoType.GLOBAL_MAX}[infoty... |
class OptionPlotoptionsColumnPointEvents(Options):
def click(self):
return self._config_get(None)
def click(self, value: Any):
self._config(value, js_type=False)
def drag(self):
return self._config_get(None)
def drag(self, value: Any):
self._config(value, js_type=False)
... |
def set_in_db_key_value_store(key, new_data):
global KV_META_CACHE
new_s = str(new_data)
if (len(new_s) > 40):
new_s = (new_s[:35] + '...')
kv_log.info("Setting kv key '%s' to '%s'", key, new_s)
if (key in KV_META_CACHE):
if (KV_META_CACHE[key] == new_data):
return
th... |
class Leaf(Tree):
def __init__(self, identifier):
self.identifier = identifier
def dfs_traverse(self, visitor):
visitor.visit_leaf(self)
def get_leaves(self):
return [self]
def get_leaves_identifiers(self):
return [self.identifier]
def __repr__(self):
return (... |
def test_changes_reflected_back(fx_asset):
with Image(filename=str(fx_asset.joinpath('apple.ico'))) as img:
with img.sequence[3] as single:
single.resize(32, 32)
assert (single.size == (32, 32))
img.sequence.instances[3] = None
uncommitted = img.sequence[3]
... |
class ConsolePrinter():
_builtins_print = builtins.print
def __init__(self, console):
self.console = console
def start(self):
builtins.print = self
def __call__(self, *values, sep=' ', end='\n', file=sys.stdout, flush=False):
if (file != sys.stdout):
self._builtins_pr... |
def _check_extern_modules(backend):
backends = SyntenyBackend.get_available_backends()
if (backend not in backends):
raise BackendException('"{0}" is not installed.'.format(backend))
if (not m2s.check_binary()):
raise BackendException("maf2synteny binary is missing, did you run 'make'?")
... |
class TimingTest(unittest.TestCase):
def test_delay(self):
delay = 0.01
src = Event.sequence(array1, interval=0.01)
e1 = src.timestamp().pluck(0)
e2 = src.delay(delay).timestamp().pluck(0)
r = e1.zip(e2).map((lambda a, b: (b - a))).mean().run()
self.assertLess(abs(r[(... |
def extractDemonzvirusBlogspotCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
chp_prefixes = [('Kagerou', 'Kagerou, Batsubyoushimasu!', 'translated'), ('Cat ', 'Me and My Beloved Cat (... |
class OptionPlotoptionsSunburstSonificationContexttracksMappingGapbetweennotes(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:... |
class worker(AppCommand):
daemon = True
redirect_stdouts = True
worker_options = [option('--with-web/--without-web', default=True, help='Enable/disable web server and related components.'), option('--web-port', '-p', default=None, type=params.TCPPort(), help=f'Port to run web server on (default: {WEB_PORT})... |
class Clip():
def __init__(self, clip_path: str, min_loud_part_duration: int, silence_part_speed: int) -> None:
self.clip = VideoFileClip(clip_path)
self.audio = Audio(self.clip.audio)
self.cut_to_method = {'silent': self.jumpcut_silent_parts, 'voiced': self.jumpcut_voiced_parts}
sel... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.