code stringlengths 281 23.7M |
|---|
class WindowEventFilter(QtCore.QObject):
def __init__(self, window):
QtCore.QObject.__init__(self)
self._window = weakref.ref(window)
def eventFilter(self, obj, e):
window = self._window()
if ((window is None) or (obj is not window.control)):
return False
typ ... |
('CupyOps')
class CupyOps(Ops):
name = 'cupy'
xp = cupy
_xp2 = cupyx
def __init__(self, device_type: DeviceTypes='gpu', device_id: int=0, **kwargs) -> None:
self.device_type = device_type
self.device_id = device_id
def to_numpy(self, data, *, byte_order=None):
if (not isinsta... |
class OptionSeriesBarSonificationContexttracksMappingHighpass(Options):
def frequency(self) -> 'OptionSeriesBarSonificationContexttracksMappingHighpassFrequency':
return self._config_sub_data('frequency', OptionSeriesBarSonificationContexttracksMappingHighpassFrequency)
def resonance(self) -> 'OptionSer... |
class ParallelRolloutRunner(RolloutRunner):
def __init__(self, n_episodes: int, max_episode_steps: int, deterministic: bool, n_processes: int, record_trajectory: bool, record_event_logs: bool):
super().__init__(n_episodes=n_episodes, max_episode_steps=max_episode_steps, deterministic=deterministic, record_t... |
def test_format__symlinks(tmp_path):
file_path_1 = (tmp_path / 'test_markdown1.md')
file_path_2 = (tmp_path / 'test_markdown2.md')
file_path_1.write_text(UNFORMATTED_MARKDOWN)
file_path_2.write_text(UNFORMATTED_MARKDOWN)
subdir_path = (tmp_path / 'subdir')
subdir_path.mkdir()
symlink_1 = (su... |
class HangmanTests(unittest.TestCase):
def test_initially_9_failures_are_allowed(self):
game = Hangman('foo')
self.assertEqual(game.get_status(), hangman.STATUS_ONGOING)
self.assertEqual(game.remaining_guesses, 9)
def test_initially_no_letters_are_guessed(self):
game = Hangman('f... |
class FingerHoleEdge(BaseEdge):
char = 'h'
description = 'Edge (parallel Finger Joint Holes)'
def __init__(self, boxes, fingerHoles=None, **kw) -> None:
settings = None
if isinstance(fingerHoles, Settings):
settings = fingerHoles
fingerHoles = FingerHoles(boxes, setti... |
def test_private_other(slave_channel):
chat = PrivateChat(channel=slave_channel, name='__name__', alias='__alias__', uid='__id__')
assert isinstance(chat.other, ChatMember)
assert (not isinstance(chat.other, SelfChatMember))
assert (not isinstance(chat.other, SystemChatMember))
assert (chat.other in... |
def verify_statistics_map(fledge_url, skip_verify_north_interface):
get_url = '/fledge/statistics'
jdoc = utils.get_request(fledge_url, get_url)
actual_stats_map = utils.serialize_stats_map(jdoc)
assert (1 <= actual_stats_map[south_asset_name.upper()])
assert (1 <= actual_stats_map['READINGS'])
... |
class MailType():
USER_REGISTER = 'user_registration'
USER_CONFIRM = 'user_confirmation'
USER_CHANGE_EMAIL = 'user_change_email'
NEW_SESSION = 'new_session'
PASSWORD_RESET = 'password_reset'
PASSWORD_CHANGE = 'password_change'
PASSWORD_RESET_AND_VERIFY = 'password_reset_verify'
EVENT_ROL... |
class TwoPiece(Boxes):
description = '\nSet *hi* larger than *h* to leave gap between the inner and outer shell. This can be used to make opening the box easier. Set *hi* smaller to only have a small inner ridge that will allow the content to be more visible after opening.\n\n:
domain = constraints.real_vector
codomain = constraints.real_vector
def __init__(self, params_fn: Optional[flowtorch.Lazy]=None, *, shape: torch.Size, context_shape: Optional[torch.Size]=None, **kwargs: Any) -> None:
self.domain = constraints.independent(constraints.r... |
class OrOp(Node):
def forward(self, *args, **kwargs):
if any([(a == True) for a in args]):
return True
elif all([(a == False) for a in args]):
return False
else:
return None
def follow(self, *args, **kwargs):
return fmap(('*', self.forward(*arg... |
def checksum_by_replay_chunk(table_name, delta_table_name, old_column_list, pk_list, id_col_name, id_limit, max_replayed, chunk_size) -> str:
col_list = ['count(*) AS `cnt`']
for col in old_column_list:
column_with_tbl = '`{}`.`{}`'.format(escape(table_name), escape(col))
chksm = wrap_checksum_f... |
class Skin(RCareWorldBaseObject):
def __init__(self, env, id: int, name: str, is_in_scene: bool=True):
super().__init__(env=env, id=id, name=name, is_in_scene=is_in_scene)
def getInfo(self) -> dict:
info_dict = {}
info_dict['forces'] = self.env.instance_channel.data[self.id]['forces']
... |
class PhotoContainer(containers.DeclarativeContainer):
database = providers.Dependency()
file_storage = providers.Dependency()
photo = providers.Factory(entities.Photo)
photo_repository = providers.Singleton(repositories.PhotoRepository, entity_factory=photo.provider, fs=file_storage, db=database) |
class OptionSeriesVennCluster(Options):
def allowOverlap(self):
return self._config_get(True)
def allowOverlap(self, flag: bool):
self._config(flag, js_type=False)
def animation(self):
return self._config_get({'duration': 500})
def animation(self, flag: bool):
self._confi... |
class StatsController(ControllerBase):
def __init__(self, req, link, data, **config):
super().__init__(req, link, data, **config)
self.dpset = data['dpset']
self.waiters = data['waiters']
def get_dpids(self, req, **_kwargs):
dps = list(self.dpset.dps.keys())
body = json.d... |
class FingerJointEdge(BaseEdge, FingerJointBase):
char = 'f'
description = 'Finger Joint'
positive = True
def draw_finger(self, f, h, style, positive: bool=True, firsthalf: bool=True) -> None:
t = self.settings.thickness
if positive:
if (style == 'springs'):
s... |
class ConcatExp(Exp):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.e1 = (build_exp(**kwargs['e1']) if isinstance(kwargs['e1'], dict) else kwargs['e1'])
self.e2 = (build_exp(**kwargs['e2']) if isinstance(kwargs['e2'], dict) else kwargs['e2'])
def __repr__(se... |
class Requested():
def find_spec(self, name, path=None, target=None):
LOADED_MODULES[name] = []
if CLIMETLAB_DEBUG_IMPORTS:
for f in inspect.stack():
if (f.filename == __file__):
continue
if ('importlib._bootstrap' in f.filename):
... |
class LigatureMorphActionTest(unittest.TestCase):
def setUp(self):
self.font = FakeFont(['.notdef', 'A', 'B', 'C'])
def testDecompileToXML(self):
a = otTables.LigatureMorphAction()
actionReader = OTTableReader(deHexStr('DEADBEEF 7FFFFFFE '))
a.decompile(OTTableReader(deHexStr('12... |
class RegistrationDB(Model):
def __init__(self, **kwargs: Any) -> None:
custom_path = kwargs.pop('custom_path', None)
super().__init__(**kwargs)
this_dir = os.getcwd()
self.db_path = (os.path.join(this_dir, 'registration.db') if (custom_path is None) else custom_path)
if (not... |
class MemoizedClass(type):
def __new__(metacls, name: str, bases: Tuple[(type, ...)], attrs: Dict[(str, Any)]) -> type:
if ('_cache' not in attrs):
attrs['_cache'] = {}
return super(MemoizedClass, metacls).__new__(metacls, name, bases, attrs)
def __call__(cls, *args):
if (arg... |
class Migration(migrations.Migration):
dependencies = [('search', '0008_awardsearch_table')]
operations = [migrations.DeleteModel(name='AwardSearchView'), migrations.DeleteModel(name='ContractAwardSearchMatview'), migrations.DeleteModel(name='DirectPaymentAwardSearchMatview'), migrations.DeleteModel(name='Grant... |
def prove_blind_and_swap(A1: POINT, B1: POINT, A2: POINT, B2: POINT, factor: int, swap=False):
if (not swap):
(C1, D1, C2, D2) = (curve.multiply(P, factor) for P in (A1, B1, A2, B2))
else:
(C1, D1, C2, D2) = (curve.multiply(P, factor) for P in (A2, B2, A1, B1))
msg = b''.join((serialize_poin... |
class OptionSeriesHeatmapSonificationTracksMappingLowpassResonance(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 generate_dynamo_db_datasets(aws_config: Optional[AWSConfig]) -> Dataset:
client = get_aws_client(service='dynamodb', aws_config=aws_config)
dynamo_tables = get_dynamo_tables(client)
described_dynamo_tables = describe_dynamo_tables(client, dynamo_tables)
dynamo_dataset = create_dynamodb_dataset(descr... |
def convert_inputs_to_MNI_space(reg_settings, hcp_templates, temp_dir, use_T2=None):
logger.info(section_header('Registering T1wImage to MNI template using FSL FNIRT'))
run_T1_FNIRT_registration(reg_settings, temp_dir)
logger.info(section_header('Applying MNI transform to label files'))
for image in ['w... |
_bpdu_type
class RstBPDUs(ConfigurationBPDUs):
VERSION_ID = PROTOCOLVERSION_ID_RSTBPDU
BPDU_TYPE = TYPE_RSTBPDU
_PACK_STR = '!B'
PACK_LEN = struct.calcsize(_PACK_STR)
def __init__(self, flags=0, root_priority=DEFAULT_BRIDGE_PRIORITY, root_system_id_extension=0, root_mac_address='00:00:00:00:00:00', ... |
class Robertson1968(CCT):
NAME = 'robertson-1968'
CHROMATICITY = 'uv-1960'
def __init__(self, cmfs: dict[(int, tuple[(float, float, float)])]=cmfs.CIE_1931_2DEG, white: VectorLike=cat.WHITES['2deg']['D65'], mired: VectorLike=MIRED_EXTENDED, sigfig: int=5, planck_step: int=1) -> None:
self.white = wh... |
class ImportManager():
online: bool = True
self_contained: bool = False
_static_path: Optional[str] = None
set_exports: bool = False
def __init__(self, page=None):
(self.page, ovr_version, self.__pkgs) = (page, {}, None)
self.force_position = {}
self.reload()
def packages... |
class build_ext(_build_ext, object):
cythonize_dir = 'build'
fplll = None
other = None
def_varnames = ['HAVE_QD', 'HAVE_LONG_DOUBLE', 'HAVE_NUMPY']
config_pxi_path = os.path.join('.', 'src', 'fpylll', 'config.pxi')
def finalize_options(self):
super(build_ext, self).finalize_options()
... |
class RedirectingResourceWithHeaders():
def on_get(self, req, resp):
raise falcon.HTTPMovedPermanently('/moved/perm', headers={'foo': 'bar'})
def on_post(self, req, resp):
raise falcon.HTTPFound('/found', headers={'foo': 'bar'})
def on_put(self, req, resp):
raise falcon.HTTPSeeOther(... |
def random_internal_ip() -> ipaddress.IPv4Address:
network = random.choice([ipaddress.IPv4Network('10.0.0.0/8'), ipaddress.IPv4Network('172.16.0.0/12'), ipaddress.IPv4Network('192.168.0.0/16')])
return ipaddress.IPv4Address(random.randrange((int(network.network_address) + 1), (int(network.broadcast_address) - 1... |
def validate_email(email, required=False):
if ((email is None) and (not required)):
return None
if ((not isinstance(email, str)) or (not email)):
raise ValueError('Invalid email: "{0}". Email must be a non-empty string.'.format(email))
parts = email.split('')
if ((len(parts) != 2) or (no... |
class PornembyDragonRainMonitor():
class PornembyDragonRainClickMonitor(Monitor):
name = 'Pornemby '
chat_user = ['PronembyTGBot2_bot', 'PronembyTGBot3_bot', 'PornembyBot']
chat_name = 'Pornemby'
chat_keyword = [None]
additional_auth = ['pornemby_pack']
allow_edit = T... |
class OptionSeriesHeatmapSonificationTracksMappingGapbetweennotes(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 make_linear_interpolator(field, grid=None, fill_value=None):
if (grid is None):
grid = field.grid
if grid.is_unstructured:
return make_linear_interpolator_unstructured(field, grid, fill_value)
else:
return make_linear_interpolator_separated(field, grid, fill_value) |
_filter('repo_url')
def repo_url(url):
parsed = urlparse(url)
if (parsed.scheme == 'copr'):
owner = parsed.netloc
prj = parsed.path.split('/')[1]
if (owner[0] == ''):
url = url_for('coprs_ns.copr_detail', group_name=owner[1:], coprname=prj)
else:
url = url... |
class TCPMappingTLSOriginationContextTest(AmbassadorTest):
extra_ports = [6789]
target: ServiceType
def init(self) -> None:
self.target = HTTP()
def manifests(self) -> str:
return (f'''
---
apiVersion: v1
kind: Secret
metadata:
name: {self.path.k8s}-clientcert
type: kubernetes.io/tls
d... |
class SpeakersCall(SoftDeletionModel):
__tablename__ = 'speakers_calls'
id = db.Column(db.Integer, primary_key=True)
announcement = db.Column(db.Text, nullable=True)
starts_at = db.Column(db.DateTime(timezone=True), nullable=False)
soft_ends_at = db.Column(db.DateTime(timezone=True), nullable=True)
... |
class OperatorSpecSchema(BaseSpecSchema):
operator_class = ma.fields.String(required=True)
operator_class_module = ma.fields.String(required=True)
property_preprocessors = ma.fields.List(ma.fields.Nested(PropertyPreprocessorSchema))
_schema
def valid_preprocessor_property_names(self, data):
... |
class VkontakteCallbackRouter(VkontaktePayloadRouter):
def extract_keys(self, context):
if isinstance(context.update, Message):
return ()
if (context.backend.get_identity() != 'vk'):
return ()
if (context.update['type'] != 'message_event'):
return ()
... |
def fillbox():
global remaininglinks
if bool(remaininglinks):
text = list_to_text(remaininglinks)
remaininglinks = []
return [text, 'Links updated!\nClick Download All! to download the rest of the links', gr.Button.update(visible=False)]
return ['', '', gr.Button.update(visible=False... |
class OptionSeriesOrganizationSonificationDefaultspeechoptionsMappingPitch(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, te... |
def lambda_handler(event, context):
print(event)
cognito_id = event['requestContext']['authorizer']['claims']['sub']
body = json.loads(event['body'])
date = str(datetime.datetime.now().isoformat())
if ('sentence_id' == ''):
body['sentence_id'] = generate_sentence_id()
try:
respon... |
class OptionPlotoptionsBoxplotSonificationDefaultspeechoptionsPointgrouping(Options):
def algorithm(self):
return self._config_get('last')
def algorithm(self, text: str):
self._config(text, js_type=False)
def enabled(self):
return self._config_get(True)
def enabled(self, flag: bo... |
def get_nonzero_filter():
nonzero_outlay = Q((((((Q(gross_outlay_amount_FYB_to_period_end__gt=0) | Q(gross_outlay_amount_FYB_to_period_end__lt=0)) | Q(USSGL487200_downward_adj_prior_year_prepaid_undeliv_order_oblig__gt=0)) | Q(USSGL487200_downward_adj_prior_year_prepaid_undeliv_order_oblig__lt=0)) | Q(USSGL497200_d... |
def construct_result(file_object):
type_of_file = file_object.processed_analysis['file_type']['result']['full']
arch_dict = file_object.processed_analysis.get('cpu_architecture', {})
architecture = _search_for_arch_keys(type_of_file, _architectures, delimiter='')
if (not architecture):
return ar... |
class CallbackPacket(cstruct.Instance):
counter: int
size: int
callback: BeaconCallback
data: bytes
def __init__(self, *args, **kwargs):
instance = c2struct.CallbackPacket(*args, **kwargs)
super().__init__(instance._type, instance._values, instance._sizes)
def __eq__(self, other)... |
def extractMeixiangsiHomeBlog(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... |
class PreviewTagPair(sublime_plugin.EventListener):
def on_query_context(self, view: sublime.View, key: str, *args):
if (key == 'emmet_tag_preview'):
return tag_pair.has_preview(view)
return None
_pair.allow_preview
def on_selection_modified_async(self, view: sublime.View):
... |
def change_ld(binary, ld, output):
if ((not binary) or (not ld) or (not output)):
log.failure("Try 'python change_ld.py -h' for more information.")
return None
binary = ELF(binary)
for segment in binary.segments:
if (segment.header['p_type'] == 'PT_INTERP'):
size = segmen... |
class NoteUpperWidget(urwid.WidgetWrap):
def __init__(self, note, onclick=None, first_corner=False, last_corner=False, **kw):
self.onclick = onclick
self.first_corner = first_corner
self.last_corner = last_corner
self.note = note
self.text = urwid.Text(self._build_text(), wra... |
def cli(args=None):
args = (args or sys.argv[2:])
if ((len(args) > 0) and (args[0] == 'balance')):
args = args[1:]
balance_main(args)
return
elif ('--layout' in args):
layout_main(args)
else:
args = argparser(args)
lmtp_serve_main(args) |
class MESH_OT_maze_mesh(bpy.types.Operator):
bl_idname = 'mesh.maze_mesh'
bl_label = 'Maze mesh selection'
bl_description = 'Generate a maze on selected part of mesh'
bl_options = {'REGISTER', 'UNDO'}
def poll(cls, context):
obj = context.edit_object
return ((obj is not None) and (ob... |
class Array(Expression):
def __init__(self, ast_node, expressions, name=None, type_string=None):
super().__init__(ast_node)
self.type_string = type_string
self.name: str = name
self.expressions = expressions
def __str__(self):
return f'Array {self.name}' |
class AnalysisKnobs():
export: t.Optional[Path] = (typer.Option(None, '-e', '--export', help='Export the fuzzability report to a path based on the file extension.Fuzzable supports exporting to `json`, `csv`, or `md`.'),)
list_ignored: bool = (typer.Option(False, help='If set, will also additionally output and/o... |
class TwoFerTest(unittest.TestCase):
def test_no_name_given(self):
self.assertEqual(two_fer(), 'One for you, one for me.')
def test_a_name_given(self):
self.assertEqual(two_fer('Alice'), 'One for Alice, one for me.')
def test_another_name_given(self):
self.assertEqual(two_fer('Bob'),... |
class Message():
def __init__(self, db, config):
if config['DEBUG']:
print('Initializing Message')
self.db = db
self.config = config
self.message_event = self.config['MESSAGE_EVENT']
if self.db:
sql = '\n CREATE TABLE IF NOT EXISTS Messa... |
class TestDispatcher(UnitTestWithNamespace):
def setUp(self) -> None:
super().setUp()
with Workflow(name='workflow', namespace=self.namespace_name) as workflow:
op = Operator(name='op')
op.action_on_condition(action=TaskAction.START, condition=Condition(expect_event_keys=['ev... |
class conv2d_bias_add_relu(conv2d_bias_add_activation):
def __init__(self, stride, pad, dilate=1, group=1) -> None:
super().__init__('relu', stride, pad, dilate=dilate, group=group)
def _get_op_attributes(self):
attr = super()._get_op_attributes()
del attr['activation']
return at... |
class Hardfork():
mod: ModuleType
def discover(cls: Type[H]) -> List[H]:
path = getattr(ethereum, '__path__', None)
if (path is None):
raise ValueError('module `ethereum` has no path information')
modules = pkgutil.iter_modules(path, (ethereum.__name__ + '.'))
modules... |
class CrawlerConfig(crawler.CrawlerConfig):
def __init__(self, storage, progresser, api_client, variables=None):
super(CrawlerConfig, self).__init__()
self.storage = storage
self.progresser = progresser
self.variables = ({} if (not variables) else variables)
self.client = api... |
def get_dependencies(primary_type, types):
deps = set()
struct_names_yet_to_be_expanded = [primary_type]
while (len(struct_names_yet_to_be_expanded) > 0):
struct_name = struct_names_yet_to_be_expanded.pop()
deps.add(struct_name)
fields = types[struct_name]
for field in fields... |
class WhoosheeStamp(object):
PATH = os.path.join(app.config['WHOOSHEE_DIR'], 'whooshee-version')
def current(cls):
packages = ['python3-flask-whooshee', 'python3-whoosh']
cmd = (['rpm', '-q', '--qf', '%{NAME}-%{VERSION}\n'] + packages)
process = Popen(cmd, stdout=PIPE, stderr=PIPE)
... |
class OptionPlotoptionsSolidgaugeSonificationDefaultinstrumentoptionsMappingPlaydelay(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... |
class FullstoryTestClient():
headers: object = {}
base_url: str = ''
def __init__(self, connection_config_fullstory: ConnectionConfig):
fullstory_secrets = connection_config_fullstory.secrets
self.headers = {'Authorization': f"Basic {fullstory_secrets['api_key']}"}
self.base_url = f"... |
class Link():
bot = 'embykeeper_auth_bot'
def __init__(self, client: Client):
self.client = client
self.log = logger.bind(scheme='telelink', username=client.me.name)
def instance(self):
rd = random.Random()
rd.seed(uuid.getnode())
return uuid.UUID(int=rd.getrandbits(1... |
class ZMQDeserializer(lg.Node):
INPUT = lg.Topic(ZMQMessage)
OUTPUT = lg.Topic(RandomMessage)
(INPUT)
(OUTPUT)
async def deserialize(self, message: ZMQMessage) -> lg.AsyncPublisher:
(yield (self.OUTPUT, RandomMessage(timestamp=time.time(), data=np.frombuffer(message.data)))) |
.xfail(raises=ImageComparisonFailure, reason='Matplotlib plots for reasons a different image size.')
.skipif((HIGH_MEMORY > memory), reason='Travis has too less memory to run it.')
def test_hicPlotMatrix_cool_log1p():
outfile = NamedTemporaryFile(suffix='.png', prefix='hicexplorer_test_cool', delete=False)
args... |
class ListMeta(Meta):
def __getitem__(self, type_elem):
if isinstance(type_elem, str):
type_elem = str2type(type_elem)
return type('ListBis', (List,), {'type_elem': type_elem})
def get_template_parameters(self):
if hasattr(self.type_elem, 'get_template_parameters'):
... |
class TestCreateIndexTemplateRunner():
('elasticsearch.Elasticsearch')
.asyncio
async def test_create_index_templates(self, es):
es.indices.put_template = mock.AsyncMock()
r = runner.CreateIndexTemplate()
params = {'templates': [('templateA', {'settings': {}}), ('templateB', {'settin... |
class Information(ErsiliaBase):
def __init__(self, model_id, config_json=None):
ErsiliaBase.__init__(self, config_json=config_json, credentials_json=None)
self.model_id = model_id
self.repository_folder = os.path.join(self._get_bento_location(model_id=self.model_id))
self.dest_folder... |
_parameters()
(name='day', period='day', fail_value=4, pass_value=1)
(name='hour', period='hour', fail_value=(4 * 24), pass_value=24)
def test_anomalyless_table_volume_anomalies_periods_params(test_id: str, dbt_project: DbtProject, period: str, fail_value: int, pass_value: int):
utc_today = (datetime.utcnow().date(... |
def start_task_execution(workflow_execution_id: int, task_name: str) -> str:
client = get_scheduler_client()
try:
return client.start_task_execution(workflow_execution_id, task_name)
except AIFlowException as e:
logger.exception('Failed to start execution for task %s with exception %s', f'{w... |
def fill_context(ctx, database, table, location, delay, latitude, longitude, geojson, spatialite, raw, **kwargs):
ctx.obj.update(database=database, table=table, location=location, delay=delay, latitude=latitude, longitude=longitude, geojson=geojson, spatialite=spatialite, raw=raw, kwargs=kwargs) |
def test_encoding_unknown_performative():
msg = OefSearchMessage(performative=OefSearchMessage.Performative.REGISTER_SERVICE, service_description=Description({'foo1': 1, 'bar1': 2}))
with pytest.raises(ValueError, match='Performative not valid:'):
with mock.patch.object(OefSearchMessage.Performative, '_... |
class OptionPlotoptionsTilemapSonificationTracksMappingPlaydelay(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 FuseSplitCatTestCase(unittest.TestCase):
def _test_fuse_split_cat_rearrange(self, M, N, split, remove_split=True):
dtype = 'float16'
M = IntImm(M)
N = IntImm(N)
input_1 = Tensor(shape=[M, N], name='input_1', is_input=True)
split_2 = ops.split()(input_1, split, 0)
... |
(scope='function')
def syncthing_manager(is_syncing, request, manager_nospawn, monkeypatch):
monkeypatch.setattr('qtile_extras.widget.syncthing.requests.get', is_syncing)
widget = qtile_extras.widget.syncthing.Syncthing(**{**{'api_key': 'apikey'}, **getattr(request, 'param', dict())})
class SyncthingConfig(... |
class OptionSeriesVennSonificationDefaultinstrumentoptionsMappingHighpassResonance(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, t... |
def load_trinity_config_from_parser_args(parser: argparse.ArgumentParser, args: argparse.Namespace, app_identifier: str, sub_configs: SubConfigs) -> TrinityConfig:
try:
return TrinityConfig.from_parser_args(args, app_identifier, sub_configs)
except AmbigiousFileSystem:
parser.error(TRINITY_AMBIG... |
class IOSAppMetadata(_AppMetadata):
def __init__(self, bundle_id, name, app_id, display_name, project_id):
super(IOSAppMetadata, self).__init__(name, app_id, display_name, project_id)
self._bundle_id = _check_is_nonempty_string(bundle_id, 'bundle_id')
def bundle_id(self):
return self._bu... |
def allow_deprecated_init(func: Callable):
(func)
def wrapper(self, *args, **kwargs):
if ((not args) and (not kwargs)):
warnings.warn("Initializing empty well is deprecated, please provide non-defaulted values, or use mywell = xtgeo.well_from_file('filename')", DeprecationWarning)
... |
def show(func=None, stop=False):
global _gui, _stop_show
if (func is None):
if (not is_ui_running()):
g = GUI()
_gui = g
if stop:
_stop_show = StopShow()
g.start_event_loop()
return
def wrapper(*args, **kw):
global _gui,... |
class OptionSeriesWindbarbDataDatalabels(Options):
def align(self):
return self._config_get('center')
def align(self, text: str):
self._config(text, js_type=False)
def allowOverlap(self):
return self._config_get(False)
def allowOverlap(self, flag: bool):
self._config(flag... |
def test_custom_field_definition_duplicate_name_rejected_update(db):
definition1 = CustomFieldDefinition.create(db=db, data={'name': 'test1', 'description': 'test', 'field_type': 'string', 'resource_type': 'system', 'field_definition': 'string'})
definition2 = CustomFieldDefinition.create(db=db, data={'name': '... |
def run_demo(viz, env, args):
global input
assert viz.check_connection(timeout_seconds=3), 'No connection could be formed quickly'
text_basic(viz, env, args)
text_update(viz, env, args)
text_callbacks(viz, env, args)
text_close(viz, env, args)
image_basic(viz, env, args)
image_callback(v... |
class CLICommand(Command):
def execute(self, session, acct):
out = io.StringIO()
nmc = NetworkManagementClient(session, acct)
for rt in nmc.route_tables.list_all():
bgp = ('N' if rt.disable_bgp_route_propagation else 'Y')
assocs = (0 if (rt.subnets is None) else len(r... |
def test():
assert ('doc1.similarity(doc2)' or ('doc2.similarity(doc1)' in __solution__)), 'Compares-tu la similarite entre les deux docs ?'
assert (0 <= float(similarity) <= 1), "La valeur de similarite doit etre un nombre flottant. L'as-tu calcule correctement ?"
__msg__.good('Bien joue !') |
def list_mapped_windows(workspace: (int | None)=None) -> list[Window]:
if (workspace is not None):
containers = _get_workspace_object(workspace)
else:
containers = SWAY.get_tree().leaves()
windows = [Window(con) for con in containers if _is_mapped_window(con)]
return windows |
class DBLogUpdateHandler(logging.Handler):
def __init__(self, db: DBDriver, id: int, interval: float=DEFAULT_INTERVAL, retries=3):
logging.Handler.__init__(self)
self.db = db
self.id = id
self.interval = interval
self.retries = retries
self.retries_left = self.retries... |
class OptionSeriesSplineSonificationDefaultinstrumentoptionsMappingVolume(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 UnionPIDDataPreparerService(abc.ABC):
def prepare(self, input_path: str, output_path: str, log_path: Optional[pathlib.Path]=None, log_level: int=logging.INFO, storage_svc: Optional[StorageService]=None) -> None:
pass
def prepare_on_container(self, input_path: str, output_path: str, onedocker_svc: ... |
def fy(raw_date):
if (raw_date is None):
return None
if isinstance(raw_date, str):
raw_date = parser.parse(raw_date)
try:
result = raw_date.year
if (raw_date.month > 9):
result += 1
except AttributeError:
raise TypeError('{} needs year and month attrib... |
((detect_target().name() == 'rocm'), 'Not supported by ROCM.')
class ConvBiasAddReluTestCase(unittest.TestCase):
def _test_conv_bias_add_relu(self, batch=4, copy_op=False, test_name='conv2d_bias_add_relu', dtype='float16'):
target = detect_target()
(CO, HH, WW, CI) = (256, 28, 28, 128)
X = T... |
def test_threshold(df_na):
imputer = DropMissingData(threshold=1)
X = imputer.fit_transform(df_na)
assert (list(X.index) == [0, 1, 4, 6, 7])
imputer = DropMissingData(threshold=0.01)
X = imputer.fit_transform(df_na)
assert (list(X.index) == [0, 1, 2, 3, 4, 5, 6, 7])
imputer = DropMissingData... |
_flyte_cli.command('update-launch-plan', cls=_FlyteSubCommand)
_state_choice
_host_option
_insecure_option
_optional_urn_option
def update_launch_plan(state, host, insecure, urn=None):
_welcome_message()
client = _get_client(host, insecure)
if (urn is None):
try:
if _stat.S_ISFIFO(_os.fs... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.