code stringlengths 281 23.7M |
|---|
def modules_scan(url, method, headers, body, scanid=None):
attack = read_scan_policy()
if (attack is None):
print('Failed to start scan.')
sys.exit(1)
if (scanid is None):
scanid = generate_scanid()
count = 0
for (key, value) in list(attack.items()):
if ((value == 'Y'... |
('importlib.import_module', side_effect=_import_module_mock)
('setuptools.setup')
class TestLedgerIntegration(BasePythonMarkdownDocs):
DOC_PATH = Path(ROOT_DIR, 'docs', 'ledger-integration.md')
def _assert_isinstance(self, locals_key, cls_or_str, locals_):
assert (locals_key in locals_)
obj = lo... |
def sys_info():
ljust = 15
out = 'SYSTEM \n'
out += (('Platform:'.ljust(ljust) + platform.platform()) + '\n')
out += '\nPYTHON \n'
out += (('Version:'.ljust(ljust) + str(sys.version).replace('\n', ' ')) + '\n')
out += (('Executable:'.ljust(ljust) + sys.executable) + '\n')
out += '\nMODULES \... |
class AnaPotBase2D(Calculator):
def __init__(self, V_str):
super(AnaPotBase2D, self).__init__()
(x, y) = symbols('x y')
V = sympify(V_str)
dVdx = diff(V, x)
dVdy = diff(V, y)
self.V = lambdify((x, y), V, 'numpy')
self.dVdx = lambdify((x, y), dVdx, 'numpy')
... |
class AnsiToWin32(object):
ANSI_RE = re.compile('\\033\\[((?:\\d|;)*)([a-zA-Z])')
def __init__(self, wrapped, convert=None, strip=None, autoreset=False):
self.wrapped = wrapped
self.autoreset = autoreset
self.stream = StreamWrapper(wrapped, self)
on_windows = sys.platform.startsw... |
class OptionPlotoptionsPolygonDragdrop(Options):
def draggableX(self):
return self._config_get(None)
def draggableX(self, flag: bool):
self._config(flag, js_type=False)
def draggableY(self):
return self._config_get(None)
def draggableY(self, flag: bool):
self._config(flag... |
class OptionPlotoptionsPyramidOnpointPosition(Options):
def offsetX(self):
return self._config_get(None)
def offsetX(self, num: float):
self._config(num, js_type=False)
def offsetY(self):
return self._config_get(None)
def offsetY(self, num: float):
self._config(num, js_ty... |
def extractOmegatranslationsBlogspotCom(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, t... |
class Plugin(plugin.PluginProto):
PLUGIN_ID = 1
PLUGIN_NAME = 'Input - Switch Device/Generic GPIO'
PLUGIN_VALUENAME1 = 'State'
def __init__(self, taskindex):
plugin.PluginProto.__init__(self, taskindex)
self.dtype = rpieGlobals.DEVICE_TYPE_SINGLE
self.vtype = rpieGlobals.SENSOR_T... |
class flow_monitor_reply_entry(loxi.OFObject):
def __init__(self, event=None):
if (event != None):
self.event = event
else:
self.event = 0
return
def pack(self):
packed = []
packed.append(struct.pack('!H', 0))
packed.append(struct.pack('!H'... |
def extractFivedollarmailBlogspotCom(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_t... |
def get_data(url, target_datetime, session=None):
s = (session or requests.Session())
headers = {'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:55.0) Gecko/ Firefox/55.0', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'}
pagereq = requests.get(url, headers=headers)
... |
def interpolate(field, xs, vals):
domain_size = (2 ** (log2(max(xs)) + 1))
assert ((domain_size * 2) <= (2 ** field.height))
domain = list(range(domain_size))
big_domain = list(range((domain_size * 2)))
z = zpoly(field, [x for x in domain if (x not in xs)])
z_values = fft(field, big_domain, z)
... |
.django_db
def test_spending_by_award_subaward_success(client, mock_tas_data):
data = {'filters': {'tas_codes': [{'aid': '028', 'main': '8006'}], 'award_type_codes': ['A', 'B', 'C', 'D']}, 'fields': ['Sub-Award ID'], 'subawards': True}
resp = client.post('/api/v2/search/spending_by_award', content_type='applica... |
class TestSuite(unittest.TestCase):
def setUp(self):
self.suite_config = {'name': 'test', 'description': 'desc', 'args': []}
self.mock_hook = MagicMock()
HookFactory.create.return_value = self.mock_hook
Suite.parse = Mock()
def test_arg_list(self):
self.assertListEqual(['... |
def get_mock_table_retention(table_data):
def _mock_table_retention(_=None, resource_type='bigquery_table'):
if (resource_type == 'bucket'):
return []
if (resource_type != 'bigquery_table'):
raise ValueError('unexpected resource type: got %s, table', resource_type)
re... |
class TrimmedEmail(fields.Email):
def _serialize(self, value, *args, **kwargs):
if hasattr(value, 'strip'):
value = value.strip()
return super()._serialize(value, *args, **kwargs)
def _deserialize(self, value, *args, **kwargs):
if hasattr(value, 'strip'):
value = ... |
.parametrize('pos1,pos2,expected', [(2, 0, 24), (2, 2, 28), (2, (- 1), 26)])
def test_custom_fn_impute(pos1, pos2, expected, mw_data):
mw_data[(pos1, pos2)] = np.nan
imputed = impy.moving_window(mw_data, func=(lambda l: (max(l) * 2)))
return_na_check(imputed)
assert (imputed[(pos1, pos2)] == expected) |
class GCSPath():
bucket: str
key: str
def __init__(self, fileURL: str) -> None:
(self.bucket, self.key) = self._get_bucket_key(fileURL)
def __eq__(self, other: 'GCSPath') -> bool:
return ((self.bucket == other.bucket) and (self.key == other.key))
def _get_bucket_key(self, fileURL: st... |
def test_websocket_endpoint_on_receive_bytes(test_client_factory):
class WebSocketApp(WebSocketEndpoint):
encoding = 'bytes'
async def on_receive(self, websocket, data):
(await websocket.send_bytes((b'Message bytes was: ' + data)))
client = test_client_factory(WebSocketApp)
with ... |
class OptionSeriesVectorSonificationDefaultinstrumentoptions(Options):
def activeWhen(self) -> 'OptionSeriesVectorSonificationDefaultinstrumentoptionsActivewhen':
return self._config_sub_data('activeWhen', OptionSeriesVectorSonificationDefaultinstrumentoptionsActivewhen)
def instrument(self):
re... |
def test_align_explode_alignments_by_taxon(o_dir, e_dir, request):
program = 'bin/align/phyluce_align_explode_alignments'
output = os.path.join(o_dir, 'mafft-exploded-by-taxon')
cmd = [os.path.join(request.config.rootdir, program), '--alignments', os.path.join(e_dir, 'mafft'), '--output', output, '--input-f... |
def stuff2icon(s):
if (s == 'ORG'):
return 'org'
elif (s == 'GEO'):
return ''
elif (s == 'FIRST'):
return '1'
elif (s == 'LAST'):
return '2'
elif (s == 'FEMALE'):
return ''
elif (s == 'MALE'):
return ''
elif (s == 'CURRENCY'):
return ''... |
def list_run_directories(solid_run_dir):
base_dir = os.path.dirname(os.path.abspath(solid_run_dir))
run_name = os.path.basename(solid_run_dir.rstrip(os.sep))
try:
base_run_info = SolidRunInfo(run_name)
except Exception:
logging.error(("'%s' not a valid SOLiD run directory name" % solid_r... |
def _get_cost_savings(measure_values, rollup_by=None, target_percentile=50):
all_percentiles = defaultdict(list)
all_savings = defaultdict(list)
cost_saving_key = str(target_percentile)
for mv in measure_values:
rollup_id = (getattr(mv, rollup_by) if rollup_by else None)
all_percentiles[... |
class GungnirSkill(TreatAs, WeaponSkill):
target = t_OtherOne()
skill_category = ['equip', 'active']
range = 3
treat_as = PhysicalCard.classes['AttackCard']
def check(self):
cl = self.associated_cards
cat = ('cards', 'showncards')
if (not all(((c.resides_in.type in cat) for c... |
def _handle_compatibility_operator(all_specifiers: List[Specifier], operator_to_specifiers: Dict[(str, Set[Specifier])], specifier: Specifier) -> None:
spec_version = Version(specifier.version)
base_version = spec_version.base_version
parts = base_version.split('.')
index_to_update = (- 2)
if (spec_... |
class OptionPlotoptionsParetoStatesSelectHalo(Options):
def attributes(self):
return self._config_get(None)
def attributes(self, value: Any):
self._config(value, js_type=False)
def opacity(self):
return self._config_get(0.25)
def opacity(self, num: float):
self._config(nu... |
def action(arguments):
common.exit_on_sigpipe()
source_format = (arguments.input_format or fileformat.from_handle(arguments.sequence_file))
with arguments.sequence_file:
sequences = SeqIO.parse(arguments.sequence_file, source_format)
if arguments.include_description:
ids = (seque... |
def _train_function(train_actors: DistributedActors, algorithm_config: ImpalaAlgorithmConfig) -> IMPALA:
impala = IMPALA(model=_policy(train_actors.env_factory()), rollout_generator=train_actors, evaluator=algorithm_config.rollout_evaluator, algorithm_config=algorithm_config, model_selection=None)
impala.train(... |
class MFContinuous(nn.Module):
def __init__(self, emb_size, emb_dim, c_vector=1e-06):
super().__init__()
self.emb_size = emb_size
self.emb_dim = emb_dim
self.c_vector = c_vector
self.embedding = nn.Embedding(emb_size, emb_dim)
self.sig = nn.Sigmoid()
self.mse ... |
class UnitStatus(base._Widget, base.PaddingMixin, base.MarginMixin):
orientations = base.ORIENTATION_HORIZONTAL
defaults = [('bus_name', 'system', "Which bus to use. Accepts 'system' or 'session'."), ('font', 'sans', 'Default font'), ('fontsize', None, 'Font size'), ('foreground', 'ffffff', 'Font colour'), ('un... |
def test_condition_tuple_branches():
def sum_sub(a: int, b: int) -> typing.NamedTuple('Outputs', sum=int, sub=int):
return ((a + b), (a - b))
def math_ops(a: int, b: int) -> typing.Tuple[(int, int)]:
(add, sub) = conditional('noDivByZero').if_((a > b)).then(sum_sub(a=a, b=b)).else_().fail('Only ... |
class StadtradHamburgStation(BikeShareStation):
def __init__(self, info):
super(StadtradHamburgStation, self).__init__()
self.latitude = float(info['geometry']['coordinates'][1])
self.longitude = float(info['geometry']['coordinates'][0])
self.name = info['properties']['name'].encode(... |
class IndexTest(unittest.TestCase):
def test_index_constant_vector_stochastic_index(self) -> None:
self.maxDiff = None
observed = BMGInference().to_dot([pos_real(), real(), neg_real(), prob(), natural()], {})
expected = '\ndigraph "graph" {\n N00[label=0.5];\n N01[label=Bernoulli];\n N02[... |
def expression(callable, rule_name, grammar):
if (ismethoddescriptor(callable) and hasattr(callable, '__func__')):
callable = callable.__func__
num_args = len(getfullargspec(callable).args)
if ismethod(callable):
num_args -= 1
if (num_args == 2):
is_simple = True
elif (num_ar... |
class ScriptForm(forms.ModelForm):
db_key = forms.CharField(label='Name/Key', help_text='Script identifier, shown in listings etc.')
db_typeclass_path = forms.ChoiceField(label='Typeclass', help_text='This is the Python-path to the class implementing the actual script functionality. <BR>If your custom class is ... |
class MasterNodeStatsRecorder():
def __init__(self, client, metrics_store, sample_interval):
self.client = client
self.metrics_store = metrics_store
self.sample_interval = sample_interval
self.logger = logging.getLogger(__name__)
def __str__(self):
return 'master node sta... |
class TestIndent():
def test_roundtrip_inline_list(self):
s = 'a: [a, b, c]\n'
output = rt(s)
assert (s == output)
def test_roundtrip_mapping_of_inline_lists(self):
s = dedent(' a: [a, b, c]\n j: [k, l, m]\n ')
output = rt(s)
assert (s == outp... |
class OptionPlotoptionsArearangeSonificationTracksMappingLowpass(Options):
def frequency(self) -> 'OptionPlotoptionsArearangeSonificationTracksMappingLowpassFrequency':
return self._config_sub_data('frequency', OptionPlotoptionsArearangeSonificationTracksMappingLowpassFrequency)
def resonance(self) -> '... |
def if_url_param(value: str, py_func) -> JsUtils.jsWrap:
return JsUtils.jsWrap(('(function(param){\nconst queryString = window.location.search; const urlParams = new URLSearchParams(queryString);\nif (urlParams.has(param)){paramValue = urlParams.get(param); %s}; \n})(%s)' % (py_func(JsUtils.jsWrap('paramValue')), J... |
class TestPartitionSeparate():
test_id = '1.1'
test_level = 1
partition = '/dev/sda1'
test = CISAudit()
(CISAudit, '_shellexec', mock_parition_exists)
def test_partition_is_separate(self):
state = self.test.audit_partition_is_separate(partition=self.partition)
assert (state == 0)... |
class TestApsEncoder():
def _encode_aps(self, aps):
return check_encoding(messaging.Message(topic='topic', apns=messaging.APNSConfig(payload=messaging.APNSPayload(aps=aps))))
.parametrize('data', NON_OBJECT_ARGS)
def test_invalid_aps(self, data):
with pytest.raises(ValueError) as excinfo:
... |
def extract_mentions(html):
if (not html):
return []
soup = BeautifulSoup(html, 'html.parser')
mentions = []
for d in soup.find_all('span', attrs={'data-type': 'mention'}):
mentions.append(frappe._dict(full_name=d.get('data-label'), email=d.get('data-id')))
return mentions |
def authenticate(request):
if ('authorization' not in request.headers):
return None
try:
(authtype, token) = request.headers['authorization'].split(' ')
except Exception as e:
print(e)
return None
if (authtype.lower() != 'bearer'):
print('not bearer')
retu... |
class LiteDRAMGENSDRPHYCRG(Module):
def __init__(self, platform, core_config):
assert (core_config['memtype'] in ['SDR'])
self.clock_domains.cd_sys = ClockDomain()
self.comb += self.cd_sys.clk.eq(platform.request('clk'))
self.specials += AsyncResetSynchronizer(self.cd_sys, platform.r... |
class TestFontTrait(BaseTestMixin, unittest.TestCase):
def setUp(self):
BaseTestMixin.setUp(self)
def tearDown(self):
BaseTestMixin.tearDown(self)
_toolkit([ToolkitName.null])
def test_font_trait_default(self):
class Foo(HasTraits):
font = Font()
f = Foo()
... |
class Test_move(unittest.TestCase):
pitch = 60
scale = _reify([11])
def test_none(self):
out = _move(None, self.scale, 1)
self.assertIsNone(out)
def test_step_none(self):
out = _move(self.pitch, self.scale, None)
self.assertIsNone(out)
def test_step_0(self):
o... |
def main(maxExamples, includeArchives, shuffle):
if includeArchives:
extractionPaths = extractArchives()
(schemas, badSchemaFiles) = loadSchemas()
print('Loaded', len(schemas), 'schemas.', flush=True)
(examples, badExampleFiles) = loadExamples()
print('Loaded', len(examples), 'examples.', fl... |
class Jump():
def LEFT(quantity: int=1) -> List[Dir]:
return ([Dir.LEFT] * quantity)
def RIGHT(quantity: int=1) -> List[Dir]:
return ([Dir.RIGHT] * quantity)
def UP(quantity: int=1) -> List[Dir]:
return ([Dir.UP] * quantity)
def DOWN(quantity: int=1) -> List[Dir]:
return ... |
def translate_inputs_to_literals(ctx: FlyteContext, incoming_values: Dict[(str, Any)], flyte_interface_types: Dict[(str, _interface_models.Variable)], native_types: Dict[(str, type)]) -> Dict[(str, _literals_models.Literal)]:
if (incoming_values is None):
raise ValueError('Incoming values cannot be None, mu... |
def test_update_user(sample_tenant):
client = tenant_mgt.auth_for_tenant(sample_tenant.tenant_id)
user = client.create_user()
try:
email = _random_email()
phone = _random_phone()
user = client.update_user(user.uid, email=email, phone_number=phone)
assert (user.tenant_id == sa... |
class Switcher(wx.Panel):
def __init__(self, parent, id, model, label=None, **kw):
wx.Panel.__init__(self, parent, id, **kw)
self.model = model
self._create_widget(model, label)
return
def _create_widget(self, model, label):
self.sizer = sizer = wx.BoxSizer(wx.VERTICAL)
... |
class StructuredRow(Row):
__slots__ = ['_changes', '_compound_rels', '_concrete', '_fields', '_virtuals']
def _from_engine(cls, data: Dict[(str, Any)]):
rv = cls(__concrete=True)
rv._fields.update(data)
return rv
def __init__(self, fields: Optional[Dict[(str, Any)]]=None, **extras: A... |
class EthSrc(MatchTest):
def runTest(self):
match = ofp.match([ofp.oxm.eth_src([0, 1, 2, 3, 4, 5])])
matching = {'correct': simple_tcp_packet(eth_src='00:01:02:03:04:05')}
nonmatching = {'incorrect': simple_tcp_packet(eth_src='00:01:02:03:04:06'), 'multicast': simple_tcp_packet(eth_src='01:0... |
def _iter_module_files():
for module in list(sys.modules.values()):
if (module is None):
continue
filename = getattr(module, '__file__', None)
if filename:
old = None
while (not os.path.isfile(filename)):
old = filename
file... |
class OptionPlotoptionsSunburstSonificationContexttracksMappingPitch(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):
... |
class DelimitedBashReceiver(protocol.Protocol):
def __init__(self):
self.buffer = BytesIO()
self.current_delimiters = []
self.handle = None
self.ping_timeout = None
self.ping_timer = None
self.timed_out = False
def command(self, cmd, delimiter=None):
if (d... |
def extractGraintransWordpressCom(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... |
class Options():
host: BasicConfig = field(default_factory=dict)
environment: BasicConfig = field(default_factory=dict)
gateway: BasicConfig = field(default_factory=dict)
def add_requirements(self, requirements: list[str]):
kind = self.environment['kind']
if (kind == 'virtualenv'):
... |
def untypable_node_reporter() -> GraphFixer:
typer = LatticeTyper()
def get_error(bmg: BMGraphBuilder, node: bn.BMGNode) -> Optional[BMGError]:
if isinstance(node, bn.ConstantNode):
return None
t = typer[node]
if ((t != bt.Untypable) and (t != bt.Tensor)):
return ... |
def channels_list(key, part, categoryId=None, forUsername=None, id=None, managedByMe=None, mine=None, mySubscribers=None, hl=None, maxResults=None, onBehalfOfContentOwner=None, pageToken=None):
args = locals()
part_params = {'contentDetails', 'id', '(deprecated) localizations', 'snippet', 'auditDetails', 'stati... |
def test_formatter_plugin(tmp_path, monkeypatch):
monkeypatch.setitem(CODEFORMATTERS, 'lang', example_formatter)
file_path = (tmp_path / 'test_markdown.md')
file_path.write_text('```lang\nother\n```\n')
assert (run((str(file_path),)) == 0)
assert (file_path.read_text() == '```lang\ndummy\n```\n') |
def ethtest_fixtures_as_pytest_fixtures(*test_files: str) -> List[Tuple[(RLP, Bytes)]]:
base_path = f'{ETHEREUM_TESTS_PATH}/RLPTests/'
test_data = dict()
for test_file in test_files:
with open(os.path.join(base_path, test_file), 'r') as fp:
test_data.update(json.load(fp))
pytest_fixt... |
.parametrize('original_schema,algorithm,expected_fingerprint', [('int', 'CRC-64-AVRO', '8f5c393f1ad57572'), ('int', 'md5', 'ef524ea1b91e73173d938ade36c1db32'), ('int', 'sha256', '3f2b87a9fe7cc9bc3981cd45e3e355309e5090aa0933d7becb6fba45'), ({'type': 'int'}, 'CRC-64-AVRO', '8f5c393f1ad57572'), ({'type': 'int'}, 'md5', 'e... |
def extractVentifrappeWordpressCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
titlemap = [('Doctoring the world Chapter ', 'Doctoring the world', 'translated'), ('Doctoring the world:... |
class TestUnsqueezeConverter(AITTestCase):
([['default', 1], ['negative_dim', (- 1)]])
def test_simple(self, name: str, dim: int):
class TestModule(torch.nn.Module):
def forward(self, x: torch.Tensor) -> torch.Tensor:
return torch.unsqueeze(x, dim)
model = TestModule(... |
class TargetCaseModel(ValueModel):
def __init__(self, analysis_config: AnalysisConfig, notifier: ErtNotifier, format_mode: bool=False):
self.analysis_config = analysis_config
self.notifier = notifier
self._format_mode = format_mode
self._custom = False
super().__init__(self.g... |
_wrapper('wolfe')
def hager_zhang(x0, p, get_phi_dphi, get_fg, conds, max_cycles, alpha_init=None, alpha_prev=None, f_prev=None, dphi0_prev=None, quad_step=False, eps=1e-06, theta=0.5, gamma=0.5, rho=5, psi_0=0.01, psi_1=0.1, psi_2=2.0, psi_low=0.1, psi_hi=10, Delta=0.7, omega=0.001, max_bisects=10):
epsk = (eps * ... |
class Notification(FlyteIdlEntity):
def __init__(self, phases, email: EmailNotification=None, pager_duty: PagerDutyNotification=None, slack: SlackNotification=None):
self._phases = phases
self._email = email
self._pager_duty = pager_duty
self._slack = slack
def phases(self):
... |
.skipcomplexnoslate
def test_multiple_custom_transfer_split():
mesh = UnitIntervalMesh(2)
mh = MeshHierarchy(mesh, 2)
mesh = mh[(- 1)]
count_V = 0
count_Q = 0
def prolong_V(coarse, fine):
nonlocal count_V
prolong(coarse, fine)
count_V += 1
def prolong_Q(fine, coarse):... |
class CloseToTrayPreference(widgets.CheckPreference, widgets.CheckConditional):
default = False
name = 'gui/close_to_tray'
condition_preference_name = 'gui/use_tray'
def __init__(self, preferences, widget):
widgets.CheckPreference.__init__(self, preferences, widget)
widgets.CheckConditio... |
class TestOFPGroupDescStats(unittest.TestCase):
length = ((ofproto.OFP_GROUP_DESC_STATS_SIZE + ofproto.OFP_BUCKET_SIZE) + ofproto.OFP_ACTION_OUTPUT_SIZE)
type_ = 128
group_id = 6606
port = 10976
max_len = ofproto.OFP_ACTION_OUTPUT_SIZE
actions = [OFPActionOutput(port, max_len)]
buf_actions =... |
('/gpustat', methods=['GET'])
def report_gpustat():
def _date_handler(obj):
if hasattr(obj, 'isoformat'):
return obj.isoformat()
else:
raise TypeError(type(obj))
response.content_type = 'application/json'
if EXCLUDE_SELF:
resp = {'error': 'Excluded self!'}
... |
def test_correct_response_with_geo_filters(client, monkeypatch, elasticsearch_transaction_index, awards_and_transactions):
setup_elasticsearch_test(monkeypatch, elasticsearch_transaction_index)
test_cases = [_test_correct_response_for_place_of_performance_county_with_geo_filters, _test_correct_response_for_plac... |
def module_transformation(output, param, subtree_parameters, tr_snippet, tr_args):
return Module(_module_transformation, render_kwds=dict(output=output, name=param.name, param_cnames_seq=param_cnames_seq, subtree_parameters=subtree_parameters, q_indices=index_cnames_seq(param, qualified=True), VALUE_NAME=VALUE_NAME... |
class OptionSeriesOrganizationDataDatalabelsTextpath(Options):
def attributes(self):
return self._config_get(None)
def attributes(self, value: Any):
self._config(value, js_type=False)
def enabled(self):
return self._config_get(False)
def enabled(self, flag: bool):
self._c... |
class CircuitBreakerError(Exception):
def __init__(self, circuit_breaker, *args, **kwargs):
super(CircuitBreakerError, self).__init__(*args, **kwargs)
self._circuit_breaker = circuit_breaker
def __str__(self, *args, **kwargs):
return ('Circuit "%s" OPEN until %s (%d failures, %d sec rema... |
class TestGethostbyname_ex(tests.LimitedTestCase):
def _make_mock_getaliases(self):
class GetAliases():
aliases = ['cname.example.com']
def __call__(self, *args, **kwargs):
return self.aliases
getaliases = GetAliases()
return getaliases
def setUp(s... |
def extractOutspanFoster(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
if (('Chapter' in item['tags']) and ('ascension' in item['tags'])):
return buildReleaseMessageWithType(item... |
class WafFirewallsResponseAllOf(ModelNormal):
allowed_values = {}
validations = {}
_property
def additional_properties_type():
lazy_import()
return (bool, date, datetime, dict, float, int, list, str, none_type)
_nullable = False
_property
def openapi_types():
lazy_imp... |
def delete_directory_contents(directory: Path) -> None:
enforce(directory.is_dir(), f"Path '{directory}' must be a directory.")
for filename in directory.iterdir():
if (filename.is_file() or filename.is_symlink()):
filename.unlink()
elif filename.is_dir():
shutil.rmtree(s... |
class Fuzzel(Selector):
def supported() -> bool:
return (is_wayland() and is_installed('fuzzel'))
def name() -> str:
return 'fuzzel'
def show_character_selection(self, characters: Dict[(str, str)], recent_characters: List[str], prompt: str, show_description: bool, use_icons: bool, keybinding... |
class LookupTable(NamedTuple):
version: int = TABLE_VERSION
file_index: Dict[(FileID, str)] = {}
entries: LookupEntries = {}
def to_json(self) -> str:
return json.dumps((self.version, self.file_index, self.entries))
def from_json(cls, value: str) -> 'LookupTable':
(version, file_inde... |
def update_rules(xkb_root, kb_index):
for filename in ['base.xml', 'evdev.xml']:
filepath = ((xkb_root / 'rules') / filename)
if (not filepath.exists()):
continue
try:
tree = etree.parse(filepath, etree.XMLParser(remove_blank_text=True))
for (locale, named... |
class FlattenConcatCategoricalStateValueNet(FlattenConcatBaseNet):
def __init__(self, obs_shapes: Dict[(str, Sequence[int])], hidden_units: List[int], non_lin: nn.Module, support_range: Tuple[(int, int)]):
super().__init__(obs_shapes, hidden_units, non_lin)
support_set_size = ((support_range[1] - su... |
class GethAdmin(Module):
is_async = False
add_peer: Method[Callable[([EnodeURI], bool)]] = Method(RPC.admin_addPeer, mungers=[default_root_munger])
datadir: Method[Callable[([], str)]] = Method(RPC.admin_datadir, is_property=True)
node_info: Method[Callable[([], NodeInfo)]] = Method(RPC.admin_nodeInfo, ... |
def main():
data = datasets.load_iris()
X = normalize(data.data[(data.target != 0)])
y = data.target[(data.target != 0)]
y[(y == 1)] = (- 1)
y[(y == 2)] = 1
(X_train, X_test, y_train, y_test) = train_test_split(X, y, test_size=0.33)
clf = SupportVectorMachine(kernel=polynomial_kernel, power=... |
class FinancialParserObjectDataClass(BaseModel):
customer_information: FinancialCustomerInformation
merchant_information: FinancialMerchantInformation
payment_information: FinancialPaymentInformation
financial_document_information: FinancialDocumentInformation
local: FinancialLocalInformation
ba... |
class ResponseCacheMiddlware():
PROCESS_REQUEST_CACHED_BODY = {'cached': True}
PROCESS_RESOURCE_CACHED_BODY = {'cached': True, 'resource': True}
def process_request(self, req, resp):
if (req.path == '/cached'):
resp.media = self.PROCESS_REQUEST_CACHED_BODY
resp.complete = Tru... |
class CriticViewPreprocessor(Preprocessor):
def __init__(self, critic_stash):
super(CriticViewPreprocessor, self).__init__()
self.critic_stash = critic_stash
def _ins(self, text):
if RE_BLOCK_SEP.match(text):
return ('\n\n%s\n\n' % self.critic_stash.store('<ins class="critic ... |
def test_commit_merges_checkpoint_into_previous(journal_db):
checkpoint = journal_db.record()
journal_db.set(b'1', b'test-a')
assert (journal_db.get(b'1') == b'test-a')
before_diff = journal_db.diff()
journal_db.commit(checkpoint)
assert (journal_db.diff() == before_diff)
assert (journal_db.... |
def are_rules_up_to_date(rules, current_version=VERSION):
version_regexp = re.compile('.*rivalcfg\\s+v([0-9]+\\.[0-9]+\\.[0-9]+(.+)?)\\s*.*')
rules_version = None
if version_regexp.match(rules):
rules_version = version_regexp.match(rules).group(1)
return (rules_version == current_version) |
.parametrize('dim, degree, quad_degree', [(dim, d, q) for dim in (0, 1) for q in range(1, 8) for d in range((q + 1))])
def test_integrate_triangle(dim, degree, quad_degree):
q = gauss_quadrature(ReferenceTriangle, quad_degree)
numeric = q.integrate((lambda x: (x[dim] ** degree)))
analytic = ((1.0 / (degree ... |
class TestAbstractDataExporter(TestCase):
def setUp(self):
self.value_type = Mock()
self.value_type.has_text = Mock(return_value=True)
self.value_type.get_text = Mock(return_value='text')
self.value_type.has_editor_value = Mock(return_value=True)
self.value_type.get_editor_va... |
def get_opt_kwargs(opt_key, layer_ind, thresh):
opt_defaults = {'lbfgs': {'mu_reg': 0.1}, 'plbfgs': {'precon_kind': 'full_fast', 'precon_update': 50}}
if (layer_ind == 0):
opt_kwargs = {'type': 'rfo', 'thresh': 'never'}
else:
if (opt_key is None):
opt_key = 'lbfgs'
opt_kw... |
class OptionPlotoptionsXrangeSonificationTracksMappingHighpassFrequency(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 DeferredMessage():
def __init__(self, message_type: Type[Message], *args: Any, **kwargs: Any) -> None:
self._message_type = message_type
self._args = args
self._kwargs = kwargs
self._message: Optional[Message] = None
def build_message(self) -> Message:
if (not self.... |
def mock_constructor(target: str, class_name: str, allow_private: bool=False, type_validation: bool=True, **kwargs: Any) -> _MockConstructorDSL:
if (not isinstance(class_name, str)):
raise ValueError('Second argument must be a string with the name of the class.')
_bail_if_private(class_name, allow_priva... |
def get_flaskbb_config(app, config_file):
if (config_file is not None):
if (not isinstance(config_file, str)):
return config_file
if os.path.exists(os.path.join(app.instance_path, config_file)):
return os.path.join(app.instance_path, config_file)
if os.path.exists(os.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.