code stringlengths 281 23.7M |
|---|
def find_msg_dependencies_with_type(pkg_name, msg_file, search_paths):
msg_context = msg_loader.MsgContext.create_default()
full_type_name = gentools.compute_full_type_name(pkg_name, os.path.basename(msg_file))
spec = msg_loader.load_msg_from_file(msg_context, msg_file, full_type_name)
try:
msg_... |
class serienRecMainChannelEdit(serienRecBaseScreen, Screen, HelpableScreen):
def __init__(self, session):
serienRecBaseScreen.__init__(self, session)
Screen.__init__(self, session)
HelpableScreen.__init__(self)
self.session = session
self.serienRecChannelList = []
sel... |
.django_db
def test_subset_of_fields_returned(client, monkeypatch, transaction_data, elasticsearch_transaction_index):
setup_elasticsearch_test(monkeypatch, elasticsearch_transaction_index)
fields = ['Award ID', 'Recipient Name', 'Mod']
request = {'filters': {'keyword': 'test', 'award_type_codes': ['A', 'B'... |
class PlotGraphicsContextMixin(object):
def __init__(self, size_or_ary, *args, **kw):
scale = (kw.pop('dpi', 72.0) / 72.0)
if ((type(size_or_ary) in (list, tuple)) and (len(size_or_ary) == 2)):
size_or_ary = (int(((size_or_ary[0] * scale) + 1)), int(((size_or_ary[1] * scale) + 1)))
... |
class ResourceRules(object):
def __init__(self, resource=None, rules=None, applies_to=scanner_rules.RuleAppliesTo.SELF, inherit_from_parents=False):
if (not isinstance(rules, set)):
rules = set([])
self.resource = resource
self.rules = rules
self.applies_to = scanner_rule... |
(scope='session')
def ethereum_testnet_config(ganache_addr, ganache_port):
new_uri = f'{ganache_addr}:{ganache_port}'
new_config = {'address': new_uri, 'chain_id': DEFAULT_GANACHE_CHAIN_ID, 'denom': ETHEREUM_DEFAULT_CURRENCY_DENOM, 'gas_price_api_key': GAS_PRICE_API_KEY}
return new_config |
class TestApplicationConfigModel():
(scope='function')
def example_config_dict(self) -> Dict[(str, str)]:
return {'setting1': 'value1', 'setting2': 'value2', 'setting3': {'nested_setting_1': 'nested_value_1', 'nested_setting_2': 'nested_value_2'}}
(scope='function')
def example_config_record(sel... |
class MySQLSearchBackend(SearchBackend):
def is_installed(self):
connection = connections[router.db_for_read(SearchEntry)]
cursor = connection.cursor()
cursor.execute("SHOW INDEX FROM watson_searchentry WHERE Key_name = 'watson_searchentry_fulltext'")
return bool(cursor.fetchall())
... |
def extractKotransalationBlogspotCom(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_t... |
class FooDemo(HasTraits):
foo = Instance(DerivedFoo, ())
configure = Button('Configure')
view = View(Label("Try configuring several times, each time changing the items on the 'Parents?' tab."), '_', HGroup(spring, Item('configure', show_label=False)))
def _configure_changed(self):
self.foo.confi... |
class SubscriptionApi(Api):
_id(Article, Section, Post, Topic)
def subscriptions(self, help_centre_object):
return self._query_zendesk(self.endpoint.subscriptions, object_type='subscriptions', id=help_centre_object)
_id(Article, Section, Post, Topic)
def create_subscription(self, help_centre_obj... |
class ModelDefinitionKeyError(Exception):
def __init__(self, ex: KeyError):
self.missed_key = ex.args[0]
def __str__(self):
return (((f'Key "{self.missed_key}" is not available. ' + 'The model definition may have changed. ') + 'Make sure you are using an Elasticsearch version compatible ') + f'w... |
class Apodizer(AgnosticOpticalElement):
def __init__(self, apodization):
self._apodization = apodization
AgnosticOpticalElement.__init__(self, True, True)
def make_instance(self, instance_data, input_grid, output_grid, wavelength):
instance_data.apodization = self.evaluate_parameter(self... |
def identify_unique_asset_codes(raw_data):
unique_asset_codes = []
for row in raw_data:
asset_code = row['asset_code']
asset_data = row['reading']
if (not any(((item['asset_code'] == asset_code) for item in unique_asset_codes))):
unique_asset_codes.append({'asset_code': asset... |
('evennia.commands.default.comms.CHANNEL_DEFAULT_TYPECLASS', DefaultChannel)
class TestCommsChannel(BaseEvenniaCommandTest):
def setUp(self):
super().setUp()
self.channel = create_channel(key='testchannel', desc='A test channel')
self.channel.connect(self.char1)
self.cmdchannel = cmd... |
.flaky(reruns=MAX_FLAKY_RERUNS)
.skipif((sys.version_info < (3, 7)), reason="cannot run on 3.6 as AttributeError: 'functools._lru_list_elem' object has no attribute '__class__'")
def test_run_with_profiling():
runner = CliRunner()
agent_name = 'myagent'
cwd = os.getcwd()
t = tempfile.mkdtemp()
shuti... |
def balance_inward(view, syntax_name):
result = []
for sel in view.sel():
regions = get_regions(view, sel.begin(), syntax_name, 'inward')
ix = (- 1)
for (i, r) in enumerate(regions):
if (r == sel):
ix = i
break
target_region = sel
... |
class OptionPlotoptionsBubbleSonificationTracksMappingRate(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.... |
class OptionPlotoptionsDumbbellSonificationContexttracksMappingHighpassFrequency(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, tex... |
.django_db
def test_show_collaborators_tab_when_can_register_as_collaborator_should_return_true(user1, event1, mocker):
mock_can_register_as_collaborator = mocker.patch('manager.templatetags.filters.can_register_as_collaborator')
mock_can_register_as_collaborator.return_value = True
assert filters.show_coll... |
.parametrize('header_name', [constants.TRACEPARENT_HEADER_NAME, constants.TRACEPARENT_LEGACY_HEADER_NAME])
def test_traceparent_handling(flask_apm_client, header_name):
with mock.patch('elasticapm.contrib.flask.TraceParent.from_string', wraps=TraceParent.from_string) as wrapped_from_string:
resp = flask_apm... |
def test_re_fork_at_prune_boundary():
def task_id(task):
return TaskID(task.idx, task.fork)
def fork_prereq(task):
return TaskID((task.idx - 1), task.parent_fork)
ti = OrderedTaskPreparation(NoPrerequisites, task_id, fork_prereq, max_depth=2)
ti.set_finished_dependency(Task(0, 0, 0))
... |
class BlogPost(Document):
title = Text()
published = Date()
tags = Keyword(multi=True)
content = Text()
def is_published(self):
return (self.published and (datetime.now() > self.published))
def _matches(cls, hit):
return fnmatch(hit['_index'], PATTERN)
class Index():
... |
class _FlowSpecL2VPNPrefixBase(_FlowSpecL2VPNComponent):
_PACK_STR = '!B6s'
def __init__(self, length, addr, type_=None):
super(_FlowSpecL2VPNPrefixBase, self).__init__(type_)
self.length = length
self.addr = addr.lower()
def parse_body(cls, buf):
(length, addr) = struct.unpa... |
.scheduler
.integration_test
.parametrize('mode, cmd_line_arguments', [pytest.param(TEST_RUN_MODE, ['poly_example/poly.ert'], id='test_run'), pytest.param(ENSEMBLE_EXPERIMENT_MODE, ['--realizations', '0,1', 'poly_example/poly.ert'], id='ensemble_experiment')])
def test_setting_env_context_during_run(mode, cmd_line_argu... |
class serienRecBaseScreen():
def __init__(self, session):
self.session = session
self.skin = None
self.chooseMenuList = MenuList([], enableWrapAround=True, content=eListboxPythonMultiContent)
self.displayTimer = None
self.skinName = None
self.num_bt_text = ()
def ... |
class OptionPlotoptionsAreasplineStates(Options):
def hover(self) -> 'OptionPlotoptionsAreasplineStatesHover':
return self._config_sub_data('hover', OptionPlotoptionsAreasplineStatesHover)
def inactive(self) -> 'OptionPlotoptionsAreasplineStatesInactive':
return self._config_sub_data('inactive',... |
class Rule_Line_Blank_Lines(Style_Rule_Line):
def __init__(self):
super().__init__('consecutive_blanks', True)
self.mandatory = True
self.is_blank = False
def apply(self, mh, cfg, filename, line_no, line):
if len(line.strip()):
self.is_blank = False
elif self.... |
class Lsvuln(BaseUtil):
def get_settings():
return dict(descr='List all vulnerabilities', optargs='', minargs=0, use_dbfile=True)
def usage(self):
return ('%s\nusage: %s <dbfile> [<sql_where_clause>]\n' % (self.get_settings()['descr'], self.utilname))
def main(self, args, opts, db_file):
... |
_admin_required
def SubscriptionsManageList(request, location_slug):
location = get_object_or_404(Location, slug=location_slug)
active = Subscription.objects.active_subscriptions().filter(location=location).order_by('-start_date')
inactive = Subscription.objects.inactive_subscriptions().filter(location=loca... |
class Record(models.Model):
MAX_UINT32 =
PRIO = 0
TTL = 300
A = 'A'
AAAA = 'AAAA'
CERT = 'CERT'
CNAME = 'CNAME'
HINFO = 'HINFO'
KEY = 'KEY'
LOC = 'LOC'
MX = 'MX'
NAPTR = 'NAPTR'
NS = 'NS'
PTR = 'PTR'
RP = 'RP'
SOA = 'SOA'
SPF = 'SPF'
SSHFP = 'SSHF... |
class PosixNamedPipeChannel(IPCChannel):
def __init__(self, logger: logging.Logger=_default_logger, loop: Optional[AbstractEventLoop]=None) -> None:
self.logger = logger
self._loop = loop
self._pipe_dir = tempfile.mkdtemp()
self._in_path = '{}/process_to_aea'.format(self._pipe_dir)
... |
class MemBar(IntervalModule, ColorRangeModule):
format = '{used_mem_bar}'
color = '#00FF00'
warn_color = '#FFFF00'
alert_color = '#FF0000'
warn_percentage = 50
alert_percentage = 80
multi_colors = False
def init(self):
self.colors = self.get_hex_color_range(self.color, self.alert... |
class TraversalNode():
def __init__(self, node: Node):
self.node = node
self.address = node.address
self.children: Dict[(CollectionAddress, List[Tuple[(TraversalNode, FieldPath, FieldPath)]])] = {}
self.parents: Dict[(CollectionAddress, List[Tuple[(TraversalNode, FieldPath, FieldPath... |
def getProperties(klass):
tmpString = '\n NSMutableArray *result = (id)[NSMutableArray array];\n unsigned int count;\n objc_property_t *props = (objc_property_t *)class_copyPropertyList((Class)$cls, &count);\n for (int i = 0; i < count; i++) {\n NSMutableDictionary *dict = (id)[NSMutabl... |
def test_turbomole_big_hessian_parsing(this_dir):
geom = geom_loader('lib:ch4_12.xyz')
control_path = (this_dir / 'control_path_big_hess')
turbo_kwargs = {'control_path': control_path}
calc = Turbomole(**turbo_kwargs)
geom.set_calculator(calc)
results = calc.parse_hessian(path=control_path)
... |
def swag_annotation(f):
(f)
def wrapper(*args, **kwargs):
if (not kwargs.pop('swag', False)):
return f(*args, **kwargs)
function = args[2]
specs = {}
for (key, value) in DEFAULT_FIELDS.items():
specs[key] = kwargs.pop(key, value)
for (variable, ann... |
_measure
class AngleSuccess(Measure):
cls_uuid: str = 'angle_success'
def __init__(self, config: Config, *args: Any, **kwargs: Any):
self._config = config
super().__init__()
def _get_uuid(self, *args: Any, **kwargs: Any) -> str:
return self.cls_uuid
def reset_metric(self, task: E... |
class TestCLIShowRepositories(CuratorTestCase):
def test_show_repository(self):
self.create_repository()
self.write_config(self.args['configfile'], testvars.client_conf_logfile.format(HOST, os.devnull))
test = clicktest.CliRunner()
result = test.invoke(repo_mgr_cli, ['--config', self... |
class Group(Entity, ACLMixin):
__auto_name__ = False
__tablename__ = 'Groups'
__mapper_args__ = {'polymorphic_identity': 'Group'}
gid = Column('id', Integer, ForeignKey('Entities.id'), primary_key=True)
users = relationship('User', secondary='Group_Users', back_populates='groups', doc='Users in this... |
class OptionPlotoptionsPictorialZones(Options):
def className(self):
return self._config_get(None)
def className(self, text: str):
self._config(text, js_type=False)
def color(self):
return self._config_get(None)
def color(self, text: str):
self._config(text, js_type=False... |
def extractDesperatemtlWordpressCom(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 print_table(target: Path, fuzzability: Fuzzability, skipped: t.Dict[(str, str)], ignore_metrics: bool, list_ignored: bool, table_export: bool=False) -> None:
table = generate_table(target, fuzzability, ignore_metrics)
if table_export:
console = Console(file=StringIO())
else:
console = Co... |
_frequency(timedelta(days=2))
def fetch_exchange(zone_key1: str='NO-NO4', zone_key2: str='SE', session: (Session | None)=None, target_datetime: (datetime | None)=None, logger: Logger=getLogger(__name__)) -> list[dict]:
return fetch_data(zone_key1=zone_key1, zone_key2=zone_key2, session=session, target_datetime=targ... |
class QueryStub(object):
def __init__(self, channel):
self.CurrentPlan = channel.unary_unary('/cosmos.upgrade.v1beta1.Query/CurrentPlan', request_serializer=cosmos_dot_upgrade_dot_v1beta1_dot_query__pb2.QueryCurrentPlanRequest.SerializeToString, response_deserializer=cosmos_dot_upgrade_dot_v1beta1_dot_query... |
.perf
.returns('GB/s')
def test_small_scan_performance(thr, exclusive, seq_size):
dtype = dtypes.normalize_type(numpy.complex128)
shape = (500, 2, 2, 512)
min_time = check_scan(thr, shape, dtype=dtype, axes=((- 1),), exclusive=exclusive, measure_time=True, seq_size=seq_size)
return (min_time, (helpers.p... |
class _AppMetadata():
def __init__(self, name, app_id, display_name, project_id):
self._name = _check_is_nonempty_string(name, 'name')
self._app_id = _check_is_nonempty_string(app_id, 'app_id')
self._display_name = _check_is_string_or_none(display_name, 'display_name')
self._project_... |
class LMTPModel():
max_batch_size: int = 1
def eos_token_id(self):
raise NotImplementedError
def load(self, model_name, **kwargs) -> 'LMTPModel':
if (':' in model_name):
backend_name = model_name.split(':')[0]
if (backend_name in LMTPModel.registry.keys()):
... |
def _format_stringmap(appid, field, stringmap, versionCode=None):
app_dir = Path('metadata', appid)
try:
next(app_dir.glob(('*/%s/*.txt' % field.lower())))
files = []
overwrites = []
for (name, descdict) in stringmap.items():
for (locale, desc) in descdict.items():
... |
.gui()
.skipif((sys.platform != 'linux'), reason='Linux specific test')
.skipif(('GITHUB_ACTIONS' in os.environ), reason='Skip on Action Runner')
def test_synchronized_capture(dbus_portal, qapp):
if (not has_screenshot_permission()):
pytest.xfail('Root UI application which started this test has no screensho... |
def recursive_update(to_update: Dict, new_values: Dict, allow_new_values: bool=False) -> None:
for (key, value) in new_values.items():
if ((not allow_new_values) and (key not in to_update)):
raise ValueError(f"Key '{key}' is not contained in the dictionary to update.")
if ((key not in to... |
def create_listener():
def listener(obj, trait_name, old, new):
listener.obj = obj
listener.trait_name = trait_name
listener.new = new
listener.old = old
listener.called += 1
listener.initialize = (lambda : initialize_listener(listener))
return initialize_listener(lis... |
class OptionPlotoptionsAreaAccessibility(Options):
def description(self):
return self._config_get(None)
def description(self, text: str):
self._config(text, js_type=False)
def descriptionFormat(self):
return self._config_get(None)
def descriptionFormat(self, text: str):
s... |
class CommandBase():
DESCRIPTION = '\n This is a default description. You should overwrite it in your sub-class.\n '
args = None
parser = None
subparser = None
def __init__(self, get_conn_func=None):
self.get_conn_func = get_conn_func
self.init()
def init(self):
pas... |
()
def quickstart(user_email: str=typer.Option(..., prompt=True, help='The admin user email'), user_password: str=typer.Option(..., prompt=True, confirmation_prompt=True, hide_input=True, help='The admin user password'), docker: bool=typer.Option(False, help='Show the Docker command to run the Fief server with required... |
def _chain_with_block_validation(VM, base_db, genesis_state, chain_cls=Chain):
klass = chain_cls.configure(__name__='TestChain', vm_configuration=((constants.GENESIS_BLOCK_NUMBER, VM.configure(consensus_class=PowConsensus)),), chain_id=1337)
chain = klass.from_genesis(base_db, _get_genesis_defaults(), genesis_s... |
class OptionPlotoptionsLineMarkerStatesHover(Options):
def animation(self) -> 'OptionPlotoptionsLineMarkerStatesHoverAnimation':
return self._config_sub_data('animation', OptionPlotoptionsLineMarkerStatesHoverAnimation)
def enabled(self):
return self._config_get(True)
def enabled(self, flag:... |
def test_node_execution_data_response():
input_blob = _common_models.UrlBlob('in', 1)
output_blob = _common_models.UrlBlob('out', 2)
obj = _execution.NodeExecutionGetDataResponse(input_blob, output_blob, _INPUT_MAP, _OUTPUT_MAP)
obj2 = _execution.NodeExecutionGetDataResponse.from_flyte_idl(obj.to_flyte_... |
class OptionPlotoptionsTimelineStatesHoverHalo(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(n... |
class RelatedField(WritableField):
widget = widgets.Select
many_widget = widgets.SelectMultiple
form_field_class = forms.ChoiceField
many_form_field_class = forms.MultipleChoiceField
null_values = (None, '', 'None')
cache_choices = False
empty_label = None
read_only = True
many = Fal... |
def register_all_params_in_track(assembled_source, complete_track_params=None):
j2env = jinja2.Environment()
internal_template_vars = default_internal_template_vars()
for macro_type in internal_template_vars:
for (env_global_key, env_global_value) in internal_template_vars[macro_type].items():
... |
class OptionSeriesNetworkgraphNodesMarkerStates(Options):
def hover(self) -> 'OptionSeriesNetworkgraphNodesMarkerStatesHover':
return self._config_sub_data('hover', OptionSeriesNetworkgraphNodesMarkerStatesHover)
def inactive(self) -> 'OptionSeriesNetworkgraphNodesMarkerStatesInactive':
return s... |
def messageListAppend(js, url, num, msg_list):
car = js['data']['cards'][num]
img = Image.open(BytesIO(requests.get(url).content))
msg_list.append(Message([{'type': 'image', 'data': {'file': f"base64://{str(image_to_base64(img.resize((int((img.size[0] * PANTOGRAPH)), int((img.size[1] * PANTOGRAPH))), Image.... |
def setup_postgres():
app = Flask(__name__)
app.config['SECRET_KEY'] = '1'
app.config['CSRF_ENABLED'] = False
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://postgres:/flask_admin_test'
app.config['SQLALCHEMY_ECHO'] = True
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAl... |
class Float():
values = None
python_type = 'float'
yaml_type = 'Float'
json_schema = {'type': 'number'}
def __init__(self, param):
self._param = param
self.yaml_default = param._defs.get('default')
if (self.yaml_default is not None):
self.yaml_default = float(self... |
def filter_firewall_service_group_data(json):
option_list = ['color', 'comment', 'fabric_object', 'member', 'name', 'proxy']
json = remove_invalid_fields(json)
dictionary = {}
for attribute in option_list:
if ((attribute in json) and (json[attribute] is not None)):
dictionary[attribu... |
def generate_csv(target, headers=None, lines=[], separator=',', quote_strings=None, none_are_empty=True, **kwargs):
assert none_are_empty
with open(target, 'w') as f:
if headers:
print(separator.join(headers), file=f)
def str_or_none(x):
if (x is None):
re... |
class DataFile(OutputFile):
_file_suffix = '.xpd'
def __init__(self, additional_suffix, directory=None, delimiter=None, time_stamp=None):
if _internals.active_exp.is_initialized:
self._subject = _internals.active_exp.subject
else:
self._subject = None
if (director... |
def as_local_files(urls: Sequence[str]):
file_paths = []
temp_files = []
for url in urls:
response = requests.get(url)
temp_file = tempfile.NamedTemporaryFile()
temp_file.write(response.content)
file_paths.append(temp_file.name)
temp_files.append(temp_file)
(yield... |
def test_get_client_root_client(db, config):
client = ClientDetail.get(db, object_id='fidesadmin', config=config, scopes=SCOPE_REGISTRY, roles=[OWNER])
assert client
assert (client.id == config.security.oauth_root_client_id)
assert (client.scopes == SCOPE_REGISTRY)
assert (client.roles == [OWNER])
... |
()
('url', required=True)
('--binary', '-b', default='google-chrome', help='Specify a specific chromium binary.')
('--outfile', '-o', default=False, help='Write the output to a file. \t\t\t\tText content will be UTF-8 encoded. \t\t\t\tBinary content will be written as-is.')
('--noprint', '-n', is_flag=True, help='Do no... |
def incorporate_child_on_success(evm: Evm, child_evm: Evm) -> None:
evm.gas_left += child_evm.gas_left
evm.logs += child_evm.logs
evm.refund_counter += child_evm.refund_counter
evm.accounts_to_delete.update(child_evm.accounts_to_delete)
evm.touched_accounts.update(child_evm.touched_accounts)
if ... |
class LangChain():
def __init__(self, name: str, api: str, config: Dict[(Any, Any)], query: Callable[(['langchain.llms.BaseLLM', Iterable[Any]], Iterable[Any])]):
self._langchain_model = LangChain._init_langchain_model(name, api, config)
self.query = query
self._check_installation()
def ... |
class ObjectTypeMibTableImpliedIndexTestCase(unittest.TestCase):
def setUp(self):
ast = parserFactory()().parse(self.__class__.__doc__)[0]
(mibInfo, symtable) = SymtableCodeGen().genCode(ast, {}, genTexts=True)
(self.mibInfo, pycode) = PySnmpCodeGen().genCode(ast, {mibInfo.name: symtable}, g... |
def send_audio(token, chat_id, audio, caption=None, duration=None, performer=None, title=None, reply_to_message_id=None, reply_markup=None, parse_mode=None, disable_notification=None, timeout=None, thumbnail=None, caption_entities=None, allow_sending_without_reply=None, protect_content=None, message_thread_id=None):
... |
def test_interact(plugintester, mocker, monkeypatch, console):
monkeypatch.setattr('brownie._cli.console.Console.__init__', (lambda *args, **kwargs: None))
monkeypatch.setattr('brownie._cli.console.Console.interact', (lambda *args, **kwargs: None))
mocker.spy(console, 'interact')
plugintester.runpytest(... |
def test_hicConvertFormat_h5_to_cool():
outfile = NamedTemporaryFile(suffix='.cool', delete=False)
outfile.close()
args = '--matrices {} --outFileName {} --inputFormat h5 --outputFormat cool'.format(original_matrix_h5, outfile.name).split()
compute(hicConvertFormat.main, args, 5)
test = hm.hiCMatrix... |
class GraphJsonEncoder(json.JSONEncoder):
def __init__(self, op_names: Dict[(Operator, str)], *args, **kwargs):
super(GraphJsonEncoder, self).__init__(*args, **kwargs)
self.op_names: Dict[(Operator, str)] = op_names
def default(self, obj):
if isinstance(obj, FuncEnum):
return... |
def setup_file_logging(logfile_path: Path, level: int=None) -> RotatingFileHandler:
if (level is None):
level = logging.DEBUG
logger = logging.getLogger()
handler_file = RotatingFileHandler(str(logfile_path), maxBytes=( * LOG_MAX_MB), backupCount=LOG_BACKUP_COUNT, delay=True)
if logfile_path.exi... |
.skipif(CLICK_IS_BEFORE_VERSION_8X, reason='Result does not have return_value attribute.')
def test_command_return_value_is_exit_code_when_not_standalone() -> None:
for expected_exit_code in range(10):
('cli')
_context
def cli(ctx: click.Context) -> None:
ctx.exit(expected_exit_c... |
def test_column_searchable_list():
(app, db, admin) = setup()
with app.app_context():
(Model1, Model2) = create_models(db)
view = CustomModelView(Model2, db.session, column_searchable_list=['string_field', 'int_field'])
admin.add_view(view)
assert view._search_supported
a... |
class GethTxPool(Module):
is_async = False
content: Method[Callable[([], TxPoolContent)]] = Method(RPC.txpool_content, is_property=True)
inspect: Method[Callable[([], TxPoolInspect)]] = Method(RPC.txpool_inspect, is_property=True)
status: Method[Callable[([], TxPoolStatus)]] = Method(RPC.txpool_status, ... |
class AccountForm(UserCreationForm):
class Meta():
model = class_from_module(settings.BASE_ACCOUNT_TYPECLASS, fallback=settings.FALLBACK_ACCOUNT_TYPECLASS)
fields = ('username', 'email')
field_classes = {'username': UsernameField}
email = forms.EmailField(help_text='A valid email address... |
def normalize(mod: torch.fx.GraphModule, expect_nodes_have_shapes: bool=False, acc_normalization_block_list: Optional[Set[Tuple[(str, Union[(str, Callable)])]]]=None):
assert (len(_normalization_dict) > 0)
graph = mod.graph
if (acc_normalization_block_list is None):
acc_normalization_block_list = se... |
class OptionPlotoptionsVennSonificationDefaultspeechoptionsMappingPitch(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:... |
def run_module():
module = AnsibleModule(argument_spec=dict(state=dict(default='present', choices=['present', 'absent']), defaults_type=dict(required=False, default='meta', choices=['meta', 'op']), name=dict(required=True), value=dict(required=False), cib_file=dict(required=False)), supports_check_mode=True)
st... |
def text_to_png(text, color='#000', bgcolor='#FFF', fontfullpath=None, fontsize=13, leftpadding=3, rightpadding=3, width=500):
REPLACEMENT_CHARACTER = 'nlnlnl'
NEWLINE_REPLACEMENT_STRING = ((' ' + REPLACEMENT_CHARACTER) + ' ')
font = (ImageFont.load_default() if (fontfullpath == None) else ImageFont.truetyp... |
def test_mfs(mesh2D):
V1 = FunctionSpace(mesh2D, 'BDM', 1)
V2 = FunctionSpace(mesh2D, 'CG', 2)
V3 = FunctionSpace(mesh2D, 'CG', 3)
W = ((V3 * V1) * V2)
u = Function(W)
(u0, u1, u2) = u.subfunctions
u0.interpolate(Constant(1))
u1.project(Constant(((- 1.0), (- 1.0))))
u2.interpolate(Co... |
class _Unavailable(object):
def __init__(self, missing):
self.__missing = missing
def Client(self, *args, **kwargs):
warn('Trying to initialize `{module}` which is not available. A placeholder object will be used instead, but it will raise `ImportError` later if there is any actual attempt at us... |
class FaucetTunneltoCoprocessorTest(FaucetTopoTestBase):
NUM_DPS = 2
NUM_HOSTS = 4
NUM_VLANS = 1
N_TAGGED = 0
N_UNTAGGED = 4
SOFTWARE_ONLY = True
def acls(self):
return {1: [{'rule': {'dl_type': IPV4_ETH, 'ip_proto': 1, 'actions': {'allow': 0, 'output': {'tunnel': {'type': 'vlan', 't... |
def extractRuisitranslationsHomeBlog(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [("I've Transmigrated Into This Movie Before", "I've Transmigrated Into This Movie Before", 't... |
class TestSwitchVariableDetection():
def test9_normal(self):
cfg = ControlFlowGraph()
cfg.add_nodes_from([(start := BasicBlock(0, instructions=[Assignment(eax(1), arg(0)), Assignment(eax(2), BinaryOperation(OperationType.plus, [eax(1), const(1)])), Branch(Condition(OperationType.greater, [eax(2), co... |
class ClsFormula(GrpCls.ClassHtml):
def __init__(self, component):
super(ClsFormula, self).__init__(component)
(self._css_container, self._css_mjx, self._css_display) = (3 * [None])
self.classList['other'].add(self.cls_container)
self.classList['other'].add(self.cls_mjx)
self... |
def __getattr__(name):
if (name == '__version__'):
try:
from importlib.metadata import version
except ImportError:
from importlib_metadata import version
from warnings import warn
warn(f"traitsui.{name} is deprecated, use importlib.metadata.version('traitsui')... |
def statsig_enterprise_runner(db, cache, statsig_enterprise_secrets, statsig_enterprise_erasure_external_references) -> ConnectorRunner:
return ConnectorRunner(db, cache, 'statsig_enterprise', statsig_enterprise_secrets, erasure_external_references=statsig_enterprise_erasure_external_references) |
def findNotesWithHighestPerformance(decks, limit, pinned, retOnly=False):
scores = _calcScores(decks, limit, retOnly)
scores = sorted(scores.items(), key=(lambda x: x[1][0]), reverse=True)
rList = []
c = 0
for r in scores:
if (str(r[1][1][0]) not in pinned):
rList.append(IndexNot... |
def getTargetInfo(snmpEngine, snmpTargetAddrName):
(snmpTargetAddrTDomain, snmpTargetAddrTAddress, snmpTargetAddrTimeout, snmpTargetAddrRetryCount, snmpTargetAddrParams) = getTargetAddr(snmpEngine, snmpTargetAddrName)
(snmpTargetParamsMPModel, snmpTargetParamsSecurityModel, snmpTargetParamsSecurityName, snmpTar... |
def setup_to_pass():
shutil.copy('/etc/login.defs', '/etc/login.defs.bak')
shutil.copy('/etc/shadow', '/etc/shadow.bak')
shellexec("sed -i 's/^\\s*PASS_MAX_DAYS.*/PASS_MAX_DAYS 365/' /etc/login.defs")
shellexec("sed -i -E '/(root|vagrant):/ s/0:99999/0:365/' /etc/shadow")
(yield None)
shutil.mov... |
def calc_distance_to_bus(net, bus, respect_switches=True, nogobuses=None, notravbuses=None, weight='weight'):
g = create_nxgraph(net, respect_switches=respect_switches, nogobuses=nogobuses, notravbuses=notravbuses)
return pd.Series(nx.single_source_dijkstra_path_length(g, bus, weight=weight)) |
def generate_dataset(size: int, exclude: Optional[Set[str]]=None) -> DatasetTuple:
ops: Ops = get_current_ops()
texts: List[str] = generate_problems(size, exclude=exclude)
examples: List[ModelX] = []
labels: List[ModelY] = []
for (i, text) in enumerate(texts):
(text, x, y) = to_example(text)... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.