code stringlengths 281 23.7M |
|---|
class TemplateMixin(models.Model):
template_key = ChoicesCharField(_('template'), max_length=100)
class Meta():
abstract = True
def template(self):
return self.TEMPLATES_DICT.get(self.template_key, self.TEMPLATES[0])
def regions(self):
return self.template.regions
def fill_te... |
class Docstring(object):
def __init__(self, docstring: Optional[str]=None, callable_: Optional[Callable]=None):
if (docstring is not None):
self._parsed_docstring = parse(docstring)
else:
self._parsed_docstring = parse(callable_.__doc__)
def input_descriptions(self) -> Di... |
def extractWwwDreampotatoCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [('Magis Grandson', "Magi's Grandson", 'translated'), ('I Was a Sword When I Reincarnated (WN)', 'I Wa... |
.parametrize('_input_type, expected_esd_hash, message_to_encode', (('Example data from EIP-712', 'be609aee343fb3c4b28e1df9e632fca64fcfaede20f02e86244efddf30957bd2', {'types': {'EIP712Domain': [{'name': 'name', 'type': 'string'}, {'name': 'version', 'type': 'string'}, {'name': 'chainId', 'type': 'uint256'}, {'name': 've... |
_os(*metadata.platforms)
def main():
masquerade = '/tmp/eggshell'
if (common.CURRENT_OS == 'linux'):
source = common.get_path('bin', 'linux.ditto_and_spawn')
common.copy_file(source, masquerade)
else:
common.create_macos_masquerade(masquerade)
common.log('Launching fake commands ... |
def upgrade():
with op.batch_alter_table('flicket_post') as batch_op:
batch_op.alter_column('hours', existing_type=sa.Numeric(precision=10, scale=0), type_=sa.Numeric(precision=10, scale=2), existing_nullable=True, existing_server_default=sa.text("'0'"))
with op.batch_alter_table('flicket_topic') as bat... |
def catch_exception(fun):
(fun, assigned=available_attrs(fun))
def wrap(*args, **kwargs):
if kwargs.pop('fail_silently', True):
try:
return fun(*args, **kwargs)
except Exception as e:
logger.exception(e)
logger.error('Got exception ... |
class OptionSeriesColumnrangeOnpointPosition(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_typ... |
.django_db
def test_state_metadata_success(client, state_data):
resp = client.get(state_metadata_endpoint('01'))
assert (resp.status_code == status.HTTP_200_OK)
assert (resp.data == EXPECTED_STATE)
resp = client.get(state_metadata_endpoint('02'))
assert (resp.status_code == status.HTTP_200_OK)
a... |
def test_use_callable_class_event_listener():
browser = pychrome.Browser()
tab = browser.new_tab()
tab.start()
tab.Network.requestWillBeSent = CallableClass(tab)
tab.Network.enable()
try:
tab.Page.navigate(url='chrome://newtab/')
except pychrome.UserAbortException:
pass
i... |
class ValveEgressACLTestCase(ValveTestBases.ValveTestNetwork):
def setUp(self):
self.setup_valves(CONFIG)
def test_vlan_acl_deny(self):
ALLOW_HOST_V6 = 'fc00:200::1:1'
DENY_HOST_V6 = 'fc00:200::1:2'
FAUCET_V100_VIP = 'fc00:100::1'
FAUCET_V200_VIP = 'fc00:200::1'
a... |
(Collection)
class CollectionAdmin(CustomAdmin):
autocomplete_fields = ['curators']
fields = ['id', 'name', 'curators']
inlines = [BookInline]
list_display = ['id', 'name']
list_display_links = ['name']
list_filter = [CuratorsFilter, BookFilter]
list_filter_auto = [AutocompleteFilterFactory(... |
.usefixtures('use_tmpdir')
def test_gen_kw_log_appended_extra():
with open('config_file.ert', 'w', encoding='utf-8') as fout:
fout.write(dedent('\n NUM_REALIZATIONS 1\n GEN_KW KW_NAME template.txt kw.txt prior.txt\n '))
with open('template.txt', 'w', encoding='utf-8') as fh:
... |
class FunctionSignature(SignatureMixin):
name = str()
return_value = TypeHint.Unknown
sometimes_null = False
def get_callback(cls, *arguments):
return cls.run
def optimize(cls, arguments):
return FunctionCall(cls.name, arguments)
def alternate_render(cls, arguments, precedence=No... |
class BaseConfiguration(object):
WriteConfigJson.json_exists()
DEBUG = False
TESTING = False
EXPLAIN_TEMPLATE_LOADING = False
try:
with open(config_file, 'r') as f:
config_data = json.load(f)
db_username = config_data['db_username']
db_password = config_data['db_p... |
def test_child_container_parent_name():
class ChildContainer(containers.DeclarativeContainer):
dependency = providers.Dependency()
class Container(containers.DeclarativeContainer):
child_container = providers.Container(ChildContainer)
with raises(errors.Error, match='Dependency "Container.ch... |
def test_entity_storage_add_entity_asset(create_test_db, create_project, prepare_entity_storage):
from stalker import Asset
project = create_project
char1 = Asset.query.filter((Asset.project == project)).filter((Asset.name == 'Char1')).first()
assert (char1 is not None)
storage = EntityStorage()
... |
def extractBlueSilverTranslations(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol or frag)) or ('preview' in item['title'].lower())):
return None
if ('Douluo Dalu' in item['tags']):
proc_str = ('%s %s' % (item['tags'], item['title']))
... |
(init=True, repr=True, eq=True, frozen=True)
class PlatformConfig(object):
endpoint: str = 'localhost:30080'
insecure: bool = False
insecure_skip_verify: bool = False
ca_cert_file_path: typing.Optional[str] = None
console_endpoint: typing.Optional[str] = None
command: typing.Optional[typing.List... |
def extractBloomingsilkBlogspotCom(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 Cli():
def __init__(self):
self.parser = None
self.list_pvcs = False
self.list_nodes = False
self.node = None
self.list_pods = False
self.pod = None
self.container = None
self.namespace = 'default'
self.all_namespaces = False
self... |
class HelpdeskCommentRequest(BaseZendeskRequest):
def put(self, endpoint, article, comment):
url = self.api._build_url(endpoint(article, comment.id))
payload = self.build_payload(comment)
return self.api._put(url, payload)
def post(self, endpoint, article, comment):
url = self.ap... |
def get_available_ram() -> int:
if (sys.platform == 'linux'):
return _get_available_ram_linux()
elif (sys.platform == 'darwin'):
return _get_available_ram_macos()
elif (sys.platform == 'win32'):
return _get_available_ram_windows()
elif sys.platform.startswith('freebsd'):
... |
.parametrize('charset,data', [('utf-8', b'Impossible byte: \xff'), ('utf-8', b'Overlong... \xfc\x83\xbf\xbf\xbf\xbf ... sequence'), ('ascii', b'\x80\x80\x80'), ('pecyn', b'AAHEHlRoZSBGYWxjb24gV2ViIEZyYW1ld29yaywgMjAxOQ==')])
def test_invalid_text_or_charset(charset, data):
data = (((b'--BOUNDARY\r\nContent-Disposit... |
def auth0_dataset_config(db: Session, auth0_connection_config: ConnectionConfig, auth0_dataset: Dict[(str, Any)]) -> Generator:
fides_key = auth0_dataset['fides_key']
auth0_connection_config.name = fides_key
auth0_connection_config.key = fides_key
auth0_connection_config.save(db=db)
ctl_dataset = Ct... |
class Number(Param[(IT, OT)]):
min_value: Optional[int] = None
max_value: Optional[int] = None
number_aliases: Mapping[(IT, OT)]
def _init_options(self, min_value: Optional[int]=None, max_value: Optional[int]=None, number_aliases: Mapping[(IT, OT)]=None, **kwargs: Any) -> None:
if (min_value is ... |
class OptionSeriesSankeyPointEvents(Options):
def click(self):
return self._config_get(None)
def click(self, value: Any):
self._config(value, js_type=False)
def drag(self):
return self._config_get(None)
def drag(self, value: Any):
self._config(value, js_type=False)
de... |
def main():
instr_set_keys = list(INSTRUCTION_SET_MAPPING.keys())
instr_mode_keys = list(INSTRUCTION_MODE_MAPPING.keys())
parser = argparse.ArgumentParser(description='Generate a Yara rule based on disassembled code', formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument('-i', '--instructio... |
def add_sync_from_checkpoint_arg(arg_group: _ArgumentGroup) -> None:
add_shared_argument(arg_group, '--sync-from-checkpoint', action=NormalizeCheckpointURI, help='Start syncing from a trusted checkpoint specified using URI syntax:By specific block, eth://block/byhash/<hash>?score=<score>Let etherscan pick a block n... |
class WebhooksApi(CRUDApi):
def __init__(self, config):
super(WebhooksApi, self).__init__(config, object_type='webhook')
def update(self, webhook_id, new_webhook):
payload = dict(webhook=json.loads(json.dumps(new_webhook, default=json_encode_for_zendesk)))
url = self._build_url(endpoint=... |
def ovlp3d_12(ax, da, A, bx, db, B):
result = numpy.zeros((3, 6), dtype=float)
x0 = ((ax + bx) ** (- 1.0))
x1 = (x0 * ((ax * A[0]) + (bx * B[0])))
x2 = (- x1)
x3 = (x2 + A[0])
x4 = (x2 + B[0])
x5 = (x3 * x4)
x6 = ((ax * bx) * x0)
x7 = ((((5. * da) * db) * (x0 ** 1.5)) * numpy.exp(((-... |
.parametrize('abi_type,should_match', (('SomeEnum.SomeValue', True), ('Some_Enum.Some_Value', True), ('SomeEnum.someValue', True), ('SomeEnum.some_value', True), ('__SomeEnum__.some_value', True), ('__SomeEnum__.__some_value__', True), ('SomeEnum.__some_value__', True), ('uint256', False)))
def test_is_probably_enum(ab... |
def get_linked_anki_notes_for_pdf_page(siac_nid: int, page: int) -> List[IndexNote]:
conn = _get_connection()
nids = conn.execute(f'select nid from notes_pdf_page where siac_nid = {siac_nid} and page = {page}').fetchall()
if ((not nids) or (len(nids) == 0)):
return []
nids_str = ','.join([str(ni... |
class ProcessMethodCommandHandler(ProcessCommandHandler):
def __init__(self, name: str):
super().__init__(name)
try:
self.method = getattr(psutil.Process, self.name)
except AttributeError:
self.method = None
return
def handle(self, param: str, process: psu... |
class TestLinearsRGBSerialize(util.ColorAssertsPyTest):
COLORS = [('color(srgb-linear 0 0.3 0.75 / 0.5)', {}, 'color(srgb-linear 0 0.3 0.75 / 0.5)'), ('color(srgb-linear 0 0.3 0.75)', {'alpha': True}, 'color(srgb-linear 0 0.3 0.75 / 1)'), ('color(srgb-linear 0 0.3 0.75 / 0.5)', {'alpha': False}, 'color(srgb-linear ... |
def get_edge_bias(cnarr, margin):
output_by_chrom = []
for (_chrom, subarr) in cnarr.by_chromosome():
tile_starts = subarr['start'].values
tile_ends = subarr['end'].values
tgt_sizes = (tile_ends - tile_starts)
losses = edge_losses(tgt_sizes, margin)
gap_sizes = (tile_star... |
.usefixtures('use_tmpdir')
def test_that_values_with_brackets_are_ommitted(caplog, joblist):
forward_model_list: List[ForwardModel] = set_up_forward_model(joblist)
forward_model_list[0].environment['ENV_VAR'] = '<SOME_BRACKETS>'
run_id = 'test_no_jobs_id'
context = SubstitutionList.from_dict({'DEFINE': ... |
class Test(unittest.TestCase):
def test_emapper_diamond(self):
in_file = 'tests/fixtures/test_queries.fa'
data_dir = 'tests/fixtures'
outdir = 'tests/integration/out'
outprefix = 'test'
obs_seed_orthologs = os.path.join(outdir, (outprefix + SEED_ORTHOLOGS_SUFFIX))
obs... |
def extractFableWind(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
if ('WATTT' in item['tags']):
return buildReleaseMessageWithType(item, 'WATTT', vol, chp, frag=frag, postfix=po... |
.skipif((ProgressBar is None), reason='requires numba_progress')
.parametrize('use_progressbar', (True, False))
def test_initialize_progressbar(use_progressbar):
with initialize_progressbar(3, use_progressbar) as progress_proxy:
if use_progressbar:
assert isinstance(progress_proxy, ProgressBar)
... |
_os(metadata.platforms)
def main():
common.log('Creating a fake unshare executable..')
masquerade = '/tmp/unshare'
source = common.get_path('bin', 'linux.ditto_and_spawn')
common.copy_file(source, masquerade)
commands = [masquerade, '-rm', 'cap_setuid']
common.log('Launching fake commands to set... |
def BuGn(range, **traits):
_data = dict(red=[(0.0, 0., 0.), (0.125, 0., 0.), (0.25, 0.8, 0.8), (0.375, 0.6, 0.6), (0.5, 0.4, 0.4), (0.625, 0., 0.), (0.75, 0., 0.), (0.875, 0.0, 0.0), (1.0, 0.0, 0.0)], green=[(0.0, 0., 0.), (0.125, 0., 0.), (0.25, 0., 0.), (0.375, 0., 0.), (0.5, 0., 0.), (0.625, 0., 0.), (0.75, 0., ... |
class OptionPlotoptionsSplineSonificationTracksMappingVolume(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... |
def test_invalid_platform_call(tmp_project):
invalid_sd_command = 'python manage.py simple_deploy --platform unsupported_platform_name'
(stdout, stderr) = msp.call_simple_deploy(tmp_project, invalid_sd_command)
assert ('The platform "unsupported_platform_name" is not currently supported.' in stderr)
che... |
class Solution():
def isAlienSorted(self, words: List[str], order: str) -> bool:
def is_in_order(prev, word, track):
for (c1, c2) in zip(prev, word):
if (c1 == c2):
continue
return (track[c1] < track[c2])
return (len(prev) <= len(wo... |
class ConfWithStatsListener(BaseConfListener):
def __init__(self, conf_with_stats):
assert conf_with_stats
super(ConfWithStatsListener, self).__init__(conf_with_stats)
conf_with_stats.add_listener(ConfWithStats.UPDATE_STATS_LOG_ENABLED_EVT, self.on_chg_stats_enabled_conf_with_stats)
... |
def execute(conn: sqlite3.Connection) -> None:
date_created = int(time.time())
conn.execute('CREATE TABLE IF NOT EXISTS MasterKeys (masterkey_id INTEGER PRIMARY KEY,parent_masterkey_id INTEGER DEFAULT NULL,derivation_type INTEGER NOT NULL,derivation_data BLOB NOT NULL,date_created INTEGER NOT NULL,date_updated ... |
class Plotly():
def surface(data: List[dict], y_columns: List[str], x_axis: str, z_axis: str) -> dict:
naps = {'datasets': [], 'series': [], 'python': True}
(z_a, x_a, agg_y) = (set(), set(), {})
for rec in data:
if (z_axis in rec):
z_a.add(rec[z_axis])
... |
def check(ip, domain, port, args, timeout, payload_map):
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket.setdefaulttimeout(int(timeout))
s.connect((ip, int(port)))
s.send(binascii.a2b_hex(args))
byte_result = s.recv(1024)
str_result = str(byte_result... |
class ConfigProxy():
def __init__(self, db: Session) -> None:
self.notifications = NotificationSettingsProxy(db)
self.execution = ExecutionSettingsProxy(db)
self.storage = StorageSettingsProxy(db)
self.security = SecuritySettingsProxy(db)
self.consent = ConsentSettingsProxy(d... |
class OptionSonificationDefaultspeechoptionsMappingRate(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 test_builder_simple_with_multi_meta_field():
manifest = build(BASE_MANIFEST, authors('some', 'guy'), license('MIT'), description('description'), keywords('awesome', 'package'), links(website='www', repository='github'), validate())
expected = assoc(BASE_MANIFEST, 'meta', {'license': 'MIT', 'authors': ['some... |
def summarize_address_range(first, last):
if (not (isinstance(first, BaseIP) and isinstance(last, BaseIP))):
raise IPTypeError('first and last must be IP addresses, not networks')
if (first.version != last.version):
raise IPTypeError('IP addresses must be same version')
if (first > last):
... |
class CommandLayer(Module):
def __init__(self, transport):
self.transport = transport
self.transport.set_command(self)
self.hdd = None
self.n = None
def set_hdd(self, hdd):
self.hdd = hdd
self.transport.n = hdd.n
self.transport.link.n = hdd.n
def callb... |
class OptionPlotoptionsBarAccessibilityPoint(Options):
def dateFormat(self):
return self._config_get(None)
def dateFormat(self, text: str):
self._config(text, js_type=False)
def dateFormatter(self):
return self._config_get(None)
def dateFormatter(self, value: Any):
self._... |
class NoteList(QTableWidget):
def __init__(self, parent):
self.parent = parent
super(NoteList, self).__init__(parent)
self.setColumnCount(4)
self.setHorizontalHeaderLabels(['Title', '', '', ''])
self.horizontalHeader().setSectionResizeMode(0, QHeaderView.ResizeMode.Stretch)
... |
def _replace_charref(s):
s = s.group(1)
if (s[0] == '#'):
if (s[1] in 'xX'):
num = int(s[2:].rstrip(';'), 16)
else:
num = int(s[1:].rstrip(';'))
if (num in _invalid_charrefs):
return _invalid_charrefs[num]
if ((55296 <= num <= 57343) or (num > ... |
class OptionPlotoptionsSankeySonificationContexttracksMappingPitch(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 TestFilterMisc(util.ColorAsserts, unittest.TestCase):
def test_srgb(self):
self.assertColorEqual(Color('red').filter('sepia', space='srgb'), Color('rgb(100.22 88.995 69.36)'))
self.assertColorNotEqual(Color('red').filter('sepia'), Color('red').filter('sepia', space='srgb'))
def test_bad_sp... |
def extractThat1VillainessCom(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 _lex_char_or_cs(text: str) -> Tuple[(str, str)]:
if (text == '\x1b'):
return ('', text)
i = 1
if text.startswith('\x1b['):
try:
i = len('\x1b[')
while (text[i] not in string.ascii_letters):
i += 1
i += 1
except IndexError:
... |
def _check_aea_version(package_configuration: PackageConfiguration) -> None:
current_aea_version = Version(__aea_version__)
version_specifiers = package_configuration.aea_version_specifiers
if (current_aea_version not in version_specifiers):
raise AEAVersionError(package_configuration.public_id, pac... |
def test_generate_predictable_pipeline_id():
app_name = 'testspinnakerapplication'
pipeline_name = 'testspinnakerpipeline'
uuid_1 = generate_predictable_pipeline_id(app_name, pipeline_name)
uuid_2 = generate_predictable_pipeline_id(app_name, pipeline_name)
assert (uuid_1 == uuid_2) |
_frequency(timedelta(days=1))
def fetch_production(zone_key: ZoneKey, session: (Session | None)=None, target_datetime: (datetime | None)=None, logger: Logger=getLogger(__name__)) -> list[dict]:
check_valid_parameters(zone_key, session, target_datetime)
ses = (session or Session())
data_mapping = PRODUCTION_... |
def _is_supported_gemm_or_bmm(gemm_or_bmm_op: Operator, slice_op: Operator) -> bool:
if (not gemm_or_bmm_op._attrs['op'].startswith(('gemm_rcr', 'bmm'))):
return False
slice_output_tensor = slice_op._attrs['outputs'][0]
slice_output_rank = slice_output_tensor._rank()
op_inputs = gemm_or_bmm_op._... |
class CanSaveMixin(HasTraits):
filepath = Str()
dirty = Bool(False)
def __getstate__(self):
state = super().__getstate__()
del state['filepath']
del state['dirty']
return state
def validate(self):
return (True, '')
def save(self):
raise NotImplementedE... |
class desc_stats_reply(stats_reply):
version = 3
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 FaucetUntaggedIPv4LACPMismatchTest(FaucetUntaggedIPv4LACPTest):
def test_untagged(self):
first_host = self.hosts_name_ordered()[0]
orig_ip = first_host.IP()
switch = self.first_switch()
bond_members = [pair[0].name for pair in first_host.connectionsTo(switch)]
bond_cmds... |
class OptionPlotoptionsFunnel3dSonificationDefaultinstrumentoptionsMappingLowpass(Options):
def frequency(self) -> 'OptionPlotoptionsFunnel3dSonificationDefaultinstrumentoptionsMappingLowpassFrequency':
return self._config_sub_data('frequency', OptionPlotoptionsFunnel3dSonificationDefaultinstrumentoptionsMa... |
def test_delivery_receipt_user(session):
data = {'deliveredWatermarkTimestampMs': '', 'irisSeqId': '1111111', 'irisTags': ['DeltaDeliveryReceipt', 'is_from_iris_fanout'], 'messageIds': ['mid.$XYZ', 'mid.$ABC'], 'requestContext': {'apiArgs': {}}, 'threadKey': {'otherUserFbId': '1234'}, 'class': 'DeliveryReceipt'}
... |
def extractAwildbardWordpressCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [('Garudeina translations', 'Garudeina', 'translated')]
for (tagname, name, tl_type) in tagmap... |
class ShadowedLocalVariablePattern(DeclarationUtils, AbstractAstPattern):
name = 'Shadowed Local Variable'
description = 'Reports local variable declarations that shadow declarations from outer scopes.'
severity = Severity.MEDIUM
tags = {}
def find_matches(self) -> Iterator[PatternMatch]:
as... |
def transform_notebook(path: Path) -> str:
(filename, assets_folder) = create_folders(path)
img_folder = (assets_folder / 'img')
plot_data_folder = (assets_folder / 'plot_data')
save_folder = assets_folder.joinpath('..').resolve()
nb = load_notebook(path)
nb_metadata = load_nb_metadata()
mdx... |
def iter_fasta_seqs(source):
if os.path.isfile(source):
if source.endswith('.gz'):
import gzip
_source = gzip.open(source)
else:
_source = open(source, 'r')
else:
_source = iter(source.split('\n'))
seq_chunks = []
seq_name = None
for line i... |
class Migration(migrations.Migration):
dependencies = [('sites', '0002_alter_domain_unique'), ('manager', '0028_reviewer')]
operations = [migrations.CreateModel(name='CustomField', fields=[('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('label', models.CharFie... |
def parseResolveInfo(parcel: ParcelParser, parent: Field) -> None:
component_info_field = parcel.parse_field('componentInfoType', 'int32', parcel.readInt32, parent)
component_info_type = component_info_field.content
if (component_info_type == 1):
parcel.parse_field('activityInfo', 'android.content.p... |
class NodeUpdateView(APIView):
LOCK = 'system_node_update:%s'
dc_bound = False
def __init__(self, request, hostname, data):
super(NodeUpdateView, self).__init__(request)
self.hostname = hostname
self.data = data
self.node = get_node(request, hostname)
def _update_v2(self,... |
_dict
def _fill_transaction(transaction, block, transaction_index, is_pending, overrides=None):
is_dynamic_fee_transaction = (any(((_ in transaction) for _ in DYNAMIC_FEE_TRANSACTION_PARAMS)) or (not any(((_ in transaction) for _ in (DYNAMIC_FEE_TRANSACTION_PARAMS + ('gas_price',))))))
if (overrides is None):
... |
def test_logger_without_stacktrace_config(logbook_logger, logbook_handler):
logbook_handler.client.config.auto_log_stacks = False
with logbook_handler.applicationbound():
logbook_logger.warning('This is a test warning')
event = logbook_handler.client.events[ERROR][0]
assert ('stacktrace' not in ... |
class ExpressionStatement(SimpleStatement):
expression: Expression
def cfg(self, expression):
return expression.cfg
def variables_post(self, expression):
return expression.variables_post
def changed_variables(self, expression):
return expression.changed_variables
def expressi... |
def test_list_plots(fs: pyfakefs.fake_filesystem.FakeFilesystem) -> None:
fs.create_file('/t/plot-k32-0.plot', st_size=(108 * GB))
fs.create_file('/t/plot-k32-1.plot', st_size=(108 * GB))
fs.create_file('/t/.plot-k32-2.plot', st_size=(108 * GB))
fs.create_file('/t/plot-k32-3.plot.2.tmp', st_size=(108 * ... |
class OptionPlotoptionsVariwideSonificationTracksMappingLowpassResonance(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 OptionSeriesTreemapSonificationTracksMappingTime(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._con... |
class ExinwanEffect(GenericAction):
card_usage = 'drop'
def apply_action(self):
g = self.game
tgt = self.target
if tgt.dead:
return False
cards = user_choose_cards(self, tgt, ('cards', 'showncards', 'equips'))
if cards:
g.process_action(DropCards(t... |
def test_addAxisDescriptor():
ds = DesignSpaceDocument()
axis = ds.addAxisDescriptor(name='Weight', tag='wght', minimum=100, default=400, maximum=900)
assert (ds.axes[0] is axis)
assert isinstance(axis, AxisDescriptor)
assert (axis.name == 'Weight')
assert (axis.tag == 'wght')
assert (axis.m... |
def test_parse_schema_accepts_nested_records_from_arrays():
parsed_schema = fastavro.parse_schema({'fields': [{'type': {'items': {'type': 'record', 'fields': [{'type': 'string', 'name': 'text'}], 'name': 'Nested'}, 'type': 'array'}, 'name': 'multiple'}, {'type': {'type': 'array', 'items': 'Nested'}, 'name': 'single... |
def fetch_consumption(zone_key: str='IN-KA', session: (Session | None)=None, target_datetime: (datetime | None)=None, logger: Logger=getLogger(__name__)) -> dict:
if target_datetime:
raise NotImplementedError('This parser is not yet able to parse past dates')
zonekey.assert_zone_key(zone_key, 'IN-KA')
... |
def _add_headers_to_environ(env, headers):
if headers:
try:
items = headers.items()
except AttributeError:
items = headers
for (name, value) in items:
name_wsgi = name.upper().replace('-', '_')
if (name_wsgi not in ('CONTENT_TYPE', 'CONTENT_LEN... |
def gnerate_all_users(cursor):
users = []
users_f = ['ZhangWei', 'LiQiang', 'ZhangSan', 'LiSi']
users.extend(user_build(users_f, 'China', 'Male'))
users_m = ['Hanmeimei', 'LiMeiMei', 'LiNa', 'ZhangLi', 'ZhangMing']
users.extend(user_build(users_m, 'China', 'Female'))
users1_f = ['James', 'John',... |
class IFLChannel(abc.ABC):
def __init__(self, **kwargs):
init_self_cfg(self, component_class=__class__, config_class=FLChannelConfig, **kwargs)
self.stats_collector = (ChannelStatsCollector() if self.cfg.report_communication_metrics else None)
def _set_defaults_in_cfg(cls, cfg):
pass
... |
(name='remove_similarities')
def remove_similarities(rated_model, object_id):
from django.apps import apps
from recommends.providers import recommendation_registry
ObjectClass = apps.get_model(*rated_model.split('.'))
provider_instance = recommendation_registry.get_provider_for_content(ObjectClass)
... |
def _brief_loop(image: 'float64[:,:]', descriptors: 'uint8[:,:]', keypoints: 'intp[:,:]', pos0: Ai2, pos1: Ai2):
for k in range(len(keypoints)):
(kr, kc) = keypoints[k]
for p in range(len(pos0)):
(pr0, pc0) = pos0[p]
(pr1, pc1) = pos1[p]
descriptors[(k, p)] = (ima... |
def parse_elasticsearch_response(hits):
results = []
for city in hits['aggregations']['cities']['buckets']:
if (len(city['states']['buckets']) > 0):
for state_code in city['states']['buckets']:
results.append(OrderedDict([('city_name', city['key']), ('state_code', state_code[... |
def test_not_codecov(cookies, tmp_path):
with run_within_dir(tmp_path):
result = cookies.bake(extra_context={'codecov': 'n'})
assert (result.exit_code == 0)
assert (not os.path.isfile(f'{result.project_path}/codecov.yaml'))
assert (not os.path.isfile(f'{result.project_path}/.github/w... |
class TestPCF2LiftMetadataCompactionStageService(IsolatedAsyncioTestCase):
def setUp(self) -> None:
self.mock_mpc_svc = MagicMock(spec=MPCService)
self.mock_mpc_svc.onedocker_svc = MagicMock()
onedocker_binary_config_map = defaultdict((lambda : OneDockerBinaryConfig(tmp_directory='/test_tmp_... |
class OptionSeriesParetoSonificationTracksMappingTremoloDepth(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... |
class OptionPlotoptionsVariablepieSonificationTracksMappingNoteduration(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):
... |
_traitsui
class TestDatetimeEditor(SimpleEditorTestMixin, unittest.TestCase):
traitsui_name = 'DatetimeEditor'
factory_name = 'datetime_editor'
def test_str_to_obj_conversions(self):
obj = None
obj_str = _datetime_to_datetime_str(obj)
self.assertEqual(obj_str, '')
self.assert... |
def create_ofinput(filename, ast):
ctx = FrontendCtx(set())
ofinput = ir.OFInput(filename, wire_versions=set(), classes=[], enums=[])
for decl_ast in ast:
if (decl_ast[0] == 'struct'):
superclass = decl_ast[3]
members = [create_member(m_ast, ctx) for m_ast in decl_ast[4]]
... |
def store_ids_in_file(id_iter: List, file_name: str='temp_file', is_numeric: bool=True) -> Tuple[(Path, int)]:
total_ids = 0
file_path = Path(file_name)
with open(str(file_path), 'w') as f:
for id_string in id_iter:
if (not id_string):
continue
total_ids += 1
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.