code stringlengths 281 23.7M |
|---|
class PrivateKey(Signer):
curve: Curve = ecdsa.SECP256k1
hash_function: Callable = hashlib.sha256
def __init__(self, private_key: Optional[Union[(bytes, str)]]=None):
if (private_key is None):
self._signing_key = ecdsa.SigningKey.generate(curve=self.curve, hashfunc=self.hash_function)
... |
class bsn_table_checksum_stats_request(bsn_stats_request):
version = 5
type = 18
stats_type = 65535
experimenter = 6035143
subtype = 11
def __init__(self, xid=None, flags=None):
if (xid != None):
self.xid = xid
else:
self.xid = None
if (flags != No... |
.django_db
def test_award_types(client, monkeypatch, sub_agency_data_1, elasticsearch_transaction_index):
setup_elasticsearch_test(monkeypatch, elasticsearch_transaction_index)
resp = client.get(url.format(toptier_code='001', filter='?fiscal_year=2021&award_type_codes=[A]'))
assert (resp.status_code == stat... |
.parametrize('elasticapm_client', [{'transaction_max_spans': 1}], indirect=True)
def test_dropped_spans(tracer):
assert (tracer._agent.config.transaction_max_spans == 1)
with tracer.start_active_span('transaction') as ot_scope_t:
with tracer.start_active_span('span') as ot_scope_s:
s = ot_sc... |
def _add_before_scripts(model: DbtModel, downstream_fal_node_unique_id: str, faldbt: FalDbt, graph: nx.DiGraph, nodeLookup: Dict[(str, FalFlowNode)]) -> Tuple[(nx.DiGraph, Dict[(str, FalFlowNode)])]:
before_scripts = model.get_scripts(before=True)
before_fal_scripts = map((lambda script_path: FalScript(faldbt, ... |
def image_callback2(viz, env, args):
def show_color_image_window(color, win=None):
image = np.full([3, 256, 256], color, dtype=float)
return viz.image(image, opts=dict(title='Colors', caption='Press arrows to alter color.'), win=win, env=env)
callback_image_window = show_color_image_window(image... |
()
('--card', default=None, type=str, help='ID of the card to unblock. Omitting this will unblock all cards.')
_decorator
def card_unblock(card: str):
if card:
card_ids = [card]
else:
card_ids = [card['id'] for card in API_CLIENT.get_cards()]
for card_id in card_ids:
API_CLIENT.unblo... |
class LastfmSource(DynamicSource):
name = 'lastfm'
def __init__(self):
DynamicSource.__init__(self)
def get_results(self, artist):
ar = urllib.parse.quote_plus(artist.encode('utf-8'))
url = (' + API_KEY)
try:
f = urllib.request.urlopen((url % ar)).read()
e... |
class AppEngineRepositoryClient(_base_repository.BaseRepositoryClient):
def __init__(self, quota_max_calls=None, quota_period=1.0, use_rate_limiter=True, cache_discovery=False, cache=None):
if (not quota_max_calls):
use_rate_limiter = False
self._apps = None
self._app_services = ... |
class VclDiff(ModelNormal):
allowed_values = {('format',): {'TEXT': 'text', 'HTML': 'html', 'HTML_SIMPLE': 'html_simple'}}
validations = {}
_property
def additional_properties_type():
return (bool, date, datetime, dict, float, int, list, str, none_type)
_nullable = False
_property
de... |
class SelfAttentionSeqBlock(ShapeNormalizationBlock):
def __init__(self, in_keys: Union[(str, List[str])], out_keys: Union[(str, List[str])], in_shapes: Union[(Sequence[int], List[Sequence[int]])], num_heads: int, dropout: Optional[float], add_input_to_output: bool, bias: bool):
in_keys = (in_keys if isinst... |
def test_answer_call_greeting(app):
global play_audio_called
global record_message_called
global voice_messaging_menu_called
play_audio_called = False
record_message_called = False
voice_messaging_menu_called = False
app.answer_call(('answer', 'greeting'), 'greeting.wav', 2, caller2)
ass... |
def send_message(msg: 'Message') -> Optional['Message']:
global middlewares, master, slaves
if (msg is None):
return
for i in middlewares:
m = i.process_message(msg)
if (m is None):
return None
msg = m
msg.verify()
if (msg.deliver_to.channel_id == master.c... |
def main():
args = _parse_commandline()
wallet = LocalWallet.generate()
ledger = LedgerClient(NetworkConfig.latest_stable_testnet())
faucet_api = FaucetApi(NetworkConfig.latest_stable_testnet())
wallet_balance = ledger.query_bank_balance(wallet.address())
while (wallet_balance < (10 ** 18)):
... |
.skipcomplex
def test_interpolate_with_arguments():
from firedrake.adjoint import ReducedFunctional, Control, taylor_test
mesh = UnitSquareMesh(10, 10)
V1 = FunctionSpace(mesh, 'CG', 1)
V2 = FunctionSpace(mesh, 'CG', 2)
(x, y) = SpatialCoordinate(mesh)
expr = (x + y)
f = interpolate(expr, V1... |
def extract_executable(filename):
with open(filename, 'r', encoding='utf-8') as filehandle:
for line in filehandle.readlines():
splitline = line.strip().split()
if ((len(splitline) > 1) and (splitline[0] == 'EXECUTABLE')):
return splitline[1]
return None |
(Output('sleep-exclamation', 'style'), [Input('sleep-date', 'children')])
def show_sleep_exclamation(dummy):
show = {'display': 'inline-block', 'fontSize': '1rem', 'color': orange, 'paddingLeft': '1%'}
hide = {'display': 'none'}
max_sleep_date = app.session.query(func.max(ouraSleepSummary.report_date)).firs... |
def build_amg_index_sets(L_sizes):
neqns = L_sizes[0][0]
velocityDOF = []
for start in range(1, 3):
velocityDOF.append(np.arange(start=start, stop=(1 + neqns), step=3, dtype='i'))
velocityDOF_full = np.vstack(velocityDOF).transpose().flatten()
velocity_u_DOF = []
velocity_u_DOF.appen... |
def train_ppo_for_beginners(args):
from ppo_for_beginners.ppo import PPO
from ppo_for_beginners.network import FeedForwardNN
hyperparameters = {}
total_timesteps = 0
if (args.env == 'Pendulum-v0'):
hyperparameters = {'timesteps_per_batch': 2048, 'max_timesteps_per_episode': 200, 'gamma': 0.9... |
.parametrize('decay', [0.995, 0.9])
.parametrize('use_num_updates', [True, False])
.parametrize('explicit_params', [True, False])
def test_val_error(decay, use_num_updates, explicit_params):
torch.manual_seed(0)
x_train = torch.rand((100, 10))
y_train = torch.rand(100).round().long()
x_val = torch.rand(... |
class OptionSeriesTilemapSonificationContexttracksMappingTime(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):
se... |
def define_def_map() -> Tuple[(List, DefMap)]:
def_map = DefMap()
instruction_list = [Assignment(Variable('v', Integer.int32_t(), 1), Variable('u', Integer.int32_t())), Assignment(Variable('v', Integer.int32_t(), 3), Constant(4)), Assignment(Variable('w', Integer.int32_t(), 1), Variable('v', Integer.int32_t(), ... |
def extractAdammentranslatesWordpressCom(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, ... |
.parametrize('y_true, y_pred', [(uniform_regression_inputs.target, uniform_regression_inputs.preds), (normal_regression_inputs.target, normal_regression_inputs.preds)])
def test_mae(y_true, y_pred):
sk_preds = y_pred.numpy()
sk_target = y_true.numpy()
sk_score = mean_absolute_error(y_true=sk_target, y_pred=... |
class DuckInterface(SqliteInterface):
target = duck
supports_foreign_key = False
requires_subquery_name = True
def _create_connection(self):
import duckdb
return duckdb.connect((self._filename or ':memory:'))
def quote_name(self, name):
return f'"{name}"'
def rollback(sel... |
class OptionSeriesTilemapData(Options):
def accessibility(self) -> 'OptionSeriesTilemapDataAccessibility':
return self._config_sub_data('accessibility', OptionSeriesTilemapDataAccessibility)
def className(self):
return self._config_get(None)
def className(self, text: str):
self._conf... |
def test_localisedNames(tmpdir):
tmpdir = str(tmpdir)
testDocPath = os.path.join(tmpdir, 'testLocalisedNames.designspace')
testDocPath2 = os.path.join(tmpdir, 'testLocalisedNames_roundtrip.designspace')
masterPath1 = os.path.join(tmpdir, 'masters', 'masterTest1.ufo')
masterPath2 = os.path.join(tmpdi... |
class TestPlaying(util.TestCase):
MARKUP = '\n <!DOCTYPE html>\n <html>\n <body>\n\n <video id="vid" width="320" height="240" controls>\n <source src="movie.mp4" type="video/mp4">\n <source src="movie.ogg" type="video/ogg">\n Your browser does not support the video tag.\n </video>\n\n ... |
class OptionPlotoptionsSunburstSonificationTracksMappingTime(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):
sel... |
class SchedulerServiceServicer(object):
def addNamespace(self, request, context):
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def getNamespace(self, request, context):
context.... |
class UnreadTopicsView(LoginRequiredMixin, ListView):
context_object_name = 'topics'
paginate_by = machina_settings.FORUM_TOPICS_NUMBER_PER_PAGE
template_name = 'forum_tracking/unread_topic_list.html'
def get_queryset(self):
forums = self.request.forum_permission_handler.get_readable_forums(Foru... |
class TestPublishUnpublish():
PUBLISH_UNPUBLISH_WITH_ARGS = [(ml.publish_model, True), (ml.unpublish_model, False)]
PUBLISH_UNPUBLISH_FUNCS = [item[0] for item in PUBLISH_UNPUBLISH_WITH_ARGS]
def setup_class(cls):
cred = testutils.MockCredential()
firebase_admin.initialize_app(cred, {'projec... |
class StripePaymentsManager():
def get_credentials(event=None):
if (not event):
settings = get_settings(from_db=True)
if ((settings['app_environment'] == 'development') and settings['stripe_test_secret_key'] and settings['stripe_test_publishable_key']):
return {'SECRE... |
class QResolver():
RDTYPE_A = 1
RDTYPE_NS = 2
RDTYPE_CNAME = 5
RDTYPE_PTR = 12
RCODE_SERVFAIL = 2
RCODE_NXDOMAIN = 3
RCODE_REFUSED = 5
SOCKET_TIMEOUT = 3
def _build_query(fqdn, rdtype=RDTYPE_A):
qname = b''.join([(len(x).to_bytes(1, 'big') + x) for x in fqdn.encode('idna').sp... |
class DumpRecord(abstract.AbstractRecord):
grammar = dump.DumpGrammar()
ext = 'dump'
def evaluate_oid(self, oid):
return univ.ObjectIdentifier(oid)
def evaluate_value(self, oid, tag, value, **context):
try:
value = self.grammar.TAG_MAP[tag](value)
except Exception as ... |
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': {... |
()
_option
('--runtime', default='3.8', help='Python version to use')
('--toolkit', default='pyside6', help='Toolkit and API to use')
('--environment', default=None, help='EDM environment to use')
('--no-environment-vars', is_flag=True, help='Do not set ETS_TOOLKIT and QT_API')
def test(edm, runtime, toolkit, environme... |
def build_image(path):
log.debug('build_image()')
log.debug('Request Path : {0}', path)
request_path = path[1:]
if (request_path == 'favicon.ico'):
return []
decoded_url = base64.b64decode(request_path).decode('utf-8')
log.debug('decoded_url : {0}', decoded_url)
image_urls = get_imag... |
class DictTransform():
def __init__(self, transforms: Dict[(RVIdentifier, dist.Transform)]):
self.transforms = transforms
def __call__(self, node_vals: RVDict) -> RVDict:
return {node: self.transforms[node](val) for (node, val) in node_vals.items()}
def inv(self, node_vals: RVDict) -> RVDict... |
def find_top_similar_results(df: pd.DataFrame, query: str, n: int):
if (len(df.index) < n):
n = len(df.index)
embedding = create_embedding(query)
df1 = df.copy()
df1['similarities'] = df1['ada_search'].apply((lambda x: cosine_similarity(x, embedding)))
best_results = df1.sort_values('similar... |
def main():
module_spec = schema_to_module_spec(versioned_schema)
mkeyname = 'name'
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 IDName():
def __init__(self):
self.id = uuid1()
self.name = None
def __str__(self):
if self.name:
return self.name
else:
return str(self.id)
def pack_message(self, msg):
return (self, msg)
def unpack_message(self, msg):
(sende... |
def make_versioned(mapper=sa.orm.mapper, session=sa.orm.session.Session, manager=versioning_manager, plugins=None, options=None, user_cls='User', cares_about_checker=None):
if (plugins is not None):
manager.plugins = plugins
if (options is not None):
manager.options.update(options)
if cares_... |
('Favourite Sessions > Favourite Sessions Collection > Create a Favourite Session')
def favourite_sessions_list_post(transaction):
with stash['app'].app_context():
event = EventFactoryBasic()
track = TrackFactoryBase()
session = SessionSubFactory(event=event, track=track)
db.session.... |
def test_color_set(session):
data = {'irisSeqId': '1111111', 'irisTags': ['DeltaAdminTextMessage', 'is_from_iris_fanout'], 'messageMetadata': {'actorFbId': '1234', 'adminText': 'You changed the chat theme to Orange.', 'folderId': {'systemFolderId': 'INBOX'}, 'messageId': 'mid.$XYZ', 'offlineThreadingId': '', 'skipB... |
class Solution():
def minSubArrayLen(self, s: int, nums: List[int]) -> int:
mlen = (len(nums) + 1)
start = 0
ss = 0
for (i, n) in enumerate(nums):
ss += n
while (ss >= s):
mlen = min(((i - start) + 1), mlen)
ss -= nums[start]
... |
def Rotate(kwargs: dict) -> OutgoingMessage:
compulsory_params = ['id', 'rotation']
optional_params = []
utility.CheckKwargs(kwargs, compulsory_params)
msg = OutgoingMessage()
msg.write_int32(kwargs['id'])
msg.write_string('Rotate')
for i in range(3):
msg.write_float32(kwargs['rotati... |
def resetRawInProgress():
print('Resetting any stalled downloads from the previous session.')
commit_interval = 50000
step = 50000
commit_every = 30
last_commit = time.time()
with db.session_context(override_timeout_ms=((60 * 1000) * 30)) as sess:
try:
print('Getting minimum ... |
def extractToffeedragontlCom(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 test_block_bodies_request_with_extra_unrequested_bodies():
headers_bundle = mk_headers((2, 3), (8, 4), (0, 1), (0, 0))
(headers, bodies, transactions_roots, trie_data_dicts, uncles_hashes) = zip(*headers_bundle)
transactions_bundles = tuple(zip(transactions_roots, trie_data_dicts))
bodies_bundle = t... |
(scope='function')
def async_w3(async_w3_base, async_result_generator_middleware):
async_w3_base.middleware_onion.add(async_result_generator_middleware)
async_w3_base.middleware_onion.add(async_attrdict_middleware)
async_w3_base.middleware_onion.add(async_local_filter_middleware)
return async_w3_base |
class OptionChartParallelaxesAccessibility(Options):
def description(self):
return self._config_get(None)
def description(self, text: str):
self._config(text, js_type=False)
def enabled(self):
return self._config_get(None)
def enabled(self, flag: bool):
self._config(flag,... |
class TestIntConversions(TestCase):
def test_int2str(self):
self.assertEqual('three', utils.int2str(3))
self.assertEqual('3rd', utils.int2str(3, adjective=True))
self.assertEqual('5th', utils.int2str(5, adjective=True))
self.assertEqual('15', utils.int2str(15))
def test_str2int(s... |
_exempt
def RoomsAvailableOnDates(request, location_slug):
location = get_object_or_404(Location, slug=location_slug)
arrive = maya.parse(request.POST['arrive']).date
depart = maya.parse(request.POST['depart']).date
free_rooms = location.rooms_free(arrive, depart)
rooms_capacity = {}
for room in... |
class OptionSeriesVariwideSonificationTracksMappingLowpassResonance(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 get_tx_tooltip(status: TxStatus, conf: int) -> str:
text = ((str(conf) + ' confirmation') + ('s' if (conf != 1) else ''))
if (status == TxStatus.UNMATURED):
text = ((text + '\n') + _('Unmatured'))
elif (status in TX_STATUS):
text = ((text + '\n') + TX_STATUS[status])
return text |
class SchemaHandler(HttpErrorMixin, APIHandler):
async def get(self, schemaspace):
schemaspace = url_unescape(schemaspace)
try:
schema_manager = SchemaManager.instance()
schemas = schema_manager.get_schemaspace_schemas(schemaspace)
except (ValidationError, ValueError,... |
def print_clients(player_number):
return
for c in p.cl.clients:
if (c.player_number == player_number):
logging.info('Player {}: {} {} BPM Pitch {:.2f}% ({:.2f}%) Beat {} Beatcnt {} pos {:.6f}'.format(c.player_number, c.model, c.bpm, ((c.pitch - 1) * 100), ((c.actual_pitch - 1) * 100), c.beat... |
def get_kernel_data_files(argv):
if any((arg.startswith('bdist') for arg in argv)):
executable = 'python'
elif any((arg.startswith('install') for arg in argv)):
executable = sys.executable
else:
return []
install_custom_kernel(executable)
return [(icoconut_custom_kernel_insta... |
def upload_save_data_body_v2(save_data: bytes, save_key_data: dict[(str, Any)]) -> tuple[(bytes, bytes)]:
boundary = f'__{random_digit_string(9)}-'.encode('utf-8')
body = b''
body += ((b'--' + boundary) + b'\r\n')
body += b'Content-Disposition: form-data; name="key"\r\n'
body += b'Content-Type: text... |
def extractEssentialvillainessWordpressCom(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... |
def multisubset2(numbers, subsets, adder=(lambda x, y: (x + y)), zero=0):
partition_size = (1 + int(math.log((len(subsets) + 1))))
numbers = numbers[:]
while ((len(numbers) % partition_size) != 0):
numbers.append(zero)
power_sets = []
for i in range(0, len(numbers), partition_size):
... |
class Pot():
def __init__(self):
self._pot = collections.Counter()
self._uid = str(uuid.uuid4().hex)
def __repr__(self):
return f'<Pot n_chips={self.total}>'
def __getitem__(self, player: Player):
if (not isinstance(player, Player)):
raise ValueError(f'Index the p... |
def test_dataset_correlation_metric_success() -> None:
current_dataset = pd.DataFrame({'numerical_feature_1': [0, 2, 2, 2, 0], 'numerical_feature_2': [0, 2, 2, 2, 0], 'category_feature': [1, 2, 4, 2, 1], 'target': [0.0, 2.0, 2.0, 2.0, 0.0], 'prediction': [0.0, 2.0, 2.0, 2.0, 0.0]})
data_mapping = ColumnMapping(... |
class PullRequest(Node):
baseRef: Optional[Ref]
baseRefName: str
body: str
closed: bool
headRef: Optional[Ref]
headRefName: str
number: GitHubNumber
_repository: GraphQLId
title: str
url: str
def repository(self, info: GraphQLResolveInfo) -> Repository:
return github_... |
def main():
parser = argparse.ArgumentParser(description='LiteSATA standalone core generator')
parser.add_argument('config', help='YAML config file')
args = parser.parse_args()
core_config = yaml.load(open(args.config).read(), Loader=yaml.Loader)
for (k, v) in core_config.items():
replaces =... |
def _select_features_for_corr(dataset: pd.DataFrame, data_definition: DataDefinition) -> tuple:
num = data_definition.get_columns(ColumnType.Numerical)
cat = data_definition.get_columns(ColumnType.Categorical)
num_for_corr = []
cat_for_corr = []
for col in num:
col_name = col.column_name
... |
class BanForm(CSRFForm):
name = 'Add ban'
action = '.mod_bans'
ban_ip4 = StringField('IPv4 address', [DataRequired(), IPAddress(ipv4=True, ipv6=False)], description='IPv4 address to ban.', render_kw={'placeholder': '123.123.123.123'})
ban_ip4_end = StringField('IPv4 address end range', [Optional(), IPAd... |
def test_generic_search_lt_gt(frontend_db, backend_db):
insert_test_fo(backend_db, 'uid_1', size=10)
insert_test_fo(backend_db, 'uid_2', size=20)
insert_test_fo(backend_db, 'uid_3', size=30)
assert (set(frontend_db.generic_search({'size': {'$lt': 25}})) == {'uid_1', 'uid_2'})
assert (set(frontend_db... |
def test_slate_hybridization_jacobi_prec_A00():
(a, L, W) = setup_poisson_3D()
w = Function(W)
params = {'mat_type': 'matfree', 'ksp_type': 'preonly', 'pc_type': 'python', 'pc_python_type': 'firedrake.HybridizationPC', 'hybridization': {'ksp_type': 'cg', 'pc_type': 'none', 'ksp_rtol': 1e-12, 'mat_type': 'ma... |
def read_associate_def(line: str):
assoc_match = FRegex.ASSOCIATE.match(line)
if (assoc_match is not None):
trailing_line = line[assoc_match.end(0):]
match_char = find_paren_match(trailing_line)
if (match_char < 0):
return ('assoc', [])
var_words = separate_def_list(t... |
class MySQLVersion():
def __init__(self, version_str):
self._version_str = version_str
self._version = ''
self._fork = ''
self._build = ''
self.parse_str()
def parse_str(self):
segments = self._version_str.split('-')
self._version = segments[0]
if ... |
class Polling(threading.Thread):
def __init__(self, master_list, master_info, callback, update_hz):
threading.Thread.__init__(self)
self.masterList = master_list
self.masterInfo = master_info
self.__callback = callback
self.__update_hz = update_hz
self.start()
def... |
class SearchSpider(Spider, SeleniumSpiderMixin):
allowed_domains = ('linkedin.com',)
def __init__(self, start_url, driver=None, name=None, *args, **kwargs):
super().__init__(*args, name=name, **kwargs)
self.start_url = start_url
self.driver = (driver or build_driver())
self.user_... |
.standalone
def main():
pd = tvtk.PolyData()
pd.points = np.random.random((1000, 3))
verts = np.arange(0, 1000, 1)
verts.shape = (1000, 1)
pd.verts = verts
pd.point_data.scalars = np.random.random(1000)
pd.point_data.scalars.name = 'scalars'
from mayavi.sources.vtk_data_source import VTK... |
class Generator(AbstractODSGenerator):
MIN_ROWS: int = 40
MAX_COLUMNS: int = 40
OUTPUT_FILE: str = 'rp2_full_report.ods'
TEMPLATE_SHEETS_TO_KEEP: Set[str] = {'__Summary'}
__in_out_sheet_transaction_2_row: Dict[(AbstractTransaction, int)] = {}
__tax_sheet_year_2_row: Dict[(_AssetAndYear, int)] = ... |
class TweetView(ModelView):
column_list = ('name', 'user_name', 'text')
column_sortable_list = ('name', 'text')
column_filters = (filters.FilterEqual('name', 'Name'), filters.FilterNotEqual('name', 'Name'), filters.FilterLike('name', 'Name'), filters.FilterNotLike('name', 'Name'), filters.BooleanEqualFilter... |
def get_settings_folder():
home = os.getenv('USERPROFILE')
if (home is None):
if (android is not None):
home = '/storage/sdcard0/'
else:
home = os.getenv('HOME')
if is_venv():
home = sys.prefix
if os.path.isdir(os.path.join(home, '~expyriment')):
r... |
class AccountWizard(BaseWizard, MessageBoxMixin):
HELP_DIRNAME = 'account-wizard'
_last_page_id: Optional[AccountPage] = None
_selected_device: Optional[Tuple[(str, DeviceInfo)]] = None
_keystore: Optional[KeyStore] = None
_keystore_type = ResultType.UNKNOWN
def __init__(self, main_window: Elect... |
def test_hyperparameter_job_config():
jc = hpo_job.HyperparameterTuningJobConfig(tuning_strategy=hpo_job.HyperparameterTuningStrategy.BAYESIAN, tuning_objective=hpo_job.HyperparameterTuningObjective(objective_type=hpo_job.HyperparameterTuningObjectiveType.MAXIMIZE, metric_name='test_metric'), training_job_early_sto... |
def test_select_subselect_with_alias():
sql_statement = '\n SELECT count(*)\n FROM (\n SELECT count(id) AS some_alias, some_column\n FROM mytable\n GROUP BY some_colun\n HAVING count(id) > 1\n ) AS foo\n '
actual = extract_signature(sql_statement)
assert ('SELECT FROM... |
class OptionPlotoptionsPieSonificationDefaultspeechoptionsMapping(Options):
def pitch(self) -> 'OptionPlotoptionsPieSonificationDefaultspeechoptionsMappingPitch':
return self._config_sub_data('pitch', OptionPlotoptionsPieSonificationDefaultspeechoptionsMappingPitch)
def playDelay(self) -> 'OptionPlotopt... |
def test_content_transfer_encoding_header(client):
data = b'--BOUNDARY\r\nContent-Disposition: form-data; name="file"; filename="bytes"\r\nContent-Transfer-Encoding: Base64Content-Type: application/x-falcon\r\n\r\nUGVyZWdyaW5lIEZhbGNvbiADLgA=\r\n--BOUNDARY\r\nContent-Disposition: form-data; name="empty"\r\nContent-... |
class OptionSeriesWaterfallSonificationContexttracksMappingLowpassResonance(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... |
.parametrize('request_1__group_by', ['42'])
.parametrize('request_2__group_by', ['something else'])
.usefixtures('request_1', 'request_2')
def test_users(dashboard_user, endpoint, session):
response = dashboard_user.get('dashboard/api/users/{0}'.format(endpoint.id))
assert (response.status_code == 200)
data... |
class TestsAchromatic(util.ColorAsserts, unittest.TestCase):
def test_achromatic(self):
self.assertEqual(Color('okhsv', [270, 0.5, 0]).is_achromatic(), True)
self.assertEqual(Color('okhsv', [270, 0, 0.5]).is_achromatic(), True)
self.assertEqual(Color('okhsv', [270, 1e-06, 0.5]).is_achromatic... |
class BlockDeclList(Block):
decl: Decl
block: Block
def decl_env(self) -> (Decl.env decl):
return self.env
def block_same(self, decl) -> (Block.same block):
return (self.same + [decl.new])
def block_env(self, decl) -> (Block.env block):
return append_dict(self.env, decl.ne... |
def extractNotsofriendlytranslationsWordpressCom(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... |
class PurgeInventoryTest(ForsetiTestCase):
def setUp(self):
ForsetiTestCase.setUp(self)
def tearDown(self):
ForsetiTestCase.tearDown(self)
def populate_data(self):
self.engine = create_test_engine()
initialize(self.engine)
self.scoped_sessionmaker = db.create_scoped_s... |
class OperatorObsidian():
def dedup(self, pages):
print('')
print('# Dedup Obsidian pages')
print('')
client = DBClient()
deduped_pages = []
for (page_id, page) in pages.items():
name = page['name']
print(f'Dedupping page, title: {name}')
... |
def parse_web_form_error(html_text, variant='a'):
soup = BeautifulSoup(html_text, 'html.parser')
if (variant == 'a'):
classes = 'alert alert-danger'
elif (variant == 'b'):
classes = 'alert alert-danger alert-dismissable'
alerts = soup.findAll('div', class_=classes)
assert (len(alerts... |
class OptionSeriesBarSonificationTracksMappingFrequency(Options):
def mapFunction(self):
return self._config_get(None)
def mapFunction(self, value: Any):
self._config(value, js_type=False)
def mapTo(self):
return self._config_get(None)
def mapTo(self, text: str):
self._co... |
def main(page: ft.Page):
def page_resize(e):
pw.value = f'{page.width} px'
pw.update()
page.on_resize = page_resize
pw = ft.Text(bottom=50, right=50, style='displaySmall')
page.overlay.append(pw)
page.add(ft.ResponsiveRow([ft.Container(ft.Text('Column 1'), padding=5, bgcolor=ft.color... |
('Setup crossenv - {arch}')
def setup_crossenv(python: Command, pip: Command, arch: str='linux-x86_64') -> Command:
cpython = ProjectPaths('cpython', arch)
crossenv = ProjectPaths('crossenv', arch)
crossenv.clean()
pip.install('crossenv')
python('-m', 'crossenv', ((cpython.install / 'bin') / 'python... |
def test_scenario_a():
winner_indices = [0, 1]
player_cards = [[Card(rank='ace', suit='hearts'), Card(rank='8', suit='diamonds')], [Card(rank='ace', suit='spades'), Card(rank='3', suit='diamonds')], [Card(rank='2', suit='spades'), Card(rank='4', suit='diamonds')]]
board_cards = [Card(rank='ace', suit='clubs... |
class TestHorizontalTypePropagation():
def test_backwards(self):
cfg = ControlFlowGraph()
cfg.add_node(BasicBlock(0, instructions=[Assignment((x := Variable('x', UnknownType(), ssa_label=0)), Constant(170, Integer.char()))]))
TypePropagation().propagate(TypeGraph.from_cfg(cfg))
asser... |
(IBodyProducer)
class StringProducer():
def __init__(self, body):
self.body = bytes(body, 'utf-8')
self.length = len(body)
def startProducing(self, consumer):
consumer.write(self.body)
return defer.succeed(None)
def pauseProducing(self):
pass
def stopProducing(sel... |
class LEDDemoHandler(Handler):
info = Instance(UIInfo)
running = Bool(True)
alive = Bool(True)
def init(self, info):
self.info = info
Thread(target=self._update_counter).start()
return True
def closed(self, info, is_ok):
self.running = False
while self.alive:
... |
('pyscf')
('thermoanalysis')
def test_opt_h2o_do_hess():
T = 398.15
run_dict = {'geom': {'type': 'redund', 'fn': 'lib:h2o.xyz'}, 'calc': {'type': 'pyscf', 'basis': 'sto3g', 'pal': 2, 'verbose': 0}, 'opt': {'thresh': 'gau', 'do_hess': True, 'T': T}}
run_result = run_from_dict(run_dict)
thermo = run_resul... |
.xfail(raises=ImageComparisonFailure, reason='Matplotlib plots for reasons a different image size.')
def test_average_regions_plot_log_vmin_vmax_colormap():
outfile = NamedTemporaryFile(suffix='.png', prefix='average_region_log1p', delete=False)
matrix = (ROOT + 'hicAverageRegions/result_range_100000.npz')
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.