code stringlengths 281 23.7M |
|---|
class OptionSeriesPolygonSonificationTracksActivewhen(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):
... |
def cached(func: Callable[(ArgsT, ReturnT)]) -> Callable[(ArgsT, ReturnT)]:
import hashlib
try:
source_code = inspect.getsource(func).encode('utf-8')
except OSError:
print(f'[warning] Function {func.__name__} can not be cached...')
return func
cache_key = hashlib.sha256(source_co... |
def extractKoiTranslationsCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
if (item['tags'] == ['Uncategorized']):
titlemap = [('Potatoes are the only thing thats needed in this... |
class OptionSeriesSolidgaugeDataEvents(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)
... |
class EnumType(type):
def _wrap(cls, attr=None):
if (attr is None):
raise NotImplementedError
if isinstance(attr, int):
for (k, v) in cls.vals.items():
if (v == attr):
return k
raise KeyError('num {0} is not mapped'.format(attr)... |
class UsersLogic(object):
def get(cls, username):
app.logger.info("Querying user '%s' by username", username)
return User.query.filter((User.username == username))
def get_by_api_login(cls, login):
return User.query.filter((User.api_login == login))
def get_multiple_with_projects(cls... |
class OptionSeriesSankeySonificationContexttracksMappingNoteduration(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):
... |
.xfail(reason='modification to initial allocation made the block fixture invalid')
def test_canonical_chain(valid_chain):
genesis_header = valid_chain.chaindb.get_canonical_block_header_by_number(constants.GENESIS_BLOCK_NUMBER)
assert (valid_chain.get_canonical_head() == genesis_header)
block = rlp.decode(v... |
class TestTorrentTrackerIPLeakNet(LocalTestCase):
def __init__(self, devices, parameters):
super().__init__(devices, parameters)
self.torrent_client = self.parameters['torrent_client']
self.torrent_client_preopened = self.parameters['torrent_client_preopened']
self._webdriver = None
... |
def generate_samples(exp_dir: str='', output_directory: Optional[str]=None, render_size: Optional[Tuple[(int, int)]]=None, video_size: Optional[Tuple[(int, int)]]=(256, 256), camera_path: str='simple_360', n_eval_cameras: int=(25 * 3), num_samples: int=2, seed: int=3, trajectory_scale: float=1.3, up: Tuple[(float, floa... |
class OptionPlotoptionsBellcurveSonificationTracksMappingGapbetweennotes(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 NXTSetFlowFormat(NiciraHeader):
def __init__(self, datapath, flow_format):
super(NXTSetFlowFormat, self).__init__(datapath, ofproto.NXT_SET_FLOW_FORMAT)
self.format = flow_format
def _serialize_body(self):
self.serialize_header()
msg_pack_into(ofproto.NX_SET_FLOW_FORMAT_PAC... |
def match_vlan_pcp(self, of_ports, priority=None):
pkt_matchvlanpcp = simple_tcp_packet(dl_vlan_enable=True, vlan_vid=1, vlan_pcp=5)
match = parse.packet_to_flow_match(pkt_matchvlanpcp)
self.assertTrue((match is not None), 'Could not generate flow match from pkt')
match.wildcards = (((ofp.OFPFW_ALL ^ of... |
(MESSAGING_STATUS, dependencies=[Security(verify_oauth_client, scopes=[MESSAGING_READ])], response_model=MessagingConfigStatusMessage, responses={HTTP_200_OK: {'content': {'application/json': {'example': {'config_status': 'configured', 'detail': 'Active default messaging service of type mailgun is fully configured'}}}}... |
class YandexMusicEntry(RB.RhythmDBEntryType):
def __init__(self, shell, client, station):
RB.RhythmDBEntryType.__init__(self, name=(('ym-' + station[:station.find('_')]) + '-entry'), save_to_disk=False)
self.shell = shell
self.db = shell.props.db
self.client = client
self.sta... |
class OptionSeriesTreemapDataDatalabels(Options):
def align(self):
return self._config_get('center')
def align(self, text: str):
self._config(text, js_type=False)
def allowOverlap(self):
return self._config_get(False)
def allowOverlap(self, flag: bool):
self._config(flag,... |
_ns.route('/g/<group_name>/<coprname>/new_build_custom/', methods=['POST'])
_ns.route('/<username>/<coprname>/new_build_custom/', methods=['POST'])
_required
_with_copr
def copr_new_build_custom(copr):
view = 'coprs_ns.copr_new_build_custom'
url_on_success = helpers.copr_url('coprs_ns.copr_builds', copr)
de... |
class stat_trigger(instruction_id):
type = 7
def __init__(self):
return
def pack(self):
packed = []
packed.append(struct.pack('!H', self.type))
packed.append(struct.pack('!H', 0))
length = sum([len(x) for x in packed])
packed[1] = struct.pack('!H', length)
... |
def test_config_inference_with_tuple_of_inference():
model = SampleModel()
compositional = bm.CompositionalInference({(model.foo, model.bar): (bm.SingleSiteAncestralMetropolisHastings(), bm.SingleSiteUniformMetropolisHastings()), model.baz: bm.GlobalNoUTurnSampler()})
compositional.infer([model.baz()], {}, ... |
def pytest_load_initial_conftests(early_config):
capsys = early_config.pluginmanager.get_plugin('capturemanager')
project_path = _get_project_path()
if project_path:
capsys.suspend()
try:
active_project = project.load(project_path)
active_project.load_config()
... |
def test_getitem(fx_asset):
with Image(filename=str(fx_asset.joinpath('apple.ico'))) as img:
size = img.size
assert (size == img.sequence[img.sequence.current_index].size)
assert (img.sequence[0].size == (32, 32))
assert (img.sequence[1].size == (16, 16))
assert (img.sequence... |
def register(registry):
register_editable_textbox_handlers(registry=registry, target_class=TextEditor, widget_getter=(lambda wrapper: wrapper._target.control))
registry.register_interaction(target_class=ReadonlyEditor, interaction_class=DisplayedText, handler=(lambda wrapper, _: wrapper._target.control.text())) |
def upgrade():
op.create_table('tags', sa.Column('deleted_at', sa.DateTime(timezone=True), nullable=True), sa.Column('id', sa.Integer(), nullable=False), sa.Column('name', sa.String(), nullable=False), sa.Column('color', sa.String(), nullable=True), sa.Column('is_read_only', sa.Boolean(), nullable=False), sa.Column... |
class IISPHSolver(SPHBase):
def __init__(self, particle_system):
super().__init__(particle_system)
self.a_ii = ti.field(dtype=float, shape=self.ps.particle_max_num)
self.density_deviation = ti.field(dtype=float, shape=self.ps.particle_max_num)
self.last_pressure = ti.field(dtype=floa... |
.parametrize('dataset, expected_missed', ((pd.DataFrame(), 0), (pd.DataFrame({'feature': []}), 0), (pd.DataFrame({'feature': [1, 2, 3]}), 0), (pd.DataFrame({'feature1': [1, None, pd.NA], 'feature2': [np.NaN, None, pd.NaT]}), 5)))
def test_get_number_of_all_pandas_missed_values(dataset: pd.DataFrame, expected_missed: in... |
class TestTCPServerConnection():
.asyncio
async def test_receive_raises_exception(self):
port = get_unused_tcp_port()
tcp_server = _make_tcp_server_connection('address_server', 'public_key_server', '127.0.0.1', port)
tcp_client = _make_tcp_client_connection('address_client', 'public_key_... |
def normalize_fixture(fixture):
normalized_fixture = {'in': tuple((((decode_hex(key) if is_0x_prefixed(key) else text_if_str(to_bytes, key)), ((decode_hex(value) if is_0x_prefixed(value) else text_if_str(to_bytes, value)) if (value is not None) else None)) for (key, value) in (fixture['in'].items() if isinstance(fi... |
class OptionPlotoptionsSunburstSonificationTracksMapping(Options):
def frequency(self) -> 'OptionPlotoptionsSunburstSonificationTracksMappingFrequency':
return self._config_sub_data('frequency', OptionPlotoptionsSunburstSonificationTracksMappingFrequency)
def gapBetweenNotes(self) -> 'OptionPlotoptionsS... |
def rename_policy(ctx, policy_id, policy_type, original_name, new_name):
headers = {'Accept': 'application/json', 'Content-Type': 'application/json', 'Authorization': f'SSWS {ctx.obj.api_token}'}
params = {}
payload = {'type': policy_type, 'name': new_name}
url = f'{ctx.obj.base_url}/policies/{policy_id... |
_toolkit([ToolkitName.qt])
(no_gui_test_assistant, 'No GuiTestAssistant')
class TestTextEditorQt(BaseTestMixin, GuiTestAssistant, UnittestTools, unittest.TestCase):
def setUp(self):
BaseTestMixin.setUp(self)
GuiTestAssistant.setUp(self)
def tearDown(self):
GuiTestAssistant.tearDown(self)... |
def test_grow_node(leaf_node, left_rule, right_rule, X):
grown_leaf = LeafNode.grow_node(leaf_node, left_rule=left_rule, right_rule=right_rule)
assert isinstance(grown_leaf, SplitNode)
assert (grown_leaf.left_child is not None)
assert (grown_leaf.right_child is not None)
assert (grown_leaf.most_rece... |
def dispatch_wp(process_m_fn, process_s_fn, wp):
results = []
try:
if (not wp.cfg.enabled):
wp.mh.register_exclusion(wp.filename)
results.append(work_package.Result(wp, False))
elif isinstance(wp, work_package.SIMULINK_File_WP):
wp.register_file()
... |
class AttendeeSearchForm(forms.Form):
def __init__(self, event_slug, *args, **kwargs):
kwargs.update(initial={'event_slug': event_slug})
super().__init__(*args, **kwargs)
self.fields['event_slug'].widget = forms.HiddenInput()
event_slug = forms.CharField()
attendee = forms.ModelChoic... |
_event
class TitleSet(ThreadEvent):
thread = attr.ib(type='_threads.Group')
title = attr.ib(type=Optional[str])
at = attr.ib(type=datetime.datetime)
def _parse(cls, session, data):
(author, thread, at) = cls._parse_metadata(session, data)
return cls(author=author, thread=thread, title=(d... |
def superlu_sparse_2_dense(sparse_matrix, output=False):
rowptr = sparse_matrix.getCSRrepresentation()[0]
colptr = sparse_matrix.getCSRrepresentation()[1]
data = sparse_matrix.getCSRrepresentation()[2]
nr = sparse_matrix.shape[0]
nc = sparse_matrix.shape[1]
return _pythonCSR_2_dense(rowptr, colp... |
class RunWatch(IntervalModule):
format_up = '{name}'
format_down = '{name}'
color_up = '#00FF00'
color_down = '#FF0000'
settings = ('format_up', 'format_down', 'color_up', 'color_down', 'path', 'name')
required = ('path', 'name')
def is_process_alive(pid):
return os.path.exists('/pro... |
class DatasetConfig(Base):
connection_config_id = Column(String, ForeignKey(ConnectionConfig.id_field_path), nullable=False)
fides_key = Column(String, index=True, unique=True, nullable=False)
ctl_dataset_id = Column(String, ForeignKey(CtlDataset.id), index=True, nullable=False)
connection_config = rela... |
def make_ua():
rrange = (lambda a, b, c=1: (((c == 1) and random.randrange(a, b)) or int(((1.0 * random.randrange((a * c), (b * c))) / c))))
ua = ('Mozilla/%d.0 (Windows NT %d.%d) AppleWebKit/%d (KHTML, like Gecko) Chrome/%d.%d Safari/%d' % (rrange(4, 7, 10), rrange(5, 7), rrange(0, 3), rrange(535, 538, 10), rr... |
class ObjectClassCount(AgencyBase):
endpoint_doc = 'usaspending_api/api_contracts/contracts/v2/agency/toptier_code/object_class/count.md'
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.params_to_validate = ['fiscal_year']
_response()
def get(self, request: Re... |
def compile_clip(pt_mod, batch_size=(1, 8), seqlen=64, dim=768, num_heads=12, depth=12, use_fp16_acc=False, convert_conv_to_gemm=False, act_layer='gelu', constants=True):
mask_seq = 0
causal = True
ait_mod = ait_CLIPTextTransformer(num_hidden_layers=depth, hidden_size=dim, num_attention_heads=num_heads, bat... |
def create_test_engine_with_file(enforce_fks=True):
(fd, tmpfile) = tempfile.mkstemp('.db', 'forseti-test-')
try:
LOGGER.info('Creating database at %s', tmpfile)
engine = create_engine('sqlite:///{}'.format(tmpfile), sqlite_enforce_fks=enforce_fks, pool_size=5, connect_args={'check_same_thread':... |
def video_categories_list(key, part, id=None, regionCode=None, hl=None):
args = locals()
if (sum([bool(p) for p in [id, regionCode]]) != 1):
raise ValueError("make sure you specify exactly one of ['id', 'regionCode']")
base_url = '
return _combine_requests(args, base_url, count=None, max_allowed... |
class EvaluatorConnectionInfo():
host: str
port: int
url: str
cert: Optional[Union[(str, bytes)]] = None
token: Optional[str] = None
def dispatch_uri(self) -> str:
return f'{self.url}/dispatch'
def client_uri(self) -> str:
return f'{self.url}/client'
def result_uri(self) ... |
class RouteMethodInfo(_Traversable):
__visit_name__ = 'route_method'
def __init__(self, method: str, source_info: str, function_name: str, internal: bool):
self.method = method
self.source_info = source_info
self.function_name = function_name
self.internal = internal
if f... |
class PaytmPaymentsManager():
def paytm_endpoint(self):
if (get_settings()['paytm_mode'] == 'test'):
url = '
else:
url = '
return url
def generate_checksum(paytm_params):
if (get_settings()['paytm_mode'] == 'test'):
merchant_key = get_settings(... |
class pygaze_init(item):
description = u'Initialize and calibrate eye tracker'
def __init__(self, name, experiment, string=None):
item.__init__(self, name, experiment, string)
self.reload_pygaze()
def reset(self):
self.var.tracker_type = u'Simple dummy'
self.var.calibrate = u... |
def insert_activity_data(df_activity_summary, df_activity_samples, days_back=7):
start = app.session.query(func.max(ouraActivitySummary.summary_date))[0][0]
start = ('1999-01-01' if (start is None) else datetime.strftime((start - timedelta(days=days_back)), '%Y-%m-%d'))
try:
app.server.logger.debug(... |
class TestSamToSoap(unittest.TestCase):
def test_sam_to_soap(self):
sam = SAMLine("SRR189243_1-SRR189243.3751\t81\tgi||gb|AE017196.1|\t60083\t30\t76M\t*\t0\t0\tTATAGTTATATAAAAGACCTGAGTAGTACGTTTTATATAATCTGATTTTATGGCTATACTTTTTTTGACATGTAGC\tAAAA7AAAA2AA7AAAAAAA1,:0/57:8855)))),''(03388*',''))))#\tNM:i:1\tMD:Z:... |
def _get_original_init(original_class: type, instance: object, owner: type) -> Any:
target_class_id = _target_class_id_by_original_class_id[id(original_class)]
if ('__init__' in _restore_dict[target_class_id]):
return _restore_dict[target_class_id]['__init__'].__get__(instance, owner)
else:
... |
(scope='function')
def hydra_task_runner() -> Callable[([Optional[str], Optional[str], Optional[str], Optional[str], Optional[List[str]], bool], TaskTestFunction)]:
def _(calling_file: Optional[str], calling_module: Optional[str], config_path: Optional[str], config_name: Optional[str], overrides: Optional[List[str]... |
class RDepConstraints(Digraph.Node):
depends_on = ['RDepDependsOn', 'RDepSolvedBy']
def __init__(self, config):
Digraph.Node.__init__(self, 'RDepConstraints')
self.config = config
def get_type_set():
return set([InputModuleTypes.reqdeps])
def rewrite(reqset):
tracer.debug... |
def test_normalize_availability_on_func_2():
func2 = availability(C2)(level_param_step_no_default)
func2 = normalize('param', ['a', 'b'])(func2)
assert (func2(level=1000, param='a', step=24) == (1000, 'a', 24))
assert (func2(level='1000', param='a', step=24) == (1000, 'a', 24))
with pytest.raises(Va... |
class S7LPDDR4PHY(DoubleRateLPDDR4PHY, S7Common):
def __init__(self, pads, *, iodelay_clk_freq, with_odelay, **kwargs):
self.iodelay_clk_freq = iodelay_clk_freq
super().__init__(pads, ser_latency=Latency(sys2x=1), des_latency=Latency(sys2x=2), phytype=self.__class__.__name__, serdes_reset_cnt=(- 1),... |
.parametrize('literal_value_pair', _parameterizers.LIST_OF_SCALAR_LITERALS_AND_PYTHON_VALUE)
def test_execution_spec(literal_value_pair):
(literal_value, _) = literal_value_pair
obj = _execution.ExecutionSpec(_identifier.Identifier(_identifier.ResourceType.LAUNCH_PLAN, 'project', 'domain', 'name', 'version'), _... |
def generate_config_docs(config: FidesConfig, outfile_path: str='.fides/fides.toml') -> None:
schema_properties: Dict[(str, Dict)] = config.schema()['properties']
object_fields = {settings_name: settings_info for (settings_name, settings_info) in schema_properties.items() if (settings_info.get('type') == 'objec... |
class SpiritingAwayAction(UserAction):
def apply_action(self):
tgt = self.target
src = self.source
g = self.game
catnames = ('cards', 'showncards', 'equips', 'fatetell')
cats = [getattr(tgt, i) for i in catnames]
card = g.user_input([src], ChoosePeerCardInputlet(self,... |
class PluginTestCase(unittest.TestCase):
def setUp(self):
ets_config_patcher = ETSConfigPatcher()
ets_config_patcher.start()
self.addCleanup(ets_config_patcher.stop)
def test_id_policy(self):
p = Plugin()
self.assertEqual('envisage.plugin.Plugin', p.id)
p = Plugin... |
def test_error_when_regression_is_true_and_target_is_binary(df_enc):
encoder = DecisionTreeEncoder(regression=True)
with pytest.raises(ValueError) as record:
encoder.fit(df_enc[['var_A', 'var_B']], df_enc['target'])
msg = 'Trying to fit a regression to a binary target is not allowed by this transfor... |
class PrepareMixin():
def prepare(cls, database: DB, pkgen: PrimaryKeyGeneratorBase, items: Iterable[PrepareMixin]) -> Iterator[PrepareMixin]:
for item in cls.merge(database, items):
if hasattr(item, 'id'):
item.id.resolve(id=pkgen.get(cls), is_new=True)
(yield item)
... |
def test_more_entries2_extend_phi_function():
(node, task) = construct_graph(5)
PhiFunctionFixer().run(task)
assert (node[0].instructions[0].origin_block == {node[1]: expressions.Variable('v', Integer.int32_t(), 1), node[4]: expressions.Variable('v', Integer.int32_t(), 1), node[2]: expressions.Variable('v',... |
def test_fake_receive_messages():
q = get_sqs_queue()
q.send_message('1235', {'attr1': 'val1', 'attr2': 111})
q.send_message('2222')
q.send_message('3333')
q.send_message('4444', {'attr1': 'v1', 'attr2': 'v2'})
msgs = q.receive_messages(10, MaxNumberOfMessages=10)
assert (len(msgs) == 4)
... |
def test_slate_hybridization_nested_schur():
(a, L, W) = setup_poisson()
w = Function(W)
params = {'mat_type': 'matfree', 'ksp_type': 'preonly', 'pc_type': 'python', 'pc_python_type': 'firedrake.HybridizationPC', 'hybridization': {'ksp_type': 'preonly', 'pc_type': 'lu', 'localsolve': {'ksp_type': 'preonly',... |
class MemoryAssistant(object):
def assertMemoryUsage(self, process, usage, slack=0, msg=None):
current_usage = self._memory_usage(process)
hard_limit = (usage * (1 + slack))
if (hard_limit < current_usage):
if (msg is None):
difference = ((current_usage - usage) /... |
def main(argv):
fonts = {}
for line in fileinput.input():
f = line.strip().split(' ')
if (not f):
continue
k = f[0]
if (k == 'FontName'):
fontname = f[1]
props = {'FontName': fontname, 'Flags': 0}
chars = {}
fonts[fontna... |
class TestResourceMixinCreation():
(autouse=True)
def patch_ patch_
pass
def setup_method(self):
self.base_url = '
self.api_key = 'super_secret_api_key'
self.user_agent = 'fintoc-python/test'
self.params = {'first_param': 'first_value', 'second_param': 'second_value'}... |
def test_spark_dataframe_return():
my_schema = FlyteSchema[kwtypes(name=str, age=int)]
(task_config=Spark())
def my_spark(a: int) -> my_schema:
session = flytekit.current_context().spark_session
df = session.createDataFrame([('Alice', a)], my_schema.column_names())
return df
def ... |
class MyAdminIndexView(admin.AdminIndexView):
('/')
def index(self):
if (not login.current_user.is_authenticated):
return redirect(url_for('.login_view'))
return super(MyAdminIndexView, self).index()
('/login/', methods=('GET', 'POST'))
def login_view(self):
form = Lo... |
def test_entity_storage_remove_entity_asset(create_test_db, create_project, prepare_entity_storage):
from stalker import Asset, Task, Version
project = create_project
char1 = Asset.query.filter((Asset.project == project)).filter((Asset.name == 'Char1')).first()
model = Task.query.filter((Task.parent == ... |
class tunnel_capability(bsn_tlv):
type = 142
def __init__(self, value=None):
if (value != None):
self.value = value
else:
self.value = 0
return
def pack(self):
packed = []
packed.append(struct.pack('!H', self.type))
packed.append(struct... |
def chain(layer1: Model[(InT, MidT)], layer2: Model[(MidT, Any)], *layers: Model[(Any, Any)]) -> Model[(InT, XY_YZ_OutT)]:
all_layers: List[Model[(Any, Any)]] = [layer1, layer2]
all_layers.extend(layers)
dims: Dict[(str, Optional[int])] = {'nO': None}
if (all_layers[0].has_dim('nI') is True):
di... |
def explode(self):
sets = settings.sets
set_bounds = {}
set_volume = {}
avg_side = 0
for bset in sets:
set_bounds[bset] = get_bbox_set(bset)
set_volume[bset] = ((set_bounds[bset]['size'].x * set_bounds[bset]['size'].y) * set_bounds[bset]['size'].z)
avg_side += set_bounds[bset... |
def get_widget_content_cast(handle, params):
log.debug('getWigetContentCast Called: {0}', params)
server = downloadUtils.get_server()
item_id = params['id']
data_manager = DataManager()
result = data_manager.get_content((('{server}/emby/Users/{userid}/Items/' + item_id) + '?format=json'))
log.de... |
def extractBluebunnytranslationsWordpressCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [('IHM', 'I Have Medicine', 'translated'), ('Loiterous', 'Loiterous', 'oel')]
for ... |
class TestJzazbz(util.ColorAssertsPyTest):
COLORS = [('red', 'color(--jzazbz 0.13438 0.11789 0.11188)'), ('orange', 'color(--jzazbz 0.16937 0.0312 0.12308)'), ('yellow', 'color(--jzazbz 0.2096 -0.02864 0.13479)'), ('green', 'color(--jzazbz 0.09203 -0.07454 0.07996)'), ('blue', 'color(--jzazbz 0.09577 -0.04085 -0.18... |
def create_new_fl_config_from_old_json(old_config_json_path, new_config_json_path=None, flsim_example=False):
new_config = {}
with open(old_config_json_path) as f:
old_config = json.load(f)
new_config = get_new_fl_config(old_config, flsim_example)
if (new_config_json_path is None):
p... |
class Spew():
def __init__(self, trace_names=None, show_values=True):
self.trace_names = trace_names
self.show_values = show_values
def __call__(self, frame, event, arg):
if (event == 'line'):
lineno = frame.f_lineno
if ('__file__' in frame.f_globals):
... |
_handler(content_types=['successful_payment'])
def got_payment(message):
bot.send_message(message.chat.id, 'Hoooooray! Thanks for payment! We will proceed your order for `{} {}` as fast as possible! Stay in touch.\n\nUse /buy again to get a Time Machine for your friend!'.format((message.successful_payment.total_amo... |
class RequirementsFixer():
errors: ErrorReport
bmg: BMGraphBuilder
_typer: LatticeTyper
_reqs: EdgeRequirements
def __init__(self, bmg: BMGraphBuilder, typer: LatticeTyper) -> None:
self.errors = ErrorReport()
self.bmg = bmg
self._typer = typer
self._reqs = EdgeRequir... |
def test_retrieving_hidden_posts(topic, user):
new_post = Post(content='stuff')
new_post.save(user, topic)
new_post.hide(user)
assert (Post.query.get(new_post.id) is None)
assert (Post.query.with_hidden().get(new_post.id) == new_post)
assert (Post.query.filter((Post.id == new_post.id)).first() i... |
class pygaze_log(item):
description = u'Writes information to the eye-tracker logfile'
def reset(self):
self.var.msg = u''
self.var.auto_log = u'no'
self.var.throttle = 2
def run(self):
self.set_item_onset()
for msg in self.var.msg.split(u'\n'):
self.exper... |
class Command(DanubeCloudCommand):
help = 'Check the existence of SECRET_KEY in local_settings.py and generate one if needed.'
def handle(self, *args, **options):
try:
from core import local_settings
except ImportError:
local_settings = None
fn = self._path(se... |
class MapTest(SeleniumTestCase):
def test_map_slider(self):
self.browser.get((self.live_server_url + '/analyse/#org=CCG&numIds=0212000AA&denomIds=2.12&selectedTab=map'))
self.find_by_xpath("//*[='leaflet-zoom-animated' and name()='svg']")
self.assertEqual(len(self.browser.find_elements(By.XP... |
def _assert_format(instances, namespace=None):
if (not namespace):
namespace = list()
if isinstance(instances, dict):
for instance_list in instances.values():
if (not _check_format(instance_list, namespace=namespace)):
return False
namespace.extend((n for ... |
def run_window_function(options):
module = 'emlearn.tools.window_function'
args = ['python3', '-m', module]
for (key, value) in options.items():
args.append('--{}={}'.format(key, value))
stdout = subprocess.check_output(' '.join(args), shell=True)
return stdout.decode('utf-8') |
class pad_last_dim(Operator):
def __init__(self, ndim: int, out_dim: int):
super().__init__()
self._attrs['op'] = 'pad_last_dim'
self._attrs['ndim'] = ndim
self._attrs['out_dim'] = out_dim
self.shape_eval_template = SHAPE_FUNC_TEMPLATE
self.shape_save_template = SHAPE... |
def get_deck_template() -> 'Template':
from jinja2 import Environment, FileSystemLoader, select_autoescape
root = os.path.dirname(os.path.abspath(__file__))
templates_dir = os.path.join(root, 'html')
env = Environment(loader=FileSystemLoader(templates_dir), autoescape=select_autoescape(enabled_extension... |
def run():
params = {'tiles': []}
for (tile, sites) in gen_sites():
for (site_type, site) in sites.items():
p = {}
p['tile'] = tile
p['site'] = site
p['CONNECTION'] = random.choice(('HARD_ZERO', 'CLOCK'))
params['tiles'].append(p)
print("\n... |
def holeCol(func):
(func)
def f(self, *args, **kw):
if ('color' in kw):
color = kw.pop('color')
else:
color = Color.INNER_CUT
self.ctx.stroke()
with self.saved_context():
self.set_source_color(color)
func(self, *args, **kw)
... |
class StalkerShotAddPrevisOutputOperator(bpy.types.Operator):
bl_label = 'Add Previs Output'
bl_idname = 'stalker.shot_add_previs_output_op'
stalker_entity_id = bpy.props.IntProperty(name='stalker_entity_id')
stalker_entity_name = bpy.props.StringProperty(name='stalker_entity_name')
def execute(self... |
def test_div_param(some_thr):
dtype = numpy.float32
input = get_test_array((1000,), dtype)
p1 = get_test_array((1,), dtype)[0]
p2 = get_test_array((1,), dtype)[0]
input_dev = some_thr.to_device(input)
output_dev = some_thr.empty_like(input_dev)
test = get_test_computation(input_dev)
scal... |
def extcodehash_eip2929(computation: ComputationAPI) -> None:
address = force_bytes_to_address(computation.stack_pop1_bytes())
state = computation.state
_consume_gas_for_account_load(computation, address, mnemonics.EXTCODEHASH)
if state.account_is_empty(address):
computation.stack_push_bytes(con... |
def infer(model, device, data_type, input_size, output_size, batch_size, args):
if (device == 'cpu'):
elap = infer_cpu(model, device, data_type, input_size, output_size, batch_size, args)
elif (device == 'gpu'):
elap = infer_gpu(model, device, data_type, input_size, output_size, batch_size, args... |
def is_boolean(value):
if isinstance(value, str):
try:
return bool_dict[value.lower()]
except KeyError:
raise VdtTypeError(value)
if (value == False):
return False
elif (value == True):
return True
else:
raise VdtTypeError(value) |
class OptionSeriesVennSonificationTracksMapping(Options):
def frequency(self) -> 'OptionSeriesVennSonificationTracksMappingFrequency':
return self._config_sub_data('frequency', OptionSeriesVennSonificationTracksMappingFrequency)
def gapBetweenNotes(self) -> 'OptionSeriesVennSonificationTracksMappingGapb... |
(x_input=INTEGER_ST)
(deadline=DEADLINE, max_examples=5)
def test_workflow_within_eager_workflow(x_input: int):
async def eager_wf(x: int) -> int:
out = (await subworkflow(x=x))
return (await double(x=out))
result = asyncio.run(eager_wf(x=x_input))
assert (result == ((x_input + 1) * 2)) |
class OptionPlotoptionsDependencywheelSonificationContexttracksMappingFrequency(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... |
def get_specialized_executioners(project) -> dict[(str, SpecializedExecutioner)]:
with open('clippinator/minions/specialized_minions.yaml') as f:
data = yaml.load(f, Loader=yaml.FullLoader)
return {line['name']: specialized_executioner(**{k.replace('-', '_'): v for (k, v) in line.items()})(project) ... |
class BackupDefineView(APIView):
order_by_default = ('vm__hostname', '-id')
order_by_fields = ('name', 'disk_id')
order_by_field_map = {'hostname': 'vm__hostname', 'created': 'id'}
def get(self, vm, define, many=False, extended=False):
if extended:
ser_class = ExtendedBackupDefineSer... |
class RevisionMiddleware():
manage_manually = False
using = None
atomic = True
def __init__(self, get_response):
self.get_response = create_revision(manage_manually=self.manage_manually, using=self.using, atomic=self.atomic, request_creates_revision=self.request_creates_revision)(get_response)
... |
def generate_edges(graph, root, graph_nodes):
edge = [root]
prev_root = None
while True:
outbound_edges = graph_nodes[root]
outbound_edges -= set((prev_root,))
if (len(outbound_edges) > 1):
graph['edges'].append(edge)
if (root not in graph['joins']):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.