code stringlengths 281 23.7M |
|---|
.parametrize('name, type_, value, expected', (('atomic_type', 'address', None, {'expected_exception': ValueError, 'match': 'Missing value for field `atomic_type` of type `address`'}), ('non_int_string', 'uint256', 'i am not an int', {'expected_exception': ValueError, 'match': re.escape("invalid literal for int() with b... |
class EmptyTransforms(TestCase, Common, Edges):
def setUp(self):
super().setUp()
self.seq = nutils.transformseq.EmptyTransforms(todims=1, fromdims=1)
self.check = ()
self.checkmissing = ((l1, i10), (x1, i14), (r1, i10))
self.checkrefs = References.empty(1)
self.checkt... |
def extractKashiistoriesBlogspotCom(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_ty... |
def compare_chrom_names(a_regions, b_regions):
a_chroms = set(a_regions.chromosome.unique())
b_chroms = set(b_regions.chromosome.unique())
if (a_chroms and a_chroms.isdisjoint(b_chroms)):
msg = 'Chromosome names do not match between files'
a_fname = a_regions.meta.get('filename')
b_f... |
def test_sensor_task():
sensor = FileSensor(name='test_sensor')
assert (sensor.task_type == 'sensor')
settings = SerializationSettings(project='project', domain='domain', version='version', env={'FOO': 'baz'}, image_config=ImageConfig(default_image=default_img, images=[default_img]))
assert (sensor.get_... |
def test_windows_10_64bit_system_details(pml_reader_windows10_64bit):
system_details = pml_reader_windows10_64bit.system_details()
assert (system_details['Computer Name'] == 'DESKTOP-6PCIALL')
assert (system_details['Operating System'] == 'Windows 10 (build 16299.2)')
assert (system_details['System Root... |
class AutoDecoder(AutoModel[DecoderModule[(TransformerConfig, KeyValueCache)]]):
_base_cls = DecoderModule
_registry = registry.decoders
def from_repo(cls, *, repo: Repository, device: Optional[torch.device]=None, quantization_config: Optional[BitsAndBytesConfig]=None) -> DecoderModule[(TransformerConfig, K... |
class OptionPlotoptionsSplineSonificationTracksMappingPlaydelay(Options):
def mapFunction(self):
return self._config_get(None)
def mapFunction(self, value: Any):
self._config(value, js_type=False)
def mapTo(self):
return self._config_get(None)
def mapTo(self, text: str):
... |
def get_labeled_model_data_list_list(label_and_layout_line_list_list: Sequence[Sequence[Tuple[(str, LayoutLine)]]], data_generator: ModelDataGenerator) -> Sequence[Sequence[LabeledLayoutModelData]]:
return [get_labeled_model_data_list(label_and_layout_line_list, data_generator=data_generator) for label_and_layout_l... |
class Jail(object):
_BACKENDS = ['pyinotify', 'polling', 'systemd']
def __init__(self, name, backend='auto', db=None):
self.__db = db
if (len(name) >= 26):
logSys.warning(('Jail name %r might be too long and some commands might not function correctly. Please shorten' % name))
... |
class OptionSeriesPieSonificationTracksMappingLowpassFrequency(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):
s... |
def extractFujotalkWordpressCom(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 test_lifespan_sync(test_client_factory):
startup_complete = False
shutdown_complete = False
def hello_world(request):
return PlainTextResponse('hello, world')
def run_startup():
nonlocal startup_complete
startup_complete = True
def run_shutdown():
nonlocal shutdow... |
def test_correct_response(client, monkeypatch, elasticsearch_transaction_index, awards_and_transactions):
setup_elasticsearch_test(monkeypatch, elasticsearch_transaction_index)
resp = client.post('/api/v2/search/spending_by_category/cfda', content_type='application/json', data=json.dumps({'filters': {'time_peri... |
class ModelInformer(BaseAction):
def __init__(self, model_id, config_json):
BaseAction.__init__(self, model_id=model_id, config_json=config_json, credentials_json=None)
self.information_file = os.path.join(self._dest_dir, self.model_id, INFORMATION_FILE)
def _write_information_json(self):
... |
class BaseTestBackendDirect():
def _send_and_check_transaction(self, eth_tester, test_transaction, _from):
transaction = assoc(test_transaction, 'from', _from)
txn_hash = eth_tester.send_transaction(transaction)
txn = eth_tester.get_transaction_by_hash(txn_hash)
self._check_transacti... |
def test_admins_removed(session):
data = {'irisSeqId': '1111111', 'irisTags': ['DeltaAdminTextMessage', 'is_from_iris_fanout'], 'messageMetadata': {'actorFbId': '1234', 'adminText': 'You removed yourself as a group admin.', 'folderId': {'systemFolderId': 'INBOX'}, 'messageId': 'mid.$XYZ', 'offlineThreadingId': '', ... |
def get_companies_employees_activity(df: DataFrame, commits_id_field: str, author_email_field: str, company_field: str, result_field: str='Commits') -> DataFrame:
return df.select(f.col(commits_id_field), f.col(author_email_field), f.col(company_field)).groupBy(author_email_field, company_field).agg(f.count(f.col(c... |
class CaseNodeSerializer(AbstractSyntaxTreeNodeSerializer):
def serialize(self, node: CaseNode) -> Dict:
data = super().serialize(node)
data.update({'expression': self._pseudo.serialize(node.expression), 'constant': self._pseudo.serialize(node.constant), 'break_case': node.break_case})
retur... |
class OptionSonificationGlobalcontexttracksMappingGapbetweennotes(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 ReferenceMixin(object):
def __init__(self, references=None, **kwargs):
if (references is None):
references = []
self.references = references
_attr
def references(cls):
secondary_table = create_secondary_table(cls.__name__, 'Link', cls.__tablename__, 'Links', ('%s_Re... |
def test_dpm_solver_diffusers():
from diffusers import DPMSolverMultistepScheduler as DiffuserScheduler
manual_seed(0)
diffusers_scheduler = DiffuserScheduler(beta_schedule='scaled_linear', beta_start=0.00085, beta_end=0.012)
diffusers_scheduler.set_timesteps(30)
refiners_scheduler = DPMSolver(num_i... |
class Benchmarks():
REPOS = os.path.join(_utils.HOME, 'repos')
PYPERFORMANCE = 'pyperformance'
PYSTON = 'pyston'
_SUITES: Dict[(str, Dict[(str, Any)])] = {PYPERFORMANCE: {'url': ' 'reldir': 'pyperformance/data-files/benchmarks', 'show_results': True}, PYSTON: {'url': ' 'reldir': 'benchmarks', 'show_resu... |
class OptionPlotoptionsPyramidSonificationDefaultinstrumentoptionsMappingHighpassResonance(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... |
class port_desc_stats_reply(stats_reply):
version = 5
type = 19
stats_type = 13
def __init__(self, xid=None, flags=None, entries=None):
if (xid != None):
self.xid = xid
else:
self.xid = None
if (flags != None):
self.flags = flags
else:
... |
class SetItemObserver():
__slots__ = ('notify', 'optional')
def __init__(self, *, notify, optional):
self.notify = notify
self.optional = optional
def __hash__(self):
return hash((type(self).__name__, self.notify, self.optional))
def __eq__(self, other):
return ((type(sel... |
def test_authentihash():
names = ['authentihash']
templates = ['{} 3f1b149d07e7e8636636b8b7f7043c40ed64a10bfb046c498432c2d4', '{} 3f1b149d07e7e8636636b8b7f7043c40ed64a10bfb046c498432c2d4', '{}: 3f1b149d07e7e8636636b8b7f7043c40ed64a10bfb046c498432c2d4', '{}: 3f1b149d07e7e8636636b8b7f7043c40ed64a10bfb046c49... |
class OptionSeriesVennSonificationDefaultinstrumentoptions(Options):
def activeWhen(self) -> 'OptionSeriesVennSonificationDefaultinstrumentoptionsActivewhen':
return self._config_sub_data('activeWhen', OptionSeriesVennSonificationDefaultinstrumentoptionsActivewhen)
def instrument(self):
return s... |
class CellDerivatives(FilterBase):
__version__ = 0
filter = Instance(tvtk.CellDerivatives, args=(), allow_none=False, record=True)
input_info = PipelineInfo(datasets=['any'], attribute_types=['any'], attributes=['any'])
output_info = PipelineInfo(datasets=['any'], attribute_types=['any'], attributes=['a... |
def upgrade():
op.add_column('rss_parser_funcs', sa.Column('last_changed', sa.DateTime(), nullable=True))
op.add_column('rss_parser_funcs_version', sa.Column('last_changed', sa.DateTime(), autoincrement=False, nullable=True))
bind = op.get_bind()
sess = Session(bind=bind)
print('Updating date/time s... |
class AbstractPluginInstaller():
_skip_docker_env = (os.getenv('FACT_INSTALLER_SKIP_DOCKER') is not None)
base_path = None
def __init__(self, distribution: (str | None)=None, skip_docker: bool=_skip_docker_env):
self.distribution = (distribution or check_distribution())
self.build_path = (se... |
def _prepare_executable(repository_path: str, exe_path: str, package_name: str, version: str) -> str:
exe_name = _parse_package_name(package_name)
executable = _build_executable_path(exe_path, exe_name)
if (repository_path.upper() != 'LOCAL'):
_download_executables(repository_path, exe_path, package... |
def extractHyakurosTumblrCom(item):
badwords = ['Manga']
if any([(bad in item['tags']) for bad in badwords]):
return None
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = ... |
class TestLabel():
def setup_method(self):
class TestSerializer(serializers.Serializer):
labeled = serializers.IntegerField(label='My label')
self.serializer = TestSerializer()
def test_label(self):
fields = self.serializer.fields
assert (fields['labeled'].label == 'M... |
def load_packages_and_modules(ss: SerializationSettings, project_root: Path, pkgs_or_mods: typing.List[str], options: typing.Optional[Options]=None) -> typing.List[FlyteControlPlaneEntity]:
ss.git_repo = _get_git_repo_url(project_root)
pkgs_and_modules = []
for pm in pkgs_or_mods:
p = Path(pm).resol... |
class TestActionController(unittest.TestCase):
def setUp(self):
self.memo = []
def perform():
self.memo.append('called')
self.action = Action(name='Test', on_perform=perform)
self.action_controller = ActionController()
def test_perform(self):
event = ActionEve... |
_stats_reply_type(ofproto.OFPST_GROUP)
class OFPGroupStats(StringifyMixin):
def __init__(self, group_id, ref_count, packet_count, byte_count, bucket_counters, length=None):
super(OFPGroupStats, self).__init__()
self.group_id = group_id
self.ref_count = ref_count
self.packet_count = p... |
def _expand_window_ragged(model: Model[(InT, InT)], Xr: Ragged) -> Tuple[(Ragged, Callable)]:
nW = model.attrs['window_size']
Y = Ragged(model.ops.seq2col(cast(Floats2d, Xr.data), nW, lengths=Xr.lengths), Xr.lengths)
def backprop(dYr: Ragged) -> Ragged:
return Ragged(model.ops.backprop_seq2col(cast(... |
_FrrZebraMessageBody.register_unknown_type()
_ZebraMessageBody.register_unknown_type()
class ZebraUnknownMessage(_ZebraMessageBody):
def __init__(self, buf):
super(ZebraUnknownMessage, self).__init__()
self.buf = buf
def parse(cls, buf, version=_DEFAULT_VERSION):
return cls(buf)
def ... |
def test_expected_mocking_and_stubbing_fixtures_ooo():
assert (fixtures_test_module.TestMockingAndStubbingFixtures.get_order_of_operations() == ['setup_class', 'set_up_test_fixture', 'setup_method', 'set_up_test_case.mocking_test.simple_mock_works', 'set_up_test_case_action.mocking_test.simple_mock_works.mocking_te... |
def _get_section_label_and_title_text_from_layout_block(layout_block: LayoutBlock) -> Tuple[(Optional[str], str)]:
(section_label_layout_block, section_title_layout_block) = get_section_label_and_title_from_layout_block(layout_block)
return (_get_layout_block_text(section_label_layout_block), section_title_layo... |
class RpmBuild(Build):
epoch = Column(Integer, default=0)
__mapper_args__ = {'polymorphic_identity': ContentType.rpm}
def evr(self):
if (not self.epoch):
self.epoch = self._get_kojiinfo()['epoch']
if (not self.epoch):
self.epoch = 0
return (str(self.ep... |
class bsn_bw_enable_get_request(bsn_header):
version = 6
type = 4
experimenter = 6035143
subtype = 19
def __init__(self, xid=None):
if (xid != None):
self.xid = xid
else:
self.xid = None
return
def pack(self):
packed = []
packed.app... |
_meta(characters.reimu.ReimuExterminateLaunchCard)
class ReimuExterminateLaunchCard():
def effect_string_before(self, act):
if (act.cause == 'damage'):
return f'{N.char(act.source)}: ()( !!!'
else:
return f'{N.char(act.target)},{N.char(act.source)}!'
def sound_effect(sel... |
class Window(QtWidgets.QDialog, QtWidgets.QPlainTextEdit):
def __init__(self, parent=None):
super().__init__(parent)
self.setGeometry(winx, winy, winwidth, winheight)
self.setWindowTitle(patch.getstring('display', 'title', default='EEGsynth logging'))
layout = QtWidgets.QVBoxLayout()... |
class STM32F4UART(BPHandler):
def __init__(self, impl=UARTPublisher):
self.model = impl
_handler(['HAL_UART_Init'])
def hal_ok(self, qemu, bp_addr):
log.info('Init Called')
return (True, 0)
_handler(['HAL_UART_GetState'])
def get_state(self, qemu, bp_addr):
log.info('... |
class XLSStyle():
def __init__(self, bold=False, color=None, bgcolor=None, wrap=False, border=None, number_format=None, font_size=None, centre=False, shrink_to_fit=False):
self.bold = bold
self.color = color
self.bgcolor = bgcolor
self.wrap = wrap
self.border = border
... |
class Command(BaseCommand):
help = 'Update DABS Submission Window Schedule table based on a file or the broker'
def add_arguments(self, parser):
parser.add_argument('--file', help='The file containing schdules. If not provided, schedules are generated based on broker.')
()
def handle(self, *args... |
class OptionSeriesPackedbubbleSonificationDefaultinstrumentoptionsMappingHighpassFrequency(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... |
class IPv4Address(BaseV4, BaseIP):
def __init__(self, address):
BaseIP.__init__(self, address)
BaseV4.__init__(self, address)
if isinstance(address, int):
self._ip = address
if ((address < 0) or (address > self._ALL_ONES)):
raise IPv4IpValidationError(... |
def plot_components(m, fcst, uncertainty=True, plot_cap=True, weekly_start=0, yearly_start=0, figsize=None):
components = ['trend']
if ((m.train_holiday_names is not None) and ('holidays' in fcst)):
components.append('holidays')
if (('weekly' in m.seasonalities) and ('weekly' in fcst)):
comp... |
def test_registering_with_the_decorator_is_working_properly(prepare_publishers):
('Test')
def some_callable():
pass
assert ('test' in publishers[PRE_PUBLISHER_TYPE])
assert isinstance(publishers[PRE_PUBLISHER_TYPE]['test'], list)
assert (publishers[PRE_PUBLISHER_TYPE]['test'][0] == some_call... |
def checkFocus(image_path):
image = cv2.imread(str(image_path))
scale_percent = 15
width = int(((image.shape[1] * scale_percent) / 100))
height = int(((image.shape[0] * scale_percent) / 100))
dim = (width, height)
resized = cv2.resize(image, dim, interpolation=cv2.INTER_AREA)
gray = cv2.cvtC... |
def advanced_search(cls, search, include):
rules = build_rules(search)
query_obj = build_query_obj(cls, search)
qs = cls.objects
if ('invalid' not in include):
qs = qs.valid()
if ('unavailable' not in include):
qs = qs.available()
if ('no_bnf_code' not in include):
qs = q... |
def post(client, **kwargs):
url = '/api/v2/disaster/spending_by_geography/'
request_body = {}
filters = {}
if kwargs.get('def_codes'):
filters['def_codes'] = kwargs['def_codes']
if kwargs.get('award_type_codes'):
filters['award_type_codes'] = kwargs['award_type_codes']
request_bo... |
('/posts', response_model=Page[schemas.Posts], dependencies=[Depends(pagination_params)])
def list_posts(response: Response, db: Session=Depends(get_db), user_id: Optional[int]=None) -> Any:
db_user = ''
if user_id:
db_user = get_user_by_id(db=db, user_id=user_id)
print(db_user)
if db_us... |
(help='parse static analysis output and save to disk')
_context
('--run-kind', type=str)
('--branch', type=str)
('--commit-hash', type=str)
('--job-id', type=str)
('--differential-id', type=int)
('--add-feature', type=str, multiple=True)
('--previous-issue-handles', type=Path(exists=True, path_type=pathlib.Path), help=... |
def import_tags(exaile):
def _on_uris_selected(widget, uris):
import_dialog = GtImporter(exaile, uris)
import_dialog.show()
file_dialog = dialogs.DirectoryOpenDialog(exaile.gui.main.window, title=_('Select directory to import grouping tags from'))
file_dialog.connect('uris-selected', _on_uri... |
def obligations_incurred_award(award_count_sub_schedule, award_count_submission, defc_codes):
award = _normal_award(592)
baker.make('awards.FinancialAccountsByAwards', award=award, parent_award_id='obligations award', disaster_emergency_fund=DisasterEmergencyFundCode.objects.filter(code='M').first(), submission... |
class TlsCertificatesResponse(ModelComposed):
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... |
class LogInstance():
def __init__(self, info: str, latency_unit: str='word') -> None:
self.info = json.loads(info.strip())
self.intervals = []
for (key, value) in self.info.items():
setattr(self, key, value)
self.index = self.info['index']
self.reference = self.in... |
def get_appointments_to_invoice(patient, company):
appointments_to_invoice = []
patient_appointments = frappe.get_list('Patient Appointment', fields='*', filters={'patient': patient.name, 'company': company, 'invoiced': 0, 'status': ['!=', 'Cancelled']}, order_by='appointment_date')
for appointment in patie... |
def __getattr__(name):
not_found = object()
result = not_found
if (name in _toolkit_imports):
from pyface.toolkit import toolkit_object
source = _toolkit_imports[name]
result = toolkit_object(f'data_view.{source}:{name}')
if (result is not_found):
raise AttributeError(f'm... |
def test_file_handler_backend_register_next_step_handler(telegram_bot, private_chat, update_type):
telegram_bot.next_step_backend = FileHandlerBackend(filename='./.handler-saves/step1.save', delay=0.1)
_bot.message_handler(commands=['start'])
def start(message):
message.text = 'entered start'
... |
def find_path(coins, frm, to, amount, online):
neighbor_map = {}
for i in range(amount, ((len(coins) - amount) + 1)):
if (coins[(i - 1)] != coins[i]):
if ((coins[(i - 1)] in online) and (coins[i] in online)):
if (coins[(i - amount):i] == ([coins[(i - 1)]] * amount)):
... |
class PaymentMethodTests(unittest.TestCase):
def test_unicode(self):
payment_method = PaymentMethod()
payment_method.Name = 'test'
self.assertEqual(str(payment_method), 'test')
def test_valid_object_name(self):
obj = PaymentMethod()
client = QuickBooks()
result = ... |
def main(webhook: str):
webhook = SyncWebhook.from_url(webhook, session=requests.Session())
threads = [Browsers, Wifi, Minecraft, BackupCodes, killprotector, fakeerror, startup, disable_defender]
username = getpass.getuser()
configcheck(threads)
for func in threads:
process = threading.Threa... |
def get_function_metrics(mh, cfg, tree):
assert isinstance(mh, Message_Handler)
assert isinstance(cfg, config.Config)
assert isinstance(tree, Compilation_Unit)
metrics = {}
justifications = {}
class Function_Visitor(AST_Visitor):
def visit(self, node, n_parent, relation):
if ... |
def action_to_str(act):
s = act.to_jsondict()[act.__class__.__name__]
t = UTIL.ofp_action_type_to_user(s['type'])
s['type'] = (t if (t != s['type']) else 'UNKNOWN')
if (t == 'SET_FIELD'):
field = s.pop('field')
s['field'] = field['OXMTlv']['field']
s['mask'] = field['OXMTlv']['ma... |
class OptionPlotoptionsPackedbubbleSonificationDefaultinstrumentoptionsMappingNoteduration(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... |
def get_baseline_config(prefilter_poses):
(time_alignment_config, hand_eye_config) = get_basic_config()
if prefilter_poses:
hand_eye_config.algorithm_name = 'baseline_filter'
else:
hand_eye_config.algorithm_name = 'baseline_no_filter'
hand_eye_config.use_baseline_approach = True
hand... |
class OptionChartPanning(Options):
def enabled(self):
return self._config_get(False)
def enabled(self, flag: bool):
self._config(flag, js_type=False)
def type(self):
return self._config_get('x')
def type(self, text: str):
self._config(text, js_type=False) |
def extractSnowbelldotBlogspotCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [('Cold King', 'Cold King, the Doctor Fei Is Running Away', 'translated'), ('the Doctor Fei Is Ru... |
class OptionPlotoptionsSankeySonificationDefaultinstrumentoptionsMappingTremoloDepth(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,... |
def extractWwwXinShouSite(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 tag... |
def key_get(obj: Dict[(str, Any)], key: str, default: Any=_KeyGetNoDefault) -> Any:
split_key = key.split('.')
KeyDoesNotExist = object()
position = obj
for component in split_key:
try:
position = position.get(component, KeyDoesNotExist)
except AttributeError:
try... |
def __plugin_loader(plugin_name):
logprint('loading {}!'.format(plugin_name))
if (not pm.pluginInfo(plugin_name, q=1, loaded=1)):
start_time = time.time()
try:
pm.loadPlugin(plugin_name)
except RuntimeError:
logprint('{} not found!'.format(plugin_name))
... |
def test_check_multi_point_multi_polyon_outside_op():
pol = Polygons((SMALL_POLY_INNER + LARGE_POLY_SHIFTED))
poi = Points([(4.0, 4.0, 0.0), (4.5, 4.0, 0.0), (7.0, 7.0, 0.0), (20.0, 5.0, 0.0)])
assert (len(poi.dataframe) == 4)
poi.operation_polygons(pol, value=1, opname='eli', inside=False, version=1)
... |
def forceStartAccessibilityServer():
if (not fb.evaluateBooleanExpression('[UIView instancesRespondToSelector:(_accessibilityElementsInContainer:)]')):
if isRunningInSimulator():
fb.evaluateEffect('[[UIApplication sharedApplication] accessibilityActivate]')
else:
fb.evaluateE... |
.django_db
def test_get_download_ids(monkeypatch, transaction_type_data, elasticsearch_transaction_index):
setup_elasticsearch_test(monkeypatch, elasticsearch_transaction_index)
results = get_download_ids(['pop tart'], 'transaction_id')
transaction_ids = list(itertools.chain.from_iterable(results))
expe... |
def parse_cnc_request(f):
data = {}
data['version'] = unpack('I', f.read(4))[0]
data['msg_type'] = unpack('I', f.read(4))[0]
if (data['msg_type'] == 1):
data = parse_cnc_request_config(f, data)
f.read(8)
elif (data['msg_type'] == 14):
data['msg_type_decoded'] = 'REPORT_TELNET... |
class OptionSeriesSankeyStatesHoverHalo(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(num, js_... |
def graphs_with_no_propagation_of_contraction_address_assignment():
x = vars('x', 3)
ptr = vars('ptr', 1, type=Pointer(int32))
in_n0 = BasicBlock(0, [_assign(UnaryOperation(OperationType.cast, [x[1]], contraction=True), _addr(x[0])), _assign(x[2], UnaryOperation(OperationType.cast, [x[1]], contraction=True)... |
(help={'fmt': 'Build a local report: report, html, json, annotate, html, xml.', 'open_browser': 'Open the coverage report in the web browser (requires --fmt html)'})
def coverage(c, fmt='report', open_browser=False):
if any(Path().glob('.coverage.*')):
_run(c, 'poetry run coverage combine')
_run(c, f'po... |
class StagingDirectory():
class Error(Exception):
pass
def __init__(self, staging_dir=None):
self._staging = os.path.normpath((staging_dir or tempfile.mkdtemp()))
safe_mkdir(self._staging)
def __deepcopy__(self, memo):
other = StagingDirectory()
memo[id(self)] = other... |
class TestVerbConjugate(TestCase):
([('have', 'have'), ('swim', 'swim'), ('give', 'give'), ('given', 'give'), ('am', 'be'), ('doing', 'do'), ('are', 'be')])
def test_verb_infinitive(self, verb, expected):
self.assertEqual(expected, conjugate.verb_infinitive(verb))
([('inf', 'have', 'have'), ('inf', ... |
(IDropHandler)
class FileDropHandler(HasTraits):
extensions = List(Str)
open_file = Callable
def can_handle_drop(self, event, target):
if event.mimeData().hasUrls():
for url in event.mimeData().urls():
file_path = url.toLocalFile()
if file_path.endswith(tu... |
def _plotGaussianKDE(axes: 'Axes', plot_config: 'PlotConfig', data: 'DataFrame', label: str):
style = plot_config.histogramStyle()
sample_range = (data.max() - data.min())
indexes = numpy.linspace((data.min() - (0.5 * sample_range)), (data.max() + (0.5 * sample_range)), 1000)
gkde = gaussian_kde(data.va... |
class Command(BaseCommand):
help = ' '.join(["Restart a 'frozen' download job.", " (frozen signifies it didn't complete or fail, and is not a monthly download job)", 'Provide a DownloadJob ID or filename to restart the download process.', 'Depending on environment settings, this will either re-queue the download o... |
def new_watched_window() -> Generator:
window_session = WindowSession({0: 1})
window_session.setup()
watcher = WindowWatcher(window_session.get_first_window())
watcher.start()
sleep(0.1)
(yield (window_session.get_first_window(), watcher))
watcher.stop()
window_session.destroy() |
class OptionPlotoptionsGaugeAccessibilityPoint(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 OptionSeriesBellcurveSonificationTracksMappingTime(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._c... |
def get_sizes_from_dtype(dtype):
if isinstance(dtype, str):
(head, props) = dtype.split('-')
if (head == 'fxp'):
if (props[0] == 's'):
signed = True
elif (props[0] == 'u'):
signed = False
else:
raise ValueError('dtyp... |
class Log():
def __init__(self, *args, **kwargs):
self.pc = kwargs['pc']
self.op = kwargs['op']
self.gas = kwargs['gas']
self.gas_cost = kwargs['gasCost']
self.memory = kwargs['memory']
self.memory_size = kwargs['memSize']
self.stack = kwargs['stack']
... |
class TASNode(Node):
def _basic_search_unit(self):
if (len(self.ancestors) == 2):
return Q(**{'tas_rendering_label__iregex': search_regex_of(self.code)})
elif (len(self.ancestors) == 1):
return Q(**{'federal_account__federal_account_code': self.code})
else:
... |
class RandomAsyncUserSelector(AsyncUserSelector):
def __init__(self, data_provider: IFLDataProvider):
super().__init__(data_provider)
def get_random_user(self) -> AsyncUserSelectorInfo:
user_index = np.random.randint(0, self.data_provider.num_train_users())
return AsyncUserSelectorInfo(u... |
class DynamoDBSchema(ConnectionConfigSecretsSchema):
region_name: str = Field(title='Region', description='The AWS region where your DynamoDB table is located (ex. us-west-2).')
aws_access_key_id: str = Field(title='Access Key ID', description='Part of the credentials that provide access to your AWS account.')
... |
class OptionSeriesWindbarbMarker(Options):
def enabled(self):
return self._config_get(None)
def enabled(self, flag: bool):
self._config(flag, js_type=False)
def enabledThreshold(self):
return self._config_get(2)
def enabledThreshold(self, num: float):
self._config(num, js... |
class VPNApplication(Component):
def __init__(self, device, config):
super().__init__(device, config)
self._connected = True
def _get_ips(self, msg, max_ips=0):
msg = (msg + ' Press enter after each one. When finished, just press enter.')
ips = []
while 1:
ip_... |
def process_csv(csv_file):
conn = sqlite3.connect(':memory:')
c = conn.cursor()
c.execute('CREATE TABLE IF NOT EXISTS vulnerabilities (user TEXT, timestamp TEXT, appname TEXT, version_file TEXT, file_version TEXT, secure_version TEXT, cve TEXT)')
conn.commit()
with open(csv_file, newline='') as csvf... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.