code stringlengths 281 23.7M |
|---|
class registry():
def has(cls, registry_name: str, func_name: str) -> bool:
if (not hasattr(cls, registry_name)):
return False
reg = getattr(cls, registry_name)
return (func_name in reg)
def get(cls, registry_name: str, func_name: str) -> Callable:
if (not hasattr(cls... |
_events(ERROR, SPAN)
def add_context_lines_to_frames(client, event):
per_file = defaultdict(list)
_process_stack_frames(event, (lambda frame: (per_file[frame['context_metadata'][0]].append(frame) if ('context_metadata' in frame) else None)))
for frames in per_file.values():
for frame in frames:
... |
class deprecated():
def __init__(self, new=None):
self.new = new
def __call__(self, old):
(old)
def wrapper(*args, **kwds):
frame = inspect.getframeinfo(inspect.currentframe().f_back)
msg = f'{frame.filename}: {frame.lineno}: '
if len(args):
... |
.skip(reason='CI runner needs more GPU memory')
.gpu
.skipif((not has_torch_cuda_gpu), reason='needs GPU & CUDA')
def test_invalid_model():
orig_config = Config().from_str(_NLP_CONFIG)
config = copy.deepcopy(orig_config)
config['components']['llm']['model']['name'] = 'x'
with pytest.raises(ValueError, m... |
class TestAddProtocolFailsWhenProtocolNotInRegistry():
def setup_class(cls):
cls.runner = CliRunner()
cls.agent_name = 'myagent'
cls.cwd = os.getcwd()
cls.t = tempfile.mkdtemp()
cls.protocol_id = 'user/unknown_protocol:0.1.0'
shutil.copytree(Path(CUR_PATH, '..', 'pack... |
class BCValidationEvaluator(Evaluator):
def __init__(self, loss: BCLoss, model_selection: Optional[ModelSelectionBase], data_loader: DataLoader, logging_prefix: Optional[str]='eval'):
self.loss = loss
self.data_loader = data_loader
self.model_selection = model_selection
self.env = No... |
def mocked_query_single_user(cognito_user_id):
return [{'Date subscribed': '2021-06-16T23:06:48.646688', 'GSI1PK': 'USER', 'List name': 'HSK Level 6', 'SK': 'LIST#1ebcad41-197a-123123#TRADITIONAL', 'Status': 'SUBSCRIBED', 'GSI1SK': 'USER#770e2827-7666-#LIST#1ebcad41-197a-123123#TRADITIONAL', 'PK': 'USER#770e2827-76... |
def _prepare_bmm_ait_module(b, m, n, k, has_bias=False):
assert (not has_bias), 'bmm_rcr_bias is not implemented! has_bias has to be false for now'
input_tensors = _prepare_batch_input_tensors(b, m, n, k, has_bias=has_bias)
Y = ops.bmm_rcr()(*input_tensors)
Y._attrs['name'] = 'y'
Y._attrs['is_output... |
def extractYomigaerutranslationWordpressCom(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, nam... |
class Item():
def __init__(self, list: ItemList, item_text: str):
self.list = list
self.item_text = item_text
self.card_item = Card(content=Container(content=Row([Icon(name=icons.CIRCLE_OUTLINED), Text(value=f'{self.item_text}')], alignment='start'), width=200, padding=7), elevation=1, data=... |
class OptionSeriesColumnrangeSonificationDefaultinstrumentoptionsMappingHighpass(Options):
def frequency(self) -> 'OptionSeriesColumnrangeSonificationDefaultinstrumentoptionsMappingHighpassFrequency':
return self._config_sub_data('frequency', OptionSeriesColumnrangeSonificationDefaultinstrumentoptionsMappin... |
class MultiplexedComplexSurfaceApodizer(OpticalElement):
def __init__(self, amplitude, surface, refractive_index):
self.amplitude = amplitude
self.surface = surface
self.refractive_index = refractive_index
def forward(self, wavefront):
apodizer_mask = 0
for (amplitude, su... |
class SyncServerConfig():
_target_: str = fullclassname(SyncServer)
_recursive_: bool = False
only_federated_params: bool = True
aggregation_type: AggregationType = AggregationType.WEIGHTED_AVERAGE
server_optimizer: ServerOptimizerConfig = ServerOptimizerConfig()
active_user_selector: ActiveUser... |
class DeleteProject(Delete):
def run(self):
self.log.debug('Action delete copr')
result = ActionResult.SUCCESS
ext_data = json.loads(self.data['data'])
ownername = ext_data['ownername']
project_dirnames = ext_data['project_dirnames']
if (not ownername):
se... |
def main():
module_spec = schema_to_module_spec(versioned_schema)
mkeyname = 'server-name'
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... |
class Order(DocType):
id = Keyword()
botName = Keyword()
securityId = Keyword()
direction = Short()
type = Keyword()
price = Float()
amount = Long()
status = Keyword()
timestamp = Date()
class Meta():
doc_type = 'doc'
all = MetaField(enabled=False)
dynamic... |
class FaucetUntaggedMeterParseTest(FaucetUntaggedTest):
REQUIRES_METERS = True
OVS_TYPE = 'user'
CONFIG_GLOBAL = '\nmeters:\n lossymeter:\n meter_id: 1\n entry:\n flags: "KBPS"\n bands:\n [\n {\n type: "DROP",\n ... |
def test_list_users(sample_tenant, tenant_user):
client = tenant_mgt.auth_for_tenant(sample_tenant.tenant_id)
page = client.list_users()
result = None
for user in page.iterate_all():
if (user.uid == tenant_user.uid):
result = user
break
assert (result.tenant_id == sam... |
def extractSilverishyouthWordpressCom(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_... |
class OptionPlotoptionsTilemapStatesHoverHalo(Options):
def attributes(self) -> 'OptionPlotoptionsTilemapStatesHoverHaloAttributes':
return self._config_sub_data('attributes', OptionPlotoptionsTilemapStatesHoverHaloAttributes)
def enabled(self):
return self._config_get(True)
def enabled(self... |
def main():
build_dir = 'gateware'
platform = arty.Platform(variant='a7-35', toolchain='vivado')
from litex.build.generic_platform import Pins, IOStandard
platform.add_extension([('do', 0, Pins('B7'), IOStandard('LVCMOS33'))])
if ('load' in sys.argv[1:]):
prog = platform.create_programmer()
... |
def tidy(x):
if isinstance(x, (list, tuple)):
return [tidy(y) for y in x]
if isinstance(x, (dict, OrderedDict)):
d = OrderedDict()
for (k, v) in x.items():
d[tidy(k)] = tidy(v)
return d
if isinstance(x, str):
if x.startswith(''):
return x[1:]
... |
class TextClassification():
def get_text(self, machine_learning_result):
plate_string = ''
for eachPredict in machine_learning_result:
plate_string += eachPredict[0]
return plate_string
def text_reconstruction(self, plate_string, position_list):
posListCopy = position... |
def switch_window_mode(direction: str, editor):
mod = utility.misc.get_addon_id()
config = mw.addonManager.getConfig(mod)
switched = config['switchLeftRight']
window_mode = WindowMode[config['window_mode']]
if (direction in ['left', 'right']):
if (window_mode == WindowMode.Both):
... |
def filter_log_fortianalyzer3_override_filter_data(json):
option_list = ['anomaly', 'dlp_archive', 'filter', 'filter_type', 'forward_traffic', 'free_style', 'gtp', 'local_traffic', 'multicast_traffic', 'severity', 'sniffer_traffic', 'voip', 'ztna_traffic']
json = remove_invalid_fields(json)
dictionary = {}
... |
class LayoutGrid(DataClass):
def rows(self):
return self._attrs['rows']
def rows(self, val):
self._attrs['rows'] = val
def columns(self):
return self._attrs['columns']
def columns(self, val):
self._attrs['columns'] = val
def pattern(self):
return self._attrs['... |
def main():
logging.basicConfig(format=LOGGING_FORMAT)
parser = argparse.ArgumentParser(description=main.__doc__)
add_debug(parser)
add_app(parser)
add_env(parser)
args = parser.parse_args()
logging.getLogger(__package__.split('.')[0]).setLevel(args.debug)
assert destroy_cloudwatch_log_e... |
def upgrade():
op.create_table('pets', sa.Column('id', sa.Integer(), nullable=False), sa.Column('name', sa.Integer(), nullable=False), sa.Column('image', sa.Text(), nullable=True), sa.Column('animal_type', sa.Text(), nullable=False), sa.Column('weight', sa.Float(), nullable=False), sa.Column('birthday', sa.Integer(... |
class ObservationNormalizationWrapper(ObservationWrapper[MazeEnv]):
def register_new_observation_normalization_strategy(cls, containing_submodule: Any):
assert isinstance(containing_submodule, ModuleType)
cls.registry_normalization_strategies.collect_modules(root_module=containing_submodule, base_ty... |
def delete_directory(path):
if os.path.exists(path):
if os.path.isdir(path):
for (root, dirs, files) in os.walk(path, topdown=False, followlinks=False):
if (not os.path.islink(root)):
for file in files:
delete_file(os.path.join(root, fi... |
def test_no_error_when_null_values_in_variable(df_vartypes):
df_na = df_vartypes.copy()
df_na.loc[(1, 'Age')] = np.nan
transformer = MathFeatures(variables=['Age', 'Marks'], func=['sum', 'mean'], missing_values='ignore')
X = transformer.fit_transform(df_na)
ref = pd.DataFrame.from_dict({'Name': ['to... |
class ConditionToSequenceRule(LoopStructuringRule):
def can_be_applied(loop_node: AbstractSyntaxTreeNode):
if ((not loop_node.is_endless_loop) or (not isinstance((body := loop_node.body), ConditionNode))):
return False
break_in_true = (body.true_branch.does_contain_break if body.true_bra... |
def console(ipc_path: Path, use_ipython: bool=True, env: Dict[(str, Any)]=None, banner: str=DEFAULT_BANNER) -> None:
if (env is None):
env = {}
if (not ipc_path.exists()):
raise FileNotFoundError(create_missing_ipc_error_message(ipc_path))
import web3
ipc_provider = web3.IPCProvider(ipc_... |
class Strategy():
def __init__(self, symbols, capital, start, end, options=default_options):
self.symbols = symbols
self.capital = capital
self.start = start
self.end = end
self.options = options.copy()
self.ts = None
self.rlog = None
self.tlog = None
... |
.perf
.returns('GB/s')
def test_large_scan_performance(thr, large_perf_shape, exclusive):
dtype = dtypes.normalize_type(numpy.int64)
min_time = check_scan(thr, large_perf_shape, dtype=dtype, axes=None, exclusive=exclusive, measure_time=True)
return (min_time, (helpers.product(large_perf_shape) * dtype.items... |
class TestStubActionUnitTestCase(UnitTestServerTestCase):
server_class = _TestServiceServer
server_settings = {}
def setUp(self):
super(TestStubActionUnitTestCase, self).setUp()
self.secondary_stub_client = Client(_secondary_stub_client_settings)
_action('test_service', 'test_action_1')
... |
def _generate_options(instr: int=10, branch: int=10, call: int=10, assign: int=10) -> Options:
options = Options()
options.set('expression-propagation-memory.maximum_instruction_complexity', instr)
options.set('expression-propagation-memory.maximum_branch_complexity', branch)
options.set('expression-pro... |
def test_delete(write_client):
write_client.create(index='test-document', id='elasticsearch-dsl-py', body={'organization': 'elasticsearch', 'created_at': '2014-03-03', 'owner': {'name': 'elasticsearch'}})
test_repo = Repository(meta={'id': 'elasticsearch-dsl-py'})
test_repo.meta.index = 'test-document'
... |
def main():
module_spec = schema_to_module_spec(versioned_schema)
mkeyname = None
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_path': {... |
class OptionSeriesCylinderMarkerStates(Options):
def hover(self) -> 'OptionSeriesCylinderMarkerStatesHover':
return self._config_sub_data('hover', OptionSeriesCylinderMarkerStatesHover)
def normal(self) -> 'OptionSeriesCylinderMarkerStatesNormal':
return self._config_sub_data('normal', OptionSer... |
class TargetEntityMixinTester(unittest.TestCase):
def setUp(self):
super(TargetEntityMixinTester, self).setUp()
self.kwargs = {'name': 'Test object', 'target_entity_type': Project}
self.test_object = TargetEntityTypeMixedClass(**self.kwargs)
def test_target_entity_type_argument_is_skippe... |
class OptionSeriesParetoTooltip(Options):
def clusterFormat(self):
return self._config_get('Clustered points: {point.clusterPointsAmount}')
def clusterFormat(self, text: str):
self._config(text, js_type=False)
def dateTimeLabelFormats(self) -> 'OptionSeriesParetoTooltipDatetimelabelformats':... |
def parse_version(ver):
m = RE_VER.match(ver)
if (m is None):
raise ValueError(f"'{ver}' is not a valid version")
major = int(m.group('major'))
minor = (int(m.group('minor')) if m.group('minor') else 0)
micro = (int(m.group('micro')) if m.group('micro') else 0)
if m.group('type'):
... |
class Pat2Feat():
def __init__(self):
self._imp = None
def get_features(self, sequences: List[list], patterns: List[list], constraints: Optional[List[_Constraint]]=None, max_span: Optional[int]=10, drop_pattern_frequency: bool=True):
if drop_pattern_frequency:
patterns = drop_frequen... |
def classify_language(text: str, target_languages: list=None) -> str:
if ((module == 'fastlid') or (module == 'fasttext')):
from fastlid import fastlid, supported_langs
classifier = fastlid
if (target_languages != None):
target_languages = [lang for lang in target_languages if (l... |
def count_start_time_trending(generator_ad_archives, args, is_verbose=False):
if (len(args) != 1):
raise Exception('start_time_trending action takes 1 arguments: output_file')
total_count = 0
output_file = args[0]
date_to_count = Counter({})
for ad_archives in generator_ad_archives:
... |
def test_cartpole_policy_model():
env = GymMazeEnv(env='CartPole-v0')
observation_spaces_dict = env.observation_spaces_dict
action_spaces_dict = env.action_spaces_dict
flat_action_space = flat_structured_space(action_spaces_dict)
distribution_mapper = DistributionMapper(action_space=flat_action_spac... |
def gen_pack_expr(oftype, value_expr, version, pyversion):
type_data = lookup_type_data(oftype, version)
if type_data:
if (pyversion == 3):
fmt = (type_data.pack3 or type_data.pack or None)
return ((fmt % value_expr) if fmt else ("loxi.unimplemented('pack %s')" % oftype))
... |
def test_generate_all_will_end_up_with_an_empty_scene(create_test_data, store_local_session, create_pymel, create_maya_env):
data = create_test_data
pm = create_pymel
gen = RepresentationGenerator(version=data['building1_yapi_model_main_v003'])
gen.generate_all()
assert (pm.sceneName() == '') |
_policy_state.command()
_context
def execute(ctx):
error = MODULE.check_options()
if error:
return
policy_id = MODULE_OPTIONS['id']['value']
policy = OktaPolicy(ctx.obj.okta.get_policy(ctx, policy_id, rules=False))
if policy:
if (policy.obj['status'] == 'ACTIVE'):
click.e... |
class SurfaceAberration(SurfaceApodizer):
def __init__(self, pupil_grid, ptv, diameter, exponent=(- 2.5), refractive_index=(- 1), aperture=None, remove_modes=None):
surface = make_power_law_error(pupil_grid, ptv, diameter, exponent, aperture, remove_modes)
SurfaceApodizer.__init__(self, surface, ref... |
class OptionPlotoptionsAreasplineSonificationDefaultspeechoptionsMappingRate(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 Container(containers.DeclarativeContainer):
config = providers.Configuration()
session = providers.Resource(boto3.session.Session, aws_access_key_id=config.aws_access_key_id, aws_secret_access_key=config.aws_secret_access_key, aws_session_token=config.aws_session_token)
s3_client = providers.Resource(... |
class BloodHoundObject():
COMMON_PROPERTIES = []
NEVER_SHOW_PROPERTIES = ['ntsecuritydescriptor', 'serviceprincipalname']
def __init__(self, object=None):
self.ObjectIdentifier = None
self.Aces = []
self.RawAces = None
self.Properties = {}
if isinstance(object, dict):... |
class OptionSeriesWordcloudSonificationContexttracksMappingNoteduration(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 colrv1_cpalv1_path(colrv1_path):
font = TTFont(colrv1_path)
fb = FontBuilder(font=font)
fb.setupCPAL([[(1.0, 0.0, 0.0, 1.0), (0.0, 1.0, 0.0, 1.0), (0.0, 0.0, 1.0, 1.0)]], paletteLabels=['test palette'], paletteEntryLabels=['first color', 'second color', 'third color'])
output_path = (colrv1_path.par... |
class BlueBirdGame():
def __init__(self):
pygame.init()
self.clock = pygame.time.Clock()
self.settings = Settings()
self.screen = pygame.display.set_mode((self.settings.screen_width, self.settings.screen_height))
pygame.display.set_caption('Blue Bird Game')
self.bird ... |
def createSeriesInfoPacket(data, beta=False, matchAuthor=False):
expect = ['title', 'author', 'tags', 'desc', 'tl_type', 'sourcesite']
allowed = ['alt_titles', 'author', 'desc', 'homepage', 'illust', 'pubdate', 'pubnames', 'sourcesite', 'tags', 'title', 'tl_type', 'update_only', 'coostate', 'type', 'genres', 'l... |
def test_traverse_overridden():
provider1 = providers.Callable(list)
provider2 = providers.Callable(dict)
selector1 = providers.Selector((lambda : 'provider1'), provider1=provider1)
provider = providers.Selector((lambda : 'provider2'), provider2=provider2)
provider.override(selector1)
all_provid... |
def create_envd_config(image_spec: ImageSpec) -> str:
base_image = (DefaultImages.default_image() if (image_spec.base_image is None) else image_spec.base_image)
if image_spec.cuda:
if (image_spec.python_version is None):
raise Exception('python_version is required when cuda and cudnn are spe... |
class record_packets(bsn_tlv):
type = 155
def __init__(self, value=None):
if (value != None):
self.value = value
else:
self.value = 0
return
def pack(self):
packed = []
packed.append(struct.pack('!H', self.type))
packed.append(struct.pa... |
def envoy_status(estats: EnvoyStats):
since_boot = interval_format(estats.time_since_boot(), '%s', 'less than a second')
since_update = 'Never updated'
if estats.time_since_update():
since_update = interval_format(estats.time_since_update(), '%s ago', 'within the last second')
return {'alive': e... |
class OptionPlotoptionsVennSonificationDefaultinstrumentoptions(Options):
def activeWhen(self) -> 'OptionPlotoptionsVennSonificationDefaultinstrumentoptionsActivewhen':
return self._config_sub_data('activeWhen', OptionPlotoptionsVennSonificationDefaultinstrumentoptionsActivewhen)
def instrument(self):
... |
class TestActionCreate_index(TestCase):
def test_init_raise(self):
self.assertRaises(TypeError, CreateIndex, name='name')
def test_init_raise_no_name(self):
client = Mock()
self.assertRaises(ConfigurationError, CreateIndex, client, name=None)
def test_init(self):
client = Moc... |
class StyleLoss(nn.Module):
def __init__(self, VGG16_ACTIVATIONS_LIST=[21], normalize=False, distance='l2', in_size=256):
super(StyleLoss, self).__init__()
self.vgg16_act = VGG16_Activations(VGG16_ACTIVATIONS_LIST)
self.vgg16_act.eval()
self.in_size = in_size
self.normalize =... |
def transform_to_conj_expr(expr: ConjunctionExpression) -> Tuple[(_core_cond.ConjunctionExpression, typing.List[Promise])]:
(left, left_promises) = transform_to_boolexpr(expr.lhs)
(right, right_promises) = transform_to_boolexpr(expr.rhs)
return (_core_cond.ConjunctionExpression(left_expression=left, right_e... |
def create_gridded_line_plot(x, y, orientation='h', color='red', width=1.0, dash='solid', value_mapper_class=LinearMapper, padding=30):
assert (len(x) == len(y))
index = ArrayDataSource(x, sort_order='none')
value = ArrayDataSource(y, sort_order='none')
index_range = DataRange1D(tight_bounds=False)
... |
def test_transaction_outcome_override(elasticapm_client):
transaction = elasticapm_client.begin_transaction('test')
elasticapm.set_transaction_outcome(constants.OUTCOME.FAILURE)
assert (transaction.outcome == constants.OUTCOME.FAILURE)
elasticapm.set_transaction_outcome(constants.OUTCOME.SUCCESS, overri... |
def test_diagonal_welford_covariance():
samples = dist.MultivariateNormal(loc=torch.rand(5), scale_tril=torch.randn(5, 5).tril()).sample((1000,))
welford = WelfordCovariance(diagonal=True)
for sample in samples:
welford.step(sample)
sample_var = torch.var(samples, dim=0)
estimated_var = welf... |
def test_expanding_sum_and_mean_multiple_vars(df_time):
expected_results = {'ambient_temp_expanding_sum': [np.nan, 31.31, 62.82, 94.97, 127.36, 159.98, 192.48, 225.0, 257.68, 291.44, 325.57, 359.65, 393.35, 427.24, 461.28], 'ambient_temp_expanding_mean': [np.nan, 31.31, 31.41, 31.6567, 31.84, 31.996, 32.08, 32.1429... |
class TestAWeighting(object):
def test_invalid_params(self):
with pytest.raises(TypeError):
A_weighting(fs='spam')
with pytest.raises(ValueError):
A_weighting(fs=10000, output='eggs')
def test_zpkbilinear_bug(self):
(z, p, k) = A_weighting(fs=48000, output='zpk')
... |
class Animation(JsonDeserializable):
def de_json(cls, json_string):
if (json_string is None):
return None
obj = cls.check_json(json_string)
if (('thumbnail' in obj) and ('file_id' in obj['thumbnail'])):
obj['thumbnail'] = PhotoSize.de_json(obj['thumbnail'])
el... |
('config_name,overrides,expected', [param('placeholder', [], [ResultDefault(config_path='placeholder', package='', is_self=True)], id='placeholder'), param('placeholder', ['group1=file1'], [ResultDefault(config_path='group1/file1', package='group1', parent='placeholder'), ResultDefault(config_path='placeholder', packag... |
class enumerate(_coconut_baseclass, _coconut.enumerate):
__slots__ = ('iter', 'start')
__doc__ = getattr(_coconut.enumerate, '__doc__', '<see help(py_enumerate)>')
def __new__(cls, iterable, start=0):
start = _coconut.operator.index(start)
self = _coconut.enumerate.__new__(cls, iterable, sta... |
def recognize_file(rec, file_path):
res = ''
res_part = ''
wf = wave.open(file_path, 'rb')
data = wf.readframes(CHUNK)
while (len(data) > 0):
data = wf.readframes(CHUNK)
if rec.AcceptWaveform(data):
result = json.loads(rec.Result())
if (len(result['text']) > 0... |
def structure(data, location):
_ = SchemaCheck(data, Schema(valid_action(), extra=True), 'action type', location).result()
retval = valid_action()
retval.update({Optional('description', default='No description given'): Any(str, *string_types)})
retval.update({Optional('options', default=settings.default... |
def generate_sfm(project_location, use_cutouts=True):
for file in os.listdir(str(project_location)):
if file.endswith('.yaml'):
config = read_config_file(path=project_location.joinpath(file))
try:
(X, Y, Z) = create_input_arrays(config)
except UnboundLocalError:
print('Un... |
class VersionOp():
def __init__(self, version=ANY, read=None, write=None, default=None, funnel=None, normalize=None):
self.version = version
self.read = read
self.write = write
self.default = default
self.funnel = funnel
self.normalize = normalize
def __str__(self... |
def main(args=None):
args = parse_arguments().parse_args(args)
viewpointObj = Viewpoint()
interactionList = []
interactionDict = {}
targetList = []
present_genes = {}
interactionFileHDF5Object = h5py.File(args.interactionFile, 'r')
keys_interactionFile = list(interactionFileHDF5Object.ke... |
def dispatch_deserialized(methods: Methods, context: Any, post_process: Callable[([Response], Iterable[Any])], deserialized: Deserialized) -> Union[(Response, List[Response], None)]:
results = map(compose(partial(dispatch_request, methods, context), create_request), make_list(deserialized))
responses = starmap(... |
class OptionPlotoptionsPyramidSonificationDefaultinstrumentoptionsMappingLowpass(Options):
def frequency(self) -> 'OptionPlotoptionsPyramidSonificationDefaultinstrumentoptionsMappingLowpassFrequency':
return self._config_sub_data('frequency', OptionPlotoptionsPyramidSonificationDefaultinstrumentoptionsMappi... |
class OptionSeriesWindbarbDataMarkerStatesHover(Options):
def animation(self) -> 'OptionSeriesWindbarbDataMarkerStatesHoverAnimation':
return self._config_sub_data('animation', OptionSeriesWindbarbDataMarkerStatesHoverAnimation)
def enabled(self):
return self._config_get(True)
def enabled(se... |
def filter_records(records, arns_to_filter_for=None, from_date=datetime.datetime(1970, 1, 1, tzinfo=pytz.utc), to_date=datetime.datetime.now(tz=pytz.utc)):
result = list(pipe(records, filterz(_by_timeframe(from_date, to_date)), filterz(_by_role_arns(arns_to_filter_for))))
if ((not result) and records):
... |
def test_layout_phylo_aa(node):
if hasattr(node, 'collapsed'):
if (node.collapsed == 1):
node.img_style['draw_descendants'] = False
if node.is_leaf:
if hasattr(node, 'sequence'):
seqface = SequenceFace(node.sequence, 'aa', fsize=10, col_w=11, interactive=False)
... |
class I18NMiddleware(I18N):
def process_update_types(self) -> list:
return ['message', 'callback_query']
def get_user_language(self, obj: Union[(types.Message, types.CallbackQuery)]):
user_id = obj.from_user.id
if (user_id not in users_lang):
users_lang[user_id] = 'en'
... |
class wxGradientEditor(wx.Frame):
def __init__(self, vtk_table, on_change_color_table=None, colors=None):
wx.Frame.__init__(self, None, (- 1), 'Color Gradient Editor', wx.DefaultPosition, [350, 400])
self.widget = wxGradientEditorWidget(self, vtk_table, on_change_color_table, colors)
self.Se... |
def calculate_intrinsic_cost(tx: Transaction) -> Uint:
data_cost = 0
for byte in tx.data:
if (byte == 0):
data_cost += TX_DATA_COST_PER_ZERO
else:
data_cost += TX_DATA_COST_PER_NON_ZERO
if (tx.to == Bytes0(b'')):
create_cost = TX_CREATE_COST
else:
... |
def wmic_rows():
rows = []
nic_rows = parse_wmic_output(check_subprocess(['wmic', 'nic'])[0])
nicconfig_rows = parse_wmic_output(check_subprocess(['wmic', 'nicconfig'])[0])
for nic_row in nic_rows:
if (nic_row['GUID'] == ''):
L.verbose("Network adapter '{}' has no GUID. Ignoring it!"... |
def mk_multisend_code(payments):
kode = b''
for (address, wei) in payments.items():
kode += b'`\x00`\x00`\x00`\x00'
encoded_wei = (utils.encode_int(wei) or b'\x00')
kode += (utils.ascii_chr((95 + len(encoded_wei))) + encoded_wei)
kode += (b's' + utils.normalize_address(address))
... |
class OptionSeriesParetoSonificationDefaultspeechoptionsMappingPitch(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('undefined')
def mapTo(self, text: st... |
class KBCodeExample(HasPrivateTraits):
code = Code()
status = Str()
kb = Button(label='Edit Key Bindings')
view = View(Group(Item('code', style='custom', resizable=True), Item('status', style='readonly'), 'kb', orientation='vertical', show_labels=False), id='KBCodeExample', key_bindings=key_bindings, ti... |
def verify_ping(fledge_url, skip_verify_north_interface, wait_time, retries):
get_url = '/fledge/ping'
ping_result = utils.get_request(fledge_url, get_url)
assert ('dataRead' in ping_result)
assert ('dataSent' in ping_result)
assert (0 < ping_result['dataRead']), 'South data NOT seen in ping header'... |
def test_schema_reference_serialization():
author = typesystem.Schema(fields={'username': typesystem.String()})
definitions = typesystem.Definitions()
definitions['Author'] = author
blog_post = typesystem.Schema(fields={'author': typesystem.Reference(to='Author', definitions=definitions), 'text': typesy... |
.django_db
def test_tas_program_activity_success(client, monkeypatch, agency_account_data, helpers):
helpers.mock_current_fiscal_year(monkeypatch)
tas = '001-X-0000-000'
resp = client.get(url.format(tas=tas, query_params=''))
expected_result = {'fiscal_year': helpers.get_mocked_current_fiscal_year(), 't... |
def _get_inline_comment_at_line(code_lines: List[str], line: int) -> str:
assert (0 <= line < len(code_lines))
assert _contains_attribute_definition(code_lines[line])
line_str = code_lines[line]
parts = line_str.split('#', maxsplit=1)
if (len(parts) != 2):
return ''
comment = parts[1].st... |
class CookieTokenAuthMixin():
def test_token_auth(self):
response = self.execute({self.user.USERNAME_FIELD: self.user.get_username(), 'password': 'dolphins'})
data = response.data['tokenAuth']
token = response.cookies.get(jwt_settings.JWT_COOKIE_NAME).value
self.assertIsNone(response... |
class Test_Parser_OFPStats(unittest.TestCase):
_ofp = {ofproto_v1_5_parser: ofproto_v1_5}
def __init__(self, methodName):
print(('init %s' % methodName))
super(Test_Parser_OFPStats, self).__init__(methodName)
def setUp(self):
pass
def tearDown(self):
pass
def _test(se... |
def test_build_transaction_with_contract_class_method(w3, math_contract_factory, math_contract, build_transaction):
txn = build_transaction(contract=math_contract_factory, contract_function='incrementCounter', tx_params={'to': math_contract.address})
assert (dissoc(txn, 'gas') == {'to': math_contract.address, '... |
_eh
class ExinwanHandler(EventHandler):
interested = ['post_card_migration']
def handle(self, evt_type, arg) -> None:
from thb.cards.base import VirtualCard, HiddenCard
from thb.cards.definition import ExinwanCard
if (evt_type == 'post_card_migration'):
moves = cast(MigrateCa... |
def extractMeiheimWordpressCom(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) i... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.