code stringlengths 281 23.7M |
|---|
class Pig():
def __init__(self, x, y, space):
self.life = 20
mass = 5
radius = 14
inertia = pm.moment_for_circle(mass, 0, radius, (0, 0))
body = pm.Body(mass, inertia)
body.position = (x, y)
shape = pm.Circle(body, radius, (0, 0))
shape.elasticity = 0.... |
class OptionSeriesTimelineSonificationContexttracks(Options):
def activeWhen(self) -> 'OptionSeriesTimelineSonificationContexttracksActivewhen':
return self._config_sub_data('activeWhen', OptionSeriesTimelineSonificationContexttracksActivewhen)
def instrument(self):
return self._config_get('pian... |
class OptionSeriesGaugeSonificationDefaultspeechoptionsMapping(Options):
def pitch(self) -> 'OptionSeriesGaugeSonificationDefaultspeechoptionsMappingPitch':
return self._config_sub_data('pitch', OptionSeriesGaugeSonificationDefaultspeechoptionsMappingPitch)
def playDelay(self) -> 'OptionSeriesGaugeSonif... |
class Platonic(Boxes):
ui_group = 'Unstable'
description = '\n'
SOLIDS = {'tetrahedron': (4, 3), 'cube': (6, 4), 'octahedron': (8, 3), 'dodecahedron': (12, 5), 'icosahedro': (20, 3)}
def __init__(self) -> None:
Boxes.__init__(self)
s... |
class SystemMetadata(_common_models.FlyteIdlEntity):
def __init__(self, execution_cluster: str):
self._execution_cluster = execution_cluster
def execution_cluster(self) -> str:
return self._execution_cluster
def to_flyte_idl(self) -> flyteidl.admin.execution_pb2.SystemMetadata:
retur... |
def _create_unfiltered_gain_and_loss_set(configuration: Configuration, accounting_engine: AccountingEngine, input_data: InputData, unfiltered_taxable_event_set: TransactionSet) -> GainLossSet:
gain_loss_set: GainLossSet = GainLossSet(configuration, input_data.asset, MIN_DATE, MAX_DATE)
new_accounting_engine: Ac... |
class WebSocketOutputWriter(BaseOutputWriter):
def __init__(self, socket):
super().__init__(allows_input=False)
self.socket = socket
async def add_interpreter_head_state(self, variable, head, prompt, where, trace, is_valid, is_final, mask, num_tokens, program_variables):
(await self.sock... |
class MaterialLibray(Queryable, smart_union=True):
id: str = Field(title='Material Library ID', description='Material Library ID')
name: str = Field(title='Material Library Name', description='Material Library Name')
medium: Optional[MediumType] = Field(title='medium', description='medium', alias='calcResul... |
class Connect(object):
def __init__(self, core: Core):
self.core = core
self._wsconn = None
core.events.game_created += self.refresh_status
core.events.game_started += self.refresh_status
core.events.game_ended += self.refresh_status
core.events.game_aborted += self.r... |
class TestAddProtocolFailsWhenDifferentPublicId():
def setup_class(cls):
cls.runner = CliRunner()
cls.agent_name = 'myagent'
cls.cwd = os.getcwd()
cls.t = tempfile.mkdtemp()
cls.protocol_id = 'different_author/default:1.0.0'
shutil.copytree(Path(CUR_PATH, '..', 'packa... |
class RefreshMixin(RefreshTokenMutationMixin, RefreshTokenMixin):
def test_refresh_token(self):
with catch_signal(refresh_token_rotated) as refresh_token_rotated_handler, back_to_the_future(seconds=1):
response = self.execute({'refreshToken': self.refresh_token.token})
data = response.da... |
class TestRestoreState(TestCase):
def setUp(self) -> None:
self.restore_state = RestoreRunState()
def test_split_path(self) -> None:
with self.subTest('Valid path'):
self.assertEqual(('fb-pc-data-bucket-wnm6', 'logging/logs_T201923/last'), self.restore_state._split_path('s3://fb-pc-d... |
.parametrize('ecl_like_file, some_valid_kwords, some_notpresent_kwords', [('E100_BO.EGRID', ['FILEHEAD', 'MAPAXES', 'ZCORN', 'NNC1'], []), ('E100_BO.GRID', ['DIMENS', 'GRIDUNIT', 'COORDS'], ['FILEHEAD']), ('E300_BO.EGRID', ['FILEHEAD', 'MAPAXES', 'ZCORN', 'NNC1'], []), ('E300_BO.GRID', ['DIMENS', 'GRIDUNIT', 'COORDS'],... |
def create_functions_section(functions):
section = ''
for f in functions:
section = (((((section + "<span class='separator'>[</span><span class='function_name'><a href='#") + f[0]) + "'>") + f[0]) + "</a></span><span class='separator'>] <span/>")
if (section != ''):
section = (("</pre><code>... |
class Faq(SoftDeletionModel):
id = db.Column(db.Integer, primary_key=True)
question = db.Column(db.String, nullable=False)
answer = db.Column(db.String, nullable=False)
event_id = db.Column(db.Integer, db.ForeignKey('events.id', ondelete='CASCADE'))
faq_type_id = db.Column(db.Integer, db.ForeignKey(... |
class InlineQueryResultCachedMpeg4Gif(InlineQueryResultCachedBase):
def __init__(self, id, mpeg4_file_id, title=None, description=None, caption=None, caption_entities=None, parse_mode=None, reply_markup=None, input_message_content=None):
InlineQueryResultCachedBase.__init__(self)
self.type = 'mpeg4_... |
def test_py_func_task_get_container():
def foo(i: int):
pass
default_img = Image(name='default', fqn='xyz.com/abc', tag='tag1')
other_img = Image(name='other', fqn='xyz.com/other', tag='tag-other')
cfg = ImageConfig(default_image=default_img, images=[default_img, other_img])
settings = Seria... |
def extractGuavareadCom(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 tagma... |
class FieldType(ABC, Generic[T]):
def isinstance(self, obj: Any) -> bool:
raise NotImplementedError()
def description(self) -> str:
raise NotImplementedError()
def python_type(self) -> type:
raise NotImplementedError()
def size(self) -> Optional[int]:
raise NotImplemented... |
class BaseOptions():
def __init__(self):
self.initialized = False
def initialize(self, parser):
parser.add_argument('--name', type=str, default='label2coco', help='name of the experiment. It decides where to store samples and models')
parser.add_argument('--gpu_ids', type=str, default='0... |
def llvm_build_dir(tool):
generator_suffix = cmake_generator_prefix()
bitness_suffix = ('_32' if (tool.bitness == 32) else '_64')
if hasattr(tool, 'git_branch'):
build_dir = ((('build_' + tool.git_branch.replace(os.sep, '-')) + generator_suffix) + bitness_suffix)
else:
build_dir = ((('bu... |
class LineSegmentTool(AbstractOverlay):
component = Instance(Component)
line = Instance(Line, args=())
points = List
event_state = Enum('normal', 'selecting', 'dragging')
proximity_distance = Int(4)
mouse_position = Optional(Tuple)
_dragged = Optional(Int)
_drag_new_point = Bool(False)
... |
class OptionSeriesTreemapSonificationContexttracksMappingGapbetweennotes(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 SnapshotDefineView(APIView):
order_by_default = ('vm__hostname', '-id')
order_by_fields = ('name', 'disk_id')
order_by_field_map = {'hostname': 'vm__hostname', 'created': 'id'}
def get(self, vm, define, many=False, extended=False):
if extended:
ser_class = ExtendedSnapshotDefin... |
def draw_frame(image, face_landmarks):
mp_drawing.draw_landmarks(image=image, landmark_list=face_landmarks, connections=mp_face_mesh.FACEMESH_TESSELATION, landmark_drawing_spec=None, connection_drawing_spec=mp_drawing_styles.get_default_face_mesh_tesselation_style())
mp_drawing.draw_landmarks(image=image, landm... |
def test_setup_load_lists(monkeypatch):
test_object = {'table': {'val1': 4, 'string_val': 'bob'}, 'wrong_table': {'val': 'wrong'}}
(columns, values, pairs) = format_insert_or_update_column_sql(mock_cursor(monkeypatch, 'mogrified'), test_object, 'table')
assert ((columns == '("val1","string_val")') or (colum... |
class RelocationSection(Section):
def __init__(self, header, name, elffile):
super(RelocationSection, self).__init__(header, name, elffile)
if (self.header['sh_type'] == 'SHT_REL'):
expected_size = self.structs.Elf_Rel.sizeof()
self.entry_struct = self.structs.Elf_Rel
... |
class TestAllLoaders(unittest.TestCase):
def test_rc4(self):
filename = os.path.join(os.path.dirname(__file__), './test_apk/loader_rc4_static_key_in_key_class.apk')
apk_object = APK(filename)
dvms = [DEX(dex) for dex in apk_object.get_all_dex()]
rc4 = LoaderRc4(apk_object, dvms, outp... |
(_gemm_matmul)
def do_matmul_i8(N: size, M: size, K: size, A: ([i8][(N, 16)] GEMM_SCRATCH), B: ([i8][(K, 16)] GEMM_SCRATCH), C: ([i32][(N, 16)] GEMM_ACCUM)):
assert (N <= 16)
assert (M <= 16)
assert (K <= 16)
for i in seq(0, N):
for j in seq(0, M):
C[(i, j)] = 0.0
for ... |
def test_fdata_fast_channel_index_conversion(tmpdir, merge_lis_prs):
fpath = os.path.join(str(tmpdir), 'fast-channels-index-conversion.lis')
content = ((headers + ['data/lis/records/curves/dfsr-fast-conversion.lis.part', 'data/lis/records/curves/fdata-fast-conversion.lis.part']) + trailers)
merge_lis_prs(fp... |
def test_fdata_suppressed_bad(tmpdir, merge_lis_prs):
fpath = os.path.join(str(tmpdir), 'suppressed-bad.lis')
content = ((headers + ['data/lis/records/curves/dfsr-suppressed-bad.lis.part']) + trailers)
merge_lis_prs(fpath, content)
with lis.load(fpath) as (f,):
dfs = f.data_format_specs()[0]
... |
class TestSF1DailyData():
data_classes = []
if os.path.exists(config['sf1_data_path']):
data_classes.append(SF1DailyData)
if (secrets['mongodb_adminusername'] is not None):
data_classes.append(SF1DailyDataMongo)
.parametrize('data_loader_class', data_classes)
.parametrize(['tickers',... |
def create_reg_sphere(settings, subject_id, meshes):
(FS_reg_sphere_name, MSMSulc_reg_sphere_name) = get_reg_sphere_names()
run_fs_reg_LR(subject_id, settings.ciftify_data_dir, settings.high_res, FS_reg_sphere_name, meshes['AtlasSpaceNative'])
if (settings.reg_name == 'MSMSulc'):
reg_sphere_name = M... |
def save_oura_token(token_dict):
app.session.execute(delete(apiTokens).where((apiTokens.service == 'Oura')))
try:
app.session.add(apiTokens(date_utc=datetime.utcnow(), service='Oura', tokens=pickle.dumps(token_dict)))
app.session.commit()
except:
app.session.rollback()
app.sessio... |
def test_validate_with_no_runtime_config(jp_environ):
runner = CliRunner()
with runner.isolated_filesystem():
pipeline_file_path = (((Path(__file__).parent / 'resources') / 'pipelines') / 'kfp_3_node_custom.pipeline')
result = runner.invoke(pipeline, ['validate', str(pipeline_file_path)])
... |
class Purge(commands.Cog, name='Purge'):
def __init__(self, client):
self.client = client
async def cog_check(self, ctx):
return self.client.user_is_admin(ctx.author)
(name='purge', hidden=True)
async def purge(self, ctx, num_messages: int):
channel = ctx.message.channel
... |
class CDCDUT(ConverterDUT):
def do_finalize(self):
self.write_user_port.clock_domain = 'user'
self.read_user_port.clock_domain = 'user'
self.write_crossbar_port.clock_domain = 'native'
self.read_crossbar_port.clock_domain = 'native'
self.submodules.write_converter = LiteDRAMN... |
_ARCH_REGISTRY.register()
class MetaArchForTest(torch.nn.Module):
def __init__(self, cfg):
super().__init__()
self.conv = torch.nn.Conv2d(3, 4, kernel_size=3, stride=1, padding=1)
self.bn = torch.nn.BatchNorm2d(4)
self.relu = torch.nn.ReLU(inplace=True)
self.avgpool = torch.n... |
def CreateSoftmaxOperator(manifest, rank=3):
operation_kind = library.OperationKind.Softmax
in_dtype = library.DataType.f16
out_dtype = library.DataType.f16
tile_descriptions = [softmax.TileDesc(256, 8, 32, 1, 8, 1, 1, 1), softmax.TileDesc(256, 8, 32, 1, 8, 1, 8, 8), softmax.TileDesc(256, 4, 64, 1, 8, 1... |
class OptionSeriesErrorbarSonificationDefaultinstrumentoptionsMappingTime(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 extractWeabooDesu(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=p... |
def test_to_from_bytes():
bf = BloomFilter(size=100, hash_funcs=2)
for ii in range(0, 1000, 20):
bf.add(ii)
data = bf.to_bytes()
bf2 = BloomFilter()
for ii in range(0, 1000, 20):
assert (ii not in bf2)
bf2.from_bytes(data)
for ii in range(0, 1000, 20):
assert (ii in b... |
.parametrize('contract_fn,event_name,call_args,expected_args', (('logNoArgs', 'LogAnonymous', [], {}), ('logNoArgs', 'LogNoArguments', [], {}), ('logSingle', 'LogSingleArg', [12345], {'arg0': 12345}), ('logSingle', 'LogSingleWithIndex', [12345], {'arg0': 12345}), ('logSingle', 'LogSingleAnonymous', [12345], {'arg0': 12... |
class OptionSeriesFunnel3dSonificationDefaultinstrumentoptionsMappingTremolo(Options):
def depth(self) -> 'OptionSeriesFunnel3dSonificationDefaultinstrumentoptionsMappingTremoloDepth':
return self._config_sub_data('depth', OptionSeriesFunnel3dSonificationDefaultinstrumentoptionsMappingTremoloDepth)
def ... |
class AppEngineAppIterator(ResourceIterator):
def iter(self):
gcp = self.client
if self.resource.enumerable():
try:
(data, metadata) = gcp.fetch_gae_app(project_id=self.resource['projectId'])
if data:
(yield FACTORIES['appengine_app'].c... |
class ResponseValidationError(PySOAServerError):
def __init__(self, action, errors):
self.action = action
self.errors = errors
def __str__(self):
return '{} had an invalid response:\n\t{}'.format(self.action, '\n\t'.join(('{} {}: {}'.format(error.pointer, error.code, error.message) for e... |
_OptParam.register_type(BGP_OPT_CAPABILITY)
class _OptParamCapability(_OptParam, TypeDisp):
_CAP_HDR_PACK_STR = '!BB'
def __init__(self, cap_code=None, cap_value=None, cap_length=None, type_=None, length=None):
super(_OptParamCapability, self).__init__(type_=BGP_OPT_CAPABILITY, length=length)
if... |
(EcsClient, '__init__')
def test_update_service(client, service):
client.update_service.return_value = RESPONSE_SERVICE
action = EcsAction(client, CLUSTER_NAME, SERVICE_NAME)
new_service = action.update_service(service)
assert isinstance(new_service, EcsService)
client.update_service.assert_called_o... |
class Solution():
def shortestDistance(self, grid: List[List[int]]) -> int:
def find_neighbors(pos, grid, visited):
deltas = [((- 1), 0), (0, (- 1)), (0, 1), (1, 0)]
for (yd, xd) in deltas:
(y, x) = ((pos[0] + yd), (pos[1] + xd))
if (not (0 <= y < len(... |
class GustafssonFullNewton_dt_controller(SC_base):
def __init__(self, model, nOptions):
from .LinearAlgebraTools import WeightedNorm
import copy
SC_base.__init__(self, model, nOptions)
self.nonlinearGrowthRateMax = 2
self.nonlinearGrowthRateMin = 0.5
self.nonlinearCon... |
class RateLimiter(logging.Filter):
def __init__(self, rate: int=3600):
self.rate = rate
self._sent = {}
def filter(self, record: logging.LogRecord) -> bool:
key = '{}:{}'.format(record.pathname, record.lineno)
try:
if (self.rate > (record.created - self._sent[key])):
... |
.django_db
def test_sibling_filters_on_both_siblings(client, monkeypatch, elasticsearch_award_index, multiple_awards_with_sibling_tas):
_setup_es(client, monkeypatch, elasticsearch_award_index)
resp = query_by_tas(client, {'require': [_tas_path(SISTER_TAS[0]), _tas_path(SISTER_TAS[1])]})
assert (resp.json()... |
('input_,is_primitive,expected', [param({'value': 99, 'obj': SimpleClassPrimitiveConf(a={'foo': '${value}'}, b=[1, '${value}'])}, True, SimpleClass(a={'foo': 99}, b=[1, 99]), id='primitive_specified_true'), param({'value': 99, 'obj': SimpleClassNonPrimitiveConf(a={'foo': '${value}'}, b=[1, '${value}'])}, False, SimpleC... |
def get_created_same_day(nid, pinned, limit) -> List[IndexNote]:
try:
nidMinusOneDay = (nid - (((24 * 60) * 60) * 1000))
nidPlusOneDay = (nid + (((24 * 60) * 60) * 1000))
res = mw.col.db.all(('select distinct notes.id, flds, tags, did, mid from notes left join cards on notes.id = cards.nid w... |
class TestProcessValue(object):
def setting_info(self):
return {'value_type': 'range', 'input_range': [100, 2000, 100], 'output_range': [2, 40, 2]}
def setting_info2(self):
return {'value_type': 'range', 'input_range': [1, 20, 1], 'output_range': [1000, 40000, 2000], 'range_length_byte': 2}
... |
class ClockSources(object):
def __init__(self):
self.sources = {}
self.merged_sources = {}
self.source_to_cmt = {}
self.used_sources_from_cmt = {}
def add_clock_source(self, source, cmt):
if (cmt not in self.sources):
self.sources[cmt] = []
self.source... |
class ChannelStatsCollector():
def __init__(self):
self.reset_channel_stats()
def reset_channel_stats(self):
self.communication_stats = {ChannelDirection.CLIENT_TO_SERVER: RandomVariableStatsTracker(), ChannelDirection.SERVER_TO_CLIENT: RandomVariableStatsTracker()}
def get_channel_stats(sel... |
def get_bpftrace_basic_examples(query: str) -> str:
loader = JSONLoader(file_path='./tools/examples.json', jq_schema='.data[].content', json_lines=True)
documents = loader.load()
embeddings = OpenAIEmbeddings()
if (not (os.path.exists('./data_save/vector_db.faiss') and os.path.exists('./data_save/vector... |
class CRawHead(ctypes.Structure):
_fields_ = [('headPosX', ctypes.c_double), ('headPosY', ctypes.c_double), ('headPosZ', ctypes.c_double), ('headYaw', ctypes.c_double), ('headPitch', ctypes.c_double), ('headRoll', ctypes.c_double), ('headPoseConfidence', ctypes.c_double), ('headTranslationSpeedX', ctypes.c_double),... |
def main():
module_spec = schema_to_module_spec(versioned_schema)
mkeyname = 'policyid'
fields = {'access_token': {'required': False, 'type': 'str', 'no_log': True}, 'enable_log': {'required': False, 'type': 'bool', 'default': False}, 'vdom': {'required': False, 'type': 'str', 'default': 'root'}, 'member_pa... |
class TestXLSWorkSheet(unittest.TestCase):
def setUp(self):
self.ws = XLSWorkSheet('Test Worksheet')
def test_work_sheet(self):
ws = self.ws
self.assertEqual(ws.title, 'Test Worksheet')
self.assertEqual(ws.last_column, 'A')
self.assertEqual(ws.last_row, 1)
def test_wo... |
class GroupService(BaseService):
def get(cls, group_id, db_session=None):
db_session = get_db_session(db_session)
return db_session.query(cls.model).get(group_id)
def by_group_name(cls, group_name, db_session=None):
db_session = get_db_session(db_session)
query = db_session.query... |
def _snapshot_initial(shot: System, event: Event) -> None:
for agent in event.agents:
if (agent.agent_type == AgentType.CUE):
agent.set_initial(shot.cue)
elif (agent.agent_type == AgentType.BALL):
agent.set_initial(shot.balls[agent.id])
elif (agent.agent_type == Agent... |
class KeyInstanceTable(BaseWalletStore):
LOGGER_NAME = 'db-table-keyinstance'
CREATE_SQL = 'INSERT INTO KeyInstances (keyinstance_id, account_id, masterkey_id, derivation_type, derivation_data, script_type, flags, description, date_created, date_updated) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'
READ_SQL = 'SE... |
class RequirementStatusAssigned(RequirementStatusBaseExt):
tval = 'assigned'
def __init__(self, _config, rid, txt):
txt_split = txt.split(':')
if (len(txt_split) != 3):
raise RMTException(93, ("%s: Assigned values invalid '%s'" % (rid, txt)))
assert (txt_split[0] == self.tval... |
class StructuredTransforms1DPeriodicInterfacesRight(TestCase, Common):
def setUp(self):
super().setUp()
self.seq = nutils.transformseq.StructuredTransforms(x1, (nutils.transformseq.IntAxis(0, 4, 4, 0, True),), 0)
self.check = ((x1, i10, e0), (x1, i11, e0), (x1, i12, e0), (x1, i13, e0))
... |
class GethMempoolStrategy(BlockGasStrategy):
def __init__(self, position: int=500, graphql_endpoint: str=None, block_duration: int=2, max_gas_price: Wei=None):
super().__init__(block_duration)
self.position = position
if (graphql_endpoint is None):
graphql_endpoint = f'{web3.prov... |
class SplitTest(unittest.TestCase):
def test_split_block(self) -> None:
mod = cst.parse_module(b'from a import x\nfrom b import y\nfrom b import y\nfrom c import x\n')
x = ImportSorter(module=mod, path=Path(), config=Config())
blocks = x.sortable_blocks(mod.children)
self.assertEqual... |
def test_redis_handler_backend_clear_next_step_handler(telegram_bot, private_chat, update_type):
if (not REDIS_TESTS):
pytest.skip('please install redis and configure redis server, then enable REDIS_TESTS')
telegram_bot.next_step_backend = RedisHandlerBackend(prefix='pyTelegramBotApi:step_backend2')
... |
def _get_caller_vars() -> Tuple[(Dict[(str, Any)], Dict[(str, Any)])]:
def _should_skip_frame(frame: FrameType) -> bool:
is_testslide = ((os.path.dirname(__file__) in frame.f_code.co_filename) and ('/tests/' not in frame.f_code.co_filename))
is_typeguard = (os.path.dirname(typeguard.__file__) in fra... |
def test_hasBothOrNeitherAngleBrackets_1():
assert hasBothOrNeitherAngleBrackets('<>')
assert hasBothOrNeitherAngleBrackets('<foo>')
assert hasBothOrNeitherAngleBrackets('< foo >')
assert hasBothOrNeitherAngleBrackets('foo')
assert (not hasBothOrNeitherAngleBrackets('<'))
assert (not hasBothOrNe... |
def extractTambutranslationsBlogspotCom(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... |
()
def teardown(session: nox.Session, volumes: bool=False, images: bool=False) -> None:
for compose_file in COMPOSE_FILE_LIST:
teardown_command = ('docker', 'compose', '-f', compose_file, 'down', '--remove-orphans')
if (volumes or ('volumes' in session.posargs)):
teardown_command = (*tea... |
def test_snapshot_revert_to_specific(w3):
w3.testing.mine(5)
block_before_snapshot = w3.eth.get_block('latest')
snapshot_idx = w3.testing.snapshot()
block_after_snapshot = w3.eth.get_block('latest')
w3.testing.mine()
w3.testing.snapshot()
w3.testing.mine()
w3.testing.snapshot()
w3.te... |
def filter_log_syslogd2_setting_data(json):
option_list = ['certificate', 'custom_field_name', 'enc_algorithm', 'facility', 'format', 'interface', 'interface_select_method', 'max_log_rate', 'mode', 'port', 'priority', 'server', 'source_ip', 'ssl_min_proto_version', 'status', 'syslog_type']
json = remove_invalid... |
def main(page: Page):
(fig, ax) = plt.subplots()
fruits = ['apple', 'blueberry', 'cherry', 'orange']
counts = [40, 100, 30, 55]
bar_labels = ['red', 'blue', '_red', 'orange']
bar_colors = ['tab:red', 'tab:blue', 'tab:red', 'tab:orange']
ax.bar(fruits, counts, label=bar_labels, color=bar_colors)
... |
def upgrade():
op.create_table('email_templates', sa.Column('id', sa.Integer(), nullable=False), sa.Column('form_id', sa.Integer(), nullable=False), sa.Column('subject', sa.Text(), nullable=False), sa.Column('from_name', sa.Text(), nullable=False), sa.Column('style', sa.Text(), nullable=False), sa.Column('body', sa... |
_fixtures_to_matrixstore
class MeasuresTests(SeleniumTestCase):
maxDiff = None
fixtures = ['functional-measures-dont-edit']
def setUpClass(cls):
call_command('loaddata', *cls.fixtures, **{'verbosity': 0})
super(MeasuresTests, cls).setUpClass()
def tearDownClass(cls):
call_command... |
class UploadDownloadFiles():
def __init__(self, args):
self.args = args
self.file_handles = getFileHandles()
file_storage = self.args.file_storage
self.obj = None
if (file_storage in self.file_handles):
self.obj = self.file_handles[file_storage](self.args)
def... |
class IPv4TCPSrcMasked(MatchTest):
def runTest(self):
match = ofp.match([ofp.oxm.eth_type(2048), ofp.oxm.ip_proto(6), ofp.oxm.tcp_src_masked(52, 254)])
matching = {'tcp sport=53': simple_tcp_packet(tcp_sport=53), 'tcp sport=52': simple_tcp_packet(tcp_sport=52)}
nonmatching = {'tcp sport=54':... |
class Test_Log_Slow_Processing(Test_verify_event_path_base):
def test_log_slow_processing_stream(self, cthread: AIOKafkaConsumerThread, tp: TP, logger):
cthread._log_slow_processing_stream(SLOW_PROCESSING_STREAM_IDLE_SINCE_START, tp, '3 seconds ago')
logger.error.assert_called_with(((((SLOW_PROCESSI... |
def fortios_firewall(data, fos, check_mode):
fos.do_member_operation('firewall', 'internet-service-group')
if data['firewall_internet_service_group']:
resp = firewall_internet_service_group(data, fos, check_mode)
else:
fos._module.fail_json(msg=('missing task body: %s' % 'firewall_internet_s... |
def get_arch(metadata=None):
if metadata:
platform = metadata['platform'].lower()
if ('x86_64' in platform):
return 'x86_64'
elif ('amd64' in platform):
return 'amd64'
procinfo = metadata['cpu_model_name'].lower()
if ('aarch64' in procinfo):
... |
def upgrade():
op.create_table('providedidentity', sa.Column('id', sa.String(length=255), nullable=False), sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=True), sa.Column('updated_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=True), sa.Colu... |
def configuration_file():
if os.path.isfile('./emissionsapi.yml'):
return './emissionsapi.yml'
expanded_file = os.path.expanduser('~/emissionsapi.yml')
if os.path.isfile(expanded_file):
return expanded_file
if os.path.isfile('/etc/emissionsapi.yml'):
return '/etc/emissionsapi.yml... |
('subprocess.run')
def test_update_sent_alerts(mock_subprocess_run, alerts_fetcher_mock: MockAlertsFetcher):
mock_alerts_ids_to_update = (['mock_alert_id'] * 60)
resource_type = ResourceType.TEST
alerts_fetcher_mock.update_sent_alerts(alert_ids=mock_alerts_ids_to_update, resource_type=resource_type)
ass... |
def add_fsdp_configs(_C: CN):
_C.FSDP = CN()
_C.FSDP.ALGORITHM = 'grad_optim'
_C.FSDP.CPU_OFFLOAD = False
_C.FSDP.BACKWARD_PREFETCH = True
_C.FSDP.USE_ORIG_PARAMS = False
_C.FSDP.AUTO_WRAP_POLICY = 'never_wrap_policy'
_C.FSDP.AUTO_WRAP_MIN_PARAMS = int(10000.0)
_C.FSDP.AUTO_WRAP_LAYER_CL... |
def adc_info(esp, efuses, args):
print('')
if (efuses['BLK_VERSION_MINOR'].get() == 1):
print(' RF_REF_I_BIAS_CONFIG: {}'.format(efuses['RF_REF_I_BIAS_CONFIG'].get()))
print(' LDO_VOL_BIAS_CONFIG_LOW: {}'.format(efuses['LDO_VOL_BIAS_CONFIG_LOW'].get()))
print(' LDO_VO... |
def printMatchesInViewOutputStringAndCopyFirstToClipboard(needle, haystack):
first = None
for match in re.finditer((('.*<.*(' + needle) + ')\\S*: (0x[0-9a-fA-F]*);.*'), haystack, re.IGNORECASE):
view = match.groups()[(- 1)]
className = fb.evaluateExpressionValue((('(id)[(' + view) + ') class]'))... |
class S3Path():
region: str
bucket: str
key: str
def __init__(self, fileURL: str) -> None:
(self.region, self.bucket, self.key) = self._get_region_bucket_key(fileURL)
def __eq__(self, other: 'S3Path') -> bool:
return ((self.region == other.region) and (self.bucket == other.bucket) an... |
class OptionSeriesColumnrangeSonificationContexttracksMappingPlaydelay(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):
... |
(suppress_health_check=[HealthCheck.function_scoped_fixture])
(grids, st.data())
def test_gridprop_to_from_file_is_identity(tmp_path, grid, data):
filepath = (tmp_path / 'gridprop.grdecl')
prop = data.draw(st.sampled_from(grid.get_xyz_corners()))
prop.to_file(filepath, fformat='grdecl')
prop_from_file =... |
def _find_files(project_root):
path_exclude_pattern = '\\.git($|\\/)|venv|_build'
file_exclude_pattern = 'fill_template_vars\\.py|\\.swp$'
filepaths = []
for (dir_path, _dir_names, file_names) in os.walk(project_root):
if (not re.search(path_exclude_pattern, dir_path)):
for file in f... |
class BasicsCharacteristic(Characteristic):
def __init__(self, bus, index, service):
Characteristic.__init__(self, bus, index, UART_BE_CHARACTERISTIC_UUID, ['write', 'read'], service)
def WriteValue(self, value, options):
global get_app_command
get_app_command = bytes(value)
prin... |
def set_sat(rgb: Vector, s: float) -> Vector:
final = ([0.0] * 3)
(indices, rgb_sort) = zip(*sorted(enumerate(rgb), key=itemgetter(1)))
if (rgb_sort[2] > rgb_sort[0]):
final[indices[1]] = (((rgb_sort[1] - rgb_sort[0]) * s) / (rgb_sort[2] - rgb_sort[0]))
final[indices[2]] = s
else:
... |
def test_iter_sse_whatwg_example1() -> None:
class Body(
def __iter__(self) -> Iterator[bytes]:
(yield b'data: YH00\n')
(yield b'data: +2\n')
(yield b'data: 10\n')
(yield b'\n')
response = headers={'content-type': 'text/event-stream'}, stream=Body())
... |
def get_qubes_version():
is_qubes = False
version = None
try:
with open('/etc/os-release') as f:
for line in f:
try:
(key, value) = line.rstrip().split('=')
except ValueError:
continue
if ((key == 'NA... |
def kill_on_exception(logname):
def _koe(func):
(func)
def __koe(*args, **kwargs):
try:
func(*args, **kwargs)
except Exception:
logging.getLogger(logname).exception('Unhandled exception, killing RYU')
logging.shutdown()
... |
class OptionSeriesSplineDragdropGuideboxDefault(Options):
def className(self):
return self._config_get('highcharts-drag-box-default')
def className(self, text: str):
self._config(text, js_type=False)
def color(self):
return self._config_get('rgba(0, 0, 0, 0.1)')
def color(self, t... |
('task_config', [{'hydra': {'run': {'dir': '${now:%Y%m%d_%H%M%S_%f}'}}}])
def test_run_dir_microseconds(tmpdir: Path, task_config: DictConfig) -> None:
cfg = OmegaConf.create(task_config)
assert isinstance(cfg, DictConfig)
integration_test(tmpdir=tmpdir, task_config=cfg, overrides=[], prints="str('%f' not i... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.