code stringlengths 281 23.7M |
|---|
(cis_audit, 'open', mock_open())
(os.path, 'exists', return_value=True)
(cis_audit.CISAudit, 'audit_package_is_installed', mock_audit_package_is_installed_true)
def test_audit_gdm_last_user_logged_in_disabled_fail(MagickMock):
state = test.audit_gdm_last_user_logged_in_disabled()
assert (state == 46) |
class HealthcarePractitioner(Document):
def onload(self):
load_address_and_contact(self)
def autoname(self):
self.name = self.practitioner_name
if frappe.db.exists('Healthcare Practitioner', self.name):
self.name = append_number_if_name_exists('Contact', self.name)
def va... |
class EosHomePathNotFoundError(ErsiliaError):
def __init__(self):
self.message = self._get_message()
self.hints = self._get_hints()
ErsiliaError.__init__(self, self.message, self.hints)
def _get_message(self):
text = 'EOS Home path not found. Looks like Ersilia is not installed c... |
class BaseConcreteCommittee(BaseCommittee):
__tablename__ = 'ofec_committee_detail_mv'
committee_id = db.Column(db.String, primary_key=True, unique=True, index=True, doc=docs.COMMITTEE_ID)
candidate_ids = db.Column(ARRAY(db.Text), doc=docs.CANDIDATE_ID)
sponsor_candidate_ids = db.Column(ARRAY(db.Text), ... |
class CmdDisasm(Cmd):
keywords = ['disasm', 'disas', 'disassemble', 'd']
description = 'Display a disassembly of a specified region in the memory.'
parser = argparse.ArgumentParser(prog=keywords[0], description=description, epilog=('Aliases: ' + ', '.join(keywords)))
parser.add_argument('--length', '-l'... |
def _calculate_iteration_count(exponent_length: int, first_32_exponent_bytes: bytes) -> int:
first_32_exponent = big_endian_to_int(first_32_exponent_bytes)
highest_bit_index = get_highest_bit_index(first_32_exponent)
if (exponent_length <= 32):
iteration_count = highest_bit_index
else:
i... |
def add_task(args, daccess):
context = args.get('context')
options = get_options(args, TASK_MUTATORS, {'deadline': {'None': None}})
if (context is None):
context = ''
if args['edit']:
(title, content) = core.editor_edit_task(args['title'], None, EDITOR)
else:
(title, content)... |
def extractYiumreBlogspotCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [('PRC', 'PRC', 'translated'), ('Loiterous', 'Loiterous', 'oel')]
for (tagname, name, tl_type) in ... |
def power_profiles(interval, activity_type='ride', power_unit='mmp', group='M'):
activity_type = (('%' + activity_type) + '%')
df_best_samples = pd.read_sql(sql=app.session.query(stravaBestSamples).filter(stravaBestSamples.type.ilike(activity_type), (stravaBestSamples.interval == interval)).statement, con=engin... |
def upgrade():
op.add_column('settings', sa.Column('logo_size', sa.Integer(), server_default='1000', nullable=False))
op.add_column('settings', sa.Column('image_size', sa.Integer(), server_default='10000', nullable=False))
op.add_column('settings', sa.Column('slide_size', sa.Integer(), server_default='20000... |
def string_to_bool(v: str):
if isinstance(v, bool):
return v
if (v.lower() in ('yes', 'true', 't', 'y', '1')):
os.environ['data_selection'] = 'True'
return True
elif (v.lower() in ('no', 'false', 'f', 'n', '0')):
os.environ['data_selection'] = 'False'
return False
... |
class RegisterForm(forms.Form):
template_name = 'auth/forms/register_form.html'
name = forms.CharField(max_length=settings.AUTH_USER_NAME_MAX_LENGTH, label='Full name', error_messages={'required': 'You need to enter your name.'}, widget=forms.TextInput(attrs={'placeholder': 'Enter your name.'}))
email = for... |
def upgrade():
op.create_table('cookies', sa.Column('id', sa.String(length=255), nullable=False), sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=True), sa.Column('updated_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=True), sa.Column('name'... |
class OptionSeriesPyramid3dLabel(Options):
def boxesToAvoid(self):
return self._config_get(None)
def boxesToAvoid(self, value: Any):
self._config(value, js_type=False)
def connectorAllowed(self):
return self._config_get(False)
def connectorAllowed(self, flag: bool):
self.... |
def make_string_array(offset, blk, pc, access=None):
function = blk.function
binary = function.binary
if (offset in binary.direct_offsets):
string_array = binary.direct_offsets[offset]
else:
addrs = binary.sections.get_rodata_addrs(offset)
strings = []
for addr in addrs:
... |
class OptionSeriesPyramidSonificationContexttracksMappingGapbetweennotes(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 OptionSeriesVariablepieSonificationPointgrouping(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):
self._... |
(params=[('cg', False), ('cg', True), ('dg', False), ('dg', True), ('file', 't11_tria.msh'), ('file', 't11_quad.msh')])
def mesh2d(request):
if (request.param[0] == 'cg'):
return UnitSquareMesh(12, 12, quadrilateral=request.param[1])
elif (request.param[0] == 'dg'):
return PeriodicUnitSquareMesh... |
def go_to_goal(goal):
global robot_rotation, robot_location
d = Distance_compute(robot_location, goal)
theta = robot_rotation[2]
kl = 1
ka = 4
vx = 0
va = 0
heading = math.atan2((goal[1] - robot_location[1]), (goal[0] - robot_location[0]))
err_theta = (heading - theta)
if (d > 0.... |
class PurgeKeys(ModelNormal):
allowed_values = {}
validations = {}
_property
def additional_properties_type():
return (bool, date, datetime, dict, float, int, list, str, none_type)
_nullable = False
_property
def openapi_types():
return {'surrogate_keys': ([str],)}
_prope... |
('value,expected', [param('range(10,11)', RangeSweep(start=10, stop=11, step=1), id='ints'), param('range (10,11)', RangeSweep(start=10, stop=11, step=1), id='ints'), param('range(1,10,2)', RangeSweep(start=1, stop=10, step=2), id='ints_with_step'), param('range(start=1,stop=10,step=2)', RangeSweep(start=1, stop=10, st... |
class MycobotTest(object):
def __init__(self):
self.mycobot = None
self.win = tkinter.Tk()
self.win.title(' Mycobot ')
self.win.geometry('918x600+10+10')
self.port_label = tkinter.Label(self.win, text=':')
self.port_label.grid(row=0)
self.port_list = ttk.Combo... |
.parametrize('enabled,recording,is_recording', [(True, True, True), (True, False, False), (False, True, False), (False, False, False)])
def test_is_recording(enabled, recording, is_recording):
c = Config(inline_dict={'enabled': enabled, 'recording': recording, 'service_name': 'foo'})
assert (c.is_recording is i... |
def test_visitor_class_nested() -> None:
src = '\n class Foo:\n class Bar:\n some_field = 4\n '
tree = ast.parse(dedent(src))
visitor = PatchHygieneVisitor()
visitor.visit(tree)
items = visitor.items
assert (items == ['Foo', 'Foo.Bar', 'Foo.Bar.some_field']) |
def _extract_pair(object_file: str, resource_type: int, project: str, domain: str, version: str, patches: Dict[(int, Callable[([_GeneratedProtocolMessageType], _GeneratedProtocolMessageType)])]) -> Tuple[(_identifier_pb2.Identifier, Union[(_core_tasks_pb2.TaskTemplate, _core_workflow_pb2.WorkflowTemplate, _launch_plan_... |
def edit_start_up_settings(_: Any) -> None:
locale_manager = locale_handler.LocalManager.from_config()
options = {'CHECK_FOR_UPDATES': bool, 'UPDATE_TO_BETAS': bool, 'HIDE_START_TEXT': bool, 'DEFAULT_START_OPTION': int, 'CREATE_BACKUP': bool}
option_values = [get_config_value_category('START_UP', option) fo... |
def fortios_log_syslogd2(data, fos):
fos.do_member_operation('log.syslogd2', 'filter')
if data['log_syslogd2_filter']:
resp = log_syslogd2_filter(data, fos)
else:
fos._module.fail_json(msg=('missing task body: %s' % 'log_syslogd2_filter'))
return ((not is_successful_status(resp)), (is_su... |
def extractChinesenoveltranslationsSimplegamesdevCom(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',... |
.parametrize('params', [(False, 1), (True, 10)])
def test_correct_param_assignment_at_init(params):
(param1, param2) = params
t = GeometricWidthDiscretiser(return_object=param1, return_boundaries=param1, precision=param2, bins=param2)
assert (t.return_object is param1)
assert (t.return_boundaries is par... |
def find_parents_and_order(glyphsets, locations):
parents = ([None] + list(range((len(glyphsets) - 1))))
order = list(range(len(glyphsets)))
if locations:
bases = (i for (i, l) in enumerate(locations) if all(((v == 0) for v in l.values())))
if bases:
base = next(bases)
... |
def set_managed_items(save_stats: dict[(str, Any)]) -> dict[(str, Any)]:
data = server_handler.check_gen_token(save_stats)
token = data['token']
save_stats = data['save_stats']
if (token is None):
helper.colored_text('Error generating token')
return save_stats
server_handler.update_m... |
def compile_to_strings(lib_name, proc_list):
orig_procs = [id(p) for p in proc_list]
def from_lines(x):
return '\n'.join(x)
proc_list = list(sorted(find_all_subprocs(proc_list), key=(lambda x: x.name)))
(ctxt_name, ctxt_def) = _compile_context_struct(find_all_configs(proc_list), lib_name)
st... |
class ObjectClassCountViewSet(DisasterBase):
endpoint_doc = 'usaspending_api/api_contracts/contracts/v2/disaster/object_class/count.md'
_response()
def post(self, request: Request) -> Response:
filters = [Q(object_class_id=OuterRef('pk')), self.all_closed_defc_submissions, self.is_in_provided_def_co... |
class Ganache7MiddleWare(BrownieMiddlewareABC):
def get_layer(cls, w3: Web3, network_type: str) -> Optional[int]:
if w3.clientVersion.lower().startswith('ganache/v7'):
return (- 100)
else:
return None
def process_request(self, make_request: Callable, method: str, params: ... |
.xfail(raises=ImageComparisonFailure, reason='Matplotlib plots for reasons a different image size.')
.skipif((LOW_MEMORY > memory), reason='Travis has too less memory to run it.')
def test_hicPlotMatrix_perChr_pca1_bigwig_vertical():
outfile = NamedTemporaryFile(suffix='.png', prefix='hicexplorer_test', delete=Fals... |
def ExRem(array1, array2):
assert array1.index.equals(array2.index), 'Indices do not match'
array = pandas.Series(False, dtype=bool, index=array1.index)
i = 0
while (i < len(array1)):
if array1[i]:
array[i] = True
for j in range(i, len(array2)):
if array2[... |
class BaseType():
__slots__ = ['pkg_name', 'type', 'string_upper_bound']
pkg_name: Optional[str]
type: str
string_upper_bound: Optional[int]
def __init__(self, type_string: str, context_package_name: Optional[str]=None):
if (type_string in PRIMITIVE_TYPES):
self.pkg_name = None
... |
class TestStrategy(bt.Strategy):
params = [('exitbars', 5), ('printlog', True)]
def __init__(self):
super().__init__()
self.dataclose = self.datas[0].close
self.order = None
self.order_cancel = None
self.buyprice = None
self.buycomm = None
self.bar_execute... |
def main(args, fn_data):
PEHE_train_ = []
PEHE_test_ = []
results_d = {}
time_start = time.time()
for _ in range(args.num_exp):
(pehe_train_curr, pehe_test_curr) = run_experiment(fn_data, mode=args.mode, test_frac=args.test_frac)
PEHE_train_.append(pehe_train_curr)
PEHE_test_... |
.usefixtures('scan_teardown')
def test_scroll_error(sync_client):
bulk = []
for x in range(4):
bulk.append({'index': {'_index': 'test_index'}})
bulk.append({'value': x})
sync_client.bulk(operations=bulk, refresh=True)
with patch.object(sync_client, 'options', return_value=sync_client), p... |
class OptionSeriesAreasplineDragdropGuideboxDefault(Options):
def className(self):
return self._config_get('highcharts-drag-box-default')
def className(self, text: str):
self._config(text, js_type=False)
def color(self):
return self._config_get('rgba(0, 0, 0, 0.1)')
def color(sel... |
class DefaultCreateModelMixin(CreateModelMixin):
def create(self: BaseGenericViewSet, request: Request, *args: Any, **kwargs: Any) -> Response:
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
instance = self.perform_create(serializer)
hea... |
def mock_requeue(called_with: tp.Optional[int]=None, not_called: bool=False):
assert (not_called or (called_with is not None))
requeue = patch('submitit.slurm.slurm.SlurmJobEnvironment._requeue', return_value=None)
with requeue as _patch:
try:
(yield)
finally:
if not_... |
class MsgStub(object):
def __init__(self, channel):
self.Transfer = channel.unary_unary('/ibc.applications.transfer.v1.Msg/Transfer', request_serializer=ibc_dot_applications_dot_transfer_dot_v1_dot_tx__pb2.MsgTransfer.SerializeToString, response_deserializer=ibc_dot_applications_dot_transfer_dot_v1_dot_tx__... |
('pyscf')
.parametrize('embedding, ref_energy', [('', (- 151.)), ('electronic', (- 151.)), ('electronic_rc', (- 151.)), ('electronic_rcd', (- 151.))])
def test_oniom_ee_charge_distribution(embedding, ref_energy, pyscf_acetaldehyd_getter):
geom = pyscf_acetaldehyd_getter(embedding=embedding)
en = geom.energy
... |
def create_unary_op(op_type: FuncEnum, args: Tuple[(Argument, ...)], kwargs: Dict[(str, Argument)], name: str) -> AITTensor:
input = (kwargs['input'] if ('input' in kwargs) else args[0])
if (not isinstance(input, (AITTensor, float, int))):
raise RuntimeError(f'Unexpected left operand {type(input)} on {n... |
class OptionSeriesCylinderSonificationContexttracksMappingTremolo(Options):
def depth(self) -> 'OptionSeriesCylinderSonificationContexttracksMappingTremoloDepth':
return self._config_sub_data('depth', OptionSeriesCylinderSonificationContexttracksMappingTremoloDepth)
def speed(self) -> 'OptionSeriesCylin... |
class OptionSeriesHistogramSonificationPointgrouping(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):
self._co... |
def publish_event(channel, event_type, data, pub_id, pub_prev_id, skip_user_ids=None, **publish_kwargs):
from django_grip import publish
if (skip_user_ids is None):
skip_user_ids = []
content_filters = []
if pub_id:
event_id = '%I'
content_filters.append('build-id')
else:
... |
def _validate_cai_enabled(cai_configs):
if (not cai_configs.get('enabled')):
LOGGER.debug('CloudAsset Inventory disabled by configuration.')
return False
if (not cai_configs.get('gcs_path', '').startswith('gs://')):
LOGGER.debug('CloudAsset Inventory not configured with a valid GCS bucke... |
_function
def ip_route_add(session, destination, device=None, gateway='', source='', ifindex=0, route_type=zebra.ZEBRA_ROUTE_KERNEL, is_selected=True):
if device:
intf = interface.ip_link_show(session, ifname=device)
if (not intf):
LOG.debug('Interface "%s" does not exist', device)
... |
def factorization_test(setup):
print('Beginning test: prove you know small integers that multiply to 91')
eqs = '\n n public\n pb0 === pb0 * pb0\n pb1 === pb1 * pb1\n pb2 === pb2 * pb2\n pb3 === pb3 * pb3\n qb0 === qb0 * qb0\n qb1 === qb1 * qb1\n qb2 === q... |
class ModelParametersGetter(BaseAction):
def __init__(self, model_id, config_json):
BaseAction.__init__(self, model_id=model_id, config_json=config_json, credentials_json=None)
def _requires_parameters(model_path):
pf = PackFile(model_path)
return pf.needs_model()
def _get_destinatio... |
class OptionPlotoptionsVariwideSonificationContexttracksMappingHighpass(Options):
def frequency(self) -> 'OptionPlotoptionsVariwideSonificationContexttracksMappingHighpassFrequency':
return self._config_sub_data('frequency', OptionPlotoptionsVariwideSonificationContexttracksMappingHighpassFrequency)
def... |
class FaucetUntaggedMultiVlansOutputTest(FaucetUntaggedTest):
CONFIG_GLOBAL = '\nvlans:\n 100:\n description: "untagged"\n unicast_flood: False\nacls:\n 1:\n - rule:\n dl_dst: "01:02:03:04:05:06"\n actions:\n output:\n set_fields:\n ... |
class BarcodePrimerTrieTestCase(unittest.TestCase):
def setUp(self):
self.barcode_str = 'p1d1bc205,TACTAGCG,CATTGCCTATG\np1d1bc206,TACTCGTC,CATTGCCTATG\np1d1bc207,TACTGTGC,CATTGCCTATG\np1d1bc208,TACTGCAG,CATTGCCTATG\np1d1bc209,TACACAGC,CATTGCCTATG\np1d1bc210,TACAGTCG,CAYGGCTA\np1d1bc211,TACGTACG,CAYGGCTA\np... |
class DraggableTabBar(QtGui.QTabBar):
def __init__(self, editor_area, parent):
super().__init__(parent)
self.editor_area = editor_area
self.setContextMenuPolicy(QtCore.Qt.ContextMenuPolicy.DefaultContextMenu)
self.drag_obj = None
def mousePressEvent(self, event):
if (even... |
def _Popen(*args, **kwargs):
customArgs = {}
allowlist = ['env', 'shell']
for arg in allowlist:
if (arg in kwargs):
customArgs[arg] = kwargs[arg]
ps = subprocess.Popen(*args, bufsize=(- 1), stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True, preexec_fn=os.setsi... |
class Sx3():
def __init__(self, channel=False):
self.channel = channel
self.channel_folder = self.channel.split('/')[(- 2)]
self.id = self.get_id()
self.api_data = self.get_api_response_data()
self.name = self.api_data['resposta']['items']['item'][0]['programes_tv'][0]['titol... |
_ns.route('/package/reset', methods=PUT)
_login_required
def package_reset():
copr = get_copr()
form = forms.BasePackageForm()
try:
package = PackagesLogic.get(copr.id, form.package_name.data)[0]
except IndexError:
raise ObjectNotFound('No package with name {name} in copr {copr}'.format(... |
class NumpyArrayWrapper(Wrapper):
def __init__(self, data, *args, **kwargs):
self.data = data
def plot_map(self, backend):
wrapper = get_wrapper(backend.option('metadata'))
if hasattr(wrapper, 'plot_numpy'):
return wrapper.plot_numpy(backend, self.data)
metadata = wra... |
def test_attribute():
params = dict(name='test', type_=str, is_required=True)
attribute = Attribute(**params)
assert (attribute is not None)
assert (attribute == Attribute(**params))
assert (attribute != Attribute(name='another', type_=int, is_required=True))
assert (str(attribute) == "Attribute... |
class ContractDownloadValidator(DownloadValidatorBase):
name = 'contract'
def __init__(self, request_data: dict):
super().__init__(request_data)
self.tinyshield_models.extend([{'key': 'award_id', 'name': 'award_id', 'type': 'any', 'models': [{'type': 'integer'}, {'type': 'text', 'text_type': 'ra... |
def check_no_lambdas(funcs: Sequence[Callable], entrypoint: str) -> None:
if all(((not is_lambda(func)) for func in funcs)):
return
message = dedent(f'''
lambda expression detected in {_truncate_seq_str(funcs, max_size=3)}
HINT: Are you trying to do something like this...?
ar... |
def get_type_converter(items):
items = iter(items)
def get_empty(v):
return (None if (v is None) else type(v)())
def default_converter(_):
return None
try:
first = next(items)
except StopIteration:
return default_converter
if (not isinstance(first, (tuple, list)))... |
def _need_maintenance_ignore_users(request):
if (not hasattr(request, 'user')):
return
user = request.user
if (settings.MAINTENANCE_MODE_LOGOUT_AUTHENTICATED_USER and user.is_authenticated):
logout(request)
user = request.user
if (settings.MAINTENANCE_MODE_IGNORE_ANONYMOUS_USER a... |
.parametrize('keep_last, ref_cycle', [(0, 9), (2, 11), (4, 13), (6, 15), (8, 17)])
def test_anapot_growing_string(keep_last, ref_cycle):
initial = AnaPot.get_geom(((- 1.05274), 1.02776, 0))
final = AnaPot.get_geom((1.94101, 3.85427, 0))
geoms = (initial, final)
gs_kwargs = {'perp_thresh': 0.5, 'reparam_... |
class OptionSeriesSunburstTooltipDatetimelabelformats(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):
self._... |
.parametrize('interfrag_hbonds', [True])
def test_interfragment_hydrogen_bonds(interfrag_hbonds):
geom = geom_loader('lib:interfrag_hydrogen_bond.xyz')
coord_info = setup_redundant(geom.atoms, geom.coords3d, interfrag_hbonds=interfrag_hbonds)
assert (bool(len(coord_info.hydrogen_bonds)) == interfrag_hbonds) |
def verify_ping(fledge_url, skip_verify_north_interface, wait_time, retries):
get_url = '/fledge/ping'
ping_result = utils.get_request(fledge_url, get_url)
assert ('dataRead' in ping_result)
assert ('dataSent' in ping_result)
assert (0 < ping_result['dataRead']), 'South data NOT seen in ping header'... |
def about(request):
article_query = Articles.objects.filter(nid=37)
article_query.update(look_count=(F('look_count') + 1))
if (not article_query):
return redirect('/')
article_obj: Articles = article_query.first()
comment_list = sub_comment_list(37)
return render(request, 'about.html', l... |
def webapi_run_async_adjoint_bwd(simulations: Tuple[(Simulation, ...)], jax_infos: Tuple[(JaxInfo, ...)], folder_name: str, path_dir: str, callback_url: str, verbose: bool, parent_tasks: List[List[str]]) -> List[JaxSimulation]:
task_names = [str(i) for i in range(len(simulations))]
simulations = dict(zip(task_n... |
class BoundFunctionBase(ir.MemberLoad, CallableImpl, ABC):
def dont_copy(self):
return (super().dont_copy + ['member_access', 'bound_expression', 'bound_cfg', 'member_load_args'])
def __init__(self, member_access, bound_expression, bound_cfg, member_load_args):
ir.MemberLoad.__init__(self, **mem... |
def test_slack_loader_load_data(slack_loader, mocker):
valid_json_query = 'in:random'
mocker.patch.object(slack_loader.client, 'search_messages', return_value={'messages': {}})
result = slack_loader.load_data(valid_json_query)
assert ('doc_id' in result)
assert ('data' in result) |
def test_plotting_quadratic():
mesh = UnitSquareMesh(10, 10)
V = FunctionSpace(mesh, 'CG', 2)
f = Function(V)
x = SpatialCoordinate(mesh)
f.interpolate(((x[0] ** 2) + (x[1] ** 2)))
(fig, axes) = plt.subplots()
contours = tricontour(f, axes=axes)
assert (contours is not None) |
class Application(Gtk.Application):
def __init__(self, options, userConfig):
super().__init__(application_id='io.github.fract4d')
self.mainWindow = None
self.options = options
self.userConfig = userConfig
resource = Gio.resource_load(fractconfig.T.find_resource('gnofract4d.gr... |
def test_weird_structure():
class ConvBlock():
n_layers: int = 4
n_filters: List[int] = field(default_factory=[16, 32, 64, 64].copy)
from enum import Enum
class Optimizers(Enum):
ADAM = 'ADAM'
RMSPROP = 'RMSPROP'
SGD = 'SGD'
class GeneratorHParams(ConvBlock):
... |
class BlockHeader(Serializable):
fields = [('prevhash', hash32), ('uncles_hash', hash32), ('coinbase', address), ('state_root', trie_root), ('tx_list_root', trie_root), ('receipts_root', trie_root), ('bloom', int256), ('difficulty', big_endian_int), ('number', big_endian_int), ('gas_limit', big_endian_int), ('gas_u... |
class PerceiverResampler(fl.Chain):
def __init__(self, latents_dim: int=1024, num_attention_layers: int=8, num_attention_heads: int=16, head_dim: int=64, num_tokens: int=8, input_dim: int=768, output_dim: int=1024, device: ((Device | str) | None)=None, dtype: (DType | None)=None) -> None:
self.latents_dim =... |
class OptionSonificationDefaultinstrumentoptionsMappingLowpassResonance(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):
... |
_in_both(MyObject)
def test_property_tristate():
m = MyObject()
print(m.tristateprop)
m.set_tristateprop(42)
loop.iter()
print(m.tristateprop)
m.set_tristateprop('')
loop.iter()
print(m.tristateprop)
m.set_tristateprop(None)
loop.iter()
print(m.tristateprop) |
def _patch_info_sequential(detailed, fsize, patch_size, compression, compression_info, dfpatch_size, data_format, dfpatch_info, to_size, diff_sizes, extra_sizes, adjustment_sizes, number_of_size_bytes):
del adjustment_sizes
number_of_diff_bytes = sum(diff_sizes)
number_of_extra_bytes = sum(extra_sizes)
... |
def main():
parser = optparse.OptionParser()
parser.add_option('--classes-dir', help='Directory containing .class files.')
parser.add_option('--jar-path', help='Jar output path.')
parser.add_option('--excluded-classes', help='List of .class file patterns to exclude from the jar.')
parser.add_option(... |
def lazy_import():
from fastly.model.timestamps import Timestamps
from fastly.model.tls_configuration_response_attributes_all_of import TlsConfigurationResponseAttributesAllOf
globals()['Timestamps'] = Timestamps
globals()['TlsConfigurationResponseAttributesAllOf'] = TlsConfigurationResponseAttributesAl... |
def test_no_record_stack_via_config(logger):
logger.client.config.auto_log_stacks = False
logger.info('This is a test of no stacks')
assert (len(logger.client.events) == 1)
event = logger.client.events[ERROR][0]
assert (event.get('culprit') == None)
assert (event['log']['message'] == 'This is a ... |
def test_cors_disallowed_preflight(test_client_factory):
def homepage(request):
pass
app = Starlette(routes=[Route('/', endpoint=homepage)], middleware=[Middleware(CORSMiddleware, allow_origins=[' allow_headers=['X-Example'])])
client = test_client_factory(app)
headers = {'Origin': ' 'Access-Con... |
class SearchsploitResult(Base):
__tablename__ = 'searchsploit_result'
def __str__(self):
return self.pretty()
def pretty(self, fullpath=False):
pad = ' '
type_padlen = 8
filename_padlen = 9
if (not fullpath):
filename = Path(self.path).name
ms... |
def rerun_game(version: str) -> None:
if (not is_ran_as_root()):
return
package_name = ('jp.co.ponos.battlecats' + version.replace('jp', ''))
subprocess.run(f'sudo pkill -f {package_name}', capture_output=True, check=False, shell=True)
subprocess.run(f'sudo monkey -p {package_name} -c android.in... |
def main():
cmt_clock_sources = ClockSources()
site_to_cmt = dict(read_site_to_cmt())
clock_region_limit = dict()
clock_region_serdes_location = dict()
db = Database(util.get_db_root(), util.get_part())
grid = db.grid()
def gen_sites(desired_site_type):
for tile_name in sorted(grid.t... |
class ConnectionManager():
def __init__(self):
self.connections = []
async def connect(self, websocket):
(await websocket.accept())
self.connections.append(websocket)
async def broadcast(self, message):
for conn in self.connections:
(await conn.send_text(message))... |
def test_ne_conversions(accounts, return_value):
data = [88, [False, False, False], accounts[2], [('0x1234', '0x6666')], string_fixture]
assert (not (return_value != data))
assert (not (return_value != tuple(data)))
data[1] = tuple(data[1])
data[3] = tuple(data[3])
assert (not (return_value != t... |
class ExecuteGitCommandThread(threading.Thread):
def __init__(self, repo, cmd, output_queue):
threading.Thread.__init__(self)
self.repo = repo
self.cmd = cmd
self.output_queue = output_queue
class ReaderThread(threading.Thread):
def __init__(self, stream):
thr... |
class Iface(fb303_asyncio.fb303.FacebookService.Iface):
def run(self, command=None, device=None, timeout=300, open_timeout=30, client_ip='', client_port='', uuid=''):
pass
def bulk_run(self, device_to_commands=None, timeout=300, open_timeout=30, client_ip='', client_port='', uuid=''):
pass
d... |
def _concat_kernel_single_input_output_param_size(op: Operator):
inputs = op._attrs['inputs']
rank = inputs[0]._rank()
size_of_one_output_meta = (CONCAT_OUTPUT_META_SIZE * rank)
total_params_size = ((CONCAT_INPUT_META_SIZE + size_of_one_output_meta) + 24)
_LOGGER.debug(f"concat op {op._attrs['name']... |
.parametrize('base, unrestricted', (('00_pyrrole_rhf', False), ('01_pyrrole_uhf', True)))
def test_transition_multipole_moments(base, unrestricted, this_dir):
base_fn = ((this_dir / 'pyrrole') / base)
json_fn = base_fn.with_suffix('.json')
cis_fn = base_fn.with_suffix('.cis')
wf = Wavefunction.from_orca... |
_defaults()
class TicketSchemaPublic(SoftDeletionSchema):
class Meta():
type_ = 'ticket'
self_view = 'v1.ticket_detail'
self_view_kwargs = {'id': '<id>'}
inflect = dasherize
_schema(pass_original=True)
def validate_date(self, data, original_data):
if ('id' in original... |
(tryfirst=True)
def flaskbb_load_blueprints(app):
forum = Blueprint('forum', __name__)
register_view(forum, routes=['/category/<int:category_id>', '/category/<int:category_id>-<slug>'], view_func=ViewCategory.as_view('view_category'))
register_view(forum, routes=['/forum/<int:forum_id>/edit', '/forum/<int:f... |
def _clone_size_policy(size_policy):
new_size_policy = QtGui.QSizePolicy()
new_size_policy.setHorizontalPolicy(size_policy.horizontalPolicy())
new_size_policy.setVerticalPolicy(size_policy.verticalPolicy())
new_size_policy.setHorizontalStretch(size_policy.horizontalStretch())
new_size_policy.setVert... |
class OptionXaxisCrosshair(Options):
def className(self):
return self._config_get(None)
def className(self, text: str):
self._config(text, js_type=False)
def color(self):
return self._config_get('#cccccc')
def color(self, text: str):
self._config(text, js_type=False)
... |
def update_messaging_config(db: Session, key: FidesKey, config: MessagingConfigRequest) -> MessagingConfigResponse:
existing_config_with_key: Optional[MessagingConfig] = MessagingConfig.get_by(db=db, field='key', value=key)
if (not existing_config_with_key):
raise MessagingConfigNotFoundException(f'No m... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.