code stringlengths 281 23.7M |
|---|
def test_cookies_with_domain_and_path():
cookies =
cookies.set('name', 'value', domain='example.com', path='/subpath/1')
cookies.set('name', 'value', domain='example.com', path='/subpath/2')
cookies.clear(domain='example.com', path='/subpath/1')
assert (len(cookies) == 1)
cookies.delete('name',... |
def webclient_options(session, *args, **kwargs):
account = session.account
clientoptions = account.db._saved_webclient_options
if (not clientoptions):
account.db._saved_webclient_options = settings.WEBCLIENT_OPTIONS.copy()
clientoptions = account.db._saved_webclient_options
try:
... |
class tools():
data = None
names = None
category = None
category_data = None
def __init__(self):
system = sys()
with open((system.conf_dir + '/Tool-X/core/data.json')) as data_file:
self.data = json.load(data_file)
with open((system.conf_dir + '/Tool-X/core/cat.js... |
def lambda_version_generator(lambda_client, lambda_function):
next_marker = None
response = lambda_client.list_versions_by_function(FunctionName=lambda_function['FunctionArn'])
while (next_marker != ''):
next_marker = ''
versions = response['Versions']
for version in versions:
... |
('orca')
def test_ch4_composite(this_dir):
'G2MS/R from
geom = geom_loader((this_dir / '00_ch4.xyz'))
calc_kwargs = {'calcs': {'ccsdt': {'type': 'orca', 'keywords': 'ccsd(t) 6-31G(d) tightscf'}, 'mp2_high': {'type': 'orca', 'keywords': 'mp2 6-311+G(2df,2p) tightscf'}, 'mp2_low': {'type': 'orca', 'keywords'... |
def _get_kwargs(*, client: Client, json_body: BodyCreateToken) -> Dict[(str, Any)]:
url = '{}/tokens/'.format(client.base_url)
headers: Dict[(str, str)] = client.get_headers()
cookies: Dict[(str, Any)] = client.get_cookies()
json_json_body = json_body.to_dict()
return {'method': 'post', 'url': url, ... |
class OptionPlotoptionsWordcloudSonificationTracksMappingPitch(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: str):
se... |
def Check_ExprEqvInContext(proc, expr0, stmts0, expr1, stmts1=None):
assert (len(stmts0) > 0)
stmts1 = (stmts1 or stmts0)
ctxt0 = ContextExtraction(proc, stmts0)
ctxt1 = ContextExtraction(proc, stmts1)
p0 = ctxt0.get_control_predicate()
G0 = ctxt0.get_pre_globenv()
p1 = ctxt1.get_control_pre... |
class OptionPlotoptionsNetworkgraphSonificationDefaultinstrumentoptionsMappingPan(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, te... |
class OptionSeriesTreemapDataAccessibility(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,... |
def test_jenkins_job_files(host):
assert host.file('/jenkins/jobs').is_directory
assert (host.file('/jenkins/jobs').user == 'jenkins')
assert (host.file('/jenkins/jobs').group == 'jenkins')
assert host.file('/jenkins/jobs/test_job').is_directory
assert (host.file('/jenkins/jobs/test_job').user == 'j... |
def _perform_key_renames(tree, changes=KEY_RENAMES):
for (section, from_key, to_key, verbose, supported) in changes:
if (section not in tree):
log.warning('No section `%s` found in configuration! This will almost certainly end up causing an error later on.', section)
continue
... |
def terrain(range, **traits):
_data = {'red': [(0.0, 0.2, 0.2), (0.15, 0.0, 0.0), (0.25, 0.0, 0.0), (0.5, 1.0, 1.0), (0.75, 0.5, 0.5), (1.0, 1.0, 1.0)], 'green': [(0.0, 0.2, 0.2), (0.15, 0.6, 0.6), (0.25, 0.8, 0.8), (0.5, 1.0, 1.0), (0.75, 0.36, 0.36), (1.0, 1.0, 1.0)], 'blue': [(0.0, 0.6, 0.6), (0.15, 1.0, 1.0), (... |
def test_clean_latex(cli, build_resources):
(books, tocs) = build_resources
path = books.joinpath('clean_cache')
result = cli.invoke(build, path.as_posix())
assert (result.exit_code == 0)
build_path = path.joinpath('_build')
assert build_path.exists()
os.mkdir(os.path.join(build_path, 'latex... |
def parse_refreshed_token(uses_pkce: bool) -> Callable:
def func(request: Request, response: Response, refresh_token: str) -> Token:
handle_errors(request, response)
refreshed = Token(response.content, uses_pkce)
if (refreshed.refresh_token is None):
refreshed._refresh_token = re... |
def type_aware_apply_formatters_to_dict_keys_and_values(key_formatters: Callable[([Any], Any)], value_formatters: Callable[([Any], Any)], dict_like_object: Union[(AttributeDict[(str, Any)], Dict[(str, Any)])]) -> Union[(ReadableAttributeDict[(str, Any)], Dict[(str, Any)])]:
formatted_dict = dict(((key_formatters(k)... |
('requests.post')
def test_deploy_sucessful(post, api_key, app_id, user, region, revision, changelog, description):
post.return_value = DeploymentResponseSuccessfulMock()
deployment = Deployment(api_key, app_id, user, region)
response = deployment.deploy(revision, changelog, description)
payload = deplo... |
def test_split_batches():
request_info1 = dm.RequestInfo(input=np.array(range(10)), parameters={})
request_info2 = dm.RequestInfo(input=np.array(range(10)), parameters={})
batch1 = dm.BatchObject(uid='00', requests_info=[request_info1, request_info2], model=small_batch_stub_model, request_objects=[])
re... |
def response(code, url, params, cc=None, etag=None, vary=None) -> Response:
r = Response(status_code=code, url=(url + (('&' + urlencode(params)) if params else '')), headers={}, content=None)
if isinstance(cc, int):
cc = f'public, max-age={cc}'
h = {'Cache-Control': cc, 'ETag': etag, 'Vary': vary}
... |
def _start():
global patch, name, path, monitor
global use_old_version, dispatcher, osc_server
global osc_address, osc_port, prefix, output_scale, output_offset
osc_address = patch.getstring('osc', 'address', default=socket.gethostbyname(socket.gethostname()))
osc_port = patch.getint('osc', 'port')
... |
.parametrize('app,expectation', [(make_app_max_parts(max_files=1), pytest.raises(MultiPartException)), (Starlette(routes=[Mount('/', app=make_app_max_parts(max_files=1))]), does_not_raise())])
def test_max_files_is_customizable_low_raises(app, expectation, test_client_factory):
client = test_client_factory(app)
... |
class bsn_log(bsn_header):
version = 4
type = 4
experimenter = 6035143
subtype = 63
def __init__(self, xid=None, loglevel=None, data=None):
if (xid != None):
self.xid = xid
else:
self.xid = None
if (loglevel != None):
self.loglevel = loglev... |
class TestVectorSTorage(unittest.IsolatedAsyncioTestCase):
async def test_object(self):
data = HashValue.hash_data('1233'.encode('utf-8'))
print(data.to_base58())
print(data.to_base36())
data2 = HashValue.from_base58(data.to_base58())
self.assertEqual(data.to_base36(), data2.... |
class OptionPlotoptionsOrganizationSonificationTracksMappingGapbetweennotes(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... |
def getVerbosityFormat(verbosity, fmt=' %(message)s', addtime=True, padding=True):
if (verbosity > 1):
if (verbosity > 3):
fmt = (' | %(module)15.15s-%(levelno)-2d: %(funcName)-20.20s |' + fmt)
if (verbosity > 2):
fmt = (' +%(relativeCreated)5d %(thread)X %(name)-25.25s %(lev... |
def base_form_assembly_visitor(expr, tensor, bcs, diagonal, form_compiler_parameters, mat_type, sub_mat_type, appctx, options_prefix, zero_bc_nodes, weight, *args):
if isinstance(expr, (ufl.form.Form, slate.TensorBase)):
return _assemble_form(expr, tensor=tensor, bcs=bcs, diagonal=diagonal, mat_type=mat_typ... |
class SerializationTransform(DashTransform):
def apply_serverside(self, callbacks):
for callback in callbacks:
f = callback.f
callback.f = self._unpack_pack_callback(callback)(f)
return callbacks
def _try_load(self, data: Any, ann=None):
raise NotImplementedError
... |
class DollControl(InstantSpellCardAction):
card_usage = 'launch'
def apply_action(self):
tl = self.target_list
assert (len(tl) == 2)
src = self.source
(attacker, victim) = tl
cards = user_choose_cards(self, attacker, ['cards', 'showncards'])
g = self.game
... |
def test_loggify():
tmpdir = tempfile.mkdtemp(prefix='copr-rpmbuild-test-loggify-')
input_file = os.path.join(tmpdir, 'input')
output_file = os.path.join(tmpdir, 'output')
with open(input_file, 'w') as fd:
fd.write(INPUT)
subprocess.call('copr-rpmbuild-loggify < {0} > {1}'.format(input_file,... |
class OptionSeriesDependencywheelSonificationPointgrouping(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 _LabelledAddrPrefix(_AddrPrefix):
_LABEL_PACK_STR = '!3B'
_WITHDRAW_LABELS = [8388608, 0]
def __init__(self, length, addr, labels=None, **kwargs):
labels = (labels if labels else [])
assert isinstance(labels, list)
is_tuple = isinstance(addr, tuple)
if is_tuple:
... |
class MyScaffoldContract(Contract):
contract_id = PublicId.from_str('fetchai/scaffold:0.1.0')
def get_raw_transaction(cls, ledger_api: LedgerApi, contract_address: str, **kwargs: Any) -> JSONLike:
raise NotImplementedError
def get_raw_message(cls, ledger_api: LedgerApi, contract_address: str, **kwar... |
class TestEIAProduction(TestEIA):
def test_fetch_production_mix(self):
self.adapter.register_uri(GET, ANY, json=json.loads(resources.files('parsers.test.mocks.EIA').joinpath('US_NW_AVRN-wind.json').read_text()))
data_list = EIA.fetch_production_mix('US-NW-PGE', self.session)
expected = [{'zo... |
class TestLinkCRC(unittest.TestCase):
def test_link_crc(self):
def generator(dut):
dut.errors = 0
(yield dut.crc.data.eq(0))
(yield dut.crc.ce.eq(1))
(yield dut.crc.reset.eq(1))
(yield)
(yield dut.crc.reset.eq(0))
datas = []... |
('usaspending_api.etl.transaction_loaders.fpds_loader.connection')
('usaspending_api.etl.transaction_loaders.derived_field_functions_fpds._fetch_subtier_agency_id', return_value=1)
('usaspending_api.etl.transaction_loaders.fpds_loader._extract_broker_objects')
('usaspending_api.etl.transaction_loaders.derived_field_fun... |
.parametrize('scheme', PERTURBATION_SCHEMES)
def test_simulated_annealing_with_time_constraints(permutation, scheme):
max_processing_time = 1
np.random.seed(1)
distance_matrix = np.random.rand(5000, 5000)
captured_output = StringIO()
sys.stdout = captured_output
simulated_annealing.solve_tsp_sim... |
class AIFlowHelpFormatter(argparse.HelpFormatter):
def _format_action(self, action: Action):
if isinstance(action, argparse._SubParsersAction):
parts = []
action_header = self._format_action_invocation(action)
action_header = ('%*s%s\n' % (self._current_indent, '', action... |
class TestStrftimeEx(unittest.TestCase):
def test_strftimeEx_01(self):
t = 0.123
fmt = '%(ms)'
result = strftimeEx(fmt, t)
self.assertEqual(result, '123')
def test_strftimeEx_02(self):
t = 0.123456
fmt = '%(us)'
result = strftimeEx(fmt, t)
self.ass... |
def dq_a2(m0, m1, m2, o0, o1, o2, n0, n1, n2):
m0 = mpmath.mpf(m0)
m1 = mpmath.mpf(m1)
m2 = mpmath.mpf(m2)
o0 = mpmath.mpf(o0)
o1 = mpmath.mpf(o1)
o2 = mpmath.mpf(o2)
n0 = mpmath.mpf(n0)
n1 = mpmath.mpf(n1)
n2 = mpmath.mpf(n2)
x0 = (- o0)
x1 = (n0 + x0)
x2 = (m0 + x0)
... |
class Config(object):
ENV = 'devel'
DATA_DIR = os.path.join(os.path.dirname(__file__), '../../data')
DATABASE = os.path.join(DATA_DIR, 'copr.db')
OPENID_STORE = os.path.join(DATA_DIR, 'openid_store')
WHOOSHEE_DIR = os.path.join(DATA_DIR, 'whooshee')
SECRET_KEY = 'THISISNOTASECRETATALL'
BACKE... |
class Query():
def __init__(self, **kwargs):
order_by = kwargs.pop('order_by')
if ((not order_by) or (not isinstance(order_by, str))):
raise ValueError('order_by field must be a non-empty string')
if (order_by not in _RESERVED_FILTERS):
if order_by.startswith('/'):
... |
def EUCL_DIST_B(a, b, support, attr1, attr2):
dist_a = (sum([descendant.dist for descendant in a[0].leaves() if (descendant.props[attr1] in (a[1] - b[1]))]) / len([i for i in a[0].leaves()]))
dist_b = (sum([descendant.dist for descendant in b[0].leaves() if (descendant.props[attr2] in (b[1] - a[1]))]) / len([i ... |
class Solution():
def minMoves2(self, nums: List[int]) -> int:
nums.sort()
(a, b) = (0, 0)
if ((len(nums) % 2) == 0):
a = ((nums[(len(nums) // 2)] + nums[((len(nums) // 2) - 1)]) // 2)
b = (a + 1)
else:
a = b = nums[(len(nums) // 2)]
(r1, r... |
def run_no_manifold():
mesh = UnitSquareMesh(3, 3)
x = SpatialCoordinate(mesh)
V0 = FunctionSpace(mesh, 'RT', 2)
V1 = FunctionSpace(mesh, 'DG', 1)
V = (V0 * V1)
bc_arg = Function(V0).project(Constant(((- 1), 0)))
bc = DirichletBC(V.sub(0), bc_arg, (1, 2, 3, 4))
(u, p) = TrialFunctions(V)... |
class TokenError(BaseModel):
error: str = Field(..., pattern='invalid_request|invalid_client|invalid_grant|unauthorized_client|unsupported_grant_type|invalid_scope')
error_description: (Any | None) = None
error_uri: (str | None) = None
def get_invalid_request(cls):
return cls(error='invalid_requ... |
class ProductFeedUploadErrorReport(AbstractObject):
def __init__(self, api=None):
super(ProductFeedUploadErrorReport, self).__init__()
self._isProductFeedUploadErrorReport = True
self._api = api
class Field(AbstractObject.Field):
file_handle = 'file_handle'
report_status ... |
def test_slugify_text_for_file_names():
assert (slugify_text_for_file_names('test') == 'test')
assert (slugify_text_for_file_names('test', 'default') == 'test')
assert (slugify_text_for_file_names('test', 'default', 50) == 'test')
assert (slugify_text_for_file_names('test', 'default', 2) == 'te')
as... |
def create_v4flowspec_actions(actions=None):
from ryu.services.protocols.bgp.api.prefix import FLOWSPEC_ACTION_TRAFFIC_RATE, FLOWSPEC_ACTION_TRAFFIC_ACTION, FLOWSPEC_ACTION_REDIRECT, FLOWSPEC_ACTION_TRAFFIC_MARKING
action_types = {FLOWSPEC_ACTION_TRAFFIC_RATE: BGPFlowSpecTrafficRateCommunity, FLOWSPEC_ACTION_TR... |
def clf(figure=None):
try:
if (figure is None):
scene = gcf()
else:
scene = figure
if (scene.scene is not None):
disable_render = scene.scene.disable_render
scene.scene.disable_render = True
scene.children[:] = []
scene._mouse_p... |
class Test(unittest.TestCase):
def setUpClass(cls):
cls.topo = fnss.full_mesh_topology(100)
cls.stack_1_name = 'stack_1'
cls.stack_1_props = {'prop1': 'val11', 'prop2': 'val12'}
cls.stack_2_name = 'stack_2'
cls.stack_2_props = {'prop1': 'val12', 'prop2': 'val22'}
cls.... |
class ScraperDbBase(DbBase.DbBase):
__metaclass__ = abc.ABCMeta
shouldCanonize = True
loggers = {}
dbConnections = {}
QUERY_DEBUG = False
def pluginName(self):
return None
def loggerPath(self):
return None
def tableKey(self):
return None
def tableName(self):
... |
class PointLineDistanceTestCase(unittest.TestCase):
def test_horizontal_line(self):
p1 = (10.0, 10.0)
p2 = (60.0, 10.0)
test = (35.0, 30.0)
dist = point_line_distance(test, p1, p2)
assert_equal(dist, 20.0)
def test_vertical_line(self):
p1 = (10.0, 10.0)
p2... |
def test_clean_tarfiles():
expected_result = 'result'
def func() -> str:
return expected_result
wrapped = clean_tarfiles(func)
with tempfile.TemporaryDirectory() as tempdir:
with cd(tempdir):
tarfile_path = Path(tempdir, 'tarfile.tar.gz')
tarfile_path.touch()
... |
.django_db
def test_require_eclipsing_exclude(client, monkeypatch, elasticsearch_award_index, award_with_tas):
_setup_es(client, monkeypatch, elasticsearch_award_index)
resp = query_by_tas(client, {'require': [_fa_path(BASIC_TAS)], 'exclude': [_agency_path(BASIC_TAS)]})
assert (resp.json()['results'] == [_a... |
def make_searchable(metadata, mapper=sa.orm.Mapper, manager=search_manager, options={}):
manager.options.update(options)
event.listen(mapper, 'instrument_class', manager.process_mapper)
event.listen(mapper, 'after_configured', manager.attach_ddl_listeners)
event.listen(metadata, 'before_create', sql_exp... |
.django_db
def test_award_update_with_list():
awards = [baker.make('search.AwardSearch', award_id=i, total_obligation=0, generated_unique_award_id=f'AWARD_{i}') for i in range(10)]
test_award = awards[3]
for i in range(5):
baker.make('search.TransactionSearch', transaction_id=(i + 1), award=test_awa... |
()
def organization_with_filter() -> Generator:
system = Organization(fides_key='organization_with_filter', name='organization_with_filter', fidesctl_meta=OrganizationMetadata(resource_filters=[ResourceFilter(type='ignore_resource_arn', value='arn:aws:rds:us-east-1::cluster:database-2')]))
(yield system) |
def initialize_app(credential=None, options=None, name=_DEFAULT_APP_NAME):
if (credential is None):
credential = credentials.ApplicationDefault()
app = App(name, credential, options)
with _apps_lock:
if (app.name not in _apps):
_apps[app.name] = app
return app
if ... |
def qotd_old_method(html_tree: lxml.html.HtmlElement) -> Tuple[(Text, Text)]:
tree = html_tree.get_element_by_id('mf-cdj')
tree = tree.xpath('div/div')[1].xpath('table/tbody/tr/td')[1]
quote = tree.xpath('div/i')[0].text_content()
author = tree.xpath('div/a')[0].text_content()
return (quote, author) |
def generate_qc_page(settings, qc_config, scene_dir, qc_subdir):
contents = qc_config.get_template_contents()
scene_file = personalize_template(contents, scene_dir, settings)
ciftify.utils.make_dir(qc_subdir, DRYRUN)
qc_html = os.path.join(qc_subdir, 'qc.html')
with open(qc_html, 'w') as qc_page:
... |
def _get_provider_cls(provider_cls_name: str) -> Type[providers.Provider]:
std_provider_type = _fetch_provider_cls_from_std(provider_cls_name)
if std_provider_type:
return std_provider_type
custom_provider_type = _import_provider_cls(provider_cls_name)
if custom_provider_type:
return cus... |
def extractForKalimdor(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol or frag)) or ('preview' in item['title'].lower())):
return None
if item['title'].startswith('Bringing The Farm To Live In Another World'):
return buildReleaseMessage... |
.flaky(reruns=3)
('elasticapm.transport.base.Transport.send')
def test_api_request_time_dynamic(mock_send, caplog, elasticapm_client):
elasticapm_client.config.update(version='1', api_request_time='1s')
with caplog.at_level('DEBUG', 'elasticapm.transport'):
transport = Transport(client=elasticapm_client... |
class ExtensionsMixin():
def register_extensions(cls, *extensions):
if (not hasattr(cls, '_extensions')):
cls._extensions = []
cls._extensions_seen = []
for ext in extensions:
if (ext in cls._extensions):
continue
extension = None
... |
class Solution():
def candy(self, ratings: List[int]) -> int:
nums = ([1] * len(ratings))
for i in range(1, len(ratings)):
if (ratings[(i - 1)] < ratings[i]):
nums[i] = (nums[(i - 1)] + 1)
for i in range((len(ratings) - 1), 0, (- 1)):
if (ratings[(i - ... |
def extractRoastedchickenpotatoWordpressCom(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, nam... |
class DatasetNotFoundError(FoundryAPIError):
def __init__(self, dataset_rid: str, response: (requests.Response | None)=None):
super().__init__((f'''Dataset {dataset_rid} not found.
''' + (response.text if (response is not None) else '')))
self.dataset_rid = dataset_rid
self.response = respon... |
def main():
p = argparse.ArgumentParser(description='Check that read headers for R1 and R2 fastq files are in agreement, and that the files form an R1/2 pair.')
p.add_argument('--version', action='version', version=('%%(prog)s %s' % get_version()))
p.add_argument('fastq_file_r1', metavar='R1.fastq', help='F... |
class Chartist():
def __init__(self, ui):
self.page = ui.page
self.chartFamily = 'Chartist'
def line(self, record=None, y_columns: list=None, x_axis: str=None, profile: types.PROFILE_TYPE=None, width: types.SIZE_TYPE=(100, '%'), height: types.SIZE_TYPE=(Defaults_html.CHARTS_HEIGHT_PX, 'px'), opt... |
(context_settings=get_width())
('--config', help='Path to configuration file.', type=click.Path(exists=True), default=settings.config_file())
('--hosts', help='Elasticsearch URL to connect to', multiple=True)
('--cloud_id', help='Shorthand to connect to Elastic Cloud instance')
('--api_token', help='The base64 encoded ... |
class RebirthOnlineLiveProcessor(HtmlProcessor.HtmlPageProcessor):
wanted_mimetypes = ['text/html']
want_priority = 80
loggerPath = 'Main.Text.RebirthOnline'
def wantsUrl(url):
if re.search('^ url):
print(("ms Wants url: '%s'" % url))
return True
return False
... |
class DateAndTime(TextualConvention, OctetString):
status = 'current'
displayHint = '2d-1d-1d,1d:1d:1d.1d,1a1d:1d'
subtypeSpec = OctetString.subtypeSpec
subtypeSpec += ConstraintsUnion(ValueSizeConstraint(8, 8), ValueSizeConstraint(11, 11))
if mibBuilder.loadTexts:
description = "A date-time... |
class CreateBackupForm(BackupForm):
define = forms.ChoiceField(label=_('Definition'), required=True, widget=forms.Select(attrs={'class': 'input-select2 narrow', 'required': 'required'}))
def __init__(self, vm, bkpdefs, *args, **kwargs):
super(CreateBackupForm, self).__init__(vm, *args, **kwargs)
... |
def filter_firewall_ipmacbinding_table_data(json):
option_list = ['ip', 'mac', 'name', 'seq_num', 'status']
json = remove_invalid_fields(json)
dictionary = {}
for attribute in option_list:
if ((attribute in json) and (json[attribute] is not None)):
dictionary[attribute] = json[attrib... |
def define_Es_shareD(num_pairs, input_nc, z_nc, ngf, K, bottleneck, n_downsample_global=3, n_blocks_global=9, max_mult=16, norm='instance', gpu_ids=[], vaeLike=False):
norm_layer = get_norm_layer(norm_type=norm)
list_of_encoders = []
for i in range(num_pairs):
encoder = E_Resnet(input_nc, z_nc, ngf,... |
class OptionSeriesNetworkgraphSonificationTracksMappingPitch(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: str):
self... |
def test_main(mock_webapi, monkeypatch, mock_job_status, tmp_path):
def save_sim_to_path(path: str) -> None:
sim = make_sim()
sim.to_file(path)
monkeypatch.setattr('builtins.input', (lambda _: 'Y'))
path = str((tmp_path / 'sim.json'))
save_sim_to_path(path)
main([path, '--task_name',... |
def _check_for_overwritten_queue_system_options(selected_queue_system: QueueSystem, queue_system_options: List[Tuple[(str, str)]]) -> None:
def generate_dict(option_list: List[Tuple[(str, str)]]) -> Dict[(str, List[str])]:
temp_dict: Dict[(str, List[str])] = defaultdict(list)
for option_string in op... |
def test_nested_dynamic_local():
def t1(a: int) -> str:
a = (a + 2)
return ('fast-' + str(a))
def ranged_int_to_str(a: int) -> typing.List[str]:
s = []
for i in range(a):
s.append(t1(a=i))
return s
def add_and_range(a: int, b: int) -> typing.List[str]:
... |
def build_queryset_for_closed_submissions(filters):
filter_year = filters.get('fy')
q = Q()
if filter_year:
selected_period = ClosedPeriod(filter_year, filters.get('quarter'), filters.get('period'))
q = _build_submission_queryset(selected_period)
else:
closed_periods = get_last_c... |
.parametrize('param, command_index, expected', [(click.Argument(['an_argument'], type=ACustomParamType()), 0, {'checked': '', 'click_type': 'my_click_custom_type', 'help': '', 'human_readable_name': 'AN ARGUMENT', 'name': '0.0.argument.my_click_custom_type.1.my_custom_type.an-argument', 'nargs': 1, 'param': 'argument',... |
class RatingColumn(Column):
name = '__rating'
display = _('Rating')
renderer = rating.RatingCellRenderer
dataproperty = 'rating'
cellproperties = {'follow-state': False}
def __init__(self, *args):
Column.__init__(self, *args)
self.cellrenderer.connect('rating-changed', self.on_ra... |
class ClassPage():
def __init__(self, component: primitives.HtmlModel=None, page: primitives.PageModel=None):
(self._css_struct, self._css_class) = (None, None)
(self.component, self.page) = (component, page)
if (component is not None):
self.page = component.page
(self.__... |
class MyPlot(HasTraits):
plot = Any()
screen_enabled = Bool(False)
screen_aspect = AspectRatio()
fixed_x = Bool(False)
fixed_y = Bool(False)
traits_view = View(VGroup(HGroup(Item('screen_enabled', label='Screen'), Item('screen_aspect', label='aspect ratio (w/h)')), HGroup(Item('fixed_x', label='... |
class ActivityCompletionClient():
service: WorkflowService
def heartbeat(self, task_token: bytes, details: object):
heartbeat(self.service, task_token, details)
def complete(self, task_token: bytes, return_value: object):
error = complete(self.service, task_token, return_value)
if er... |
class ADVI(AutoGuideVI):
def get_guide(query, distrib):
def param_loc():
return ((torch.rand_like(biject_to(distrib.support).inv(distrib.sample())) * 4.0) - 2.0)
def param_scale():
return ((0.01 + (torch.rand_like(biject_to(distrib.support).inv(distrib.sample())) * 4.0)) - 2.... |
def fail_safe(temperature, neutrons_produced_per_second, threshold):
output = (temperature * neutrons_produced_per_second)
operational_percentage = ((output / threshold) * 100)
if (operational_percentage < 90):
status_code = 'LOW'
elif (operational_percentage <= 110):
status_code = 'NORM... |
def upgrade():
op.create_table('user_favourite_events', sa.Column('id', sa.Integer(), nullable=False), sa.Column('event_id', sa.Integer(), nullable=True), sa.Column('user_id', sa.Integer(), nullable=True), sa.ForeignKeyConstraint(['event_id'], ['events.id'], ondelete='CASCADE'), sa.ForeignKeyConstraint(['user_id'],... |
class OptionPlotoptionsSunburstTraverseupbuttonPosition(Options):
def align(self):
return self._config_get('right')
def align(self, text: str):
self._config(text, js_type=False)
def verticalAlign(self):
return self._config_get('top')
def verticalAlign(self, text: str):
se... |
('sys.argv', ['flakehell'])
def test_lint_help(capsys):
result = main(['lint', '--help'])
assert (result == (0, ''))
captured = capsys.readouterr()
assert (captured.err == '')
assert ('-h, --help' in captured.out)
assert ('--builtins' in captured.out)
assert ('--isort-show-traceback' in capt... |
def get_layout_document_with_graphics_replaced_by_graphics(layout_document: LayoutDocument, semantic_graphics: Iterable[SemanticGraphic]) -> LayoutDocument:
return get_layout_document_with_text_or_graphic_replaced_by_graphics(layout_document, semantic_graphics=semantic_graphics, is_replace_overlapping_text=False) |
def add_tool(tool):
tool.is_sdk = False
tools.append(tool)
if find_tool(str(tool)):
raise Exception((((((('Duplicate tool ' + str(tool)) + '! Existing:\n{') + ', '.join((('%s: %s' % item) for item in vars(find_tool(str(tool))).items()))) + '}, New:\n{') + ', '.join((('%s: %s' % item) for item in var... |
class ONNXInput(BaseNode):
__identifier__ = 'nodes.node'
NODE_NAME = 'input'
def __init__(self):
super(ONNXInput, self).__init__(qgraphics_item=CustomNodeItem)
self.set_layout_direction(LayoutDirectionEnum.VERTICAL.value)
self.node_name = ''
self.shape = []
self.dtype... |
def _validate_accounting_methods(country: AbstractCountry) -> List[str]:
package: ModuleType = import_module(_ACCOUNTING_METHOD_PACKAGE)
plugin_name: str
is_package: bool
result: List[str] = []
accounting_methods: Set[str] = country.get_accounting_methods()
if (not country.get_default_accounting... |
def prism(range, **traits):
_data = {'red': ((0.0, 1.0, 1.0), (0.031746, 1.0, 1.0), (0.047619, 0.0, 0.0), (0.063492, 0.0, 0.0), (0.079365, 0.666667, 0.666667), (0.095238, 1.0, 1.0), (0.126984, 1.0, 1.0), (0.142857, 0.0, 0.0), (0.15873, 0.0, 0.0), (0.174603, 0.666667, 0.666667), (0.190476, 1.0, 1.0), (0.222222, 1.0,... |
class ChannelDBManager(TypedObjectManager):
def get_all_channels(self):
return self.all()
def get_channel(self, channelkey):
dbref = self.dbref(channelkey)
if dbref:
try:
return self.get(id=dbref)
except self.model.DoesNotExist:
pas... |
class InputDataValidationIssues():
def __init__(self) -> None:
self.empty_counter: Counter[str] = Counter()
self.format_error_counter: Counter[str] = Counter()
self.range_error_counter: Counter[str] = Counter()
self.max_issue_count_til_error: Dict[(str, Dict[(str, int)])] = {}
... |
class LogWindow(BaseHUDElement):
def __init__(self):
self.top_spot = (- 0.95)
self.spacer = 0.05
self.scale1 = 0.04
self.scale2 = 0.04
self.on_screen = deque([])
self.colors = {'bad': (0.8, 0.2, 0.2, 1), 'neutral': (0.4, 0.7, 0.9, 1), 'good': (0.2, 0.8, 0.2, 1)}
d... |
class MsgServicer(object):
def ChannelOpenInit(self, request, context):
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def ChannelOpenTry(self, request, context):
context.set_code... |
def make_registry(directory, output, recursive=True):
directory = Path(directory)
if recursive:
pattern = '**/*'
else:
pattern = '*'
files = sorted((str(path.relative_to(directory)) for path in directory.glob(pattern) if path.is_file()))
hashes = [file_hash(str((directory / fname))) ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.