code stringlengths 281 23.7M |
|---|
def findFirst2(path, fileName, level, searchAttributes, pktFlags=smb.SMB.FLAGS2_UNICODE, isSMB2=False):
if (pktFlags & smb.SMB.FLAGS2_UNICODE):
encoding = 'utf-16le'
else:
encoding = 'ascii'
fileName = normalize_path(fileName)
pathName = os.path.join(path, fileName)
if (not isInFileJ... |
def keygen(get_keyring=get_keyring):
warn_signatures()
(WheelKeys, keyring) = get_keyring()
ed25519ll = signatures.get_ed25519ll()
wk = WheelKeys().load()
keypair = ed25519ll.crypto_sign_keypair()
vk = native(urlsafe_b64encode(keypair.vk))
sk = native(urlsafe_b64encode(keypair.sk))
kr = ... |
class OptionPlotoptionsCylinderSonificationContexttracksMappingRate(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 TestDiscordGetIdEmail():
.asyncio
async def test_success(self, get_respx_call_args):
request = respx.get(re.compile(f'^{PROFILE_ENDPOINT}')).mock(return_value=Response(200, json=profile_verified_email_response))
(user_id, user_email) = (await client.get_id_email('TOKEN'))
(_, heade... |
class TestUslugifyCasedEncoded(util.MdCase):
extension = ['markdown.extensions.toc']
extension_configs = {'markdown.extensions.toc': {'slugify': slugs.uslugify_cased_encoded}}
def test_slug(self):
with pytest.warns(DeprecationWarning):
self.check_markdown('# Testing cased unicode-slugs_h... |
def run_subprocess_with_logging(command_line, header=None, level=logging.INFO, stdin=None, env=None, detach=False):
logger = logging.getLogger(__name__)
logger.debug('Running subprocess [%s] with logging.', command_line)
command_line_args = shlex.split(command_line)
pre_exec = (os.setpgrp if detach else... |
def dataclass_from_dict(cls: type, src: typing.Dict[(str, typing.Any)]) -> typing.Any:
field_types_lookup = {field.name: field.type for field in dataclasses.fields(cls)}
constructor_inputs = {}
for (field_name, value) in src.items():
if dataclasses.is_dataclass(field_types_lookup[field_name]):
... |
def extractJadeslipWordpressCom(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,... |
class ConvBlock(nn.Module):
def __init__(self, in_planes, out_planes, norm='batch'):
super(ConvBlock, self).__init__()
self.norm = norm
self.conv1 = conv3x3(in_planes, int((out_planes / 2)), norm=norm)
self.conv2 = conv3x3(int((out_planes / 2)), int((out_planes / 4)), norm=norm)
... |
class FipaDialogue(BaseFipaDialogue):
__slots__ = ('_proposal', '_terms', '_counterparty_signature')
def __init__(self, dialogue_label: DialogueLabel, self_address: Address, role: Dialogue.Role, message_class: Type[FipaMessage]=FipaMessage) -> None:
BaseFipaDialogue.__init__(self, dialogue_label=dialogu... |
def to_omnetpp(topology, path=None):
try:
from mako.template import Template
except ImportError:
raise ImportError('Cannot import mako.template module. Make sure mako is installed on this machine.')
set_delays = True
set_capacities = True
if ((not ('capacity_unit' in topology.graph))... |
class TestESP8266V1Image(BaseTestCase):
ELF = 'esp8266-nonosssdk20-iotdemo.elf'
BIN_LOAD = 'esp8266-nonosssdk20-iotdemo.elf-0x00000.bin'
BIN_IROM = 'esp8266-nonosssdk20-iotdemo.elf-0x10000.bin'
def setup_class(self):
super(TestESP8266V1Image, self).setup_class()
self.run_elf2image(self, ... |
class Capability():
def __init__(self, name='', namespace='', cap_type='', images=[], description='', nodes=[]):
self.namespace = namespace
self.name = name
self.type = cap_type
self.images = (images if images else [])
self.description = description
self.nodes = (node... |
class CcrClient(NamespacedClient):
_rewrite_parameters()
async def delete_auto_follow_pattern(self, *, name: str, error_trace: t.Optional[bool]=None, filter_path: t.Optional[t.Union[(str, t.Sequence[str])]]=None, human: t.Optional[bool]=None, pretty: t.Optional[bool]=None) -> ObjectApiResponse[t.Any]:
i... |
def _dequantize(obj):
if (obj is None):
return None
elif (type(obj) == torch.Tensor):
if (obj.dtype != torch.float32):
return obj.to(torch.float32)
else:
return obj
else:
resultTensor = obj.value()[0]
if (resultTensor.dtype != torch.float32):
... |
def store_providers(path):
global settings
global public
global private
public1_string = ''
private1_string = ''
public1_predefined_string = ''
private1_predefined_string = ''
public2_string = ''
private2_string = ''
public2_predefined_string = ''
private2_predefined_string =... |
class LoansViewSet(LoansMixin, LoansPaginationMixin, FabaOutlayMixin, ElasticsearchAccountDisasterBase):
endpoint_doc = 'usaspending_api/api_contracts/contracts/v2/disaster/federal_account/loans.md'
agg_key = 'financial_accounts_by_award.treasury_account_id'
nested_nonzero_fields = {'obligation': 'transacti... |
.parametrize('uri_template,', ['/{id:int(2)}', '/{id:int(min=124)}', '/{id:int(num_digits=3, max=100)}'])
def test_int_converter_rejections(client, uri_template):
resource1 = IDResource()
client.app.add_route(uri_template, resource1)
result = client.simulate_get('/123')
assert (result.status_code == 404... |
def create_tree_structure(df, groups, cols, aggregations):
results = {}
for (_, row) in df.iterrows():
stack = []
result = results
for field in groups:
value = row[field]
stack.append((field, value))
if (field not in result):
result[fie... |
def register_webhooks(shopify_url: str, password: str) -> List[Webhook]:
new_webhooks = []
unregister_webhooks(shopify_url, password)
with Session.temp(shopify_url, API_VERSION, password):
for topic in WEBHOOK_EVENTS:
webhook = Webhook.create({'topic': topic, 'address': get_callback_url(... |
def get_registry_query_or_enum_key_extra_details(metadata, event, extra_detail_io, details_info):
event.category = 'Read'
key_information_class = RegistryKeyInformationClass(details_info['information_class'])
if (event.operation == RegistryOperation.RegEnumKey.name):
event.details['Index'] = details... |
def print_tree(node: LN, results: Capture=None, filename: Filename=None, indent: int=0, recurse: int=(- 1)):
filename = (filename or Filename(''))
tab = (INDENT_STR * indent)
if (filename and (indent == 0)):
click.secho(filename, fg='red', bold=True)
if isinstance(node, Leaf):
click.echo... |
class TestNeedlemanWunschDecoder(unittest.TestCase):
def setUp(self):
if torch.cuda.is_available():
cuda_device = torch.device('cuda')
torch.manual_seed(2)
(B, S, N, M) = (3, 3, 5, 5)
self.theta = torch.rand(B, N, M, requires_grad=True, dtype=torch.float32, de... |
def test_comp_interface():
string = write_rpc_request(1, 'initialize', {'rootPath': str(test_dir)})
file_path = ((test_dir / 'subdir') / 'test_generic.f90')
string += comp_request(file_path, 14, 10)
(errcode, results) = run_request(string, ['--use_signature_help'])
assert (errcode == 0)
exp_resu... |
def extractVrumjaCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [('supreme lord', 'supreme lord', 'translated'), ('PRC', 'PRC', 'translated'), ('Loiterous', 'Loiterous', 'oel... |
class MibScalarInstance(ManagedMibObject):
def __init__(self, typeName, instId, syntax):
ManagedMibObject.__init__(self, (typeName + instId), syntax)
self.typeName = typeName
self.instId = instId
def getValue(self, name, **context):
((debug.logger & debug.FLAG_INS) and debug.logg... |
class TaxCodeTests(unittest.TestCase):
def test_unicode(self):
tax = TaxRate()
tax.Name = 'test'
self.assertEqual(str(tax), 'test')
def test_valid_object_name(self):
obj = TaxRate()
client = QuickBooks()
result = client.isvalid_object_name(obj.qbo_object_name)
... |
def setup_logging():
global mod_logger
import logging
from logging.config import dictConfig
from logging.handlers import RotatingFileHandler
dictConfig({'version': 1, 'formatters': {'default': {'format': '[%(asctime)s] %(levelname)s in %(module)s: %(message)s'}}, 'handlers': {'wsgi': {'class': 'logg... |
def filter_log_memory_filter_data(json):
option_list = ['admin', 'anomaly', 'auth', 'cpu_memory_usage', 'dhcp', 'dns', 'event', 'filter', 'filter_type', 'forward_traffic', 'free_style', 'gtp', 'ha', 'ipsec', 'ldb_monitor', 'local_traffic', 'multicast_traffic', 'netscan_discovery', 'netscan_vulnerability', 'notifica... |
class CallableImpl():
def __init__(self):
self.setup_called = False
self.flattened_expression_values = []
self.cfg = CfgSimple.empty()
def setup(self, call_info: FunctionCallInfo):
if self.setup_called:
return
self.setup_called = True
self.setup_impl(c... |
class OptionSeriesAreasplinerangeSonificationContexttracksMappingTremolo(Options):
def depth(self) -> 'OptionSeriesAreasplinerangeSonificationContexttracksMappingTremoloDepth':
return self._config_sub_data('depth', OptionSeriesAreasplinerangeSonificationContexttracksMappingTremoloDepth)
def speed(self) ... |
class XarTestCase(unittest.TestCase):
def _unxar(self, xarfile, outdir):
with open(xarfile, 'rb') as fh:
first_line = fh.readline()
shebang = first_line.decode('utf-8').strip()
self.assertEqual(shebang, xar_builder.BORING_SHEBANG)
saw_stop = False
... |
def deepMerge(tgt, src):
if isinstance(src, list):
tgt.extend(src)
elif isinstance(src, dict):
for name in src:
m = src[name]
if (name not in tgt):
tgt[name] = copy.deepcopy(m)
else:
deepMerge(tgt[name], m)
else:
ret... |
class GaussianMixtureModel(object):
def __init__(self, k):
self.K = k
_variable
def alpha(self, k):
return dist.Dirichlet((5 * torch.ones(k)))
_variable
def mu(self, c):
return dist.Normal(0, 10)
_variable
def sigma(self, c):
return dist.Gamma(1, 10)
_vari... |
def phylogeny(node):
leaf_color = '#000000'
node.img_style['shape'] = 'square'
node.img_style['size'] = 2
if hasattr(node, 'evoltype'):
if (node.evoltype == 'D'):
node.img_style['fgcolor'] = '#FF0000'
node.img_style['hz_line_color'] = '#FF0000'
node.img_style[... |
class OptionsPanelPoints(Options):
def background_color(self):
return self.get(self.page.theme.success[1])
_color.setter
def background_color(self, val):
self.set(val)
def div_css(self):
return self.get({})
_css.setter
def div_css(self, css):
self.set(css)
def... |
class View(ViewElement):
id = AnId
content = Content
menubar = Any
toolbar = Any
action_manager_builder = Any
statusbar = ViewStatus
buttons = Buttons
default_button = AButton
key_bindings = AKeyBindings
handler = AHandler
model_view = AModelView
title = ATitle
icon =... |
_op([GapCursorA, ConfigA, ConfigFieldA, NewExprA('gap_cursor')])
def write_config(proc, gap_cursor, config, field, rhs):
stmtc = gap_cursor.anchor()
before = (gap_cursor.type() == ic.GapType.Before)
stmt = stmtc._impl
(ir, fwd, cfg) = scheduling.DoConfigWrite(stmt, config, field, rhs, before=before)
... |
def annotate_hit_line(arguments):
(hit, annot, seed_ortholog_score, seed_ortholog_evalue, tax_scope_mode, tax_scope_ids, target_taxa, target_orthologs, excluded_taxa, go_evidence, go_excluded, data_dir, annotation, novel_fams_dict) = arguments
if (annotation is not None):
return ((hit, annotation), True... |
def test_data_integrity_test_different_missing_values_one_column() -> None:
test_dataset = pd.DataFrame({'feature1': ['n/a', 'b', 'a'], 'feature2': ['b', '', None]})
suite = TestSuite(tests=[TestColumnNumberOfDifferentMissingValues(column_name='feature1')])
suite.run(current_data=test_dataset, reference_dat... |
class IntMatcherTest(testslide.TestCase):
def testAnyInt(self):
self.assertEqual(testslide.matchers.AnyInt(), 666)
self.assertEqual(testslide.matchers.AnyInt(), 42)
self.assertNotEqual(testslide.matchers.AnyInt(), 'derp')
def test_NotThisInt(self):
self.assertEqual(testslide.matc... |
def fetch_rio_magnetic():
warnings.warn('The Rio magnetic anomaly dataset is deprecated and will be removed in Verde v2.0.0. Use a different dataset instead.', FutureWarning, stacklevel=2)
data_file = REGISTRY.fetch('rio-magnetic.csv.xz')
data = pd.read_csv(data_file, compression='xz')
return data |
def _render_symtable(data, *, depth='minimal'):
namewidth = 15
(table, top, root) = data
if (not depth):
depth = 'minimal'
if (depth == 'full'):
table = _build_symtable_snapshot(root)
elif (depth == 'top'):
table = _build_symtable_snapshot(top)
elif (depth == 'minimal'):
... |
.parametrize('ops', ALL_OPS)
def test_alloc(ops):
float_methods = (ops.alloc1f, ops.alloc2f, ops.alloc3f, ops.alloc4f)
for (i, method) in enumerate(float_methods):
shape = ((1,) * (i + 1))
arr = method(*shape)
assert (arr.dtype == numpy.float32)
assert (arr.ndim == len(shape))
... |
class ObserverExpression():
__slots__ = ()
def __or__(self, expression):
return ParallelObserverExpression(self, expression)
def then(self, expression):
return SeriesObserverExpression(self, expression)
def match(self, filter, notify=True):
return self.then(match(filter=filter, n... |
class IgdbInfo(Base):
__tablename__ = 'igdb_info'
id: Mapped[int] = mapped_column(primary_key=True)
game: Mapped[(Game | None)] = relationship('Game', back_populates='igdb_info', default=None)
url: Mapped[(str | None)] = mapped_column(default=None)
name: Mapped[(str | None)] = mapped_column(default=... |
class _SortEntry():
_type_none = 0
_type_bool_false = 1
_type_bool_true = 2
_type_numeric = 3
_type_string = 4
_type_object = 5
def __init__(self, key, value, order_by):
self._key = key
self._value = value
if (order_by in ('$key', '$priority')):
self._inde... |
class BsOffCanvas(StructComponent):
css_classes = ['offcanvas']
_option_cls = OptBsWidget.OffCanvas
name = 'Bootstrap OffCanvas'
str_repr = '<div {attrs}>{content}</div>'
_js__builder__ = 'var carousel = new bootstrap.Offcanvas(htmlObj, options)'
def options(self) -> OptBsWidget.OffCanvas:
... |
def LoadFirmwareImage(chip, image_file):
def select_image_class(f, chip):
chip = re.sub('[-()]', '', chip.lower())
if (chip != 'esp8266'):
return {'esp32': ESP32FirmwareImage, 'esp32s2': ESP32S2FirmwareImage, 'esp32s3beta2': ESP32S3BETA2FirmwareImage, 'esp32s3': ESP32S3FirmwareImage, 'es... |
class CombatParticipant(Base):
__tablename__ = 'combat_participant'
combat_participant_id = Column(Integer, primary_key=True)
combat_id = Column(ForeignKey(Combat.combat_id), index=True)
war_participant_id = Column(ForeignKey(WarParticipant.warparticipant_id), index=True)
is_attacker = Column(Boolea... |
class CIDRRange():
def __init__(self, spec: str) -> None:
self.error: Optional[str] = None
self.address: Optional[str] = None
self.prefix_len: Optional[int] = None
prefix: Optional[str] = None
pfx_len: Optional[int] = None
addr: Optional[Union[(IPv4Address, IPv6Addres... |
def extractWebnoveltranslationWordpressCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [('BTSTTA', 'Bringing the Supermarket to the Apocalypse', 'translated')]
for (tagnam... |
def readtext(path):
if isinstance(path, pathlib.Path):
with path.open() as f:
return f.read()
if isinstance(path, str):
with open(path) as f:
return f.read()
if isinstance(path, io.TextIOBase):
return path.read()
raise TypeError('readtext requires a path-l... |
def _build(tmpdir, ext):
from distutils.core import Distribution
import distutils.errors
dist = Distribution({'ext_modules': [ext]})
dist.parse_config_files()
options = dist.get_option_dict('build_ext')
options['force'] = ('ffiplatform', True)
options['build_lib'] = ('ffiplatform', tmpdir)
... |
def get_stage_flow(game_type: PrivateComputationGameType, pcs_feature_enums: Set[PCSFeature], stage_flow_cls: Optional[Type[PrivateComputationBaseStageFlow]]=None) -> Type[PrivateComputationBaseStageFlow]:
selected_stage_flow_cls = unwrap_or_default(optional=stage_flow_cls, default=(PrivateComputationPCF2StageFlow ... |
class Ui_InfoDialog(object):
def setupUi(self, InfoDialog):
InfoDialog.setObjectName('InfoDialog')
InfoDialog.resize(640, 480)
InfoDialog.setWindowTitle('Dialog')
self.gridLayout = QtWidgets.QGridLayout(InfoDialog)
self.gridLayout.setObjectName('gridLayout')
self.colo... |
def main():
args = parse_args()
if args.update:
update()
if ((os.name != 'nt') and (sys.platform != 'darwin')):
if args.install:
systemd_service.install()
if args.uninstall:
systemd_service.uninstall()
if args.enable:
systemd_service.enable... |
def test_decimal_precision_is_a_positive_int():
'
schema = {'type': 'record', 'name': 'test_scale_is_an_int', 'fields': [{'name': 'field', 'type': {'logicalType': 'decimal', 'precision': (- 5), 'scale': 2, 'type': 'bytes'}}]}
with pytest.raises(SchemaParseException, match='decimal precision must be a positi... |
def test_intrinsics():
string = write_rpc_request(1, 'initialize', {'rootPath': str((test_dir / 'signature'))})
file_path = ((test_dir / 'signature') / 'nested_sigs.f90')
string += sigh_request(file_path, 8, 77)
(errcode, results) = run_request(string, ['--hover_signature', '--use_signature_help', '-n',... |
def _mark_storage_warm(computation: ComputationAPI, slot: int) -> bool:
storage_address = computation.msg.storage_address
if computation.state.is_storage_warm(storage_address, slot):
return False
else:
computation.state.mark_storage_warm(storage_address, slot)
return True |
('/view', methods=['GET'])
def view():
req_url = request.args.get('url')
if (not req_url):
return render_template('error.html', title='Viewer', message='Error! No page specified!')
version = request.args.get('version')
if version:
return render_template('error.html', title='Error', messa... |
_json
class Collation(Element):
children: List[Element] = field(default_factory=list)
def __hash__(self):
return hash(f'{self.id}-{self.code}')
def __eq__(self, other):
return ((self.__class__ == other.__class__) and (self.id == other.id) and (self.code == other.code) and (self.description =... |
def getsize(object: Any) -> Tuple[(int, int)]:
if isinstance(object, BLACKLIST):
raise TypeError(('getsize() does not take argument of type: ' + str(type(object))))
seen_ids = set()
size_in_byte = 0
objects = [object]
while objects:
need_referents = []
for obj in objects:
... |
.usefixtures('use_tmpdir')
def test_that_magic_strings_get_substituted_in_workflow():
script_file_contents = dedent('\n SCRIPT script.py\n ARGLIST <A>\n ARG_TYPE 0 INT\n ')
workflow_file_contents = dedent('\n script <ZERO>\n ')
script_file_path = os.path.join(os.get... |
class ProcessDetailsDialog(QtWidgets.QDialog, uic.loadUiType(DIALOG_UI_PATH)[0]):
LOG_TAG = '[ProcessDetails]: '
_notification_callback = QtCore.pyqtSignal(ui_pb2.NotificationReply)
TAB_STATUS = 0
TAB_DESCRIPTORS = 1
TAB_IOSTATS = 2
TAB_MAPS = 3
TAB_STACK = 4
TAB_ENVS = 5
TABS = {TAB... |
([Output('oura-activity-content-kpi-trend', 'children'), Output('oura-activity-content-kpi-trend', 'style'), Output('current-activity-content-trend', 'children')], [Input('goal-progress-button', 'n_clicks'), Input('total-burn-button', 'n_clicks'), Input('walking-equivalency-button', 'n_clicks')], [State('current-activi... |
def extractTeaserboynovelWordpressCom(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_... |
_os(*metadata.platforms)
def main(args=None):
slow_commands = ['gpresult.exe /z', 'systeminfo.exe']
commands = ['ipconfig /all', 'net localgroup administrators', 'net user', 'net user administrator', 'net user /domaintasklist', 'net view', 'net view /domain', ('net view \\\\%s' % common.get_ip()), 'netstat -nao... |
class InlineModelFormField(FormField):
widget = InlineFormWidget()
def __init__(self, form_class, pk, form_opts=None, **kwargs):
super(InlineModelFormField, self).__init__(form_class, **kwargs)
self._pk = pk
self.form_opts = form_opts
def get_pk(self):
if isinstance(self._pk,... |
class AdCreativeObjectStorySpec(AbstractObject):
def __init__(self, api=None):
super(AdCreativeObjectStorySpec, self).__init__()
self._isAdCreativeObjectStorySpec = True
self._api = api
class Field(AbstractObject.Field):
instagram_actor_id = 'instagram_actor_id'
link_data... |
class Batch(WebContainer):
simulations: Dict[(TaskName, SimulationType)] = pd.Field(..., title='Simulations', description='Mapping of task names to Simulations to run as a batch.')
folder_name: str = pd.Field('default', title='Folder Name', description='Name of folder to store member of each batch on web UI.')
... |
def storage(request):
if ((not request) or (not hasattr(request, 'param'))):
file_does_not_exist = False
else:
file_does_not_exist = request.param.get('file_does_not_exist', False)
if file_does_not_exist:
with tempfile.TemporaryDirectory() as tmp_dir:
filename = os.path.j... |
def test_fname():
assert (fname('data', 'json') == 'data.json')
assert (fname('data.json', 'json') == 'data.json')
assert (fname('pic', 'png') == 'pic.png')
assert (fname('pic.png', 'png') == 'pic.png')
assert (fname('report.pdf', 'pdf') == 'report.pdf')
assert (fname('report.png', 'pdf') == 're... |
def draw(input_file_name: Path, output_file_name: Path, boundary_box: BoundaryBox, configuration: Optional[MapConfiguration]=None) -> None:
if (configuration is None):
configuration = MapConfiguration(SCHEME)
osm_data: OSMData = OSMData()
osm_data.parse_osm_file(input_file_name)
flinger: Mercato... |
class Solution():
def accountsMerge(self, accounts: List[List[str]]) -> List[List[str]]:
def get_connections(accounts):
track = {}
emails = {}
for (i, acc) in enumerate(accounts):
if (i not in track):
track[i] = []
for (... |
def _get_session(path: Path) -> BaseSession:
is_memory = (path.name == ':memory:')
if is_memory:
database_uri = 'sqlite:///:memory:'
else:
database_uri = f'sqlite:///{path.resolve()}'
engine = create_engine(database_uri)
Session = sessionmaker(bind=engine)
session = Session()
... |
def get_record_csv(storage, ensemble_id1, keyword, poly_ran):
csv = run_in_loop(records.get_ensemble_record(db=storage, name=keyword, ensemble_id=ensemble_id1)).body
record_df1 = pd.read_csv(io.BytesIO(csv), index_col=0, float_precision='round_trip')
assert (len(record_df1.columns) == poly_ran['gen_data_ent... |
def set_cli_author(click_context: click.Context) -> None:
config = get_or_create_cli_config()
cli_author = config.get(AUTHOR_KEY, None)
if (cli_author is None):
raise click.ClickException('The AEA configurations are not initialized. Use `aea init` before continuing.')
click_context.obj.set_confi... |
.integration_test
.parametrize('config_str, expected, extra_files, expectation', [('GEN_KW KW_NAME template.txt kw.txt prior.txt\nRANDOM_SEED 1234', 'MY_KEYWORD -0.881423', [], does_not_raise()), ('GEN_KW KW_NAME template.txt kw.txt prior.txt INIT_FILES:custom_param%d', 'MY_KEYWORD 1.31', [('custom_param0', 'MY_KEYWORD... |
(('cfg', 'expected'), [param({'_target_': 'tests.instantiate.ArgsClass', 'child': {'_target_': 'tests.instantiate.ArgsClass'}}, ArgsClass(child=ArgsClass()), id='config:no_params'), param({'_target_': 'tests.instantiate.ArgsClass', '_args_': [1], 'child': {'_target_': 'tests.instantiate.ArgsClass', '_args_': [2]}}, Arg... |
def build_resnet_backbone(depth, activation):
norm = 'BN'
activation = activation
num_groups = 1
stride_in_1x1 = False
num_groups = 1
width_per_group = 64
bottleneck_channels = (num_groups * width_per_group)
in_channels = 64
out_channels = 256
stem = BasicStem(in_channels=3, out_... |
class Axis(BasicObject):
attributes = {'AXIS-ID': utils.scalar, 'COORDINATES': utils.vector, 'SPACING': utils.scalar}
def __init__(self, attic, lf):
super().__init__(attic, lf=lf)
def axis_id(self):
return self['AXIS-ID']
def coordinates(self):
return self['COORDINATES']
def ... |
class DiscarderHandler(THBEventHandler):
interested = ['action_after', 'action_shootdown']
def handle(self, evt_type, act):
if ((evt_type == 'action_shootdown') and isinstance(act, ActionStageLaunchCard)):
src = act.source
if (not src.has_skill(Discarder)):
return... |
class EnvoyEventProcessor(AbstractGamestateDataProcessor):
ID = 'envoy_events'
DEPENDENCIES = [CountryProcessor.ID, LeaderProcessor.ID]
def extract_data_from_gamestate(self, dependencies):
countries_dict = dependencies[CountryProcessor.ID]
leaders = dependencies[LeaderProcessor.ID]
f... |
def load_hydra_config(config_module: str, config_name: str, hydra_overrides: Dict[(str, str)]) -> DictConfig:
with initialize_config_module(config_module=config_module):
cfg = compose(config_name=config_name, overrides=[((key + '=') + str(val)) for (key, val) in hydra_overrides.items()])
return cfg |
def remove_duplicate_sg(security_groups):
for (each_sg, duplicate_sg_name) in SECURITYGROUP_REPLACEMENTS.items():
if ((each_sg in security_groups) and (duplicate_sg_name in security_groups)):
LOG.info('Duplicate SG found. Removing %s in favor of %s.', duplicate_sg_name, each_sg)
secu... |
class UpdateNoIdMixin(object):
qbo_object_name = ''
qbo_json_object_name = ''
def save(self, qb=None, request_id=None):
if (not qb):
qb = QuickBooks()
json_data = qb.update_object(self.qbo_object_name, self.to_json(), request_id=request_id)
obj = type(self).from_json(json... |
def _call(func_name: str, ret_val: List[Expression]=None, operands: List[Expression]=None) -> Assignment:
if (not ret_val):
ret_val = list()
if (not operands):
operands = list()
return Assignment(ListOperation(ret_val), Call(ImportedFunctionSymbol(func_name, 66), operands)) |
def lazy_import():
from fastly.model.domain_inspector_entry import DomainInspectorEntry
from fastly.model.historical_domains import HistoricalDomains
from fastly.model.historical_domains_meta import HistoricalDomainsMeta
from fastly.model.historical_domains_response_all_of import HistoricalDomainsRespon... |
_server.peripheral_model
class EthernetModel(object):
frame_queues = defaultdict(deque)
calc_crc = True
rx_frame_isr = None
rx_isr_enabled = False
frame_times = defaultdict(deque)
def enable_rx_isr(cls, interface_id):
cls.rx_isr_enabled = True
if (cls.frame_queues[interface_id] a... |
class OptionSeriesColumnDataDragdropDraghandle(Options):
def className(self):
return self._config_get('highcharts-drag-handle')
def className(self, text: str):
self._config(text, js_type=False)
def color(self):
return self._config_get('#fff')
def color(self, text: str):
s... |
class OptionSeriesBulletSonificationContexttracksMappingLowpass(Options):
def frequency(self) -> 'OptionSeriesBulletSonificationContexttracksMappingLowpassFrequency':
return self._config_sub_data('frequency', OptionSeriesBulletSonificationContexttracksMappingLowpassFrequency)
def resonance(self) -> 'Opt... |
def map_ec2route_to_route(route: Dict[(str, Any)]) -> Route:
destination_cidr = route['DestinationCidrBlock']
route_target_type = RouteTargetType.OTHER
route_target_id = ''
if ('VpcPeeringConnectionId' in route):
route_target_type = RouteTargetType.VPC_PEERING
route_target_id = route['Vp... |
class SurfaceAberrationAtDistance(OpticalElement):
def __init__(self, surface_aberration, distance):
self.fresnel = FresnelPropagator(surface_aberration.input_grid, distance)
self.surface_aberration = surface_aberration
def forward(self, wavefront):
wf = self.fresnel.forward(wavefront)
... |
_invites_misc_routes.route('/speaker-invites/<int:speaker_invite_id>/reject-invite')
_required
def reject_invite(speaker_invite_id):
try:
speaker_invite = SpeakerInvite.query.filter_by(id=speaker_invite_id).one()
except NoResultFound:
raise NotFoundError({'source': ''}, 'Speaker Invite Not Found... |
class OptionPlotoptionsBellcurvePointEvents(Options):
def click(self):
return self._config_get(None)
def click(self, value: Any):
self._config(value, js_type=False)
def drag(self):
return self._config_get(None)
def drag(self, value: Any):
self._config(value, js_type=False... |
def is_dbt_package_up_to_date() -> bool:
installed_version = _get_installed_dbt_package_version()
if (installed_version is None):
return False
required_version = _get_required_dbt_package_version()
if (not required_version):
return True
return (installed_version == required_version) |
class ChatMessage(ft.Row):
def __init__(self, message: Message):
super().__init__()
self.vertical_alignment = 'start'
self.controls = [ft.CircleAvatar(content=ft.Text(self.get_initials(message.user_name)), color=ft.colors.WHITE, bgcolor=self.get_avatar_color(message.user_name)), ft.Column([f... |
def test_variable_COLR_without_VarIndexMap():
font1 = TTFont()
font1.setGlyphOrder(['.notdef', 'A'])
font1['COLR'] = buildCOLR({'A': (ot.PaintFormat.PaintSolid, 0, 1.0)})
font2 = deepcopy(font1)
font2['COLR'].table.BaseGlyphList.BaseGlyphPaintRecord[0].Paint.Alpha = 0.0
master_fonts = [font1, fo... |
class FilterInterface(object):
def __init__(self):
self.is_valid = False
self._re_do_not_sync = EMPTY_PATTERN
self._re_do_not_sync_from_list = EMPTY_PATTERN
self._re_hide_nodes = EMPTY_PATTERN
self._re_hide_topics = EMPTY_PATTERN
self._re_hide_services = EMPTY_PATTERN... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.