code stringlengths 281 23.7M |
|---|
def link_functions(functions, functions_mro):
functions_by_name = {f.ast_node.name: f for (f, _) in reversed(functions_mro)}
functions_by_id = {f.ast_node.id: f for (f, _) in reversed(functions_mro)}
for (_, blocks) in functions.values():
for block in blocks:
if isinstance(block.transfer... |
def _print_info(portal_info_dict, server_info_dict):
ind = (' ' * 8)
def _prepare_dict(dct):
out = {}
for (key, value) in dct.items():
if isinstance(value, list):
value = '\n{}'.format(ind).join((str(val) for val in value))
out[key] = value
return ... |
def lazy_import():
from fastly.model.schemas_waf_firewall_version import SchemasWafFirewallVersion
from fastly.model.schemas_waf_firewall_version_data import SchemasWafFirewallVersionData
from fastly.model.type_waf_rule_revision import TypeWafRuleRevision
from fastly.model.waf_rule_revision import WafRu... |
class SevenSegmentClock(SevenSegmentPattern):
description = 'You need a LED stripe that is wound through all segments in an S pattern and then continuing to the next digit while the stripe being upright on its side. Selecting *debug* gives a better idea how things fit together.\n\nAdding a diffuser on top or at the... |
class TestAsyncExampleWeights():
.parametrize('example_weight_config, example_weight_class', AsyncExampleWeightsTestUtils.EXAMPLE_WEIGHT_TEST_CONFIGS)
def test_string_conversion(self, example_weight_config: AsyncExampleWeightConfig, example_weight_class: ExampleWeight) -> None:
obj = instantiate(example... |
class SpinnakerDns():
def __init__(self, app=None, env=None, region=None, elb_subnet=None, prop_path=None):
self.log = logging.getLogger(__name__)
self.domain = DOMAIN
self.env = env
self.region = region
self.elb_subnet = elb_subnet
self.app = app
self.generat... |
def create_file_csv(userCheckIns):
headers = ['Ticket Id', 'Date Time', 'Track Name', 'Session Name', 'Speaker Name', 'Type']
columns = ['ticket_holder_id', 'created_at', 'track_name', 'session_name', 'speaker_name', 'type']
rows = [headers]
for userCheckIn in userCheckIns:
data = []
for... |
class Technology(Base):
__tablename__ = 'technology'
technology_id = Column(Integer, primary_key=True)
country_id = Column(ForeignKey(Country.country_id), index=True)
technology_name_id = Column(ForeignKey(SharedDescription.description_id))
is_completed = Column(Boolean, index=True, default=False)
... |
def set_my_commands(token, commands, scope=None, language_code=None):
method_url = 'setMyCommands'
payload = {'commands': _convert_list_json_serializable(commands)}
if scope:
payload['scope'] = scope.to_json()
if language_code:
payload['language_code'] = language_code
return _make_re... |
def process_value(setting_info, colors):
header_length = setting_info['rgbgradient_header']['header_length']
led_id_offsets = setting_info['rgbgradient_header']['led_id_offsets']
duration_offset = setting_info['rgbgradient_header']['duration_offset']
duration_length = setting_info['rgbgradient_header'][... |
def extractPhosphorescesWordpressCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [('ilybf', 'Ive Liked Your Boyfriend for A Long Time', 'translated'), ('PRC', 'PRC', 'translat... |
(name='max_abs_diff_analytic')
def fixture_max_abs_diff_analytic(bottom, top, quadratic_params, quadratic_density, straight_line_analytic):
(factor, vertex_radius, _) = quadratic_params
(density_bottom, density_top) = (quadratic_density(bottom), quadratic_density(top))
slope = ((density_top - density_bottom... |
.parametrize('center, ref_candidates', ((5, (8, 7, 0)), (4, (12, 13, 3)), (0, (6, 1, 5))))
def test_find_candidates(center, ref_candidates, geom):
bond_sets = [set(bond) for bond in find_bonds(geom.atoms, geom.coords3d).tolist()]
candidates = find_candidates(center, bond_sets)
assert (set(candidates) == set... |
class Modals():
def __init__(self, ui):
self.page = ui.page
def forms(self, components: html.Html.Html, action: str, method: str, header=None, footer=None, helper: types.HELPER_TYPE=None) -> html.HtmlContainer.Modal:
if (not (type(components) == list)):
components = [components]
... |
class Keyboard(BaseKeyboard):
def __init__(self, disptype=settings.DISPTYPE, **args):
if (disptype == 'pygame'):
from pygaze._keyboard.pygamekeyboard import PyGameKeyboard as Keyboard
elif (disptype == 'psychopy'):
from pygaze._keyboard.psychopykeyboard import PsychoPyKeyboar... |
class IsCloseTests(unittest.TestCase):
isclose = staticmethod(isclose)
def assertIsClose(self, a, b, *args, **kwargs):
self.assertTrue(self.isclose(a, b, *args, **kwargs), msg=('%s and %s should be close!' % (a, b)))
def assertIsNotClose(self, a, b, *args, **kwargs):
self.assertFalse(self.is... |
class DbtRunResult():
native_run_result: Optional[RunResultsArtifact]
(details='Use native_run_result instead')
def nativeRunResult(self):
return self.native_run_result
def results(self) -> Sequence[RunResultOutput]:
if self.native_run_result:
return self.native_run_result.re... |
def prepare_message(caller: Address, target: Union[(Bytes0, Address)], value: U256, data: Bytes, gas: Uint, env: Environment, code_address: Optional[Address]=None, should_transfer_value: bool=True, is_static: bool=False, preaccessed_addresses: FrozenSet[Address]=frozenset(), preaccessed_storage_keys: FrozenSet[Tuple[(A... |
.parametrize('number_of_realizations', [100, 200])
def test_that_update_for_a_linear_model_works_with_rowscaling(number_of_realizations):
true_model = LinearModel(a_true, b_true)
ensemble = [LinearModel.random() for _ in range(number_of_realizations)]
A = np.array([[realization.a for realization in ensemble... |
def topic(request, topic_id):
topic = Topic.objects.get(id=topic_id)
is_owner = False
if (request.user == topic.owner):
is_owner = True
if ((topic.owner != request.user) and (not topic.public)):
raise Http404
entries = topic.entry_set.order_by('-date_added')
context = {'topic': t... |
class TreasureHuntHandler(THBEventHandler):
interested = ['action_before']
execute_before = ['CiguateraHandler']
def handle(self, evt_type, act):
if ((evt_type == 'action_before') and isinstance(act, FatetellStage)):
tgt = act.target
if (not tgt.has_skill(TreasureHunt)):
... |
.parametrize('batch_size, drop_last', [(2, False), (8, False), (2, True), (8, True)])
def test_batch_sampler_array(dataset, batch_size, drop_last):
sampler = LengthBasedBatchSampler(dataset, batch_size, drop_last)
EXPECTED_LENGTH = ((SAMPLES // batch_size) if drop_last else ((SAMPLES // batch_size) + (SAMPLES %... |
class ArrayMeta(Meta):
def __getitem__(self, parameters):
if (not isinstance(parameters, tuple)):
parameters = (parameters,)
dtype = None
ndim = None
memview = False
mem_layout = MemLayout.C_or_F
shape = None
positive_indices = False
params... |
class StartCLIParser():
def __init__(self):
super(StartCLIParser, self).__init__()
self.parser = DagdaStartParser(prog='dagda.py start', usage=start_parser_text)
self.parser.add_argument('-d', '--debug', action='store_true')
self.parser.add_argument('-s', '--server_host', type=str)
... |
class OptionSeriesBarSonificationDefaultinstrumentoptionsMappingNoteduration(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: s... |
class ReceiveView(QWidget):
_qr_window: Optional[QR_Window] = None
def __init__(self, main_window: 'ElectrumWindow', account_id: int) -> None:
super().__init__(main_window)
self._main_window = weakref.proxy(main_window)
self._account_id = account_id
self._account = main_window._w... |
def malformed_replyto_error(status):
if request_wants_json():
return jsonerror(500, {'error': '_replyto or email field has not been sent correctly'})
return (render_template('error.html', title='Invalid email address', text=u'You entered <span class="code">{address}</span>. That is an invalid email addr... |
def create_plot():
numpoints = 100
low = (- 5)
high = 15.0
x = linspace(low, high, numpoints)
pd = ArrayPlotData(index=x)
p = Plot(pd, bgcolor='oldlace', padding=50, border_visible=True)
for i in range(10):
pd.set_data(('y' + str(i)), jn(i, x))
p.plot(('index', ('y' + str(i))... |
def read_beats_schema(version: str=None):
if (version and (version.lower() == 'main')):
return json.loads(read_gzip(get_etc_path('beats_schemas', 'main.json.gz')))
version = (Version.parse(version) if version else None)
beats_schemas = get_versions()
if (version and (version not in beats_schemas... |
class ValveRestBcastTestCase(ValveTestBases.ValveTestNetwork):
CONFIG = ('\ndps:\n s1:\n%s\n interfaces:\n p1:\n number: 1\n native_vlan: 0x100\n restricted_bcast_arpnd: true\n p2:\n number: 2\n native_vlan: 0... |
class FilterGreater(BasePyMongoFilter):
def apply(self, query, value):
try:
value = float(value)
except ValueError:
value = 0
query.append({self.column: {'$gt': value}})
return query
def operation(self):
return lazy_gettext('greater than') |
class GroupList(ResourceList):
def query(self, view_kwargs):
query_ = self.session.query(Group)
if (view_kwargs.get('user_id') and ('GET' in request.method)):
query_ = query_.filter_by(user_id=view_kwargs['user_id'])
return query_
view_kwargs = True
decorators = (api.has_... |
def book() -> Struct:
return Struct(name='Book', members={0: ComplexTypeMember(size=32, name='title', offset=0, type=Pointer(Integer.char())), 4: ComplexTypeMember(size=32, name='num_pages', offset=4, type=Integer.int32_t()), 8: ComplexTypeMember(size=32, name='author', offset=8, type=Pointer(Integer.char()))}, siz... |
class Bits(object):
MAX_BITS = 32
def _build_seen_list(self, num):
seen = []
looking_for = 0
count = 0
for _ in range(self.MAX_BITS):
if ((num & 1) != looking_for):
seen.append(count)
looking_for = (not looking_for)
coun... |
(base=RequestContextTask, name='sponsor.logo.urls', bind=True)
def sponsor_logos_url_task(self, event_id):
sponsors = Sponsor.query.filter_by(event_id=event_id, deleted_at=None).all()
for sponsor in sponsors:
try:
logging.info(f'Sponsor logo url generation task started {sponsor.logo_url}')
... |
class Integrations():
def get_integration(config: Config, tracking: Optional[Tracking]=None, override_config_defaults: bool=False) -> BaseIntegration:
if config.has_slack:
return SlackIntegration(config=config, tracking=tracking, override_config_defaults=override_config_defaults)
else:
... |
def downgrade():
op.drop_constraint('email_role_event_uc', 'role_invites', type_='unique')
op.create_unique_constraint('email_role_event_uc', 'role_invites', ['email', 'role_id', 'event_id'])
op.drop_constraint('uq_event_discount_code', 'discount_codes', type_='unique')
op.create_unique_constraint('uq_e... |
('/calls', methods=['GET'])
def calls():
number = request.args.get('number')
search_text = request.args.get('search')
search_type = request.args.get('submit')
search_criteria = ''
if search_text:
if (search_type == 'phone'):
number = transform_number(search_text)
sear... |
def _parse_worker_params(model_name: str=None, model_path: str=None, **kwargs) -> ModelWorkerParameters:
worker_args = EnvArgumentParser()
env_prefix = None
if model_name:
env_prefix = EnvArgumentParser.get_env_prefix(model_name)
worker_params: ModelWorkerParameters = worker_args.parse_args_into... |
.parametrize(('test_input', 'expected_output'), [([], []), ([(1, 2), (2, 3), (1, 3)], [[1, 2, 3]]), ([(1, 2), (2, 3), (1, 3), (1, 4), (2, 4), (3, 4), (1, 5), (2, 5), (3, 5), (4, 5)], [[1, 2, 3, 4, 5]]), ([(1, 2), (2, 3), (1, 3), (1, 4)], [[1, 2, 3], [1, 4]]), ([(1, 2), (2, 3), (1, 3), (1, 4), (3, 4)], [[1, 2, 3], [1, 3... |
def test_oidcclient_login_retry(mocker, client):
oauth2client = mocker.Mock()
client.client = oauth2client
client._tokens = None
client.storage.load.side_effect = (lambda k, d: d)
prompt = mocker.patch('bodhi.client.oidcclient.click.prompt')
prompt.return_value = 'result-code'
secho = mocker... |
def main():
segmk = Segmaker('design.bits')
print('Loading tags')
with open('params.json') as f:
params = json.load(f)
for row in params:
base_name = 'BUFHCE_X{}Y{}'.format(row['x'], row['y'])
segmk.add_site_tag(row['site'], '{}.IN_USE'.format(base_name), row['IN_USE'])
i... |
class IObserver(abc.ABC):
def __hash__(self):
raise NotImplementedError('__hash__ must be implemented.')
def __eq__(self, other):
raise NotImplementedError('__eq__ must be implemented.')
def notify(self):
raise NotImplementedError('notify property must be implemented.')
def iter_... |
.object(source_manager.SourceManager, 'get_source_tree')
def test_find_all_images_from_specified_tags_fail(mock_source_tree):
job_control = proto_control.JobControl(remote=False, scavenging_benchmark=True)
mock_source_tree.return_value = None
manager = source_manager.SourceManager(job_control)
hashes = ... |
def test_zeroed_in_1st_lr():
with pytest.raises(RuntimeError) as excinfo:
_ = dlis.load('data/chap2/zeroed-in-1st-lr.dlis')
assert ('Too short logical record' in str(excinfo.value))
dbg = 'Physical tell: 188 (dec), Logical Record tell: 100 (dec), Logical Record Segment tell: 100 (dec)'
assert (d... |
('pandas.DataFrame.to_parquet')
('pandas.read_parquet')
('flytekit.types.structured.basic_dfs.get_fsspec_storage_options')
def test_pandas_to_parquet_azure_storage_options(mock_get_fsspec_storage_options, mock_read_parquet, mock_to_parquet):
df = pd.DataFrame({'Name': ['Tom', 'Joseph'], 'Age': [20, 22]})
encode... |
class OptionSeriesWordcloudSonificationDefaultinstrumentoptionsMappingPlaydelay(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 extractAm23MtranslationBlogspotCom(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... |
def compile(args):
project_path = (args.path or os.getcwd())
sys.path.append(project_path)
reports_path = utils.get_report_path(project_path)
with open(os.path.join(reports_path, ('%s.md' % args.name)), 'w') as md:
md_dta = md.read()
page = Report()
page.py.markdown.resolve(md_dta)
t... |
class requires(Decorator):
def __init__(self, condition=None, otherwise=None):
if ((condition is None) or (otherwise is None)):
raise SyntaxError('requires usage: (condition, otherwise)')
if ((not callable(otherwise)) and (not isinstance(otherwise, str))):
raise SyntaxError("... |
def get_path(path):
if (type(path) is not str):
if inspect.isclass(path):
klass = path
else:
klass = path.__class__
module_name = klass.__module__
module = sys.modules[module_name]
if (module_name == '__main__'):
dirs = [os.path.dirname(sys... |
class LinearHeatPerturbation(HeatPerturbation):
temperature_ref: pd.NonNegativeFloat = pd.Field(..., title='Reference temperature', description='Temperature at which perturbation is zero.', units=KELVIN)
coeff: Union[(float, Complex)] = pd.Field(..., title='Thermo-optic Coefficient', description='Sensitivity (d... |
class OptionPlotoptionsBubbleSonificationContexttracksMappingVolume(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 mocked_dynamodb_scan():
all_contacts = [{'ListId': '1-simplified', 'SubscriberEmail': '', 'CharacterSet': 'simplified', 'DateSubscribed': '3/18/20', 'Status': 'subscribed'}, {'ListId': '3-traditional', 'SubscriberEmail': '', 'CharacterSet': 'traditional', 'DateSubscribed': '3/18/20', 'Status': 'unsubscribed'}]
... |
class HistogramStatsRequestBadTLVs(base_tests.SimpleProtocol):
def runTest(self):
request = ofp.message.bsn_generic_stats_request(name='histogram', tlvs=[])
(reply, _) = self.controller.transact(request)
self.assertBsnError(reply, 'Expected name TLV, found empty list')
request = ofp.... |
def call(evm: Evm) -> None:
gas = Uint(pop(evm.stack))
to = to_address(pop(evm.stack))
value = pop(evm.stack)
memory_input_start_position = pop(evm.stack)
memory_input_size = pop(evm.stack)
memory_output_start_position = pop(evm.stack)
memory_output_size = pop(evm.stack)
extend_memory = ... |
def flatten_tree(tree, leaf='argmax'):
flat = []
assert (tree.node_count == len(tree.value))
assert (tree.value.shape[1] == 1)
for (left, right, feature, th, value) in zip(tree.children_left, tree.children_right, tree.feature, tree.threshold, tree.value):
if ((left == (- 1)) and (right == (- 1))... |
class PrivateComputationMRPIDOnlyTestStageFlow(PrivateComputationBaseStageFlow):
_order_ = 'CREATED PC_PRE_VALIDATION UNION_PID_MR_MULTIKEY'
CREATED = PrivateComputationStageFlowData(initialized_status=PrivateComputationInstanceStatus.CREATION_INITIALIZED, started_status=PrivateComputationInstanceStatus.CREATIO... |
('/job-execution')
def job_execution_metadata():
workflow_execution_id = request.args.get('workflow_execution_id')
job_execution_list = (scheduler.list_job_executions(workflow_execution_id) if workflow_execution_id else None)
page_job_executions = (Paginator(job_execution_list, int(request.args.get('pageSiz... |
class OptionPlotoptionsAreasplineSonificationDefaultinstrumentoptionsMappingHighpass(Options):
def frequency(self) -> 'OptionPlotoptionsAreasplineSonificationDefaultinstrumentoptionsMappingHighpassFrequency':
return self._config_sub_data('frequency', OptionPlotoptionsAreasplineSonificationDefaultinstrumento... |
def test_pubsub_topic():
pubsub = Pubsub(EventService())
subscriber = DummySubscriber()
publisher = pubsub.create_event_topic(DummyInterface)
pubsub.register_subscriber(subscriber)
publisher.event1()
publisher.event2(param1=1, param2=2)
assert (len(subscriber.events) == 2)
record = subsc... |
def _create_plot_component():
numpts = 500
x1 = random(numpts)
y1 = random(numpts)
x2 = (x1 + (standard_normal(numpts) * 0.05))
y2 = (y1 + (standard_normal(numpts) * 0.05))
pd = ArrayPlotData()
pd.set_data('index', column_stack([x1, x2]).reshape((- 1)))
pd.set_data('value', column_stack(... |
def main():
parser = argparse.ArgumentParser(description='Create timing worksheet for 7-series timing analysis.')
util.db_root_arg(parser)
util.part_arg(parser)
parser.add_argument('--timing_json', required=True)
parser.add_argument('--output_xlsx', required=True)
parser.add_argument('--wire_fil... |
def test_grid_analytic_refinement():
max_dl_list = np.array([0.5, 0.5, 0.4, 0.1, 0.4])
len_interval_list = np.array([2.0, 0.5, 0.2, 0.1, 0.3])
max_scale = 1.5
periodic = True
(left_dl, right_dl) = MESHER.grid_multiple_interval_analy_refinement(max_dl_list, len_interval_list, max_scale, periodic)
... |
class bsn_vport_l2gre(bsn_vport):
type = 1
def __init__(self, flags=None, port_no=None, loopback_port_no=None, local_mac=None, nh_mac=None, src_ip=None, dst_ip=None, dscp=None, ttl=None, vpn=None, rate_limit=None, if_name=None):
if (flags != None):
self.flags = flags
else:
... |
class TestELFHash(unittest.TestCase):
def test_elf_hash(self):
self.assertEqual(ELFHashTable.elf_hash(''), 0)
self.assertEqual(ELFHashTable.elf_hash('main'), 473086)
self.assertEqual(ELFHashTable.elf_hash('printf'), )
self.assertEqual(ELFHashTable.elf_hash('exit'), 446212)
se... |
def add_transaction_to_group(group: Dict[(str, Any)], transaction: TransactionDict) -> Tuple[(Dict[(str, Any)], Dict[(str, int)])]:
for key in ['gasPrice', 'nonce', 'secretKey', 'to']:
if ((key in transaction) and (transaction[key] != group[key])):
raise ValueError(f"Can't add transaction as it ... |
class TestLocalBlobManager(unittest.TestCase):
def setUpClass(cls) -> None:
os.mkdir(_TMP_FOLDER)
os.mkdir(_UPLOAD_FOLDER)
os.mkdir(_DOWNLOAD_FOLDER)
def tearDownClass(cls) -> None:
if os.path.exists(_TMP_FOLDER):
shutil.rmtree(_TMP_FOLDER)
def setUp(self) -> None... |
class LedgerApiDialogues(Model, BaseLedgerApiDialogues):
def __init__(self, **kwargs: Any) -> None:
Model.__init__(self, **kwargs)
def role_from_first_message(message: Message, receiver_address: Address) -> Dialogue.Role:
return BaseLedgerApiDialogue.Role.AGENT
BaseLedgerApiDialo... |
class OptionPlotoptionsSunburstSonification(Options):
def contextTracks(self) -> 'OptionPlotoptionsSunburstSonificationContexttracks':
return self._config_sub_data('contextTracks', OptionPlotoptionsSunburstSonificationContexttracks)
def defaultInstrumentOptions(self) -> 'OptionPlotoptionsSunburstSonific... |
def test_get_included_sum(stats_update_db, backend_db):
(fw, parent_fo, child_fo) = create_fw_with_parent_and_child()
(fw.size, parent_fo.size, child_fo.size) = (1337, 25, 175)
backend_db.add_object(fw)
backend_db.add_object(parent_fo)
backend_db.add_object(child_fo)
result = stats_update_db.get... |
def extractGalaxytranslations97Com(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_typ... |
class Recyclebin(BaseAligo):
def _core_move_file_to_trash(self, body: MoveFileToTrashRequest) -> MoveFileToTrashResponse:
response = self.post(V2_RECYCLEBIN_TRASH, body=body)
return self._result(response, MoveFileToTrashResponse, [202, 204])
def _core_batch_move_to_trash(self, body: BatchMoveToT... |
class OptionPlotoptionsSplineDragdrop(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,... |
def format_suffix_patterns(urlpatterns, suffix_required=False, allowed=None):
suffix_kwarg = api_settings.FORMAT_SUFFIX_KWARG
if allowed:
if (len(allowed) == 1):
allowed_pattern = allowed[0]
else:
allowed_pattern = ('(%s)' % '|'.join(allowed))
suffix_pattern = ('\... |
class TestChangePasswordForm(object):
def test_transforms_to_expected_change_object(self):
data = MultiDict({'old_password': 'old_password', 'new_password': 'password', 'confirm_new_password': 'password', 'submit': True})
form = forms.ChangePasswordForm(formdata=data)
expected = PasswordUpda... |
def _gather_deleted_transaction_keys(config: dict, fabs_external_data_load_date_key: str='fabs', fpds_external_data_load_date_key: str='fpds') -> Optional[Dict[(Union[(str, Any)], Dict[(str, Any)])]]:
if (not config['process_deletes']):
logger.info(format_log(f'Skipping the S3 CSV fetch for deleted transact... |
class Command(BaseRevisionCommand):
help = 'Deletes revisions for a given app [and model].'
def add_arguments(self, parser):
super().add_arguments(parser)
parser.add_argument('--days', default=0, type=int, help='Delete only revisions older than the specified number of days.')
parser.add_... |
class ValveTestOrderedTunnel2DP(ValveTestBases.ValveTestTunnel):
SRC_ID = 6
DST_ID = 2
SAME_ID = 4
NONE_ID = 3
CONFIG = "\nacls:\n src_acl:\n - rule:\n dl_type: 0x0800\n ip_proto: 1\n actions:\n output:\n - tunnel: {dp: s2,... |
class Markdown():
doc_tag = 'div'
output_formats = {'html': to_html_string, 'xhtml': to_xhtml_string}
def __init__(self, **kwargs):
self.tab_length = kwargs.get('tab_length', 4)
self.ESCAPED_CHARS = ['\\', '`', '*', '_', '{', '}', '[', ']', '(', ')', '>', '#', '+', '-', '.', '!']
sel... |
class FlyteDirToMultipartBlobTransformer(TypeTransformer[FlyteDirectory]):
def __init__(self):
super().__init__(name='FlyteDirectory', t=FlyteDirectory)
def get_format(t: typing.Type[FlyteDirectory]) -> str:
return t.extension()
def _blob_type(format: str) -> _core_types.BlobType:
re... |
class OptionPlotoptionsScatter3dSonificationDefaultinstrumentoptionsMappingHighpassFrequency(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 map... |
class TagList(ResourceList):
def query(self, view_kwargs):
query_ = self.session.query(Tag)
if view_kwargs.get('event_id'):
event = safe_query_kwargs(Event, view_kwargs, 'event_id')
query_ = query_.join(Event).filter((Event.id == event.id)).order_by(Tag.id.asc())
retu... |
class MDTextEdit(QTextEdit):
def __init__(self, parent=None):
super(QTextEdit, self).__init__(parent)
self.text_was_pasted = False
def setMarkdown(self, markdown):
if ('setMarkdown' in QTextEdit.__dict__):
super(MDTextEdit, self).setMarkdown(markdown)
else:
... |
def extractRvstranslationsWordpressCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [('AUC', 'Appreciation of Unconventional Plants', 'translated'), ('HCTCTM', 'How Could This ... |
def resize_volume_claim(volume_name, new_capacity):
data = {'capacity': new_capacity}
response = get_session().patch((base_volume_url + '/{}'.format(volume_name)), data=data)
if (response.status_code != 200):
raise get_exception(response)
else:
return response.json()['message'] |
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName('MainWindow')
MainWindow.resize(400, 500)
MainWindow.setMinimumSize(QtCore.QSize(400, 500))
MainWindow.setMaximumSize(QtCore.QSize(400, 510))
MainWindow.setToolTip('')
MainWindow.setA... |
def extractLadysheeptrslWordpressCom(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... |
class OptionSeriesColumnrangeSonificationDefaultinstrumentoptionsMappingTremoloDepth(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,... |
.parametrize('test_input,case_id,entity_id,expected', [('110', 1, 2, [{'text': '110', 'title': '11', 'type': 'regulation', 'url': '/regulations/110/CURRENT'}]), ('110.21', 1, 2, [{'text': '110.21', 'title': '11', 'type': 'regulation', 'url': '/regulations/110-21/CURRENT'}]), ('114.5(a)(3)', 1, 2, [{'text': '114.5(a)(3)... |
def get_prompt(params, data_points, losses, hoped_for_loss):
return '# black box function to be minimized\ndef f({func_params}) -> float:\n """\n parameters:\n{docstring}\n\n returns:\n float: the loss\n """\n return black_box_loss({names})\n\n# experimentally observed data\n# new experiments ... |
class _SecurityCenterOrganizationsFindingsRepository(repository_mixins.CreateQueryMixin, repository_mixins.ListQueryMixin, repository_mixins.PatchResourceMixin, _base_repository.GCPRepository):
def __init__(self, **kwargs):
LOGGER.debug('Creating _SecurityCenterOrganizationsFindingsRepositoryClient')
... |
class AbstractExpiringValue():
def __init__(self, refresh_fn, max_age):
self._refresh_fn = refresh_fn
self._max_age = max_age
self._lock = threading.Lock()
def value(self, refresh=False):
with self._lock:
if ((not refresh) and (not self.is_expired())):
... |
def test_assert_log_level(log_capture):
with AssertLogLevel(log_capture, 'WARNING', contains_str='ABC'):
td.log.warning('ABC')
td.log.warning('ABC')
with pytest.raises(Exception):
assert_log_level(log_capture, 'WARNING', contains_str='DEF')
log_capture.clear()
td.log.info('ABC')
... |
def extractRothramnWordpressCom(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) ... |
def dump_pe(process_controller: ProcessController, pe_file_path: str, image_base: int, oep: int, iat_addr: int, iat_size: int, add_new_iat: bool) -> bool:
process_controller.clear_cached_data()
gc.collect()
with TemporaryDirectory() as tmp_dir:
TMP_FILE_PATH1 = os.path.join(tmp_dir, 'unlicense.tmp2'... |
_decorator(deprecated, name='list')
_decorator(deprecated, name='retrieve')
class AwardAggregateViewSet(FilterQuerysetMixin, AggregateQuerysetMixin, CachedDetailViewSet):
serializer_class = AggregateSerializer
def get_queryset(self):
queryset = Award.objects.all()
queryset = self.filter_records(... |
class desc_stats_reply(stats_reply):
version = 2
type = 19
stats_type = 0
def __init__(self, xid=None, flags=None, mfr_desc=None, hw_desc=None, sw_desc=None, serial_num=None, dp_desc=None):
if (xid != None):
self.xid = xid
else:
self.xid = None
if (flags !... |
class OverworldMapProvider(wilderness.WildernessMapProvider):
def is_valid_coordinates(self, wilderness, coordinates):
in_lower_bound = super().is_valid_coordinates(wilderness, coordinates)
if (not in_lower_bound):
return False
(x, y) = coordinates
if (x >= map.OverworldM... |
class OptionSeriesTreegraphSonificationContexttracksMappingHighpass(Options):
def frequency(self) -> 'OptionSeriesTreegraphSonificationContexttracksMappingHighpassFrequency':
return self._config_sub_data('frequency', OptionSeriesTreegraphSonificationContexttracksMappingHighpassFrequency)
def resonance(s... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.