code stringlengths 101 5.91M |
|---|
def test_regulartype_numpytype():
t = RegularType(NumpyType('int32'), 5)
assert (str(ak.types.from_datashape(str(t), highlevel=False)) == str(t)) |
(eq=False)
class Thread(RefObj):
lib_list: Table = dc.field(repr=False, hash=None, compare=False)
name: str
processType: str
processStartupTime: float
registerTime: float
isMainThread: bool
processName: str
pid: int
tid: int
markers: Table = dc.field(default_factory=Table)
samples: Table = dc.field(default_factory=Table)
stackTable: Table = dc.field(default_factory=Table)
frameTable: Table = dc.field(default_factory=Table)
funcTable: Table = dc.field(default_factory=Table)
resourceTable: Table = dc.field(default_factory=Table)
nativeSymbols: Table = dc.field(default_factory=Table)
stringArray: Table = dc.field(default_factory=Table)
pausedRanges: list = dc.field(default_factory=list)
processShutdownTime: float = None
unregisterTime: float = None
def __post_init__(self):
self.markers.type = Marker
self.stringArray.type = str
def add_resource(self, *args, **kargs):
func = Resource(self.stringArray, self.lib_list, *args, **kargs)
self.resourceTable.get_id(func)
return func
def add_function(self, *args, **kargs):
func = Function(self.stringArray, self.resourceTable, *args, **kargs)
self.funcTable.get_id(func)
return func
def add_symbol(self, *args, **kargs):
symbol = nativeSymbol(self.stringArray, self.lib_list, *args, **kargs)
self.nativeSymbols.get_id(symbol)
return symbol
def add_frame(self, *args, **kargs):
frame = Frame(self.stringArray, self.funcTable, self.nativeSymbols, *args, **kargs)
self.frameTable.get_id(frame)
return frame
def add_stack(self, *args, **kargs):
stack = Stack(self.frameTable, self.stackTable, *args, **kargs)
self.stackTable.get_id(stack)
return stack
def add_sample(self, *args, **kargs):
sample = Sample(self.stackTable, *args, **kargs)
self.samples.get_id(sample)
return sample
def add_marker(self, *args, **kargs):
marker = Marker(self.stringArray, *args, **kargs)
self.markers.get_id(marker)
return marker |
def premul_lstm_cell_no_bias(igates, hidden, w_hh, b_hh):
(hx, cx) = hidden
gates = ((igates + torch.mm(hx, w_hh.t())) + b_hh)
(ingate, forgetgate, cellgate, outgate) = gates.chunk(4, 1)
ingate = torch.sigmoid(ingate)
forgetgate = torch.sigmoid(forgetgate)
cellgate = torch.tanh(cellgate)
outgate = torch.sigmoid(outgate)
cy = ((forgetgate * cx) + (ingate * cellgate))
hy = (outgate * torch.tanh(cy))
return (hy, cy) |
def plot(dfs, anomalies=[]):
if isinstance(dfs, pd.DataFrame):
dfs = [dfs]
if (not isinstance(anomalies, list)):
anomalies = [anomalies]
df = dfs[0]
time = convert_date(df['timestamp'])
months = mdates.MonthLocator()
days = mdates.DayLocator()
month_fmt = mdates.DateFormatter('%b')
fig = plt.figure(figsize=(30, 6))
ax = fig.add_subplot(111)
for df in dfs:
plt.plot(time, df['value'])
colors = (['red'] + (['green'] * (len(anomalies) - 1)))
for (i, anomaly) in enumerate(anomalies):
if (not isinstance(anomaly, list)):
anomaly = list(anomaly[['start', 'end']].itertuples(index=False))
for (_, anom) in enumerate(anomaly):
t1 = convert_date_single(anom[0])
t2 = convert_date_single(anom[1])
plt.axvspan(t1, t2, color=colors[i], alpha=0.2)
plt.title('NYC Taxi Demand', size=34)
plt.ylabel('# passengers', size=30)
plt.xlabel('Time', size=30)
plt.xticks(size=26)
plt.yticks(size=26)
plt.xlim([time[0], time[(- 1)]])
ax.xaxis.set_major_locator(months)
ax.xaxis.set_major_formatter(month_fmt)
ax.xaxis.set_minor_locator(days)
ylabels = [('{:,.0f}'.format(x) + 'K') for x in (ax.get_yticks() / 1000)]
ax.set_yticklabels(ylabels)
plt.show() |
def _rebuild_tensor(storage, storage_offset, size, stride):
class_name = storage.__class__.__name__.replace('Storage', 'Tensor')
module = importlib.import_module(storage.__module__)
tensor_class = getattr(module, class_name)
return tensor_class().set_(storage, storage_offset, size, stride) |
class MLP(nn.Module):
def __init__(self, feat_len, num_class, hidden=[64, 32], dropout=[0]):
super().__init__()
(self.feat_len, self.hidden) = (feat_len, num_class)
self.tran1 = nn.Linear(feat_len, hidden[0], bias=False)
self.tran2 = nn.Linear(hidden[0], hidden[1], bias=False)
self.acvt = nn.Sequential(nn.ReLU(), nn.Dropout(dropout[0]))
self.classifier = nn.Linear(hidden[1], num_class, bias=False)
def forward(self, x, neighbor):
x = nf.normalize(x)
x = self.tran1(x)
x = self.acvt(x)
x = self.tran2(x)
x = self.acvt(x)
return self.classifier(x).squeeze(1) |
def test_record_array_with_object_field():
y = ma.masked_array([(1, '2'), (3, '4')], mask=[(0, 0), (0, 1)], dtype=[('a', int), ('b', object)])
y[1] |
class MultiscaleDiscrSingleInput(SingleToMultiScaleInputMixin, DiscriminatorMultiToSingleOutputStackedMixin, MultiscaleDiscriminatorSimple):
pass |
def remove_if_exists(path: Path) -> None:
if (not path.exists()):
logger.debug(f"Doesn't exist: {path}")
return
elif path.is_dir():
logger.debug(f'Removing directory: {path}')
shutil.rmtree(path)
else:
logger.debug(f'Removing file: {path}')
path.unlink() |
def register_types(module):
root_module = module.get_root()
module.add_enum('PbbAddressLength', ['IPV4', 'IPV6'], import_from_module='ns.network')
module.add_enum('ethernet_header_t', ['LENGTH', 'VLAN', 'QINQ'], import_from_module='ns.network')
module.add_enum('LogLevel', ['LOG_NONE', 'LOG_ERROR', 'LOG_LEVEL_ERROR', 'LOG_WARN', 'LOG_LEVEL_WARN', 'LOG_DEBUG', 'LOG_LEVEL_DEBUG', 'LOG_INFO', 'LOG_LEVEL_INFO', 'LOG_FUNCTION', 'LOG_LEVEL_FUNCTION', 'LOG_LOGIC', 'LOG_LEVEL_LOGIC', 'LOG_ALL', 'LOG_LEVEL_ALL', 'LOG_PREFIX_FUNC', 'LOG_PREFIX_TIME', 'LOG_PREFIX_NODE', 'LOG_PREFIX_LEVEL', 'LOG_PREFIX_ALL'], import_from_module='ns.core')
module.add_class('Address', import_from_module='ns.network')
module.add_enum('MaxSize_e', ['MAX_SIZE'], outer_class=root_module['ns3::Address'], import_from_module='ns.network')
module.add_class('ApplicationContainer', import_from_module='ns.network')
module.add_class('AsciiFile', import_from_module='ns.network')
module.add_class('AsciiTraceHelper', import_from_module='ns.network')
module.add_class('AsciiTraceHelperForDevice', allow_subclassing=True, import_from_module='ns.network')
module.add_class('AttributeConstructionList', import_from_module='ns.core')
module.add_class('Item', import_from_module='ns.core', outer_class=root_module['ns3::AttributeConstructionList'])
module.add_class('Buffer', import_from_module='ns.network')
module.add_class('Iterator', import_from_module='ns.network', outer_class=root_module['ns3::Buffer'])
module.add_class('BulkSendHelper')
module.add_class('ByteTagIterator', import_from_module='ns.network')
module.add_class('Item', import_from_module='ns.network', outer_class=root_module['ns3::ByteTagIterator'])
module.add_class('ByteTagList', import_from_module='ns.network')
module.add_class('Iterator', import_from_module='ns.network', outer_class=root_module['ns3::ByteTagList'])
module.add_class('Item', import_from_module='ns.network', outer_class=root_module['ns3::ByteTagList::Iterator'])
module.add_class('CallbackBase', import_from_module='ns.core')
module.add_class('ChannelList', import_from_module='ns.network')
module.add_class('DataOutputCallback', allow_subclassing=True, import_from_module='ns.stats')
module.add_class('DataRate', import_from_module='ns.network')
module.add_class('DefaultDeleter', import_from_module='ns.core', template_parameters=['ns3::AttributeAccessor'])
module.add_class('DefaultDeleter', import_from_module='ns.core', template_parameters=['ns3::AttributeChecker'])
module.add_class('DefaultDeleter', import_from_module='ns.core', template_parameters=['ns3::AttributeValue'])
module.add_class('DefaultDeleter', import_from_module='ns.core', template_parameters=['ns3::CallbackImplBase'])
module.add_class('DefaultDeleter', import_from_module='ns.core', template_parameters=['ns3::EventImpl'])
module.add_class('DefaultDeleter', import_from_module='ns.core', template_parameters=['ns3::Hash::Implementation'])
module.add_class('DefaultDeleter', import_from_module='ns.core', template_parameters=['ns3::NetDeviceQueue'])
module.add_class('DefaultDeleter', import_from_module='ns.core', template_parameters=['ns3::NixVector'])
module.add_class('DefaultDeleter', import_from_module='ns.core', template_parameters=['ns3::OutputStreamWrapper'])
module.add_class('DefaultDeleter', import_from_module='ns.core', template_parameters=['ns3::Packet'])
module.add_class('DefaultDeleter', import_from_module='ns.core', template_parameters=['ns3::PbbAddressBlock'])
module.add_class('DefaultDeleter', import_from_module='ns.core', template_parameters=['ns3::PbbMessage'])
module.add_class('DefaultDeleter', import_from_module='ns.core', template_parameters=['ns3::PbbTlv'])
module.add_class('DefaultDeleter', import_from_module='ns.core', template_parameters=['ns3::QueueItem'])
module.add_class('DefaultDeleter', import_from_module='ns.core', template_parameters=['ns3::TraceSourceAccessor'])
module.add_class('DelayJitterEstimation', import_from_module='ns.network')
module.add_class('EventId', import_from_module='ns.core')
module.add_class('Hasher', import_from_module='ns.core')
module.add_class('Inet6SocketAddress', import_from_module='ns.network')
root_module['ns3::Inet6SocketAddress'].implicitly_converts_to(root_module['ns3::Address'])
module.add_class('InetSocketAddress', import_from_module='ns.network')
root_module['ns3::InetSocketAddress'].implicitly_converts_to(root_module['ns3::Address'])
module.add_class('Ipv4Address', import_from_module='ns.network')
root_module['ns3::Ipv4Address'].implicitly_converts_to(root_module['ns3::Address'])
module.add_class('Ipv4Mask', import_from_module='ns.network')
module.add_class('Ipv6Address', import_from_module='ns.network')
root_module['ns3::Ipv6Address'].implicitly_converts_to(root_module['ns3::Address'])
module.add_class('Ipv6Prefix', import_from_module='ns.network')
module.add_class('LogComponent', import_from_module='ns.core')
module.add_class('Mac16Address', import_from_module='ns.network')
root_module['ns3::Mac16Address'].implicitly_converts_to(root_module['ns3::Address'])
module.add_class('Mac48Address', import_from_module='ns.network')
root_module['ns3::Mac48Address'].implicitly_converts_to(root_module['ns3::Address'])
module.add_class('Mac64Address', import_from_module='ns.network')
root_module['ns3::Mac64Address'].implicitly_converts_to(root_module['ns3::Address'])
module.add_class('NetDeviceContainer', import_from_module='ns.network')
module.add_class('NodeContainer', import_from_module='ns.network')
module.add_class('NodeList', import_from_module='ns.network')
module.add_class('NonCopyable', destructor_visibility='protected', import_from_module='ns.core')
module.add_class('ObjectBase', allow_subclassing=True, import_from_module='ns.core')
module.add_class('ObjectDeleter', import_from_module='ns.core')
module.add_class('ObjectFactory', import_from_module='ns.core')
module.add_class('OnOffHelper')
module.add_class('PacketLossCounter')
module.add_class('PacketMetadata', import_from_module='ns.network')
module.add_class('Item', import_from_module='ns.network', outer_class=root_module['ns3::PacketMetadata'])
module.add_enum('ItemType', ['PAYLOAD', 'HEADER', 'TRAILER'], outer_class=root_module['ns3::PacketMetadata::Item'], import_from_module='ns.network')
module.add_class('ItemIterator', import_from_module='ns.network', outer_class=root_module['ns3::PacketMetadata'])
module.add_class('PacketSinkHelper')
module.add_class('PacketSocketAddress', import_from_module='ns.network')
root_module['ns3::PacketSocketAddress'].implicitly_converts_to(root_module['ns3::Address'])
module.add_class('PacketSocketHelper', import_from_module='ns.network')
module.add_class('PacketTagIterator', import_from_module='ns.network')
module.add_class('Item', import_from_module='ns.network', outer_class=root_module['ns3::PacketTagIterator'])
module.add_class('PacketTagList', import_from_module='ns.network')
module.add_class('TagData', import_from_module='ns.network', outer_class=root_module['ns3::PacketTagList'])
module.add_class('ParameterLogger', import_from_module='ns.core')
module.add_class('PbbAddressTlvBlock', import_from_module='ns.network')
module.add_class('PbbTlvBlock', import_from_module='ns.network')
module.add_class('PcapFile', import_from_module='ns.network')
module.add_class('PcapHelper', import_from_module='ns.network')
module.add_enum('DataLinkType', ['DLT_NULL', 'DLT_EN10MB', 'DLT_PPP', 'DLT_RAW', 'DLT_IEEE802_11', 'DLT_LINUX_SLL', 'DLT_PRISM_HEADER', 'DLT_IEEE802_11_RADIO', 'DLT_IEEE802_15_4', 'DLT_NETLINK'], outer_class=root_module['ns3::PcapHelper'], import_from_module='ns.network')
module.add_class('PcapHelperForDevice', allow_subclassing=True, import_from_module='ns.network')
module.add_class('SimpleNetDeviceHelper', import_from_module='ns.network')
module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::Object', 'ns3::ObjectBase', 'ns3::ObjectDeleter'], parent=root_module['ns3::ObjectBase'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'))
module.add_class('Simulator', destructor_visibility='private', import_from_module='ns.core')
module.add_enum('', ['NO_CONTEXT'], outer_class=root_module['ns3::Simulator'], import_from_module='ns.core')
module.add_class('StatisticalSummary', allow_subclassing=True, import_from_module='ns.stats')
module.add_class('SystemWallClockMs', import_from_module='ns.core')
module.add_class('Tag', import_from_module='ns.network', parent=root_module['ns3::ObjectBase'])
module.add_class('TagBuffer', import_from_module='ns.network')
module.add_class('TimeWithUnit', import_from_module='ns.core')
module.add_class('TracedValue', import_from_module='ns.core', template_parameters=['unsigned int'])
module.add_class('TypeId', import_from_module='ns.core')
module.add_enum('AttributeFlag', ['ATTR_GET', 'ATTR_SET', 'ATTR_CONSTRUCT', 'ATTR_SGC'], outer_class=root_module['ns3::TypeId'], import_from_module='ns.core')
module.add_enum('SupportLevel', ['SUPPORTED', 'DEPRECATED', 'OBSOLETE'], outer_class=root_module['ns3::TypeId'], import_from_module='ns.core')
module.add_class('AttributeInformation', import_from_module='ns.core', outer_class=root_module['ns3::TypeId'])
module.add_class('TraceSourceInformation', import_from_module='ns.core', outer_class=root_module['ns3::TypeId'])
module.add_class('UdpClientHelper')
module.add_class('UdpEchoClientHelper')
module.add_class('UdpEchoServerHelper')
module.add_class('UdpServerHelper')
module.add_class('UdpTraceClientHelper')
module.add_class('empty', import_from_module='ns.core')
module.add_class('int64x64_t', import_from_module='ns.core')
module.add_enum('impl_type', ['int128_impl', 'cairo_impl', 'ld_impl'], outer_class=root_module['ns3::int64x64_t'], import_from_module='ns.core')
module.add_class('Chunk', import_from_module='ns.network', parent=root_module['ns3::ObjectBase'])
module.add_class('DeviceNameTag', import_from_module='ns.network', parent=root_module['ns3::Tag'])
module.add_class('FlowIdTag', import_from_module='ns.network', parent=root_module['ns3::Tag'])
module.add_class('Header', import_from_module='ns.network', parent=root_module['ns3::Chunk'])
module.add_class('LlcSnapHeader', import_from_module='ns.network', parent=root_module['ns3::Header'])
module.add_class('Object', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter >'])
module.add_class('AggregateIterator', import_from_module='ns.core', outer_class=root_module['ns3::Object'])
module.add_class('PacketBurst', import_from_module='ns.network', parent=root_module['ns3::Object'])
module.add_class('PacketSocketTag', import_from_module='ns.network', parent=root_module['ns3::Tag'])
module.add_class('PcapFileWrapper', import_from_module='ns.network', parent=root_module['ns3::Object'])
module.add_class('QueueBase', import_from_module='ns.network', parent=root_module['ns3::Object'])
module.add_enum('QueueMode', ['QUEUE_MODE_PACKETS', 'QUEUE_MODE_BYTES'], outer_class=root_module['ns3::QueueBase'], import_from_module='ns.network')
module.add_class('QueueLimits', import_from_module='ns.network', parent=root_module['ns3::Object'])
module.add_class('RadiotapHeader', import_from_module='ns.network', parent=root_module['ns3::Header'])
module.add_enum('FrameFlag', ['FRAME_FLAG_NONE', 'FRAME_FLAG_CFP', 'FRAME_FLAG_SHORT_PREAMBLE', 'FRAME_FLAG_WEP', 'FRAME_FLAG_FRAGMENTED', 'FRAME_FLAG_FCS_INCLUDED', 'FRAME_FLAG_DATA_PADDING', 'FRAME_FLAG_BAD_FCS', 'FRAME_FLAG_SHORT_GUARD'], outer_class=root_module['ns3::RadiotapHeader'], import_from_module='ns.network')
module.add_enum('ChannelFlags', ['CHANNEL_FLAG_NONE', 'CHANNEL_FLAG_TURBO', 'CHANNEL_FLAG_CCK', 'CHANNEL_FLAG_OFDM', 'CHANNEL_FLAG_SPECTRUM_2GHZ', 'CHANNEL_FLAG_SPECTRUM_5GHZ', 'CHANNEL_FLAG_PASSIVE', 'CHANNEL_FLAG_DYNAMIC', 'CHANNEL_FLAG_GFSK'], outer_class=root_module['ns3::RadiotapHeader'], import_from_module='ns.network')
module.add_enum('McsKnown', ['MCS_KNOWN_NONE', 'MCS_KNOWN_BANDWIDTH', 'MCS_KNOWN_INDEX', 'MCS_KNOWN_GUARD_INTERVAL', 'MCS_KNOWN_HT_FORMAT', 'MCS_KNOWN_FEC_TYPE', 'MCS_KNOWN_STBC', 'MCS_KNOWN_NESS', 'MCS_KNOWN_NESS_BIT_1'], outer_class=root_module['ns3::RadiotapHeader'], import_from_module='ns.network')
module.add_enum('McsFlags', ['MCS_FLAGS_NONE', 'MCS_FLAGS_BANDWIDTH_40', 'MCS_FLAGS_BANDWIDTH_20L', 'MCS_FLAGS_BANDWIDTH_20U', 'MCS_FLAGS_GUARD_INTERVAL', 'MCS_FLAGS_HT_GREENFIELD', 'MCS_FLAGS_FEC_TYPE', 'MCS_FLAGS_STBC_STREAMS', 'MCS_FLAGS_NESS_BIT_0'], outer_class=root_module['ns3::RadiotapHeader'], import_from_module='ns.network')
module.add_enum('AmpduFlags', ['A_MPDU_STATUS_NONE', 'A_MPDU_STATUS_REPORT_ZERO_LENGTH', 'A_MPDU_STATUS_IS_ZERO_LENGTH', 'A_MPDU_STATUS_LAST_KNOWN', 'A_MPDU_STATUS_LAST', 'A_MPDU_STATUS_DELIMITER_CRC_ERROR', 'A_MPDU_STATUS_DELIMITER_CRC_KNOWN'], outer_class=root_module['ns3::RadiotapHeader'], import_from_module='ns.network')
module.add_enum('VhtKnown', ['VHT_KNOWN_NONE', 'VHT_KNOWN_STBC', 'VHT_KNOWN_TXOP_PS_NOT_ALLOWED', 'VHT_KNOWN_GUARD_INTERVAL', 'VHT_KNOWN_SHORT_GI_NSYM_DISAMBIGUATION', 'VHT_KNOWN_LDPC_EXTRA_OFDM_SYMBOL', 'VHT_KNOWN_BEAMFORMED', 'VHT_KNOWN_BANDWIDTH', 'VHT_KNOWN_GROUP_ID', 'VHT_KNOWN_PARTIAL_AID'], outer_class=root_module['ns3::RadiotapHeader'], import_from_module='ns.network')
module.add_enum('VhtFlags', ['VHT_FLAGS_NONE', 'VHT_FLAGS_STBC', 'VHT_FLAGS_TXOP_PS_NOT_ALLOWED', 'VHT_FLAGS_GUARD_INTERVAL', 'VHT_FLAGS_SHORT_GI_NSYM_DISAMBIGUATION', 'VHT_FLAGS_LDPC_EXTRA_OFDM_SYMBOL', 'VHT_FLAGS_BEAMFORMED'], outer_class=root_module['ns3::RadiotapHeader'], import_from_module='ns.network')
module.add_class('RandomVariableStream', import_from_module='ns.core', parent=root_module['ns3::Object'])
module.add_class('SeqTsHeader', parent=root_module['ns3::Header'])
module.add_class('SequentialRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream'])
module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::AttributeAccessor', 'ns3::empty', 'ns3::DefaultDeleter<ns3::AttributeAccessor>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'))
module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::AttributeChecker', 'ns3::empty', 'ns3::DefaultDeleter<ns3::AttributeChecker>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'))
module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::AttributeValue', 'ns3::empty', 'ns3::DefaultDeleter<ns3::AttributeValue>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'))
module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::CallbackImplBase', 'ns3::empty', 'ns3::DefaultDeleter<ns3::CallbackImplBase>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'))
module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::EventImpl', 'ns3::empty', 'ns3::DefaultDeleter<ns3::EventImpl>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'))
module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::Hash::Implementation', 'ns3::empty', 'ns3::DefaultDeleter<ns3::Hash::Implementation>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'))
module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::NetDeviceQueue', 'ns3::empty', 'ns3::DefaultDeleter<ns3::NetDeviceQueue>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'))
module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::NixVector', 'ns3::empty', 'ns3::DefaultDeleter<ns3::NixVector>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'))
module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::OutputStreamWrapper', 'ns3::empty', 'ns3::DefaultDeleter<ns3::OutputStreamWrapper>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'))
module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::Packet', 'ns3::empty', 'ns3::DefaultDeleter<ns3::Packet>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'))
module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::PbbAddressBlock', 'ns3::empty', 'ns3::DefaultDeleter<ns3::PbbAddressBlock>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'))
module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::PbbMessage', 'ns3::empty', 'ns3::DefaultDeleter<ns3::PbbMessage>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'))
module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::PbbPacket', 'ns3::Header', 'ns3::DefaultDeleter<ns3::PbbPacket>'], parent=root_module['ns3::Header'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'))
module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::PbbTlv', 'ns3::empty', 'ns3::DefaultDeleter<ns3::PbbTlv>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'))
module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::QueueItem', 'ns3::empty', 'ns3::DefaultDeleter<ns3::QueueItem>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'))
module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::TraceSourceAccessor', 'ns3::empty', 'ns3::DefaultDeleter<ns3::TraceSourceAccessor>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'))
module.add_class('SllHeader', import_from_module='ns.network', parent=root_module['ns3::Header'])
module.add_enum('PacketType', ['UNICAST_FROM_PEER_TO_ME', 'BROADCAST_BY_PEER', 'MULTICAST_BY_PEER', 'INTERCEPTED_PACKET', 'SENT_BY_US'], outer_class=root_module['ns3::SllHeader'], import_from_module='ns.network')
module.add_class('Socket', import_from_module='ns.network', parent=root_module['ns3::Object'])
module.add_enum('SocketErrno', ['ERROR_NOTERROR', 'ERROR_ISCONN', 'ERROR_NOTCONN', 'ERROR_MSGSIZE', 'ERROR_AGAIN', 'ERROR_SHUTDOWN', 'ERROR_OPNOTSUPP', 'ERROR_AFNOSUPPORT', 'ERROR_INVAL', 'ERROR_BADF', 'ERROR_NOROUTETOHOST', 'ERROR_NODEV', 'ERROR_ADDRNOTAVAIL', 'ERROR_ADDRINUSE', 'SOCKET_ERRNO_LAST'], outer_class=root_module['ns3::Socket'], import_from_module='ns.network')
module.add_enum('SocketType', ['NS3_SOCK_STREAM', 'NS3_SOCK_SEQPACKET', 'NS3_SOCK_DGRAM', 'NS3_SOCK_RAW'], outer_class=root_module['ns3::Socket'], import_from_module='ns.network')
module.add_enum('SocketPriority', ['NS3_PRIO_BESTEFFORT', 'NS3_PRIO_FILLER', 'NS3_PRIO_BULK', 'NS3_PRIO_INTERACTIVE_BULK', 'NS3_PRIO_INTERACTIVE', 'NS3_PRIO_CONTROL'], outer_class=root_module['ns3::Socket'], import_from_module='ns.network')
module.add_enum('Ipv6MulticastFilterMode', ['INCLUDE', 'EXCLUDE'], outer_class=root_module['ns3::Socket'], import_from_module='ns.network')
module.add_class('SocketFactory', import_from_module='ns.network', parent=root_module['ns3::Object'])
module.add_class('SocketIpTosTag', import_from_module='ns.network', parent=root_module['ns3::Tag'])
module.add_class('SocketIpTtlTag', import_from_module='ns.network', parent=root_module['ns3::Tag'])
module.add_class('SocketIpv6HopLimitTag', import_from_module='ns.network', parent=root_module['ns3::Tag'])
module.add_class('SocketIpv6TclassTag', import_from_module='ns.network', parent=root_module['ns3::Tag'])
module.add_class('SocketPriorityTag', import_from_module='ns.network', parent=root_module['ns3::Tag'])
module.add_class('SocketSetDontFragmentTag', import_from_module='ns.network', parent=root_module['ns3::Tag'])
module.add_class('Time', import_from_module='ns.core')
module.add_enum('Unit', ['Y', 'D', 'H', 'MIN', 'S', 'MS', 'US', 'NS', 'PS', 'FS', 'LAST'], outer_class=root_module['ns3::Time'], import_from_module='ns.core')
root_module['ns3::Time'].implicitly_converts_to(root_module['ns3::int64x64_t'])
module.add_class('TraceSourceAccessor', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >'])
module.add_class('Trailer', import_from_module='ns.network', parent=root_module['ns3::Chunk'])
module.add_class('TriangularRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream'])
module.add_class('UniformRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream'])
module.add_class('WeibullRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream'])
module.add_class('ZetaRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream'])
module.add_class('ZipfRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream'])
module.add_class('Application', import_from_module='ns.network', parent=root_module['ns3::Object'])
module.add_class('AttributeAccessor', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >'])
module.add_class('AttributeChecker', allow_subclassing=False, automatic_type_narrowing=True, import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >'])
module.add_class('AttributeValue', allow_subclassing=False, automatic_type_narrowing=True, import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >'])
module.add_class('BooleanChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker'])
module.add_class('BooleanValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue'])
module.add_class('BulkSendApplication', parent=root_module['ns3::Application'])
module.add_class('CallbackChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker'])
module.add_class('CallbackImplBase', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >'])
module.add_class('CallbackValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue'])
module.add_class('Channel', import_from_module='ns.network', parent=root_module['ns3::Object'])
module.add_class('ConstantRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream'])
module.add_class('DataCalculator', import_from_module='ns.stats', parent=root_module['ns3::Object'])
module.add_class('DataCollectionObject', import_from_module='ns.stats', parent=root_module['ns3::Object'])
module.add_class('DataOutputInterface', import_from_module='ns.stats', parent=root_module['ns3::Object'])
module.add_class('DataRateChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker'])
module.add_class('DataRateValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue'])
module.add_class('DeterministicRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream'])
module.add_class('DoubleValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue'])
module.add_class('DynamicQueueLimits', import_from_module='ns.network', parent=root_module['ns3::QueueLimits'])
module.add_class('EmpiricalRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream'])
module.add_class('EmptyAttributeAccessor', import_from_module='ns.core', parent=root_module['ns3::AttributeAccessor'])
module.add_class('EmptyAttributeChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker'])
module.add_class('EmptyAttributeValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue'])
module.add_class('EnumChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker'])
module.add_class('EnumValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue'])
module.add_class('ErlangRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream'])
module.add_class('ErrorModel', import_from_module='ns.network', parent=root_module['ns3::Object'])
module.add_class('EthernetHeader', import_from_module='ns.network', parent=root_module['ns3::Header'])
module.add_class('EthernetTrailer', import_from_module='ns.network', parent=root_module['ns3::Trailer'])
module.add_class('EventImpl', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >'])
module.add_class('ExponentialRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream'])
module.add_class('GammaRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream'])
module.add_class('IntegerValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue'])
module.add_class('Ipv4AddressChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker'])
module.add_class('Ipv4AddressValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue'])
module.add_class('Ipv4MaskChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker'])
module.add_class('Ipv4MaskValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue'])
module.add_class('Ipv6AddressChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker'])
module.add_class('Ipv6AddressValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue'])
module.add_class('Ipv6PrefixChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker'])
module.add_class('Ipv6PrefixValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue'])
module.add_class('ListErrorModel', import_from_module='ns.network', parent=root_module['ns3::ErrorModel'])
module.add_class('LogNormalRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream'])
module.add_class('Mac16AddressChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker'])
module.add_class('Mac16AddressValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue'])
module.add_class('Mac48AddressChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker'])
module.add_class('Mac48AddressValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue'])
module.add_class('Mac64AddressChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker'])
module.add_class('Mac64AddressValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue'])
module.add_class('MinMaxAvgTotalCalculator', import_from_module='ns.stats', template_parameters=['unsigned int'], parent=[root_module['ns3::DataCalculator'], root_module['ns3::StatisticalSummary']])
module.add_class('NetDevice', import_from_module='ns.network', parent=root_module['ns3::Object'])
module.add_enum('PacketType', ['PACKET_HOST', 'NS3_PACKET_HOST', 'PACKET_BROADCAST', 'NS3_PACKET_BROADCAST', 'PACKET_MULTICAST', 'NS3_PACKET_MULTICAST', 'PACKET_OTHERHOST', 'NS3_PACKET_OTHERHOST'], outer_class=root_module['ns3::NetDevice'], import_from_module='ns.network')
module.add_class('NetDeviceQueue', import_from_module='ns.network', parent=root_module['ns3::SimpleRefCount< ns3::NetDeviceQueue, ns3::empty, ns3::DefaultDeleter<ns3::NetDeviceQueue> >'])
module.add_class('NetDeviceQueueInterface', import_from_module='ns.network', parent=root_module['ns3::Object'])
module.add_class('NixVector', import_from_module='ns.network', parent=root_module['ns3::SimpleRefCount< ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >'])
module.add_class('Node', import_from_module='ns.network', parent=root_module['ns3::Object'])
module.add_class('NormalRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream'])
module.add_class('ObjectFactoryChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker'])
module.add_class('ObjectFactoryValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue'])
module.add_class('OnOffApplication', parent=root_module['ns3::Application'])
module.add_class('OutputStreamWrapper', import_from_module='ns.network', parent=root_module['ns3::SimpleRefCount< ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> >'])
module.add_class('Packet', import_from_module='ns.network', parent=root_module['ns3::SimpleRefCount< ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> >'])
module.add_class('PacketSink', parent=root_module['ns3::Application'])
module.add_class('PacketSizeMinMaxAvgTotalCalculator', import_from_module='ns.network', parent=root_module['ns3::MinMaxAvgTotalCalculator< unsigned int >'])
module.add_class('PacketSocket', import_from_module='ns.network', parent=root_module['ns3::Socket'])
module.add_class('PacketSocketClient', import_from_module='ns.network', parent=root_module['ns3::Application'])
module.add_class('PacketSocketFactory', import_from_module='ns.network', parent=root_module['ns3::SocketFactory'])
module.add_class('PacketSocketServer', import_from_module='ns.network', parent=root_module['ns3::Application'])
module.add_class('ParetoRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream'])
module.add_class('PbbAddressBlock', import_from_module='ns.network', parent=root_module['ns3::SimpleRefCount< ns3::PbbAddressBlock, ns3::empty, ns3::DefaultDeleter<ns3::PbbAddressBlock> >'])
module.add_class('PbbAddressBlockIpv4', import_from_module='ns.network', parent=root_module['ns3::PbbAddressBlock'])
module.add_class('PbbAddressBlockIpv6', import_from_module='ns.network', parent=root_module['ns3::PbbAddressBlock'])
module.add_class('PbbMessage', import_from_module='ns.network', parent=root_module['ns3::SimpleRefCount< ns3::PbbMessage, ns3::empty, ns3::DefaultDeleter<ns3::PbbMessage> >'])
module.add_class('PbbMessageIpv4', import_from_module='ns.network', parent=root_module['ns3::PbbMessage'])
module.add_class('PbbMessageIpv6', import_from_module='ns.network', parent=root_module['ns3::PbbMessage'])
module.add_class('PbbPacket', import_from_module='ns.network', parent=root_module['ns3::SimpleRefCount< ns3::PbbPacket, ns3::Header, ns3::DefaultDeleter<ns3::PbbPacket> >'])
module.add_class('PbbTlv', import_from_module='ns.network', parent=root_module['ns3::SimpleRefCount< ns3::PbbTlv, ns3::empty, ns3::DefaultDeleter<ns3::PbbTlv> >'])
module.add_class('Probe', import_from_module='ns.stats', parent=root_module['ns3::DataCollectionObject'])
module.add_class('Queue', import_from_module='ns.network', template_parameters=['ns3::Packet'], parent=root_module['ns3::QueueBase'])
module.add_class('Queue', import_from_module='ns.network', template_parameters=['ns3::QueueDiscItem'], parent=root_module['ns3::QueueBase'])
module.add_class('QueueItem', import_from_module='ns.network', parent=root_module['ns3::SimpleRefCount< ns3::QueueItem, ns3::empty, ns3::DefaultDeleter<ns3::QueueItem> >'])
module.add_enum('Uint8Values', ['IP_DSFIELD'], outer_class=root_module['ns3::QueueItem'], import_from_module='ns.network')
module.add_class('RateErrorModel', import_from_module='ns.network', parent=root_module['ns3::ErrorModel'])
module.add_enum('ErrorUnit', ['ERROR_UNIT_BIT', 'ERROR_UNIT_BYTE', 'ERROR_UNIT_PACKET'], outer_class=root_module['ns3::RateErrorModel'], import_from_module='ns.network')
module.add_class('ReceiveListErrorModel', import_from_module='ns.network', parent=root_module['ns3::ErrorModel'])
module.add_class('SimpleChannel', import_from_module='ns.network', parent=root_module['ns3::Channel'])
module.add_class('SimpleNetDevice', import_from_module='ns.network', parent=root_module['ns3::NetDevice'])
module.add_class('TimeValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue'])
module.add_class('TypeIdChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker'])
module.add_class('TypeIdValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue'])
module.add_class('UdpClient', parent=root_module['ns3::Application'])
module.add_class('UdpEchoClient', parent=root_module['ns3::Application'])
module.add_class('UdpEchoServer', parent=root_module['ns3::Application'])
module.add_class('UdpServer', parent=root_module['ns3::Application'])
module.add_class('UdpTraceClient', parent=root_module['ns3::Application'])
module.add_class('UintegerValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue'])
module.add_class('AddressChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker'])
module.add_class('AddressValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue'])
module.add_class('ApplicationPacketProbe', parent=root_module['ns3::Probe'])
module.add_class('BinaryErrorModel', import_from_module='ns.network', parent=root_module['ns3::ErrorModel'])
module.add_class('BurstErrorModel', import_from_module='ns.network', parent=root_module['ns3::ErrorModel'])
module.add_class('CallbackImpl', import_from_module='ns.core', template_parameters=['bool', 'ns3::Ptr<ns3::NetDevice>', 'ns3::Ptr<const ns3::Packet>', 'unsigned short', 'const ns3::Address &', 'const ns3::Address &', 'ns3::NetDevice::PacketType', 'ns3::empty', 'ns3::empty', 'ns3::empty'], parent=root_module['ns3::CallbackImplBase'])
module.add_class('CallbackImpl', import_from_module='ns.core', template_parameters=['bool', 'ns3::Ptr<ns3::NetDevice>', 'ns3::Ptr<const ns3::Packet>', 'unsigned short', 'const ns3::Address &', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'], parent=root_module['ns3::CallbackImplBase'])
module.add_class('CallbackImpl', import_from_module='ns.core', template_parameters=['bool', 'ns3::Ptr<ns3::Socket>', 'const ns3::Address &', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'], parent=root_module['ns3::CallbackImplBase'])
module.add_class('CallbackImpl', import_from_module='ns.core', template_parameters=['ns3::ObjectBase *', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'], parent=root_module['ns3::CallbackImplBase'])
module.add_class('CallbackImpl', import_from_module='ns.core', template_parameters=['unsigned char', 'ns3::Ptr<ns3::QueueItem>', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'], parent=root_module['ns3::CallbackImplBase'])
module.add_class('CallbackImpl', import_from_module='ns.core', template_parameters=['void', 'ns3::Ptr<const ns3::Packet>', 'const ns3::Address &', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'], parent=root_module['ns3::CallbackImplBase'])
module.add_class('CallbackImpl', import_from_module='ns.core', template_parameters=['void', 'ns3::Ptr<const ns3::Packet>', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'], parent=root_module['ns3::CallbackImplBase'])
module.add_class('CallbackImpl', import_from_module='ns.core', template_parameters=['void', 'ns3::Ptr<const ns3::QueueDiscItem>', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'], parent=root_module['ns3::CallbackImplBase'])
module.add_class('CallbackImpl', import_from_module='ns.core', template_parameters=['void', 'ns3::Ptr<ns3::NetDevice>', 'ns3::Ptr<const ns3::Packet>', 'unsigned short', 'const ns3::Address &', 'const ns3::Address &', 'ns3::NetDevice::PacketType', 'ns3::empty', 'ns3::empty', 'ns3::empty'], parent=root_module['ns3::CallbackImplBase'])
module.add_class('CallbackImpl', import_from_module='ns.core', template_parameters=['void', 'ns3::Ptr<ns3::NetDevice>', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'], parent=root_module['ns3::CallbackImplBase'])
module.add_class('CallbackImpl', import_from_module='ns.core', template_parameters=['void', 'ns3::Ptr<ns3::Socket>', 'const ns3::Address &', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'], parent=root_module['ns3::CallbackImplBase'])
module.add_class('CallbackImpl', import_from_module='ns.core', template_parameters=['void', 'ns3::Ptr<ns3::Socket>', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'], parent=root_module['ns3::CallbackImplBase'])
module.add_class('CallbackImpl', import_from_module='ns.core', template_parameters=['void', 'ns3::Ptr<ns3::Socket>', 'unsigned int', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'], parent=root_module['ns3::CallbackImplBase'])
module.add_class('CallbackImpl', import_from_module='ns.core', template_parameters=['void', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'], parent=root_module['ns3::CallbackImplBase'])
module.add_class('CallbackImpl', import_from_module='ns.core', template_parameters=['void', 'unsigned int', 'unsigned int', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'], parent=root_module['ns3::CallbackImplBase'])
module.add_class('CounterCalculator', import_from_module='ns.stats', template_parameters=['unsigned int'], parent=root_module['ns3::DataCalculator'])
module.add_class('ErrorChannel', import_from_module='ns.network', parent=root_module['ns3::SimpleChannel'])
module.add_class('PacketCounterCalculator', import_from_module='ns.network', parent=root_module['ns3::CounterCalculator< unsigned int >'])
module.add_class('PacketProbe', import_from_module='ns.network', parent=root_module['ns3::Probe'])
module.add_class('PbbAddressTlv', import_from_module='ns.network', parent=root_module['ns3::PbbTlv'])
module.add_class('QueueDiscItem', import_from_module='ns.network', parent=root_module['ns3::QueueItem'])
module.add_container('std::map< std::string, ns3::LogComponent * >', ('std::string', 'ns3::LogComponent *'), container_type=u'map')
module.add_container('std::list< ns3::Ptr< ns3::Packet > >', 'ns3::Ptr< ns3::Packet >', container_type=u'list')
module.add_container('std::vector< ns3::Ipv6Address >', 'ns3::Ipv6Address', container_type=u'vector')
module.add_container('std::list< unsigned int >', 'unsigned int', container_type=u'list')
module.add_container('std::list< ns3::Ptr< ns3::Socket > >', 'ns3::Ptr< ns3::Socket >', container_type=u'list')
typehandlers.add_type_alias(u'ns3::SequenceNumber< unsigned int, int >', u'ns3::SequenceNumber32')
typehandlers.add_type_alias(u'ns3::SequenceNumber< unsigned int, int >*', u'ns3::SequenceNumber32*')
typehandlers.add_type_alias(u'ns3::SequenceNumber< unsigned int, int >&', u'ns3::SequenceNumber32&')
typehandlers.add_type_alias(u'ns3::SequenceNumber< unsigned short, short >', u'ns3::SequenceNumber16')
typehandlers.add_type_alias(u'ns3::SequenceNumber< unsigned short, short >*', u'ns3::SequenceNumber16*')
typehandlers.add_type_alias(u'ns3::SequenceNumber< unsigned short, short >&', u'ns3::SequenceNumber16&')
typehandlers.add_type_alias(u'ns3::SequenceNumber< unsigned char, signed char >', u'ns3::SequenceNumber8')
typehandlers.add_type_alias(u'ns3::SequenceNumber< unsigned char, signed char >*', u'ns3::SequenceNumber8*')
typehandlers.add_type_alias(u'ns3::SequenceNumber< unsigned char, signed char >&', u'ns3::SequenceNumber8&')
typehandlers.add_type_alias(u'ns3::Callback< bool, ns3::Ptr< ns3::Packet >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', u'ns3::GenericPhyTxStartCallback')
typehandlers.add_type_alias(u'ns3::Callback< bool, ns3::Ptr< ns3::Packet >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >*', u'ns3::GenericPhyTxStartCallback*')
typehandlers.add_type_alias(u'ns3::Callback< bool, ns3::Ptr< ns3::Packet >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >&', u'ns3::GenericPhyTxStartCallback&')
typehandlers.add_type_alias(u'ns3::Callback< void, ns3::Ptr< ns3::Packet const >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', u'ns3::GenericPhyTxEndCallback')
typehandlers.add_type_alias(u'ns3::Callback< void, ns3::Ptr< ns3::Packet const >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >*', u'ns3::GenericPhyTxEndCallback*')
typehandlers.add_type_alias(u'ns3::Callback< void, ns3::Ptr< ns3::Packet const >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >&', u'ns3::GenericPhyTxEndCallback&')
typehandlers.add_type_alias(u'ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', u'ns3::GenericPhyRxStartCallback')
typehandlers.add_type_alias(u'ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >*', u'ns3::GenericPhyRxStartCallback*')
typehandlers.add_type_alias(u'ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >&', u'ns3::GenericPhyRxStartCallback&')
typehandlers.add_type_alias(u'ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', u'ns3::GenericPhyRxEndErrorCallback')
typehandlers.add_type_alias(u'ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >*', u'ns3::GenericPhyRxEndErrorCallback*')
typehandlers.add_type_alias(u'ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >&', u'ns3::GenericPhyRxEndErrorCallback&')
typehandlers.add_type_alias(u'ns3::Callback< void, ns3::Ptr< ns3::Packet >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', u'ns3::GenericPhyRxEndOkCallback')
typehandlers.add_type_alias(u'ns3::Callback< void, ns3::Ptr< ns3::Packet >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >*', u'ns3::GenericPhyRxEndOkCallback*')
typehandlers.add_type_alias(u'ns3::Callback< void, ns3::Ptr< ns3::Packet >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >&', u'ns3::GenericPhyRxEndOkCallback&')
typehandlers.add_type_alias(u'void ( * ) ( std::ostream & )', u'ns3::LogTimePrinter')
typehandlers.add_type_alias(u'void ( * ) ( std::ostream & )*', u'ns3::LogTimePrinter*')
typehandlers.add_type_alias(u'void ( * ) ( std::ostream & )&', u'ns3::LogTimePrinter&')
typehandlers.add_type_alias(u'void ( * ) ( std::ostream & )', u'ns3::LogNodePrinter')
typehandlers.add_type_alias(u'void ( * ) ( std::ostream & )*', u'ns3::LogNodePrinter*')
typehandlers.add_type_alias(u'void ( * ) ( std::ostream & )&', u'ns3::LogNodePrinter&')
nested_module = module.add_cpp_namespace('FatalImpl')
register_types_ns3_FatalImpl(nested_module)
nested_module = module.add_cpp_namespace('Hash')
register_types_ns3_Hash(nested_module)
nested_module = module.add_cpp_namespace('TracedValueCallback')
register_types_ns3_TracedValueCallback(nested_module)
nested_module = module.add_cpp_namespace('addressUtils')
register_types_ns3_addressUtils(nested_module)
nested_module = module.add_cpp_namespace('internal')
register_types_ns3_internal(nested_module)
nested_module = module.add_cpp_namespace('tests')
register_types_ns3_tests(nested_module) |
.parametrize('inspec_and_axis', (general_cases(False) + large_reduction_cases_for_layer_norm()))
def test_layer_normalization(inspec_and_axis, nnabla_opts):
(inspec, axis) = inspec_and_axis
fb = FunctionBenchmark(PF.layer_normalization, inspec, [], dict(), nnabla_opts.ext, nnabla_opts.ext_kwargs)
fb.benchmark()
fb.write(writer=nnabla_opts.function_benchmark_writer) |
class BatchNorm2dSyncFunc(Function):
def forward(ctx, x, weight, bias, running_mean, running_var, extra, compute_stats=True, momentum=0.1, eps=1e-05):
def _parse_extra(ctx, extra):
ctx.is_master = extra['is_master']
if ctx.is_master:
ctx.master_queue = extra['master_queue']
ctx.worker_queues = extra['worker_queues']
ctx.worker_ids = extra['worker_ids']
else:
ctx.master_queue = extra['master_queue']
ctx.worker_queue = extra['worker_queue']
if (extra is not None):
_parse_extra(ctx, extra)
ctx.compute_stats = compute_stats
ctx.momentum = momentum
ctx.eps = eps
ctx.affine = ((weight is not None) and (bias is not None))
if ctx.compute_stats:
N = (_count_samples(x) * (ctx.master_queue.maxsize + 1))
assert (N > 1)
(xsum, xsqsum) = _backend.syncbn_sum_sqsum(x.detach())
if ctx.is_master:
(xsums, xsqsums) = ([xsum], [xsqsum])
for _ in range(ctx.master_queue.maxsize):
(xsum_w, xsqsum_w) = ctx.master_queue.get()
ctx.master_queue.task_done()
xsums.append(xsum_w)
xsqsums.append(xsqsum_w)
xsum = comm.reduce_add(xsums)
xsqsum = comm.reduce_add(xsqsums)
mean = (xsum / N)
sumvar = (xsqsum - (xsum * mean))
var = (sumvar / N)
uvar = (sumvar / (N - 1))
tensors = comm.broadcast_coalesced((mean, uvar, var), ([mean.get_device()] + ctx.worker_ids))
for (ts, queue) in zip(tensors[1:], ctx.worker_queues):
queue.put(ts)
else:
ctx.master_queue.put((xsum, xsqsum))
(mean, uvar, var) = ctx.worker_queue.get()
ctx.worker_queue.task_done()
running_mean.mul_((1 - ctx.momentum)).add_((ctx.momentum * mean))
running_var.mul_((1 - ctx.momentum)).add_((ctx.momentum * uvar))
ctx.N = N
ctx.save_for_backward(x, weight, bias, mean, var)
else:
(mean, var) = (running_mean, running_var)
z = _backend.syncbn_forward(x, weight, bias, mean, var, ctx.affine, ctx.eps)
return z
_differentiable
def backward(ctx, dz):
(x, weight, bias, mean, var) = ctx.saved_tensors
dz = dz.contiguous()
(sum_dz, sum_dz_xhat) = _backend.syncbn_backward_xhat(dz, x, mean, var, ctx.eps)
if ctx.is_master:
(sum_dzs, sum_dz_xhats) = ([sum_dz], [sum_dz_xhat])
for _ in range(ctx.master_queue.maxsize):
(sum_dz_w, sum_dz_xhat_w) = ctx.master_queue.get()
ctx.master_queue.task_done()
sum_dzs.append(sum_dz_w)
sum_dz_xhats.append(sum_dz_xhat_w)
sum_dz = comm.reduce_add(sum_dzs)
sum_dz_xhat = comm.reduce_add(sum_dz_xhats)
sum_dz /= ctx.N
sum_dz_xhat /= ctx.N
tensors = comm.broadcast_coalesced((sum_dz, sum_dz_xhat), ([mean.get_device()] + ctx.worker_ids))
for (ts, queue) in zip(tensors[1:], ctx.worker_queues):
queue.put(ts)
else:
ctx.master_queue.put((sum_dz, sum_dz_xhat))
(sum_dz, sum_dz_xhat) = ctx.worker_queue.get()
ctx.worker_queue.task_done()
(dx, dweight, dbias) = _backend.syncbn_backward(dz, x, weight, bias, mean, var, sum_dz, sum_dz_xhat, ctx.affine, ctx.eps)
return (dx, dweight, dbias, None, None, None, None, None, None) |
class UnsupportedNodeError(NotSupportedError):
def __init__(self, ctx, offending_node):
node_type = type(offending_node)
range_len = len(node_start_tokens.get(node_type, ' '))
source_range = ctx.make_range(offending_node.lineno, offending_node.col_offset, (offending_node.col_offset + range_len))
feature_name = pretty_node_names.get(node_type, node_type.__name__)
msg = "{} aren't supported".format(feature_name)
super(NotSupportedError, self).__init__(source_range, msg) |
def get_score(weights, model, cache, example_dataset, batch_size, get_loss, get_regular):
final_state_dict = {}
lora_module_list = list(cache.keys())
keys = cache[lora_module_list[0]].keys()
for (i, peft_model_id) in enumerate(lora_module_list):
lora_state_dict = cache[peft_model_id]
if (i == 0):
for key in keys:
final_state_dict[key] = (weights[i] * lora_state_dict[key])
else:
for key in keys:
final_state_dict[key] = (final_state_dict[key] + (weights[i] * lora_state_dict[key]))
set_peft_model_state_dict(model, final_state_dict)
loss = get_loss(example_dataset, model, batch_size)
metric_val = (loss + get_regular(weights))
return metric_val |
class TestInputPipelineDef(tf.test.TestCase):
def test_without_extra_args(self):
pipeline_def = yaml.load('\n class: ParallelTextInputPipeline\n params:\n source_files: ["file1"]\n target_files: ["file2"]\n num_epochs: 1\n shuffle: True\n ')
pipeline = input_pipeline.make_input_pipeline_from_def(pipeline_def, tf.contrib.learn.ModeKeys.TRAIN)
self.assertIsInstance(pipeline, input_pipeline.ParallelTextInputPipeline)
self.assertEqual(pipeline.params['source_files'], ['file1'])
self.assertEqual(pipeline.params['target_files'], ['file2'])
self.assertEqual(pipeline.params['num_epochs'], 1)
self.assertEqual(pipeline.params['shuffle'], True)
def test_with_extra_args(self):
pipeline_def = yaml.load('\n class: ParallelTextInputPipeline\n params:\n source_files: ["file1"]\n target_files: ["file2"]\n num_epochs: 1\n shuffle: True\n ')
pipeline = input_pipeline.make_input_pipeline_from_def(def_dict=pipeline_def, mode=tf.contrib.learn.ModeKeys.TRAIN, num_epochs=5, shuffle=False)
self.assertIsInstance(pipeline, input_pipeline.ParallelTextInputPipeline)
self.assertEqual(pipeline.params['source_files'], ['file1'])
self.assertEqual(pipeline.params['target_files'], ['file2'])
self.assertEqual(pipeline.params['num_epochs'], 5)
self.assertEqual(pipeline.params['shuffle'], False) |
def plot_detections(rois, id, obj_id, imagePath, targetPath='vis_detections'):
img = cv2.imread(os.path.join(imagePath, ('%05d.jpg' % id)))
for i in range(rois.shape[0]):
roi = rois[i]
cv2.rectangle(img, pt1=(roi[1], roi[0]), pt2=(roi[3], roi[2]), color=(0, 255, 0), thickness=2)
img = cv2.putText(img, ('%d: %f' % (i, 0.0)), (roi[1], roi[0]), cv2.FONT_HERSHEY_SIMPLEX, 1.0, (255, 255, 255))
if (not os.path.exists(targetPath)):
os.makedirs(targetPath)
cv2.imwrite(os.path.join(targetPath, ('%05d.jpg' % id)), img) |
_model('nacrf_transformer')
class NACRFTransformerModel(NATransformerModel):
def __init__(self, args, encoder, decoder):
super().__init__(args, encoder, decoder)
self.crf_layer = DynamicCRF(num_embedding=len(self.tgt_dict), low_rank=args.crf_lowrank_approx, beam_size=args.crf_beam_approx)
def allow_ensemble(self):
return False
def add_args(parser):
NATransformerModel.add_args(parser)
parser.add_argument('--crf-lowrank-approx', type=int, help='the dimension of low-rank approximation of transition')
parser.add_argument('--crf-beam-approx', type=int, help='the beam size for apporixmating the normalizing factor')
parser.add_argument('--word-ins-loss-factor', type=float, help='weights on NAT loss used to co-training with CRF loss.')
def forward(self, src_tokens, src_lengths, prev_output_tokens, tgt_tokens, **kwargs):
encoder_out = self.encoder(src_tokens, src_lengths=src_lengths, **kwargs)
length_out = self.decoder.forward_length(normalize=False, encoder_out=encoder_out)
length_tgt = self.decoder.forward_length_prediction(length_out, encoder_out, tgt_tokens)
word_ins_out = self.decoder(normalize=False, prev_output_tokens=prev_output_tokens, encoder_out=encoder_out)
(word_ins_tgt, word_ins_mask) = (tgt_tokens, tgt_tokens.ne(self.pad))
crf_nll = (- self.crf_layer(word_ins_out, word_ins_tgt, word_ins_mask))
crf_nll = (crf_nll / word_ins_mask.type_as(crf_nll).sum((- 1))).mean()
return {'word_ins': {'out': word_ins_out, 'tgt': word_ins_tgt, 'mask': word_ins_mask, 'ls': self.args.label_smoothing, 'nll_loss': True, 'factor': self.args.word_ins_loss_factor}, 'word_crf': {'loss': crf_nll}, 'length': {'out': length_out, 'tgt': length_tgt, 'factor': self.decoder.length_loss_factor}}
def forward_decoder(self, decoder_out, encoder_out, decoding_format=None, **kwargs):
output_tokens = decoder_out.output_tokens
output_scores = decoder_out.output_scores
history = decoder_out.history
output_masks = output_tokens.ne(self.pad)
word_ins_out = self.decoder(normalize=False, prev_output_tokens=output_tokens, encoder_out=encoder_out)
(_scores, _tokens) = self.crf_layer.forward_decoder(word_ins_out, output_masks)
output_tokens.masked_scatter_(output_masks, _tokens[output_masks])
output_scores.masked_scatter_(output_masks, _scores[output_masks])
if (history is not None):
history.append(output_tokens.clone())
return decoder_out._replace(output_tokens=output_tokens, output_scores=output_scores, attn=None, history=history) |
def restoration_inference(model, img, ref=None):
cfg = model.cfg
device = next(model.parameters()).device
keys_to_remove = ['gt', 'gt_path']
for key in keys_to_remove:
for pipeline in list(cfg.test_pipeline):
if (('key' in pipeline) and (key == pipeline['key'])):
cfg.test_pipeline.remove(pipeline)
if (('keys' in pipeline) and (key in pipeline['keys'])):
pipeline['keys'].remove(key)
if (len(pipeline['keys']) == 0):
cfg.test_pipeline.remove(pipeline)
if (('meta_keys' in pipeline) and (key in pipeline['meta_keys'])):
pipeline['meta_keys'].remove(key)
test_pipeline = Compose(cfg.test_pipeline)
if ref:
data = dict(lq_path=img, ref_path=ref)
else:
data = dict(lq_path=img)
data = test_pipeline(data)
data = scatter(collate([data], samples_per_gpu=1), [device])[0]
with torch.no_grad():
result = model(test_mode=True, **data)
return result['output'] |
class SagePackageTestCase(unittest.TestCase):
def run_command(self, *args, **kwds):
env = dict(os.environ)
env.update(kwds.get('env', {}))
env['PATH'] = ((PATH + os.pathsep) + env['PATH'])
kwds.update(stdin=None, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env)
log.debug('running {}: {}'.format(args, kwds))
proc = subprocess.Popen(args, **kwds)
(stdout, stderr) = proc.communicate()
stdout = stdout.decode('utf-8')
stderr = stderr.decode('utf-8')
log.debug(u'stdout="{}", stderr="{}"'.format(stdout, stderr))
rc = proc.returncode
return (rc, stdout, stderr)
def test_config(self):
(rc, stdout, stderr) = self.run_command(EXECUTABLE, 'config')
self.assertEqual(stderr, '')
self.assertEqual(rc, 0)
self.assertTrue(stdout.startswith('Configuration:\n'))
def test_list(self):
(rc, stdout, stderr) = self.run_command(EXECUTABLE, 'list')
self.assertEqual(stderr, '')
self.assertEqual(rc, 0)
self.assertTrue(('configure' in stdout.splitlines()))
def test_name(self):
pkg = Package('configure')
(rc, stdout, stderr) = self.run_command(EXECUTABLE, 'name', pkg.tarball_filename)
self.assertEqual(stderr, '')
self.assertEqual(rc, 0)
self.assertEqual(stdout.rstrip(), 'configure')
def test_tarball(self):
pkg = Package('configure')
(rc, stdout, stderr) = self.run_command(EXECUTABLE, 'tarball', pkg.name)
self.assertEqual(stderr, '')
self.assertEqual(rc, 0)
self.assertEqual(stdout.rstrip(), pkg.tarball_filename)
def test_apropos(self):
(rc, stdout, stderr) = self.run_command(EXECUTABLE, 'apropos', 'python')
self.assertEqual(stderr, '')
self.assertEqual(rc, 0)
self.assertTrue(stdout.startswith('Did you mean:'))
def test_download(self):
pkg = Package('configure')
with CapturedLog() as _:
pkg.tarball.download()
(rc, stdout, stderr) = self.run_command(EXECUTABLE, 'download', pkg.name)
self.assertTrue(stderr.startswith('Using cached file'))
self.assertEqual(rc, 0)
self.assertEqual(stdout.rstrip(), pkg.tarball.upstream_fqn)
def test_update(self):
pkg = Package('configure')
self.assertEqual(pkg.patchlevel, (- 1))
(rc, stdout, stderr) = self.run_command(EXECUTABLE, 'update', pkg.name, pkg.version)
self.assertEqual(stderr, '')
self.assertEqual(rc, 0)
self.assertEqual(stdout, '')
def test_fix_checksum(self):
pkg = Package('configure')
(rc, stdout, stderr) = self.run_command(EXECUTABLE, 'fix-checksum', 'configure')
self.assertEqual(stderr, '')
self.assertEqual(rc, 0)
self.assertEqual(stdout.rstrip(), 'Checksum of {0} (tarball {1}) unchanged'.format(pkg.name, pkg.tarball_filename))
def test_create(self):
tmp = tempfile.mkdtemp()
with open(os.path.join(tmp, 'configure.ac'), 'w+') as f:
f.write('test')
os.mkdir(os.path.join(tmp, 'build'))
os.mkdir(os.path.join(tmp, 'build', 'pkgs'))
os.mkdir(os.path.join(tmp, 'upstream'))
with open(os.path.join(tmp, 'upstream', 'Foo-13.5.tgz'), 'w+') as f:
f.write('tarball content')
(rc, stdout, stderr) = self.run_command(EXECUTABLE, 'create', 'foo', '--version', '13.5', '--tarball', 'Foo-VERSION.tgz', '--type', 'standard', env=dict(SAGE_ROOT=tmp))
self.assertEqual(rc, 0)
with open(os.path.join(tmp, 'build', 'pkgs', 'foo', 'package-version.txt')) as f:
self.assertEqual(f.read(), '13.5\n')
with open(os.path.join(tmp, 'build', 'pkgs', 'foo', 'type')) as f:
self.assertEqual(f.read(), 'standard\n')
with open(os.path.join(tmp, 'build', 'pkgs', 'foo', 'checksums.ini')) as f:
self.assertEqual(f.read(), ((('tarball=Foo-VERSION.tgz\n' + 'sha1=15d0e36e27c69bc758231f8e9add837f40a40cd0\n') + 'md5=bc62fed5e35f31aeea2af95c00473d4d\n') + 'cksum=\n'))
shutil.rmtree(tmp) |
class NeuralSpectralKernel(gpflow.kernels.Kernel):
def __init__(self, input_dim, active_dims=None, Q=1, hidden_sizes=None):
super().__init__(input_dim, active_dims=active_dims)
self.Q = Q
if (hidden_sizes is None):
hidden_sizes = (32, 32)
self.num_hidden = len(hidden_sizes)
for (v, final_size) in zip(['freq', 'len', 'var'], [input_dim, input_dim, 1]):
self._create_nn_params(v, hidden_sizes, final_size)
def _create_nn_params(self, prefix, hidden_sizes, final_size):
for q in range(self.Q):
input_dim = self.input_dim
for (level, hidden_size) in enumerate(hidden_sizes):
name_W = '{prefix}_W_{level}'.format(prefix=prefix, level=level)
name_b = '{prefix}_b_{level}'.format(prefix=prefix, level=level)
if (not hasattr(self, name_W)):
params = _create_params(input_dim, hidden_size)
setattr(self, name_W, params[0])
setattr(self, name_b, params[1])
input_dim = hidden_size
params = _create_params(input_dim, final_size)
setattr(self, '{prefix}_{q}_W_final'.format(prefix=prefix, q=q), params[0])
setattr(self, '{prefix}_{q}_b_final'.format(prefix=prefix, q=q), params[1])
_as_tensors
def _nn_function(self, x, prefix, q, dropout=0.8, final_activation=tf.nn.softplus):
for level in range(self.num_hidden):
W = getattr(self, '{prefix}_W_{level}'.format(prefix=prefix, level=level))
b = getattr(self, '{prefix}_b_{level}'.format(prefix=prefix, level=level))
x = tf.nn.selu(tf.nn.xw_plus_b(x, W, b))
W = getattr(self, '{prefix}_{q}_W_final'.format(prefix=prefix, q=q))
b = getattr(self, '{prefix}_{q}_b_final'.format(prefix=prefix, q=q))
return final_activation(tf.nn.xw_plus_b(x, W, b))
_as_tensors
def K(self, X, X2=None):
if (X2 is None):
X2 = X
kern = 0.0
for q in range(self.Q):
(freq, freq2) = (self._nn_function(X, 'freq', q), self._nn_function(X2, 'freq', q))
(lens, lens2) = (self._nn_function(X, 'len', q), self._nn_function(X2, 'len', q))
(var, var2) = (self._nn_function(X, 'var', q), self._nn_function(X2, 'var', q))
Xr = tf.expand_dims(X, 1)
X2r = tf.expand_dims(X2, 0)
l1 = tf.expand_dims(lens, 1)
l2 = tf.expand_dims(lens2, 0)
L = (tf.square(l1) + tf.square(l2))
D = (tf.square((Xr - X2r)) / L)
D = tf.reduce_sum(D, 2)
det = tf.sqrt((((2 * l1) * l2) / L))
det = tf.reduce_prod(det, 2)
E = (det * tf.exp((- D)))
muX = (tf.reduce_sum((freq * X), 1, keepdims=True) - tf.transpose(tf.reduce_sum((freq2 * X2), 1, keepdims=True)))
COS = tf.cos(((2 * np.pi) * muX))
WW = tf.matmul(var, var2, transpose_b=True)
kern += ((WW * E) * COS)
if (X == X2):
return robust_kernel(kern, tf.shape(X)[0])
else:
return kern
_as_tensors
def Kdiag(self, X):
kd = settings.jitter
for q in range(self.Q):
kd += tf.square(self._nn_function(X, 'var', q))
return tf.squeeze(kd) |
class TestScenarios(unittest.TestCase):
def compare_times(self, evaluator, h_idx=0):
trajectory_hr = evaluator.evaluate_one_optimal_one_greedy_human(h_idx=h_idx, display=DISPLAY)
time_taken_hr = trajectory_hr['ep_lengths'][0]
print(('\n' * 5), '\n', ('-' * 50))
trajectory_rr = evaluator.evaluate_optimal_pair(display=DISPLAY)
time_taken_rr = trajectory_rr['ep_lengths'][0]
print('H+R time taken: ', time_taken_hr)
print('R+R time taken: ', time_taken_rr)
self.assertGreater(time_taken_hr, time_taken_rr)
def test_scenario_1(self):
scenario_1_mdp = OvercookedGridworld.from_layout_name('small_corridor', start_order_list=['any'], cook_time=5)
mlp = MediumLevelPlanner.from_pickle_or_compute(scenario_1_mdp, NO_COUNTERS_PARAMS, force_compute=force_compute)
a0 = GreedyHumanModel(mlp)
a1 = CoupledPlanningAgent(mlp)
agent_pair = AgentPair(a0, a1)
start_state = OvercookedState([P((2, 1), s, Obj('onion', (2, 1))), P((10, 2), s)], {}, order_list=['onion'])
env = OvercookedEnv(scenario_1_mdp, start_state_fn=(lambda : start_state))
env.run_agents(agent_pair, include_final_state=True, display=DISPLAY)
def test_scenario_1_s(self):
scenario_1_mdp = OvercookedGridworld.from_layout_name('scenario1_s', start_order_list=['any'], cook_time=5)
mlp = MediumLevelPlanner.from_pickle_or_compute(scenario_1_mdp, NO_COUNTERS_PARAMS, force_compute=force_compute)
a0 = GreedyHumanModel(mlp)
a1 = CoupledPlanningAgent(mlp)
agent_pair = AgentPair(a0, a1)
start_state = OvercookedState([P((2, 1), s, Obj('onion', (2, 1))), P((4, 2), s)], {}, order_list=['onion'])
env = OvercookedEnv(scenario_1_mdp, start_state_fn=(lambda : start_state))
(trajectory, time_taken_hr, _, _) = env.run_agents(agent_pair, include_final_state=True, display=DISPLAY)
env.reset()
print(('\n' * 5))
print(('-' * 50))
a0 = CoupledPlanningAgent(mlp)
a1 = CoupledPlanningAgent(mlp)
agent_pair = AgentPair(a0, a1)
(trajectory, time_taken_rr, _, _) = env.run_agents(agent_pair, include_final_state=True, display=DISPLAY)
print('H+R time taken: ', time_taken_hr)
print('R+R time taken: ', time_taken_rr)
self.assertGreater(time_taken_hr, time_taken_rr)
def test_scenario_2(self):
start_state = OvercookedState([P((5, 2), n), P((7, 2), n)], {(6, 3): Obj('soup', (6, 3), ('onion', 2, 0))}, order_list=['onion'])
mdp_params = {'layout_name': 'scenario2', 'cook_time': 5}
env_params = {'start_state_fn': (lambda : start_state)}
eva = AgentEvaluator(mdp_params, env_params)
self.compare_times(eva)
def test_scenario_3(self):
mdp_params = {'layout_name': 'scenario3', 'cook_time': 5}
mdp = OvercookedGridworld.from_layout_name(**mdp_params)
start_state = mdp.get_standard_start_state()
start_state.objects = {(8, 1): Obj('soup', (8, 1), ('onion', 2, 0))}
start_state.order_list = ['onion']
valid_counters = [(5, 3)]
one_counter_params = {'start_orientations': False, 'wait_allowed': False, 'counter_goals': valid_counters, 'counter_drop': valid_counters, 'counter_pickup': [], 'same_motion_goals': True}
env_params = {'start_state_fn': (lambda : start_state), 'horizon': 1000}
eva = AgentEvaluator(mdp_params, env_params, mlp_params=one_counter_params, force_compute=force_compute)
self.compare_times(eva)
def test_scenario_4(self):
mdp_params = {'layout_name': 'scenario4', 'cook_time': 5}
mdp = OvercookedGridworld.from_layout_name(**mdp_params)
start_state = mdp.get_standard_start_state()
start_state.objects = {(8, 1): Obj('soup', (8, 1), ('onion', 2, 5))}
start_state.order_list = ['onion']
env_params = {'start_state_fn': (lambda : start_state), 'horizon': 1000}
eva = AgentEvaluator(mdp_params, env_params, force_compute=force_compute)
self.compare_times(eva)
def test_schelling_s(self):
eva = AgentEvaluator({'layout_name': 'schelling_s', 'start_order_list': ['any', 'any'], 'cook_time': 5}, force_compute=force_compute)
start_state = eva.env.mdp.get_standard_start_state()
start_state.objects = {(2, 0): Obj('soup', (2, 0), ('onion', 2, 5)), (2, 4): Obj('soup', (2, 4), ('onion', 2, 5))}
eva.start_state = start_state
self.compare_times(eva, h_idx=1)
def test_unidentifiable(self):
eva = AgentEvaluator({'layout_name': 'unident', 'start_order_list': ['any', 'any'], 'cook_time': 5}, force_compute=force_compute)
start_state = eva.env.mdp.get_standard_start_state()
start_state.objects = {(5, 2): Obj('soup', (5, 2), ('onion', 2, 0)), (5, 3): Obj('soup', (5, 3), ('onion', 3, 5))}
eva.start_state = start_state
self.compare_times(eva, h_idx=0)
def test_unidentifiable_s(self):
eva = AgentEvaluator({'layout_name': 'unident_s', 'start_order_list': ['any', 'any'], 'cook_time': 5}, force_compute=force_compute)
start_state = eva.env.mdp.get_standard_start_state()
start_state.objects = {(4, 2): Obj('soup', (4, 2), ('onion', 2, 0)), (4, 3): Obj('soup', (4, 3), ('onion', 3, 5))}
eva.start_state = start_state
self.compare_times(eva, h_idx=0) |
def main():
configs = collect_configurations()
statistics_file = eval(configs)
make_plots(statistics_file) |
_function_dispatch(_apply_along_axis_dispatcher)
def apply_along_axis(func1d, axis, arr, *args, **kwargs):
arr = asanyarray(arr)
nd = arr.ndim
axis = normalize_axis_index(axis, nd)
in_dims = list(range(nd))
inarr_view = transpose(arr, ((in_dims[:axis] + in_dims[(axis + 1):]) + [axis]))
inds = ndindex(inarr_view.shape[:(- 1)])
inds = ((ind + (Ellipsis,)) for ind in inds)
try:
ind0 = next(inds)
except StopIteration:
raise ValueError('Cannot apply_along_axis when any iteration dimensions are 0')
res = asanyarray(func1d(inarr_view[ind0], *args, **kwargs))
buff = zeros((inarr_view.shape[:(- 1)] + res.shape), res.dtype)
buff_dims = list(range(buff.ndim))
buff_permute = ((buff_dims[0:axis] + buff_dims[(buff.ndim - res.ndim):buff.ndim]) + buff_dims[axis:(buff.ndim - res.ndim)])
if (not isinstance(res, matrix)):
buff = res.__array_prepare__(buff)
buff[ind0] = res
for ind in inds:
buff[ind] = asanyarray(func1d(inarr_view[ind], *args, **kwargs))
if (not isinstance(res, matrix)):
buff = res.__array_wrap__(buff)
return transpose(buff, buff_permute)
else:
out_arr = transpose(buff, buff_permute)
return res.__array_wrap__(out_arr) |
class PromptDataSetClass(Dataset):
def __init__(self, dataframe, tokenizer, source_len, target_len, source_text, target_text, return_dict=False):
self.tokenizer = tokenizer
self.data = dataframe
self.source_len = source_len
self.summ_len = target_len
self.target_text = self.data[target_text]
self.source_text = self.data[source_text]
self.return_dict = return_dict
def __len__(self):
return len(self.target_text)
def __getitem__(self, index):
source_text = str(self.source_text[index])
target_text = str(self.target_text[index])
source_text = ' '.join(source_text.split())
target_text = ' '.join(target_text.split())
source = self.tokenizer.batch_encode_plus([source_text], max_length=self.source_len, pad_to_max_length=True, truncation=True, padding='max_length', return_tensors='pt')
target = self.tokenizer.batch_encode_plus([target_text], max_length=self.summ_len, pad_to_max_length=True, truncation=True, padding='max_length', return_tensors='pt')
source_ids = source['input_ids'].squeeze()
source_mask = source['attention_mask'].squeeze()
target_ids = target['input_ids'].squeeze()
target_mask = target['attention_mask'].squeeze()
if self.return_dict:
return {'source_ids': source_ids.to(dtype=torch.long), 'source_mask': source_mask.to(dtype=torch.long), 'target_ids': target_ids.to(dtype=torch.long), 'target_ids_y': target_ids.to(dtype=torch.long)}
else:
return (source_ids.to(dtype=torch.long), source_mask.to(dtype=torch.long), target_ids.to(dtype=torch.long), target_ids.to(dtype=torch.long)) |
def test_capture_tuple():
program = 'def f(x):\n try:\n risky()\n except (a.AError, b.BError):\n raise\n'
__assert_found(program, 'a.AError', 'b.BError') |
def list_to_string(x):
if x:
s = str(x).replace('[', '').replace(']', '').replace(',', '')
else:
s = '-'
return s |
def register_methods(root_module):
register_Ns3Address_methods(root_module, root_module['ns3::Address'])
register_Ns3ApplicationContainer_methods(root_module, root_module['ns3::ApplicationContainer'])
register_Ns3AsciiTraceHelper_methods(root_module, root_module['ns3::AsciiTraceHelper'])
register_Ns3AsciiTraceHelperForDevice_methods(root_module, root_module['ns3::AsciiTraceHelperForDevice'])
register_Ns3AsciiTraceHelperForIpv4_methods(root_module, root_module['ns3::AsciiTraceHelperForIpv4'])
register_Ns3AsciiTraceHelperForIpv6_methods(root_module, root_module['ns3::AsciiTraceHelperForIpv6'])
register_Ns3AttributeConstructionList_methods(root_module, root_module['ns3::AttributeConstructionList'])
register_Ns3AttributeConstructionListItem_methods(root_module, root_module['ns3::AttributeConstructionList::Item'])
register_Ns3Bar_methods(root_module, root_module['ns3::Bar'])
register_Ns3BlockAckAgreement_methods(root_module, root_module['ns3::BlockAckAgreement'])
register_Ns3BlockAckCache_methods(root_module, root_module['ns3::BlockAckCache'])
register_Ns3Buffer_methods(root_module, root_module['ns3::Buffer'])
register_Ns3BufferIterator_methods(root_module, root_module['ns3::Buffer::Iterator'])
register_Ns3ByteTagIterator_methods(root_module, root_module['ns3::ByteTagIterator'])
register_Ns3ByteTagIteratorItem_methods(root_module, root_module['ns3::ByteTagIterator::Item'])
register_Ns3ByteTagList_methods(root_module, root_module['ns3::ByteTagList'])
register_Ns3ByteTagListIterator_methods(root_module, root_module['ns3::ByteTagList::Iterator'])
register_Ns3ByteTagListIteratorItem_methods(root_module, root_module['ns3::ByteTagList::Iterator::Item'])
register_Ns3CallbackBase_methods(root_module, root_module['ns3::CallbackBase'])
register_Ns3CapabilityInformation_methods(root_module, root_module['ns3::CapabilityInformation'])
register_Ns3DataRate_methods(root_module, root_module['ns3::DataRate'])
register_Ns3DefaultDeleter__Ns3AttributeAccessor_methods(root_module, root_module['ns3::DefaultDeleter< ns3::AttributeAccessor >'])
register_Ns3DefaultDeleter__Ns3AttributeChecker_methods(root_module, root_module['ns3::DefaultDeleter< ns3::AttributeChecker >'])
register_Ns3DefaultDeleter__Ns3AttributeValue_methods(root_module, root_module['ns3::DefaultDeleter< ns3::AttributeValue >'])
register_Ns3DefaultDeleter__Ns3CallbackImplBase_methods(root_module, root_module['ns3::DefaultDeleter< ns3::CallbackImplBase >'])
register_Ns3DefaultDeleter__Ns3ChannelCoordinationListener_methods(root_module, root_module['ns3::DefaultDeleter< ns3::ChannelCoordinationListener >'])
register_Ns3DefaultDeleter__Ns3EventImpl_methods(root_module, root_module['ns3::DefaultDeleter< ns3::EventImpl >'])
register_Ns3DefaultDeleter__Ns3HashImplementation_methods(root_module, root_module['ns3::DefaultDeleter< ns3::Hash::Implementation >'])
register_Ns3DefaultDeleter__Ns3InterferenceHelperEvent_methods(root_module, root_module['ns3::DefaultDeleter< ns3::InterferenceHelper::Event >'])
register_Ns3DefaultDeleter__Ns3NixVector_methods(root_module, root_module['ns3::DefaultDeleter< ns3::NixVector >'])
register_Ns3DefaultDeleter__Ns3OutputStreamWrapper_methods(root_module, root_module['ns3::DefaultDeleter< ns3::OutputStreamWrapper >'])
register_Ns3DefaultDeleter__Ns3Packet_methods(root_module, root_module['ns3::DefaultDeleter< ns3::Packet >'])
register_Ns3DefaultDeleter__Ns3TraceSourceAccessor_methods(root_module, root_module['ns3::DefaultDeleter< ns3::TraceSourceAccessor >'])
register_Ns3DefaultDeleter__Ns3WifiMacQueueItem_methods(root_module, root_module['ns3::DefaultDeleter< ns3::WifiMacQueueItem >'])
register_Ns3EdcaParameter_methods(root_module, root_module['ns3::EdcaParameter'])
register_Ns3EventId_methods(root_module, root_module['ns3::EventId'])
register_Ns3Hasher_methods(root_module, root_module['ns3::Hasher'])
register_Ns3Inet6SocketAddress_methods(root_module, root_module['ns3::Inet6SocketAddress'])
register_Ns3InetSocketAddress_methods(root_module, root_module['ns3::InetSocketAddress'])
register_Ns3InterferenceHelper_methods(root_module, root_module['ns3::InterferenceHelper'])
register_Ns3InterferenceHelperSnrPer_methods(root_module, root_module['ns3::InterferenceHelper::SnrPer'])
register_Ns3Ipv4Address_methods(root_module, root_module['ns3::Ipv4Address'])
register_Ns3Ipv4InterfaceAddress_methods(root_module, root_module['ns3::Ipv4InterfaceAddress'])
register_Ns3Ipv4InterfaceContainer_methods(root_module, root_module['ns3::Ipv4InterfaceContainer'])
register_Ns3Ipv4Mask_methods(root_module, root_module['ns3::Ipv4Mask'])
register_Ns3Ipv6Address_methods(root_module, root_module['ns3::Ipv6Address'])
register_Ns3Ipv6InterfaceAddress_methods(root_module, root_module['ns3::Ipv6InterfaceAddress'])
register_Ns3Ipv6InterfaceContainer_methods(root_module, root_module['ns3::Ipv6InterfaceContainer'])
register_Ns3Ipv6Prefix_methods(root_module, root_module['ns3::Ipv6Prefix'])
register_Ns3LogComponent_methods(root_module, root_module['ns3::LogComponent'])
register_Ns3Mac48Address_methods(root_module, root_module['ns3::Mac48Address'])
register_Ns3MacLowTransmissionParameters_methods(root_module, root_module['ns3::MacLowTransmissionParameters'])
register_Ns3MpduInfo_methods(root_module, root_module['ns3::MpduInfo'])
register_Ns3NetDeviceContainer_methods(root_module, root_module['ns3::NetDeviceContainer'])
register_Ns3NodeContainer_methods(root_module, root_module['ns3::NodeContainer'])
register_Ns3ObjectBase_methods(root_module, root_module['ns3::ObjectBase'])
register_Ns3ObjectDeleter_methods(root_module, root_module['ns3::ObjectDeleter'])
register_Ns3ObjectFactory_methods(root_module, root_module['ns3::ObjectFactory'])
register_Ns3OrganizationIdentifier_methods(root_module, root_module['ns3::OrganizationIdentifier'])
register_Ns3OriginatorBlockAckAgreement_methods(root_module, root_module['ns3::OriginatorBlockAckAgreement'])
register_Ns3PacketMetadata_methods(root_module, root_module['ns3::PacketMetadata'])
register_Ns3PacketMetadataItem_methods(root_module, root_module['ns3::PacketMetadata::Item'])
register_Ns3PacketMetadataItemIterator_methods(root_module, root_module['ns3::PacketMetadata::ItemIterator'])
register_Ns3PacketTagIterator_methods(root_module, root_module['ns3::PacketTagIterator'])
register_Ns3PacketTagIteratorItem_methods(root_module, root_module['ns3::PacketTagIterator::Item'])
register_Ns3PacketTagList_methods(root_module, root_module['ns3::PacketTagList'])
register_Ns3PacketTagListTagData_methods(root_module, root_module['ns3::PacketTagList::TagData'])
register_Ns3ParameterLogger_methods(root_module, root_module['ns3::ParameterLogger'])
register_Ns3PcapFile_methods(root_module, root_module['ns3::PcapFile'])
register_Ns3PcapHelper_methods(root_module, root_module['ns3::PcapHelper'])
register_Ns3PcapHelperForDevice_methods(root_module, root_module['ns3::PcapHelperForDevice'])
register_Ns3PcapHelperForIpv4_methods(root_module, root_module['ns3::PcapHelperForIpv4'])
register_Ns3PcapHelperForIpv6_methods(root_module, root_module['ns3::PcapHelperForIpv6'])
register_Ns3SchInfo_methods(root_module, root_module['ns3::SchInfo'])
register_Ns3SignalNoiseDbm_methods(root_module, root_module['ns3::SignalNoiseDbm'])
register_Ns3SimpleRefCount__Ns3Object_Ns3ObjectBase_Ns3ObjectDeleter_methods(root_module, root_module['ns3::SimpleRefCount< ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter >'])
register_Ns3Simulator_methods(root_module, root_module['ns3::Simulator'])
register_Ns3StatusCode_methods(root_module, root_module['ns3::StatusCode'])
register_Ns3Tag_methods(root_module, root_module['ns3::Tag'])
register_Ns3TagBuffer_methods(root_module, root_module['ns3::TagBuffer'])
register_Ns3TimeWithUnit_methods(root_module, root_module['ns3::TimeWithUnit'])
register_Ns3TracedValue__Unsigned_int_methods(root_module, root_module['ns3::TracedValue< unsigned int >'])
register_Ns3TxInfo_methods(root_module, root_module['ns3::TxInfo'])
register_Ns3TxProfile_methods(root_module, root_module['ns3::TxProfile'])
register_Ns3TypeId_methods(root_module, root_module['ns3::TypeId'])
register_Ns3TypeIdAttributeInformation_methods(root_module, root_module['ns3::TypeId::AttributeInformation'])
register_Ns3TypeIdTraceSourceInformation_methods(root_module, root_module['ns3::TypeId::TraceSourceInformation'])
register_Ns3Vector2D_methods(root_module, root_module['ns3::Vector2D'])
register_Ns3Vector3D_methods(root_module, root_module['ns3::Vector3D'])
register_Ns3VendorSpecificContentManager_methods(root_module, root_module['ns3::VendorSpecificContentManager'])
register_Ns3VsaInfo_methods(root_module, root_module['ns3::VsaInfo'])
register_Ns3WaveBsmHelper_methods(root_module, root_module['ns3::WaveBsmHelper'])
register_Ns3WaveHelper_methods(root_module, root_module['ns3::WaveHelper'])
register_Ns3WifiHelper_methods(root_module, root_module['ns3::WifiHelper'])
register_Ns3WifiMacHelper_methods(root_module, root_module['ns3::WifiMacHelper'])
register_Ns3WifiMode_methods(root_module, root_module['ns3::WifiMode'])
register_Ns3WifiModeFactory_methods(root_module, root_module['ns3::WifiModeFactory'])
register_Ns3WifiPhyHelper_methods(root_module, root_module['ns3::WifiPhyHelper'])
register_Ns3WifiPhyListener_methods(root_module, root_module['ns3::WifiPhyListener'])
register_Ns3WifiRemoteStation_methods(root_module, root_module['ns3::WifiRemoteStation'])
register_Ns3WifiRemoteStationInfo_methods(root_module, root_module['ns3::WifiRemoteStationInfo'])
register_Ns3WifiRemoteStationState_methods(root_module, root_module['ns3::WifiRemoteStationState'])
register_Ns3WifiTxVector_methods(root_module, root_module['ns3::WifiTxVector'])
register_Ns3YansWifiChannelHelper_methods(root_module, root_module['ns3::YansWifiChannelHelper'])
register_Ns3YansWifiPhyHelper_methods(root_module, root_module['ns3::YansWifiPhyHelper'])
register_Ns3Empty_methods(root_module, root_module['ns3::empty'])
register_Ns3Int64x64_t_methods(root_module, root_module['ns3::int64x64_t'])
register_Ns3Chunk_methods(root_module, root_module['ns3::Chunk'])
register_Ns3Header_methods(root_module, root_module['ns3::Header'])
register_Ns3HigherLayerTxVectorTag_methods(root_module, root_module['ns3::HigherLayerTxVectorTag'])
register_Ns3InternetStackHelper_methods(root_module, root_module['ns3::InternetStackHelper'])
register_Ns3Ipv4Header_methods(root_module, root_module['ns3::Ipv4Header'])
register_Ns3Ipv6Header_methods(root_module, root_module['ns3::Ipv6Header'])
register_Ns3MgtAddBaRequestHeader_methods(root_module, root_module['ns3::MgtAddBaRequestHeader'])
register_Ns3MgtAddBaResponseHeader_methods(root_module, root_module['ns3::MgtAddBaResponseHeader'])
register_Ns3MgtAssocRequestHeader_methods(root_module, root_module['ns3::MgtAssocRequestHeader'])
register_Ns3MgtAssocResponseHeader_methods(root_module, root_module['ns3::MgtAssocResponseHeader'])
register_Ns3MgtDelBaHeader_methods(root_module, root_module['ns3::MgtDelBaHeader'])
register_Ns3MgtProbeRequestHeader_methods(root_module, root_module['ns3::MgtProbeRequestHeader'])
register_Ns3MgtProbeResponseHeader_methods(root_module, root_module['ns3::MgtProbeResponseHeader'])
register_Ns3NqosWaveMacHelper_methods(root_module, root_module['ns3::NqosWaveMacHelper'])
register_Ns3Object_methods(root_module, root_module['ns3::Object'])
register_Ns3ObjectAggregateIterator_methods(root_module, root_module['ns3::Object::AggregateIterator'])
register_Ns3PcapFileWrapper_methods(root_module, root_module['ns3::PcapFileWrapper'])
register_Ns3QosWaveMacHelper_methods(root_module, root_module['ns3::QosWaveMacHelper'])
register_Ns3QueueBase_methods(root_module, root_module['ns3::QueueBase'])
register_Ns3RandomVariableStream_methods(root_module, root_module['ns3::RandomVariableStream'])
register_Ns3SequentialRandomVariable_methods(root_module, root_module['ns3::SequentialRandomVariable'])
register_Ns3SimpleRefCount__Ns3AttributeAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeAccessor__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >'])
register_Ns3SimpleRefCount__Ns3AttributeChecker_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeChecker__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >'])
register_Ns3SimpleRefCount__Ns3AttributeValue_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeValue__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >'])
register_Ns3SimpleRefCount__Ns3CallbackImplBase_Ns3Empty_Ns3DefaultDeleter__lt__ns3CallbackImplBase__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >'])
register_Ns3SimpleRefCount__Ns3ChannelCoordinationListener_Ns3Empty_Ns3DefaultDeleter__lt__ns3ChannelCoordinationListener__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::ChannelCoordinationListener, ns3::empty, ns3::DefaultDeleter<ns3::ChannelCoordinationListener> >'])
register_Ns3SimpleRefCount__Ns3EventImpl_Ns3Empty_Ns3DefaultDeleter__lt__ns3EventImpl__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >'])
register_Ns3SimpleRefCount__Ns3HashImplementation_Ns3Empty_Ns3DefaultDeleter__lt__ns3HashImplementation__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> >'])
register_Ns3SimpleRefCount__Ns3InterferenceHelperEvent_Ns3Empty_Ns3DefaultDeleter__lt__ns3InterferenceHelperEvent__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::InterferenceHelper::Event, ns3::empty, ns3::DefaultDeleter<ns3::InterferenceHelper::Event> >'])
register_Ns3SimpleRefCount__Ns3Ipv4MulticastRoute_Ns3Empty_Ns3DefaultDeleter__lt__ns3Ipv4MulticastRoute__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::Ipv4MulticastRoute, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4MulticastRoute> >'])
register_Ns3SimpleRefCount__Ns3Ipv4Route_Ns3Empty_Ns3DefaultDeleter__lt__ns3Ipv4Route__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::Ipv4Route, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4Route> >'])
register_Ns3SimpleRefCount__Ns3NixVector_Ns3Empty_Ns3DefaultDeleter__lt__ns3NixVector__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >'])
register_Ns3SimpleRefCount__Ns3OutputStreamWrapper_Ns3Empty_Ns3DefaultDeleter__lt__ns3OutputStreamWrapper__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> >'])
register_Ns3SimpleRefCount__Ns3Packet_Ns3Empty_Ns3DefaultDeleter__lt__ns3Packet__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> >'])
register_Ns3SimpleRefCount__Ns3TraceSourceAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3TraceSourceAccessor__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >'])
register_Ns3SimpleRefCount__Ns3WifiInformationElement_Ns3Empty_Ns3DefaultDeleter__lt__ns3WifiInformationElement__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::WifiInformationElement, ns3::empty, ns3::DefaultDeleter<ns3::WifiInformationElement> >'])
register_Ns3SimpleRefCount__Ns3WifiMacQueueItem_Ns3Empty_Ns3DefaultDeleter__lt__ns3WifiMacQueueItem__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::WifiMacQueueItem, ns3::empty, ns3::DefaultDeleter<ns3::WifiMacQueueItem> >'])
register_Ns3Socket_methods(root_module, root_module['ns3::Socket'])
register_Ns3SocketIpTosTag_methods(root_module, root_module['ns3::SocketIpTosTag'])
register_Ns3SocketIpTtlTag_methods(root_module, root_module['ns3::SocketIpTtlTag'])
register_Ns3SocketIpv6HopLimitTag_methods(root_module, root_module['ns3::SocketIpv6HopLimitTag'])
register_Ns3SocketIpv6TclassTag_methods(root_module, root_module['ns3::SocketIpv6TclassTag'])
register_Ns3SocketPriorityTag_methods(root_module, root_module['ns3::SocketPriorityTag'])
register_Ns3SocketSetDontFragmentTag_methods(root_module, root_module['ns3::SocketSetDontFragmentTag'])
register_Ns3Time_methods(root_module, root_module['ns3::Time'])
register_Ns3TraceSourceAccessor_methods(root_module, root_module['ns3::TraceSourceAccessor'])
register_Ns3Trailer_methods(root_module, root_module['ns3::Trailer'])
register_Ns3TriangularRandomVariable_methods(root_module, root_module['ns3::TriangularRandomVariable'])
register_Ns3UniformRandomVariable_methods(root_module, root_module['ns3::UniformRandomVariable'])
register_Ns3VendorSpecificActionHeader_methods(root_module, root_module['ns3::VendorSpecificActionHeader'])
register_Ns3VsaManager_methods(root_module, root_module['ns3::VsaManager'])
register_Ns3WaveBsmStats_methods(root_module, root_module['ns3::WaveBsmStats'])
register_Ns3WeibullRandomVariable_methods(root_module, root_module['ns3::WeibullRandomVariable'])
register_Ns3Wifi80211pHelper_methods(root_module, root_module['ns3::Wifi80211pHelper'])
register_Ns3WifiActionHeader_methods(root_module, root_module['ns3::WifiActionHeader'])
register_Ns3WifiActionHeaderActionValue_methods(root_module, root_module['ns3::WifiActionHeader::ActionValue'])
register_Ns3WifiInformationElement_methods(root_module, root_module['ns3::WifiInformationElement'])
register_Ns3WifiMac_methods(root_module, root_module['ns3::WifiMac'])
register_Ns3WifiMacHeader_methods(root_module, root_module['ns3::WifiMacHeader'])
register_Ns3WifiMacQueueItem_methods(root_module, root_module['ns3::WifiMacQueueItem'])
register_Ns3WifiPhy_methods(root_module, root_module['ns3::WifiPhy'])
register_Ns3WifiRemoteStationManager_methods(root_module, root_module['ns3::WifiRemoteStationManager'])
register_Ns3YansWavePhyHelper_methods(root_module, root_module['ns3::YansWavePhyHelper'])
register_Ns3YansWifiPhy_methods(root_module, root_module['ns3::YansWifiPhy'])
register_Ns3ZetaRandomVariable_methods(root_module, root_module['ns3::ZetaRandomVariable'])
register_Ns3ZipfRandomVariable_methods(root_module, root_module['ns3::ZipfRandomVariable'])
register_Ns3AmpduSubframeHeader_methods(root_module, root_module['ns3::AmpduSubframeHeader'])
register_Ns3AmsduSubframeHeader_methods(root_module, root_module['ns3::AmsduSubframeHeader'])
register_Ns3Application_methods(root_module, root_module['ns3::Application'])
register_Ns3AttributeAccessor_methods(root_module, root_module['ns3::AttributeAccessor'])
register_Ns3AttributeChecker_methods(root_module, root_module['ns3::AttributeChecker'])
register_Ns3AttributeValue_methods(root_module, root_module['ns3::AttributeValue'])
register_Ns3BlockAckManager_methods(root_module, root_module['ns3::BlockAckManager'])
register_Ns3BooleanChecker_methods(root_module, root_module['ns3::BooleanChecker'])
register_Ns3BooleanValue_methods(root_module, root_module['ns3::BooleanValue'])
register_Ns3BsmApplication_methods(root_module, root_module['ns3::BsmApplication'])
register_Ns3CallbackChecker_methods(root_module, root_module['ns3::CallbackChecker'])
register_Ns3CallbackImplBase_methods(root_module, root_module['ns3::CallbackImplBase'])
register_Ns3CallbackValue_methods(root_module, root_module['ns3::CallbackValue'])
register_Ns3Channel_methods(root_module, root_module['ns3::Channel'])
register_Ns3ChannelCoordinationListener_methods(root_module, root_module['ns3::ChannelCoordinationListener'])
register_Ns3ChannelCoordinator_methods(root_module, root_module['ns3::ChannelCoordinator'])
register_Ns3ChannelManager_methods(root_module, root_module['ns3::ChannelManager'])
register_Ns3ChannelScheduler_methods(root_module, root_module['ns3::ChannelScheduler'])
register_Ns3ConstantRandomVariable_methods(root_module, root_module['ns3::ConstantRandomVariable'])
register_Ns3CtrlBAckRequestHeader_methods(root_module, root_module['ns3::CtrlBAckRequestHeader'])
register_Ns3CtrlBAckResponseHeader_methods(root_module, root_module['ns3::CtrlBAckResponseHeader'])
register_Ns3DataRateChecker_methods(root_module, root_module['ns3::DataRateChecker'])
register_Ns3DataRateValue_methods(root_module, root_module['ns3::DataRateValue'])
register_Ns3DcaTxop_methods(root_module, root_module['ns3::DcaTxop'])
register_Ns3DcfManager_methods(root_module, root_module['ns3::DcfManager'])
register_Ns3DefaultChannelScheduler_methods(root_module, root_module['ns3::DefaultChannelScheduler'])
register_Ns3DeterministicRandomVariable_methods(root_module, root_module['ns3::DeterministicRandomVariable'])
register_Ns3DoubleValue_methods(root_module, root_module['ns3::DoubleValue'])
register_Ns3DsssParameterSet_methods(root_module, root_module['ns3::DsssParameterSet'])
register_Ns3DsssParameterSetChecker_methods(root_module, root_module['ns3::DsssParameterSetChecker'])
register_Ns3DsssParameterSetValue_methods(root_module, root_module['ns3::DsssParameterSetValue'])
register_Ns3EdcaParameterSet_methods(root_module, root_module['ns3::EdcaParameterSet'])
register_Ns3EdcaParameterSetChecker_methods(root_module, root_module['ns3::EdcaParameterSetChecker'])
register_Ns3EdcaParameterSetValue_methods(root_module, root_module['ns3::EdcaParameterSetValue'])
register_Ns3EdcaTxopN_methods(root_module, root_module['ns3::EdcaTxopN'])
register_Ns3EmpiricalRandomVariable_methods(root_module, root_module['ns3::EmpiricalRandomVariable'])
register_Ns3EmptyAttributeAccessor_methods(root_module, root_module['ns3::EmptyAttributeAccessor'])
register_Ns3EmptyAttributeChecker_methods(root_module, root_module['ns3::EmptyAttributeChecker'])
register_Ns3EmptyAttributeValue_methods(root_module, root_module['ns3::EmptyAttributeValue'])
register_Ns3EnumChecker_methods(root_module, root_module['ns3::EnumChecker'])
register_Ns3EnumValue_methods(root_module, root_module['ns3::EnumValue'])
register_Ns3ErlangRandomVariable_methods(root_module, root_module['ns3::ErlangRandomVariable'])
register_Ns3ErpInformation_methods(root_module, root_module['ns3::ErpInformation'])
register_Ns3ErpInformationChecker_methods(root_module, root_module['ns3::ErpInformationChecker'])
register_Ns3ErpInformationValue_methods(root_module, root_module['ns3::ErpInformationValue'])
register_Ns3ErrorRateModel_methods(root_module, root_module['ns3::ErrorRateModel'])
register_Ns3EventImpl_methods(root_module, root_module['ns3::EventImpl'])
register_Ns3ExponentialRandomVariable_methods(root_module, root_module['ns3::ExponentialRandomVariable'])
register_Ns3ExtendedSupportedRatesIE_methods(root_module, root_module['ns3::ExtendedSupportedRatesIE'])
register_Ns3GammaRandomVariable_methods(root_module, root_module['ns3::GammaRandomVariable'])
register_Ns3HeCapabilities_methods(root_module, root_module['ns3::HeCapabilities'])
register_Ns3HeCapabilitiesChecker_methods(root_module, root_module['ns3::HeCapabilitiesChecker'])
register_Ns3HeCapabilitiesValue_methods(root_module, root_module['ns3::HeCapabilitiesValue'])
register_Ns3HtCapabilities_methods(root_module, root_module['ns3::HtCapabilities'])
register_Ns3HtCapabilitiesChecker_methods(root_module, root_module['ns3::HtCapabilitiesChecker'])
register_Ns3HtCapabilitiesValue_methods(root_module, root_module['ns3::HtCapabilitiesValue'])
register_Ns3HtOperation_methods(root_module, root_module['ns3::HtOperation'])
register_Ns3HtOperationChecker_methods(root_module, root_module['ns3::HtOperationChecker'])
register_Ns3HtOperationValue_methods(root_module, root_module['ns3::HtOperationValue'])
register_Ns3IntegerValue_methods(root_module, root_module['ns3::IntegerValue'])
register_Ns3Ipv4_methods(root_module, root_module['ns3::Ipv4'])
register_Ns3Ipv4AddressChecker_methods(root_module, root_module['ns3::Ipv4AddressChecker'])
register_Ns3Ipv4AddressValue_methods(root_module, root_module['ns3::Ipv4AddressValue'])
register_Ns3Ipv4L3Protocol_methods(root_module, root_module['ns3::Ipv4L3Protocol'])
register_Ns3Ipv4MaskChecker_methods(root_module, root_module['ns3::Ipv4MaskChecker'])
register_Ns3Ipv4MaskValue_methods(root_module, root_module['ns3::Ipv4MaskValue'])
register_Ns3Ipv4MulticastRoute_methods(root_module, root_module['ns3::Ipv4MulticastRoute'])
register_Ns3Ipv4Route_methods(root_module, root_module['ns3::Ipv4Route'])
register_Ns3Ipv4RoutingProtocol_methods(root_module, root_module['ns3::Ipv4RoutingProtocol'])
register_Ns3Ipv6_methods(root_module, root_module['ns3::Ipv6'])
register_Ns3Ipv6AddressChecker_methods(root_module, root_module['ns3::Ipv6AddressChecker'])
register_Ns3Ipv6AddressValue_methods(root_module, root_module['ns3::Ipv6AddressValue'])
register_Ns3Ipv6L3Protocol_methods(root_module, root_module['ns3::Ipv6L3Protocol'])
register_Ns3Ipv6PmtuCache_methods(root_module, root_module['ns3::Ipv6PmtuCache'])
register_Ns3Ipv6PrefixChecker_methods(root_module, root_module['ns3::Ipv6PrefixChecker'])
register_Ns3Ipv6PrefixValue_methods(root_module, root_module['ns3::Ipv6PrefixValue'])
register_Ns3LogNormalRandomVariable_methods(root_module, root_module['ns3::LogNormalRandomVariable'])
register_Ns3Mac48AddressChecker_methods(root_module, root_module['ns3::Mac48AddressChecker'])
register_Ns3Mac48AddressValue_methods(root_module, root_module['ns3::Mac48AddressValue'])
register_Ns3MacLow_methods(root_module, root_module['ns3::MacLow'])
register_Ns3MgtBeaconHeader_methods(root_module, root_module['ns3::MgtBeaconHeader'])
register_Ns3MobilityModel_methods(root_module, root_module['ns3::MobilityModel'])
register_Ns3MpduAggregator_methods(root_module, root_module['ns3::MpduAggregator'])
register_Ns3MsduAggregator_methods(root_module, root_module['ns3::MsduAggregator'])
register_Ns3NetDevice_methods(root_module, root_module['ns3::NetDevice'])
register_Ns3NixVector_methods(root_module, root_module['ns3::NixVector'])
register_Ns3Node_methods(root_module, root_module['ns3::Node'])
register_Ns3NormalRandomVariable_methods(root_module, root_module['ns3::NormalRandomVariable'])
register_Ns3ObjectFactoryChecker_methods(root_module, root_module['ns3::ObjectFactoryChecker'])
register_Ns3ObjectFactoryValue_methods(root_module, root_module['ns3::ObjectFactoryValue'])
register_Ns3OrganizationIdentifierChecker_methods(root_module, root_module['ns3::OrganizationIdentifierChecker'])
register_Ns3OrganizationIdentifierValue_methods(root_module, root_module['ns3::OrganizationIdentifierValue'])
register_Ns3OutputStreamWrapper_methods(root_module, root_module['ns3::OutputStreamWrapper'])
register_Ns3Packet_methods(root_module, root_module['ns3::Packet'])
register_Ns3ParetoRandomVariable_methods(root_module, root_module['ns3::ParetoRandomVariable'])
register_Ns3PointerChecker_methods(root_module, root_module['ns3::PointerChecker'])
register_Ns3PointerValue_methods(root_module, root_module['ns3::PointerValue'])
register_Ns3Queue__Ns3WifiMacQueueItem_methods(root_module, root_module['ns3::Queue< ns3::WifiMacQueueItem >'])
register_Ns3RegularWifiMac_methods(root_module, root_module['ns3::RegularWifiMac'])
register_Ns3Ssid_methods(root_module, root_module['ns3::Ssid'])
register_Ns3SsidChecker_methods(root_module, root_module['ns3::SsidChecker'])
register_Ns3SsidValue_methods(root_module, root_module['ns3::SsidValue'])
register_Ns3StringChecker_methods(root_module, root_module['ns3::StringChecker'])
register_Ns3StringValue_methods(root_module, root_module['ns3::StringValue'])
register_Ns3SupportedRates_methods(root_module, root_module['ns3::SupportedRates'])
register_Ns3TimeValue_methods(root_module, root_module['ns3::TimeValue'])
register_Ns3TypeIdChecker_methods(root_module, root_module['ns3::TypeIdChecker'])
register_Ns3TypeIdValue_methods(root_module, root_module['ns3::TypeIdValue'])
register_Ns3UintegerValue_methods(root_module, root_module['ns3::UintegerValue'])
register_Ns3Vector2DChecker_methods(root_module, root_module['ns3::Vector2DChecker'])
register_Ns3Vector2DValue_methods(root_module, root_module['ns3::Vector2DValue'])
register_Ns3Vector3DChecker_methods(root_module, root_module['ns3::Vector3DChecker'])
register_Ns3Vector3DValue_methods(root_module, root_module['ns3::Vector3DValue'])
register_Ns3VhtCapabilities_methods(root_module, root_module['ns3::VhtCapabilities'])
register_Ns3VhtCapabilitiesChecker_methods(root_module, root_module['ns3::VhtCapabilitiesChecker'])
register_Ns3VhtCapabilitiesValue_methods(root_module, root_module['ns3::VhtCapabilitiesValue'])
register_Ns3VhtOperation_methods(root_module, root_module['ns3::VhtOperation'])
register_Ns3VhtOperationChecker_methods(root_module, root_module['ns3::VhtOperationChecker'])
register_Ns3VhtOperationValue_methods(root_module, root_module['ns3::VhtOperationValue'])
register_Ns3WaveMacLow_methods(root_module, root_module['ns3::WaveMacLow'])
register_Ns3WaveNetDevice_methods(root_module, root_module['ns3::WaveNetDevice'])
register_Ns3WifiMacQueue_methods(root_module, root_module['ns3::WifiMacQueue'])
register_Ns3WifiModeChecker_methods(root_module, root_module['ns3::WifiModeChecker'])
register_Ns3WifiModeValue_methods(root_module, root_module['ns3::WifiModeValue'])
register_Ns3YansWifiChannel_methods(root_module, root_module['ns3::YansWifiChannel'])
register_Ns3AddressChecker_methods(root_module, root_module['ns3::AddressChecker'])
register_Ns3AddressValue_methods(root_module, root_module['ns3::AddressValue'])
register_Ns3CallbackImpl__Bool_Ns3Ptr__lt__const_ns3Packet__gt___Const_ns3Address___amp___Unsigned_int_Unsigned_int_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, root_module['ns3::CallbackImpl< bool, ns3::Ptr<const ns3::Packet>, const ns3::Address &, unsigned int, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >'])
register_Ns3CallbackImpl__Bool_Ns3Ptr__lt__ns3NetDevice__gt___Ns3Ptr__lt__const_ns3Packet__gt___Unsigned_short_Const_ns3Address___amp___Const_ns3Address___amp___Ns3NetDevicePacketType_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, root_module['ns3::CallbackImpl< bool, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<const ns3::Packet>, unsigned short, const ns3::Address &, const ns3::Address &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >'])
register_Ns3CallbackImpl__Bool_Ns3Ptr__lt__ns3NetDevice__gt___Ns3Ptr__lt__const_ns3Packet__gt___Unsigned_short_Const_ns3Address___amp___Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, root_module['ns3::CallbackImpl< bool, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<const ns3::Packet>, unsigned short, const ns3::Address &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >'])
register_Ns3CallbackImpl__Bool_Ns3Ptr__lt__ns3Socket__gt___Const_ns3Address___amp___Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, root_module['ns3::CallbackImpl< bool, ns3::Ptr<ns3::Socket>, const ns3::Address &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >'])
register_Ns3CallbackImpl__Bool_Ns3Ptr__lt__ns3WifiMac__gt___Const_ns3OrganizationIdentifier___amp___Ns3Ptr__lt__const_ns3Packet__gt___Const_ns3Address___amp___Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, root_module['ns3::CallbackImpl< bool, ns3::Ptr<ns3::WifiMac>, const ns3::OrganizationIdentifier &, ns3::Ptr<const ns3::Packet>, const ns3::Address &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >'])
register_Ns3CallbackImpl__Ns3ObjectBase___star___Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, root_module['ns3::CallbackImpl< ns3::ObjectBase *, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >'])
register_Ns3CallbackImpl__Void_Const_ns3Ipv4Header___amp___Ns3Ptr__lt__const_ns3Packet__gt___Ns3Ipv4L3ProtocolDropReason_Ns3Ptr__lt__ns3Ipv4__gt___Unsigned_int_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, root_module['ns3::CallbackImpl< void, const ns3::Ipv4Header &, ns3::Ptr<const ns3::Packet>, ns3::Ipv4L3Protocol::DropReason, ns3::Ptr<ns3::Ipv4>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty >'])
register_Ns3CallbackImpl__Void_Const_ns3Ipv4Header___amp___Ns3Ptr__lt__const_ns3Packet__gt___Unsigned_int_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, root_module['ns3::CallbackImpl< void, const ns3::Ipv4Header &, ns3::Ptr<const ns3::Packet>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >'])
register_Ns3CallbackImpl__Void_Const_ns3Ipv6Header___amp___Ns3Ptr__lt__const_ns3Packet__gt___Ns3Ipv6L3ProtocolDropReason_Ns3Ptr__lt__ns3Ipv6__gt___Unsigned_int_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, root_module['ns3::CallbackImpl< void, const ns3::Ipv6Header &, ns3::Ptr<const ns3::Packet>, ns3::Ipv6L3Protocol::DropReason, ns3::Ptr<ns3::Ipv6>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty >'])
register_Ns3CallbackImpl__Void_Const_ns3Ipv6Header___amp___Ns3Ptr__lt__const_ns3Packet__gt___Unsigned_int_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, root_module['ns3::CallbackImpl< void, const ns3::Ipv6Header &, ns3::Ptr<const ns3::Packet>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >'])
register_Ns3CallbackImpl__Void_Const_ns3WifiMacHeader___amp___Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, root_module['ns3::CallbackImpl< void, const ns3::WifiMacHeader &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >'])
register_Ns3CallbackImpl__Void_Ns3Address_Ns3Address_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, root_module['ns3::CallbackImpl< void, ns3::Address, ns3::Address, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >'])
register_Ns3CallbackImpl__Void_Ns3Mac48Address_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, root_module['ns3::CallbackImpl< void, ns3::Mac48Address, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >'])
register_Ns3CallbackImpl__Void_Ns3Ptr__lt__const_ns3MobilityModel__gt___Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, root_module['ns3::CallbackImpl< void, ns3::Ptr<const ns3::MobilityModel>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >'])
register_Ns3CallbackImpl__Void_Ns3Ptr__lt__const_ns3Packet__gt___Ns3Ptr__lt__ns3Ipv4__gt___Unsigned_int_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, root_module['ns3::CallbackImpl< void, ns3::Ptr<const ns3::Packet>, ns3::Ptr<ns3::Ipv4>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >'])
register_Ns3CallbackImpl__Void_Ns3Ptr__lt__const_ns3Packet__gt___Ns3Ptr__lt__ns3Ipv6__gt___Unsigned_int_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, root_module['ns3::CallbackImpl< void, ns3::Ptr<const ns3::Packet>, ns3::Ptr<ns3::Ipv6>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >'])
register_Ns3CallbackImpl__Void_Ns3Ptr__lt__const_ns3Packet__gt___Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, root_module['ns3::CallbackImpl< void, ns3::Ptr<const ns3::Packet>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >'])
register_Ns3CallbackImpl__Void_Ns3Ptr__lt__const_ns3Packet__gt___Unsigned_short_Ns3WifiTxVector_Ns3MpduInfo_Ns3SignalNoiseDbm_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, root_module['ns3::CallbackImpl< void, ns3::Ptr<const ns3::Packet>, unsigned short, ns3::WifiTxVector, ns3::MpduInfo, ns3::SignalNoiseDbm, ns3::empty, ns3::empty, ns3::empty, ns3::empty >'])
register_Ns3CallbackImpl__Void_Ns3Ptr__lt__const_ns3Packet__gt___Unsigned_short_Ns3WifiTxVector_Ns3MpduInfo_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, root_module['ns3::CallbackImpl< void, ns3::Ptr<const ns3::Packet>, unsigned short, ns3::WifiTxVector, ns3::MpduInfo, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >'])
register_Ns3CallbackImpl__Void_Ns3Ptr__lt__const_ns3WifiMacQueueItem__gt___Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, root_module['ns3::CallbackImpl< void, ns3::Ptr<const ns3::WifiMacQueueItem>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >'])
register_Ns3CallbackImpl__Void_Ns3Ptr__lt__ns3NetDevice__gt___Ns3Ptr__lt__const_ns3Packet__gt___Unsigned_short_Const_ns3Address___amp___Const_ns3Address___amp___Ns3NetDevicePacketType_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, root_module['ns3::CallbackImpl< void, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<const ns3::Packet>, unsigned short, const ns3::Address &, const ns3::Address &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >'])
register_Ns3CallbackImpl__Void_Ns3Ptr__lt__ns3NetDevice__gt___Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, root_module['ns3::CallbackImpl< void, ns3::Ptr<ns3::NetDevice>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >'])
register_Ns3CallbackImpl__Void_Ns3Ptr__lt__ns3Packet__gt___Const_ns3WifiMacHeader___star___Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, root_module['ns3::CallbackImpl< void, ns3::Ptr<ns3::Packet>, const ns3::WifiMacHeader *, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >'])
register_Ns3CallbackImpl__Void_Ns3Ptr__lt__ns3Socket__gt___Const_ns3Address___amp___Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, root_module['ns3::CallbackImpl< void, ns3::Ptr<ns3::Socket>, const ns3::Address &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >'])
register_Ns3CallbackImpl__Void_Ns3Ptr__lt__ns3Socket__gt___Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, root_module['ns3::CallbackImpl< void, ns3::Ptr<ns3::Socket>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >'])
register_Ns3CallbackImpl__Void_Ns3Ptr__lt__ns3Socket__gt___Unsigned_int_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, root_module['ns3::CallbackImpl< void, ns3::Ptr<ns3::Socket>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >'])
register_Ns3CallbackImpl__Void_Ns3Time_Ns3Time_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, root_module['ns3::CallbackImpl< void, ns3::Time, ns3::Time, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >'])
register_Ns3CallbackImpl__Void_Unsigned_int_Unsigned_int_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, root_module['ns3::CallbackImpl< void, unsigned int, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >'])
register_Ns3OcbWifiMac_methods(root_module, root_module['ns3::OcbWifiMac'])
register_Ns3HashImplementation_methods(root_module, root_module['ns3::Hash::Implementation'])
register_Ns3HashFunctionFnv1a_methods(root_module, root_module['ns3::Hash::Function::Fnv1a'])
register_Ns3HashFunctionHash32_methods(root_module, root_module['ns3::Hash::Function::Hash32'])
register_Ns3HashFunctionHash64_methods(root_module, root_module['ns3::Hash::Function::Hash64'])
register_Ns3HashFunctionMurmur3_methods(root_module, root_module['ns3::Hash::Function::Murmur3'])
return |
def batchnorm3d_to_instancenorm3d(model):
conversion_count = 0
for (name, module) in reversed(model._modules.items()):
if (len(list(module.children())) > 0):
(model._modules[name], num_converted) = batchnorm3d_to_instancenorm3d(module)
conversion_count += num_converted
if isinstance(module, nn.BatchNorm3d):
layer_new = nn.InstanceNorm3d(module.num_features, eps=module.eps, momentum=module.momentum, affine=module.affine, track_running_stats=False)
layer_new.weight = module.weight
layer_new.bias = module.bias
model._modules[name] = layer_new
conversion_count += 1
return (model, conversion_count) |
def run_batch(cur_batch, model):
mean = np.array([0.485, 0.456, 0.406]).reshape(1, 3, 1, 1)
std = np.array([0.229, 0.224, 0.224]).reshape(1, 3, 1, 1)
image_batch = np.concatenate(cur_batch, 0).astype(np.float32)
image_batch = (((image_batch / 255.0) - mean) / std)
image_batch = torch.FloatTensor(image_batch).cuda()
image_batch = torch.autograd.Variable(image_batch, volatile=True)
feats = model(image_batch)
feats = feats.data.cpu().clone().numpy()
return feats |
def test_interpolate_as():
source = torch.rand((1, 5, 4, 4))
target = torch.rand((1, 1, 16, 16))
result = interpolate_as(source, target)
assert (result.shape == torch.Size((1, 5, 16, 16)))
result = interpolate_as(source, target.squeeze(0))
assert (result.shape == torch.Size((1, 5, 16, 16)))
result = interpolate_as(source.squeeze(0), target)
assert (result.shape == torch.Size((5, 16, 16)))
target = np.random.rand(16, 16)
result = interpolate_as(source.squeeze(0), target)
assert (result.shape == torch.Size((5, 16, 16))) |
(for_each_device=True)
def cunnex(strFunction):
return cupy.cuda.compile_with_cache(globals()[strFunction]).get_function(strFunction) |
class DatasetJsonifier(ABC):
input_dir: str
name: str
split: str
data: Sequence[Any] = None
def load_raw_data(self):
raise
def export_to_json(self, output_dir, examples_per_shard: Optional[int]=None):
if (not self.data):
print('[WARNING] no data to write; returning.')
return
if self.split:
fp = os.path.join(output_dir, (self.name + f'-{self.split}.json'))
else:
fp = os.path.join(output_dir, (self.name + '.json'))
print(f'[INFO] writing {len(self.data)} records to {fp}')
with open(fp, 'w') as f:
for elem in self.data:
f.write((json.dumps(elem) + '\n'))
return |
def hessian_vector_product(f, params):
g = flat_grad(f, params)
x = tf.placeholder(tf.float32, shape=g.shape)
return (x, flat_grad(tf.reduce_sum((g * x)), params)) |
def test_get_n_splits_BlockBootstrap() -> None:
cv = BlockBootstrap(n_resamplings=3)
assert (cv.get_n_splits() == 3) |
def project(bipartite):
nodes_papers = {n for (n, d) in bipartite.nodes(data=True) if (d['bipartite'] == 0)}
nodes_authors = (set(bipartite) - nodes_papers)
graph_papers = nxb.weighted_projected_graph(bipartite, nodes_papers)
graph_authors = nxb.weighted_projected_graph(bipartite, nodes_authors)
print(f'projection: {graph_papers.number_of_nodes():,} papers and {graph_papers.number_of_edges():,} edges')
print(f'projection: {graph_authors.number_of_nodes():,} authors and {graph_authors.number_of_edges():,} edges')
return (graph_papers, graph_authors) |
_utils.test(require=ti.extension.sparse)
def test_pointer_is_active():
x = ti.field(ti.f32)
s = ti.field(ti.i32)
n = 128
ptr = ti.root.pointer(ti.i, n)
ptr.dense(ti.i, n).place(x)
ti.root.place(s)
def func():
for i in range((n * n)):
s[None] += ti.is_active(ptr, ti.rescale_index(x, ptr, [i]))
x[0] = 1
x[127] = 1
x[256] = 1
func()
assert (s[None] == 256) |
def load_model(model_path, gpuid=None):
model = load(os.path.join(model_path, 'outer_model.est'))
if (gpuid == None):
gpuid = model.gpuid
else:
gpuid = str(gpuid)
os.environ['CUDA_VISIBLE_DEVICES'] = gpuid
model.gpuid = gpuid
model._model = load_tf_model(os.path.join(model_path, 'inner_model.h5'))
return model |
def setUpModule():
if (not (CAFFE_FOUND and os.path.exists('data/testdata/caffe_translator'))):
return
caffenet = caffe_pb2.NetParameter()
caffenet_pretrained = caffe_pb2.NetParameter()
with open('data/testdata/caffe_translator/deploy.prototxt') as f:
text_format.Merge(f.read(), caffenet)
with open('data/testdata/caffe_translator/bvlc_reference_caffenet.caffemodel') as f:
caffenet_pretrained.ParseFromString(f.read())
for remove_legacy_pad in [True, False]:
(net, pretrained_params) = caffe_translator.TranslateModel(caffenet, caffenet_pretrained, is_test=True, remove_legacy_pad=remove_legacy_pad)
with open('data/testdata/caffe_translator/bvlc_reference_caffenet.translatedmodel', 'w') as fid:
fid.write(str(net))
for param in pretrained_params.protos:
workspace.FeedBlob(param.name, utils.Caffe2TensorToNumpyArray(param))
data = np.load('data/testdata/caffe_translator/data_dump.npy').astype(np.float32)
workspace.FeedBlob('data', data)
workspace.RunNetOnce(net.SerializeToString()) |
def _make_timedelta(value):
if (not isinstance(value, timedelta)):
return timedelta(seconds=value)
return value |
def resolve(module_name, dotted_path):
if (module_name in sys.modules):
mod = sys.modules[module_name]
else:
mod = __import__(module_name)
if (dotted_path is None):
result = mod
else:
parts = dotted_path.split('.')
result = getattr(mod, parts.pop(0))
for p in parts:
result = getattr(result, p)
return result |
class TestCodeWriter(CythonTest):
def t(self, codestr):
self.assertCode(codestr, self.fragment(codestr).root)
def test_print(self):
self.t(u'\n print x, y\n print x + y ** 2\n print x, y, z,\n ')
def test_if(self):
self.t(u'if x:\n pass')
def test_ifelifelse(self):
self.t(u'\n if x:\n pass\n elif y:\n pass\n elif z + 34 ** 34 - 2:\n pass\n else:\n pass\n ')
def test_def(self):
self.t(u'\n def f(x, y, z):\n pass\n def f(x = 34, y = 54, z):\n pass\n ')
def test_longness_and_signedness(self):
self.t(u'def f(unsigned long long long long long int y):\n pass')
def test_signed_short(self):
self.t(u'def f(signed short int y):\n pass')
def test_typed_args(self):
self.t(u'def f(int x, unsigned long int y):\n pass')
def test_cdef_var(self):
self.t(u'\n cdef int hello\n cdef int hello = 4, x = 3, y, z\n ')
def test_for_loop(self):
self.t(u'\n for x, y, z in f(g(h(34) * 2) + 23):\n print x, y, z\n else:\n print 43\n ')
def test_inplace_assignment(self):
self.t(u'x += 43')
def test_attribute(self):
self.t(u'a.x') |
def power_spectrum_multipoles(input_array, kbins=10, box_dims=None, los_axis=0, output=['P0', 'P2', 'P4', 'nmodes'], exclude_zero_modes=False):
assert ((los_axis >= 0) and (los_axis <= len(input_array.shape)))
box_dims = _get_dims(box_dims, input_array.shape)
ps = power_spectrum_nd(input_array, box_dims)
(k_comp, k) = _get_k(input_array, box_dims)
kbins = _get_kbins(kbins, box_dims, k)
dk = ((kbins[1:] - kbins[:(- 1)]) / 2.0)
mu = _get_mu(k_comp, k, los_axis)
if exclude_zero_modes:
good_idx = _get_nonzero_idx(ps.shape, los_axis)
else:
good_idx = np.ones_like(ps)
if ('P0' in output):
P0 = np.ones_like(mu)
if ('P2' in output):
P2 = (0.5 * ((3.0 * (mu ** 2)) - 1.0))
if ('P4' in output):
P4 = ((4.375 * ((mu ** 2) - 0.115587)) * ((mu ** 2) - 0.741556))
n_kbins = (len(kbins) - 1)
multipoles = {}
if ('P0' in output):
multipoles['P0'] = np.zeros(n_kbins)
if ('P2' in output):
multipoles['P2'] = np.zeros(n_kbins)
if ('P4' in output):
multipoles['P4'] = np.zeros(n_kbins)
nmodes = np.zeros(n_kbins)
for i in range(n_kbins):
kmin = kbins[i]
kmax = kbins[(i + 1)]
idx = get_eval()('(k >= kmin) & (k < kmax)')
idx *= good_idx
nmodes[i] = len(np.nonzero(idx))
if ('P0' in output):
multipoles['P0'][i] = (np.sum((ps[idx] * P0[idx])) / np.sum((P0[idx] ** 2)))
if ('P2' in output):
multipoles['P2'][i] = (np.sum((ps[idx] * P2[idx])) / np.sum((P2[idx] ** 2)))
if ('P4' in output):
multipoles['P4'][i] = (np.sum((ps[idx] * P4[idx])) / np.sum((P4[idx] ** 2)))
multipoles['nmodes'] = nmodes
return (multipoles, (kbins[:(- 1)] + dk)) |
def dump_metrics(file_path: str, metrics, log: bool=False) -> None:
metrics_json = json.dumps(metrics, indent=2)
with open(file_path, 'w') as metrics_file:
metrics_file.write(metrics_json)
if log:
logger.info('Metrics: %s', metrics_json) |
class CSharp4Listener(ParseTreeListener):
def enterNamespace_name(self, ctx):
pass
def exitNamespace_name(self, ctx):
pass
def enterType121_name(self, ctx):
pass
def exitType121_name(self, ctx):
pass
def enterIdentifier(self, ctx):
pass
def exitIdentifier(self, ctx):
pass
def enterNamespace_or_type121_name(self, ctx):
pass
def exitNamespace_or_type121_name(self, ctx):
pass
def enterType121_argument_list_opt(self, ctx):
pass
def exitType121_argument_list_opt(self, ctx):
pass
def enterType121(self, ctx):
pass
def exitType121(self, ctx):
pass
def enterBase_type121(self, ctx):
pass
def exitBase_type121(self, ctx):
pass
def enterSimple_type121(self, ctx):
pass
def exitSimple_type121(self, ctx):
pass
def enterNumeric_type121(self, ctx):
pass
def exitNumeric_type121(self, ctx):
pass
def enterIntegral_type121(self, ctx):
pass
def exitIntegral_type121(self, ctx):
pass
def enterFloating_point_type121(self, ctx):
pass
def exitFloating_point_type121(self, ctx):
pass
def enterNullable_type121(self, ctx):
pass
def exitNullable_type121(self, ctx):
pass
def enterNon_nullable_value_type121(self, ctx):
pass
def exitNon_nullable_value_type121(self, ctx):
pass
def enterReference_type121(self, ctx):
pass
def exitReference_type121(self, ctx):
pass
def enterClass_type121(self, ctx):
pass
def exitClass_type121(self, ctx):
pass
def enterInterface_type121(self, ctx):
pass
def exitInterface_type121(self, ctx):
pass
def enterDelegate_type121(self, ctx):
pass
def exitDelegate_type121(self, ctx):
pass
def enterType121_argument_list(self, ctx):
pass
def exitType121_argument_list(self, ctx):
pass
def enterType121_arguments(self, ctx):
pass
def exitType121_arguments(self, ctx):
pass
def enterType121_argument(self, ctx):
pass
def exitType121_argument(self, ctx):
pass
def enterType121_void(self, ctx):
pass
def exitType121_void(self, ctx):
pass
def enterVariable_reference(self, ctx):
pass
def exitVariable_reference(self, ctx):
pass
def enterArgument_list(self, ctx):
pass
def exitArgument_list(self, ctx):
pass
def enterArgument(self, ctx):
pass
def exitArgument(self, ctx):
pass
def enterArgument_name(self, ctx):
pass
def exitArgument_name(self, ctx):
pass
def enterArgument_value(self, ctx):
pass
def exitArgument_value(self, ctx):
pass
def enterPrimary_expression(self, ctx):
pass
def exitPrimary_expression(self, ctx):
pass
def enterPrimary_expression_start(self, ctx):
pass
def exitPrimary_expression_start(self, ctx):
pass
def enterBracket_expression(self, ctx):
pass
def exitBracket_expression(self, ctx):
pass
def enterSimple_name(self, ctx):
pass
def exitSimple_name(self, ctx):
pass
def enterParenthesized_expression(self, ctx):
pass
def exitParenthesized_expression(self, ctx):
pass
def enterMember_access(self, ctx):
pass
def exitMember_access(self, ctx):
pass
def enterPredefined_type121(self, ctx):
pass
def exitPredefined_type121(self, ctx):
pass
def enterExpression_list(self, ctx):
pass
def exitExpression_list(self, ctx):
pass
def enterThis_access(self, ctx):
pass
def exitThis_access(self, ctx):
pass
def enterBase_access(self, ctx):
pass
def exitBase_access(self, ctx):
pass
def enterObject_creation_expression(self, ctx):
pass
def exitObject_creation_expression(self, ctx):
pass
def enterObject_or_collection_initializer(self, ctx):
pass
def exitObject_or_collection_initializer(self, ctx):
pass
def enterObject_initializer(self, ctx):
pass
def exitObject_initializer(self, ctx):
pass
def enterMember_initializer_list(self, ctx):
pass
def exitMember_initializer_list(self, ctx):
pass
def enterMember_initializer(self, ctx):
pass
def exitMember_initializer(self, ctx):
pass
def enterInitializer_value(self, ctx):
pass
def exitInitializer_value(self, ctx):
pass
def enterCollection_initializer(self, ctx):
pass
def exitCollection_initializer(self, ctx):
pass
def enterElement_initializer_list(self, ctx):
pass
def exitElement_initializer_list(self, ctx):
pass
def enterElement_initializer(self, ctx):
pass
def exitElement_initializer(self, ctx):
pass
def enterArray_creation_expression(self, ctx):
pass
def exitArray_creation_expression(self, ctx):
pass
def enterDelegate_creation_expression(self, ctx):
pass
def exitDelegate_creation_expression(self, ctx):
pass
def enterAnonymous_object_creation_expression(self, ctx):
pass
def exitAnonymous_object_creation_expression(self, ctx):
pass
def enterAnonymous_object_initializer(self, ctx):
pass
def exitAnonymous_object_initializer(self, ctx):
pass
def enterMember_declarator_list(self, ctx):
pass
def exitMember_declarator_list(self, ctx):
pass
def enterMember_declarator(self, ctx):
pass
def exitMember_declarator(self, ctx):
pass
def enterType121of_expression(self, ctx):
pass
def exitType121of_expression(self, ctx):
pass
def enterUnbound_type121_name(self, ctx):
pass
def exitUnbound_type121_name(self, ctx):
pass
def enterGeneric_dimension_specifier(self, ctx):
pass
def exitGeneric_dimension_specifier(self, ctx):
pass
def enterCommas(self, ctx):
pass
def exitCommas(self, ctx):
pass
def enterChecked_expression(self, ctx):
pass
def exitChecked_expression(self, ctx):
pass
def enterUnchecked_expression(self, ctx):
pass
def exitUnchecked_expression(self, ctx):
pass
def enterDefault_value_expression(self, ctx):
pass
def exitDefault_value_expression(self, ctx):
pass
def enterUnary_expression(self, ctx):
pass
def exitUnary_expression(self, ctx):
pass
def enterScan_for_cast_generic_precedence(self, ctx):
pass
def exitScan_for_cast_generic_precedence(self, ctx):
pass
def enterCast_disambiguation_token(self, ctx):
pass
def exitCast_disambiguation_token(self, ctx):
pass
def enterPre_increment_expression(self, ctx):
pass
def exitPre_increment_expression(self, ctx):
pass
def enterPre_decrement_expression(self, ctx):
pass
def exitPre_decrement_expression(self, ctx):
pass
def enterCast_expression(self, ctx):
pass
def exitCast_expression(self, ctx):
pass
def enterMultiplicative_expression(self, ctx):
pass
def exitMultiplicative_expression(self, ctx):
pass
def enterAdditive_expression(self, ctx):
pass
def exitAdditive_expression(self, ctx):
pass
def enterShift_expression(self, ctx):
pass
def exitShift_expression(self, ctx):
pass
def enterRelational_expression(self, ctx):
pass
def exitRelational_expression(self, ctx):
pass
def enterScan_for_shift_generic_precedence(self, ctx):
pass
def exitScan_for_shift_generic_precedence(self, ctx):
pass
def enterShift_disambiguation_token(self, ctx):
pass
def exitShift_disambiguation_token(self, ctx):
pass
def enterIstype121(self, ctx):
pass
def exitIstype121(self, ctx):
pass
def enterIs_disambiguation_token(self, ctx):
pass
def exitIs_disambiguation_token(self, ctx):
pass
def enterEquality_expression(self, ctx):
pass
def exitEquality_expression(self, ctx):
pass
def enterAnd_expression(self, ctx):
pass
def exitAnd_expression(self, ctx):
pass
def enterExclusive_or_expression(self, ctx):
pass
def exitExclusive_or_expression(self, ctx):
pass
def enterInclusive_or_expression(self, ctx):
pass
def exitInclusive_or_expression(self, ctx):
pass
def enterConditional_and_expression(self, ctx):
pass
def exitConditional_and_expression(self, ctx):
pass
def enterConditional_or_expression(self, ctx):
pass
def exitConditional_or_expression(self, ctx):
pass
def enterNull_coalescing_expression(self, ctx):
pass
def exitNull_coalescing_expression(self, ctx):
pass
def enterConditional_expression(self, ctx):
pass
def exitConditional_expression(self, ctx):
pass
def enterLambda_expression(self, ctx):
pass
def exitLambda_expression(self, ctx):
pass
def enterAnonymous_method_expression(self, ctx):
pass
def exitAnonymous_method_expression(self, ctx):
pass
def enterAnonymous_function_signature(self, ctx):
pass
def exitAnonymous_function_signature(self, ctx):
pass
def enterExplicit_anonymous_function_signature(self, ctx):
pass
def exitExplicit_anonymous_function_signature(self, ctx):
pass
def enterExplicit_anonymous_function_parameter_list(self, ctx):
pass
def exitExplicit_anonymous_function_parameter_list(self, ctx):
pass
def enterExplicit_anonymous_function_parameter(self, ctx):
pass
def exitExplicit_anonymous_function_parameter(self, ctx):
pass
def enterAnonymous_function_parameter_modifier(self, ctx):
pass
def exitAnonymous_function_parameter_modifier(self, ctx):
pass
def enterImplicit_anonymous_function_signature(self, ctx):
pass
def exitImplicit_anonymous_function_signature(self, ctx):
pass
def enterImplicit_anonymous_function_parameter_list(self, ctx):
pass
def exitImplicit_anonymous_function_parameter_list(self, ctx):
pass
def enterImplicit_anonymous_function_parameter(self, ctx):
pass
def exitImplicit_anonymous_function_parameter(self, ctx):
pass
def enterAnonymous_function_body(self, ctx):
pass
def exitAnonymous_function_body(self, ctx):
pass
def enterQuery_expression(self, ctx):
pass
def exitQuery_expression(self, ctx):
pass
def enterFrom_clause(self, ctx):
pass
def exitFrom_clause(self, ctx):
pass
def enterQuery_body(self, ctx):
pass
def exitQuery_body(self, ctx):
pass
def enterQuery_body_clauses(self, ctx):
pass
def exitQuery_body_clauses(self, ctx):
pass
def enterQuery_body_clause(self, ctx):
pass
def exitQuery_body_clause(self, ctx):
pass
def enterLet_clause(self, ctx):
pass
def exitLet_clause(self, ctx):
pass
def enterWhere_clause(self, ctx):
pass
def exitWhere_clause(self, ctx):
pass
def enterJoin_clause(self, ctx):
pass
def exitJoin_clause(self, ctx):
pass
def enterJoin_into_clause(self, ctx):
pass
def exitJoin_into_clause(self, ctx):
pass
def enterCombined_join_clause(self, ctx):
pass
def exitCombined_join_clause(self, ctx):
pass
def enterOrderby_clause(self, ctx):
pass
def exitOrderby_clause(self, ctx):
pass
def enterOrderings(self, ctx):
pass
def exitOrderings(self, ctx):
pass
def enterOrdering(self, ctx):
pass
def exitOrdering(self, ctx):
pass
def enterOrdering_direction(self, ctx):
pass
def exitOrdering_direction(self, ctx):
pass
def enterSelect_or_group_clause(self, ctx):
pass
def exitSelect_or_group_clause(self, ctx):
pass
def enterSelect_clause(self, ctx):
pass
def exitSelect_clause(self, ctx):
pass
def enterGroup_clause(self, ctx):
pass
def exitGroup_clause(self, ctx):
pass
def enterQuery_continuation(self, ctx):
pass
def exitQuery_continuation(self, ctx):
pass
def enterAssignment(self, ctx):
pass
def exitAssignment(self, ctx):
pass
def enterAssignment_operator(self, ctx):
pass
def exitAssignment_operator(self, ctx):
pass
def enterExpression(self, ctx):
pass
def exitExpression(self, ctx):
pass
def enterNon_assignment_expression(self, ctx):
pass
def exitNon_assignment_expression(self, ctx):
pass
def enterConstant_expression(self, ctx):
pass
def exitConstant_expression(self, ctx):
pass
def enterBoolean_expression(self, ctx):
pass
def exitBoolean_expression(self, ctx):
pass
def enterStatement(self, ctx):
pass
def exitStatement(self, ctx):
pass
def enterEmbedded_statement(self, ctx):
pass
def exitEmbedded_statement(self, ctx):
pass
def enterSimple_embedded_statement(self, ctx):
pass
def exitSimple_embedded_statement(self, ctx):
pass
def enterBlock(self, ctx):
pass
def exitBlock(self, ctx):
pass
def enterStatement_list(self, ctx):
pass
def exitStatement_list(self, ctx):
pass
def enterEmpty_statement(self, ctx):
pass
def exitEmpty_statement(self, ctx):
pass
def enterLabeled_statement(self, ctx):
pass
def exitLabeled_statement(self, ctx):
pass
def enterDeclaration_statement(self, ctx):
pass
def exitDeclaration_statement(self, ctx):
pass
def enterLocal_variable_declaration(self, ctx):
pass
def exitLocal_variable_declaration(self, ctx):
pass
def enterLocal_variable_type121(self, ctx):
pass
def exitLocal_variable_type121(self, ctx):
pass
def enterLocal_variable_declarators(self, ctx):
pass
def exitLocal_variable_declarators(self, ctx):
pass
def enterLocal_variable_declarator(self, ctx):
pass
def exitLocal_variable_declarator(self, ctx):
pass
def enterLocal_variable_initializer(self, ctx):
pass
def exitLocal_variable_initializer(self, ctx):
pass
def enterLocal_constant_declaration(self, ctx):
pass
def exitLocal_constant_declaration(self, ctx):
pass
def enterExpression_statement(self, ctx):
pass
def exitExpression_statement(self, ctx):
pass
def enterStatement_expression(self, ctx):
pass
def exitStatement_expression(self, ctx):
pass
def enterSelection_statement(self, ctx):
pass
def exitSelection_statement(self, ctx):
pass
def enterIfBodyBlock(self, ctx):
pass
def exitIfBodyBlock(self, ctx):
pass
def enterIfBodySingle(self, ctx):
pass
def exitIfBodySingle(self, ctx):
pass
def enterIf_statement(self, ctx):
pass
def exitIf_statement(self, ctx):
pass
def enterSwitch_statement(self, ctx):
pass
def exitSwitch_statement(self, ctx):
pass
def enterSwitch_block(self, ctx):
pass
def exitSwitch_block(self, ctx):
pass
def enterSwitch_sections(self, ctx):
pass
def exitSwitch_sections(self, ctx):
pass
def enterSwitch_section(self, ctx):
pass
def exitSwitch_section(self, ctx):
pass
def enterSwitch_labels(self, ctx):
pass
def exitSwitch_labels(self, ctx):
pass
def enterSwitch_label(self, ctx):
pass
def exitSwitch_label(self, ctx):
pass
def enterIteration_statement(self, ctx):
pass
def exitIteration_statement(self, ctx):
pass
def enterWhile_statement(self, ctx):
pass
def exitWhile_statement(self, ctx):
pass
def enterDo_statement(self, ctx):
pass
def exitDo_statement(self, ctx):
pass
def enterFor_statement(self, ctx):
pass
def exitFor_statement(self, ctx):
pass
def enterFor_initializer(self, ctx):
pass
def exitFor_initializer(self, ctx):
pass
def enterFor_condition(self, ctx):
pass
def exitFor_condition(self, ctx):
pass
def enterFor_iterator(self, ctx):
pass
def exitFor_iterator(self, ctx):
pass
def enterStatement_expression_list(self, ctx):
pass
def exitStatement_expression_list(self, ctx):
pass
def enterForeach_statement(self, ctx):
pass
def exitForeach_statement(self, ctx):
pass
def enterJump_statement(self, ctx):
pass
def exitJump_statement(self, ctx):
pass
def enterBreak_statement(self, ctx):
pass
def exitBreak_statement(self, ctx):
pass
def enterContinue_statement(self, ctx):
pass
def exitContinue_statement(self, ctx):
pass
def enterGoto_statement(self, ctx):
pass
def exitGoto_statement(self, ctx):
pass
def enterReturn_statement(self, ctx):
pass
def exitReturn_statement(self, ctx):
pass
def enterThrow_statement(self, ctx):
pass
def exitThrow_statement(self, ctx):
pass
def enterTry_statement(self, ctx):
pass
def exitTry_statement(self, ctx):
pass
def enterCatch_clauses(self, ctx):
pass
def exitCatch_clauses(self, ctx):
pass
def enterSpecific_catch_clauses(self, ctx):
pass
def exitSpecific_catch_clauses(self, ctx):
pass
def enterSpecific_catch_clause(self, ctx):
pass
def exitSpecific_catch_clause(self, ctx):
pass
def enterGeneral_catch_clause(self, ctx):
pass
def exitGeneral_catch_clause(self, ctx):
pass
def enterFinally_clause(self, ctx):
pass
def exitFinally_clause(self, ctx):
pass
def enterChecked_statement(self, ctx):
pass
def exitChecked_statement(self, ctx):
pass
def enterUnchecked_statement(self, ctx):
pass
def exitUnchecked_statement(self, ctx):
pass
def enterLock_statement(self, ctx):
pass
def exitLock_statement(self, ctx):
pass
def enterUsing_statement(self, ctx):
pass
def exitUsing_statement(self, ctx):
pass
def enterResource_acquisition(self, ctx):
pass
def exitResource_acquisition(self, ctx):
pass
def enterYield_statement(self, ctx):
pass
def exitYield_statement(self, ctx):
pass
def enterCompilation_unit(self, ctx):
pass
def exitCompilation_unit(self, ctx):
pass
def enterNamespace_declaration(self, ctx):
pass
def exitNamespace_declaration(self, ctx):
pass
def enterQualified_identifier(self, ctx):
pass
def exitQualified_identifier(self, ctx):
pass
def enterNamespace_body(self, ctx):
pass
def exitNamespace_body(self, ctx):
pass
def enterExtern_alias_directives(self, ctx):
pass
def exitExtern_alias_directives(self, ctx):
pass
def enterExtern_alias_directive(self, ctx):
pass
def exitExtern_alias_directive(self, ctx):
pass
def enterUsing_directives(self, ctx):
pass
def exitUsing_directives(self, ctx):
pass
def enterUsing_directive(self, ctx):
pass
def exitUsing_directive(self, ctx):
pass
def enterUsing_alias_directive(self, ctx):
pass
def exitUsing_alias_directive(self, ctx):
pass
def enterUsing_namespace_directive(self, ctx):
pass
def exitUsing_namespace_directive(self, ctx):
pass
def enterNamespace_member_declarations(self, ctx):
pass
def exitNamespace_member_declarations(self, ctx):
pass
def enterNamespace_member_declaration(self, ctx):
pass
def exitNamespace_member_declaration(self, ctx):
pass
def enterType121_declaration(self, ctx):
pass
def exitType121_declaration(self, ctx):
pass
def enterQualified_alias_member(self, ctx):
pass
def exitQualified_alias_member(self, ctx):
pass
def enterClass_declaration(self, ctx):
pass
def exitClass_declaration(self, ctx):
pass
def enterClass_modifiers(self, ctx):
pass
def exitClass_modifiers(self, ctx):
pass
def enterClass_modifier(self, ctx):
pass
def exitClass_modifier(self, ctx):
pass
def enterType121_parameter_list(self, ctx):
pass
def exitType121_parameter_list(self, ctx):
pass
def enterType121_parameters(self, ctx):
pass
def exitType121_parameters(self, ctx):
pass
def enterType121_parameter(self, ctx):
pass
def exitType121_parameter(self, ctx):
pass
def enterClass_base(self, ctx):
pass
def exitClass_base(self, ctx):
pass
def enterInterface_type121_list(self, ctx):
pass
def exitInterface_type121_list(self, ctx):
pass
def enterType121_parameter_constraints_clauses(self, ctx):
pass
def exitType121_parameter_constraints_clauses(self, ctx):
pass
def enterType121_parameter_constraints_clause(self, ctx):
pass
def exitType121_parameter_constraints_clause(self, ctx):
pass
def enterType121_parameter_constraints(self, ctx):
pass
def exitType121_parameter_constraints(self, ctx):
pass
def enterPrimary_constraint(self, ctx):
pass
def exitPrimary_constraint(self, ctx):
pass
def enterSecondary_constraints(self, ctx):
pass
def exitSecondary_constraints(self, ctx):
pass
def enterConstructor_constraint(self, ctx):
pass
def exitConstructor_constraint(self, ctx):
pass
def enterClass_body(self, ctx):
pass
def exitClass_body(self, ctx):
pass
def enterClass_member_declarations(self, ctx):
pass
def exitClass_member_declarations(self, ctx):
pass
def enterClass_member_declaration(self, ctx):
pass
def exitClass_member_declaration(self, ctx):
pass
def enterAll_member_modifiers(self, ctx):
pass
def exitAll_member_modifiers(self, ctx):
pass
def enterAll_member_modifier(self, ctx):
pass
def exitAll_member_modifier(self, ctx):
pass
def enterCommon_member_declaration(self, ctx):
pass
def exitCommon_member_declaration(self, ctx):
pass
def enterType121d_member_declaration(self, ctx):
pass
def exitType121d_member_declaration(self, ctx):
pass
def enterConstant_declarators(self, ctx):
pass
def exitConstant_declarators(self, ctx):
pass
def enterConstant_declarator(self, ctx):
pass
def exitConstant_declarator(self, ctx):
pass
def enterVariable_declarators(self, ctx):
pass
def exitVariable_declarators(self, ctx):
pass
def enterVariable_declarator(self, ctx):
pass
def exitVariable_declarator(self, ctx):
pass
def enterVariable_initializer(self, ctx):
pass
def exitVariable_initializer(self, ctx):
pass
def enterMethod_declaration(self, ctx):
pass
def exitMethod_declaration(self, ctx):
pass
def enterMethod_header(self, ctx):
pass
def exitMethod_header(self, ctx):
pass
def enterMethod_modifiers(self, ctx):
pass
def exitMethod_modifiers(self, ctx):
pass
def enterMethod_modifier(self, ctx):
pass
def exitMethod_modifier(self, ctx):
pass
def enterReturn_type121(self, ctx):
pass
def exitReturn_type121(self, ctx):
pass
def enterMember_name(self, ctx):
pass
def exitMember_name(self, ctx):
pass
def enterMethod_body(self, ctx):
pass
def exitMethod_body(self, ctx):
pass
def enterFormal_parameter_list(self, ctx):
pass
def exitFormal_parameter_list(self, ctx):
pass
def enterFixed_parameters(self, ctx):
pass
def exitFixed_parameters(self, ctx):
pass
def enterFixed_parameter(self, ctx):
pass
def exitFixed_parameter(self, ctx):
pass
def enterDefault_argument(self, ctx):
pass
def exitDefault_argument(self, ctx):
pass
def enterParameter_modifier(self, ctx):
pass
def exitParameter_modifier(self, ctx):
pass
def enterParameter_array(self, ctx):
pass
def exitParameter_array(self, ctx):
pass
def enterProperty_declaration(self, ctx):
pass
def exitProperty_declaration(self, ctx):
pass
def enterProperty_modifiers(self, ctx):
pass
def exitProperty_modifiers(self, ctx):
pass
def enterProperty_modifier(self, ctx):
pass
def exitProperty_modifier(self, ctx):
pass
def enterAccessor_declarations(self, ctx):
pass
def exitAccessor_declarations(self, ctx):
pass
def enterGet_accessor_declaration(self, ctx):
pass
def exitGet_accessor_declaration(self, ctx):
pass
def enterSet_accessor_declaration(self, ctx):
pass
def exitSet_accessor_declaration(self, ctx):
pass
def enterAccessor_modifier(self, ctx):
pass
def exitAccessor_modifier(self, ctx):
pass
def enterAccessor_body(self, ctx):
pass
def exitAccessor_body(self, ctx):
pass
def enterEvent_declaration(self, ctx):
pass
def exitEvent_declaration(self, ctx):
pass
def enterEvent_modifiers(self, ctx):
pass
def exitEvent_modifiers(self, ctx):
pass
def enterEvent_modifier(self, ctx):
pass
def exitEvent_modifier(self, ctx):
pass
def enterEvent_accessor_declarations(self, ctx):
pass
def exitEvent_accessor_declarations(self, ctx):
pass
def enterAdd_accessor_declaration(self, ctx):
pass
def exitAdd_accessor_declaration(self, ctx):
pass
def enterRemove_accessor_declaration(self, ctx):
pass
def exitRemove_accessor_declaration(self, ctx):
pass
def enterIndexer_declaration(self, ctx):
pass
def exitIndexer_declaration(self, ctx):
pass
def enterIndexer_modifiers(self, ctx):
pass
def exitIndexer_modifiers(self, ctx):
pass
def enterIndexer_modifier(self, ctx):
pass
def exitIndexer_modifier(self, ctx):
pass
def enterIndexer_declarator(self, ctx):
pass
def exitIndexer_declarator(self, ctx):
pass
def enterOperator_declaration(self, ctx):
pass
def exitOperator_declaration(self, ctx):
pass
def enterOperator_modifiers(self, ctx):
pass
def exitOperator_modifiers(self, ctx):
pass
def enterOperator_modifier(self, ctx):
pass
def exitOperator_modifier(self, ctx):
pass
def enterOperator_declarator(self, ctx):
pass
def exitOperator_declarator(self, ctx):
pass
def enterUnary_operator_declarator(self, ctx):
pass
def exitUnary_operator_declarator(self, ctx):
pass
def enterOverloadable_unary_operator(self, ctx):
pass
def exitOverloadable_unary_operator(self, ctx):
pass
def enterBinary_operator_declarator(self, ctx):
pass
def exitBinary_operator_declarator(self, ctx):
pass
def enterOverloadable_binary_operator(self, ctx):
pass
def exitOverloadable_binary_operator(self, ctx):
pass
def enterOverloadable_operator(self, ctx):
pass
def exitOverloadable_operator(self, ctx):
pass
def enterConversion_operator_declarator(self, ctx):
pass
def exitConversion_operator_declarator(self, ctx):
pass
def enterOperator_body(self, ctx):
pass
def exitOperator_body(self, ctx):
pass
def enterConstructor_declaration(self, ctx):
pass
def exitConstructor_declaration(self, ctx):
pass
def enterConstructor_modifiers(self, ctx):
pass
def exitConstructor_modifiers(self, ctx):
pass
def enterConstructor_modifier(self, ctx):
pass
def exitConstructor_modifier(self, ctx):
pass
def enterConstructor_declarator(self, ctx):
pass
def exitConstructor_declarator(self, ctx):
pass
def enterConstructor_initializer(self, ctx):
pass
def exitConstructor_initializer(self, ctx):
pass
def enterConstructor_body(self, ctx):
pass
def exitConstructor_body(self, ctx):
pass
def enterStatic_constructor_declaration(self, ctx):
pass
def exitStatic_constructor_declaration(self, ctx):
pass
def enterStatic_constructor_modifiers(self, ctx):
pass
def exitStatic_constructor_modifiers(self, ctx):
pass
def enterStatic_constructor_body(self, ctx):
pass
def exitStatic_constructor_body(self, ctx):
pass
def enterDestructor_declaration(self, ctx):
pass
def exitDestructor_declaration(self, ctx):
pass
def enterDestructor_body(self, ctx):
pass
def exitDestructor_body(self, ctx):
pass
def enterBody(self, ctx):
pass
def exitBody(self, ctx):
pass
def enterStruct_declaration(self, ctx):
pass
def exitStruct_declaration(self, ctx):
pass
def enterStruct_modifiers(self, ctx):
pass
def exitStruct_modifiers(self, ctx):
pass
def enterStruct_modifier(self, ctx):
pass
def exitStruct_modifier(self, ctx):
pass
def enterStruct_interfaces(self, ctx):
pass
def exitStruct_interfaces(self, ctx):
pass
def enterStruct_body(self, ctx):
pass
def exitStruct_body(self, ctx):
pass
def enterStruct_member_declarations(self, ctx):
pass
def exitStruct_member_declarations(self, ctx):
pass
def enterStruct_member_declaration(self, ctx):
pass
def exitStruct_member_declaration(self, ctx):
pass
def enterArray_type121(self, ctx):
pass
def exitArray_type121(self, ctx):
pass
def enterNon_array_type121(self, ctx):
pass
def exitNon_array_type121(self, ctx):
pass
def enterRank_specifiers(self, ctx):
pass
def exitRank_specifiers(self, ctx):
pass
def enterRank_specifier(self, ctx):
pass
def exitRank_specifier(self, ctx):
pass
def enterDim_separators(self, ctx):
pass
def exitDim_separators(self, ctx):
pass
def enterArray_initializer(self, ctx):
pass
def exitArray_initializer(self, ctx):
pass
def enterVariable_initializer_list(self, ctx):
pass
def exitVariable_initializer_list(self, ctx):
pass
def enterInterface_declaration(self, ctx):
pass
def exitInterface_declaration(self, ctx):
pass
def enterInterface_modifiers(self, ctx):
pass
def exitInterface_modifiers(self, ctx):
pass
def enterInterface_modifier(self, ctx):
pass
def exitInterface_modifier(self, ctx):
pass
def enterVariant_type121_parameter_list(self, ctx):
pass
def exitVariant_type121_parameter_list(self, ctx):
pass
def enterVariant_type121_parameters(self, ctx):
pass
def exitVariant_type121_parameters(self, ctx):
pass
def enterVariance_annotation(self, ctx):
pass
def exitVariance_annotation(self, ctx):
pass
def enterInterface_base(self, ctx):
pass
def exitInterface_base(self, ctx):
pass
def enterInterface_body(self, ctx):
pass
def exitInterface_body(self, ctx):
pass
def enterInterface_member_declarations(self, ctx):
pass
def exitInterface_member_declarations(self, ctx):
pass
def enterInterface_member_declaration(self, ctx):
pass
def exitInterface_member_declaration(self, ctx):
pass
def enterInterface_method_declaration(self, ctx):
pass
def exitInterface_method_declaration(self, ctx):
pass
def enterInterface_property_declaration(self, ctx):
pass
def exitInterface_property_declaration(self, ctx):
pass
def enterInterface_accessors(self, ctx):
pass
def exitInterface_accessors(self, ctx):
pass
def enterInterface_event_declaration(self, ctx):
pass
def exitInterface_event_declaration(self, ctx):
pass
def enterInterface_indexer_declaration(self, ctx):
pass
def exitInterface_indexer_declaration(self, ctx):
pass
def enterEnum_declaration(self, ctx):
pass
def exitEnum_declaration(self, ctx):
pass
def enterEnum_base(self, ctx):
pass
def exitEnum_base(self, ctx):
pass
def enterEnum_body(self, ctx):
pass
def exitEnum_body(self, ctx):
pass
def enterEnum_modifiers(self, ctx):
pass
def exitEnum_modifiers(self, ctx):
pass
def enterEnum_modifier(self, ctx):
pass
def exitEnum_modifier(self, ctx):
pass
def enterEnum_member_declarations(self, ctx):
pass
def exitEnum_member_declarations(self, ctx):
pass
def enterEnum_member_declaration(self, ctx):
pass
def exitEnum_member_declaration(self, ctx):
pass
def enterDelegate_declaration(self, ctx):
pass
def exitDelegate_declaration(self, ctx):
pass
def enterDelegate_modifiers(self, ctx):
pass
def exitDelegate_modifiers(self, ctx):
pass
def enterDelegate_modifier(self, ctx):
pass
def exitDelegate_modifier(self, ctx):
pass
def enterGlobal_attributes(self, ctx):
pass
def exitGlobal_attributes(self, ctx):
pass
def enterGlobal_attribute_sections(self, ctx):
pass
def exitGlobal_attribute_sections(self, ctx):
pass
def enterGlobal_attribute_section(self, ctx):
pass
def exitGlobal_attribute_section(self, ctx):
pass
def enterGlobal_attribute_target_specifier(self, ctx):
pass
def exitGlobal_attribute_target_specifier(self, ctx):
pass
def enterGlobal_attribute_target(self, ctx):
pass
def exitGlobal_attribute_target(self, ctx):
pass
def enterAttributes(self, ctx):
pass
def exitAttributes(self, ctx):
pass
def enterAttribute_sections(self, ctx):
pass
def exitAttribute_sections(self, ctx):
pass
def enterAttribute_section(self, ctx):
pass
def exitAttribute_section(self, ctx):
pass
def enterAttribute_target_specifier(self, ctx):
pass
def exitAttribute_target_specifier(self, ctx):
pass
def enterAttribute_target(self, ctx):
pass
def exitAttribute_target(self, ctx):
pass
def enterAttribute_list(self, ctx):
pass
def exitAttribute_list(self, ctx):
pass
def enterAttribute(self, ctx):
pass
def exitAttribute(self, ctx):
pass
def enterAttribute_name(self, ctx):
pass
def exitAttribute_name(self, ctx):
pass
def enterAttribute_arguments(self, ctx):
pass
def exitAttribute_arguments(self, ctx):
pass
def enterPositional_argument_list(self, ctx):
pass
def exitPositional_argument_list(self, ctx):
pass
def enterPositional_argument(self, ctx):
pass
def exitPositional_argument(self, ctx):
pass
def enterNamed_argument_list(self, ctx):
pass
def exitNamed_argument_list(self, ctx):
pass
def enterNamed_argument(self, ctx):
pass
def exitNamed_argument(self, ctx):
pass
def enterAttribute_argument_expression(self, ctx):
pass
def exitAttribute_argument_expression(self, ctx):
pass
def enterClass_modifier_unsafe(self, ctx):
pass
def exitClass_modifier_unsafe(self, ctx):
pass
def enterStruct_modifier_unsafe(self, ctx):
pass
def exitStruct_modifier_unsafe(self, ctx):
pass
def enterInterface_modifier_unsafe(self, ctx):
pass
def exitInterface_modifier_unsafe(self, ctx):
pass
def enterDelegate_modifier_unsafe(self, ctx):
pass
def exitDelegate_modifier_unsafe(self, ctx):
pass
def enterField_modifier_unsafe(self, ctx):
pass
def exitField_modifier_unsafe(self, ctx):
pass
def enterMethod_modifier_unsafe(self, ctx):
pass
def exitMethod_modifier_unsafe(self, ctx):
pass
def enterProperty_modifier_unsafe(self, ctx):
pass
def exitProperty_modifier_unsafe(self, ctx):
pass
def enterEvent_modifier_unsafe(self, ctx):
pass
def exitEvent_modifier_unsafe(self, ctx):
pass
def enterIndexer_modifier_unsafe(self, ctx):
pass
def exitIndexer_modifier_unsafe(self, ctx):
pass
def enterOperator_modifier_unsafe(self, ctx):
pass
def exitOperator_modifier_unsafe(self, ctx):
pass
def enterConstructor_modifier_unsafe(self, ctx):
pass
def exitConstructor_modifier_unsafe(self, ctx):
pass
def enterDestructor_declaration_unsafe(self, ctx):
pass
def exitDestructor_declaration_unsafe(self, ctx):
pass
def enterStatic_constructor_modifiers_unsafe(self, ctx):
pass
def exitStatic_constructor_modifiers_unsafe(self, ctx):
pass
def enterEmbedded_statement_unsafe(self, ctx):
pass
def exitEmbedded_statement_unsafe(self, ctx):
pass
def enterUnsafe_statement(self, ctx):
pass
def exitUnsafe_statement(self, ctx):
pass
def enterType121_unsafe(self, ctx):
pass
def exitType121_unsafe(self, ctx):
pass
def enterPointer_type121(self, ctx):
pass
def exitPointer_type121(self, ctx):
pass
def enterUnmanaged_type121(self, ctx):
pass
def exitUnmanaged_type121(self, ctx):
pass
def enterPrimary_no_array_creation_expression_unsafe(self, ctx):
pass
def exitPrimary_no_array_creation_expression_unsafe(self, ctx):
pass
def enterUnary_expression_unsafe(self, ctx):
pass
def exitUnary_expression_unsafe(self, ctx):
pass
def enterPointer_indirection_expression(self, ctx):
pass
def exitPointer_indirection_expression(self, ctx):
pass
def enterAddressof_expression(self, ctx):
pass
def exitAddressof_expression(self, ctx):
pass
def enterSizeof_expression(self, ctx):
pass
def exitSizeof_expression(self, ctx):
pass
def enterFixed_statement(self, ctx):
pass
def exitFixed_statement(self, ctx):
pass
def enterFixed_pointer_declarators(self, ctx):
pass
def exitFixed_pointer_declarators(self, ctx):
pass
def enterFixed_pointer_declarator(self, ctx):
pass
def exitFixed_pointer_declarator(self, ctx):
pass
def enterFixed_pointer_initializer(self, ctx):
pass
def exitFixed_pointer_initializer(self, ctx):
pass
def enterStruct_member_declaration_unsafe(self, ctx):
pass
def exitStruct_member_declaration_unsafe(self, ctx):
pass
def enterFixed_size_buffer_declaration(self, ctx):
pass
def exitFixed_size_buffer_declaration(self, ctx):
pass
def enterFixed_size_buffer_modifiers(self, ctx):
pass
def exitFixed_size_buffer_modifiers(self, ctx):
pass
def enterFixed_size_buffer_modifier(self, ctx):
pass
def exitFixed_size_buffer_modifier(self, ctx):
pass
def enterBuffer_element_type121(self, ctx):
pass
def exitBuffer_element_type121(self, ctx):
pass
def enterFixed_size_buffer_declarators(self, ctx):
pass
def exitFixed_size_buffer_declarators(self, ctx):
pass
def enterFixed_size_buffer_declarator(self, ctx):
pass
def exitFixed_size_buffer_declarator(self, ctx):
pass
def enterLocal_variable_initializer_unsafe(self, ctx):
pass
def exitLocal_variable_initializer_unsafe(self, ctx):
pass
def enterStackalloc_initializer(self, ctx):
pass
def exitStackalloc_initializer(self, ctx):
pass
def enterFrom_contextual_keyword(self, ctx):
pass
def exitFrom_contextual_keyword(self, ctx):
pass
def enterLet_contextual_keyword(self, ctx):
pass
def exitLet_contextual_keyword(self, ctx):
pass
def enterWhere_contextual_keyword(self, ctx):
pass
def exitWhere_contextual_keyword(self, ctx):
pass
def enterJoin_contextual_keyword(self, ctx):
pass
def exitJoin_contextual_keyword(self, ctx):
pass
def enterOn_contextual_keyword(self, ctx):
pass
def exitOn_contextual_keyword(self, ctx):
pass
def enterEquals_contextual_keyword(self, ctx):
pass
def exitEquals_contextual_keyword(self, ctx):
pass
def enterInto_contextual_keyword(self, ctx):
pass
def exitInto_contextual_keyword(self, ctx):
pass
def enterOrderby_contextual_keyword(self, ctx):
pass
def exitOrderby_contextual_keyword(self, ctx):
pass
def enterAscending_contextual_keyword(self, ctx):
pass
def exitAscending_contextual_keyword(self, ctx):
pass
def enterDescending_contextual_keyword(self, ctx):
pass
def exitDescending_contextual_keyword(self, ctx):
pass
def enterSelect_contextual_keyword(self, ctx):
pass
def exitSelect_contextual_keyword(self, ctx):
pass
def enterGroup_contextual_keyword(self, ctx):
pass
def exitGroup_contextual_keyword(self, ctx):
pass
def enterBy_contextual_keyword(self, ctx):
pass
def exitBy_contextual_keyword(self, ctx):
pass
def enterPartial_contextual_keyword(self, ctx):
pass
def exitPartial_contextual_keyword(self, ctx):
pass
def enterAlias_contextual_keyword(self, ctx):
pass
def exitAlias_contextual_keyword(self, ctx):
pass
def enterYield_contextual_keyword(self, ctx):
pass
def exitYield_contextual_keyword(self, ctx):
pass
def enterGet_contextual_keyword(self, ctx):
pass
def exitGet_contextual_keyword(self, ctx):
pass
def enterSet_contextual_keyword(self, ctx):
pass
def exitSet_contextual_keyword(self, ctx):
pass
def enterAdd_contextual_keyword(self, ctx):
pass
def exitAdd_contextual_keyword(self, ctx):
pass
def enterRemove_contextual_keyword(self, ctx):
pass
def exitRemove_contextual_keyword(self, ctx):
pass
def enterDynamic_contextual_keyword(self, ctx):
pass
def exitDynamic_contextual_keyword(self, ctx):
pass
def enterArglist(self, ctx):
pass
def exitArglist(self, ctx):
pass
def enterRight_arrow(self, ctx):
pass
def exitRight_arrow(self, ctx):
pass
def enterRight_shift(self, ctx):
pass
def exitRight_shift(self, ctx):
pass
def enterRight_shift_assignment(self, ctx):
pass
def exitRight_shift_assignment(self, ctx):
pass
def enterLiteral(self, ctx):
pass
def exitLiteral(self, ctx):
pass
def enterBoolean_literal(self, ctx):
pass
def exitBoolean_literal(self, ctx):
pass
def enterKeyword(self, ctx):
pass
def exitKeyword(self, ctx):
pass
def enterClass_definition(self, ctx):
pass
def exitClass_definition(self, ctx):
pass
def enterStruct_definition(self, ctx):
pass
def exitStruct_definition(self, ctx):
pass
def enterInterface_definition(self, ctx):
pass
def exitInterface_definition(self, ctx):
pass
def enterEnum_definition(self, ctx):
pass
def exitEnum_definition(self, ctx):
pass
def enterDelegate_definition(self, ctx):
pass
def exitDelegate_definition(self, ctx):
pass
def enterEvent_declaration2(self, ctx):
pass
def exitEvent_declaration2(self, ctx):
pass
def enterField_declaration2(self, ctx):
pass
def exitField_declaration2(self, ctx):
pass
def enterProperty_declaration2(self, ctx):
pass
def exitProperty_declaration2(self, ctx):
pass
def enterConstant_declaration2(self, ctx):
pass
def exitConstant_declaration2(self, ctx):
pass
def enterIndexer_declaration2(self, ctx):
pass
def exitIndexer_declaration2(self, ctx):
pass
def enterDestructor_definition(self, ctx):
pass
def exitDestructor_definition(self, ctx):
pass
def enterConstructor_declaration2(self, ctx):
pass
def exitConstructor_declaration2(self, ctx):
pass
def enterMethod_declaration2(self, ctx):
pass
def exitMethod_declaration2(self, ctx):
pass
def enterMethod_member_name(self, ctx):
pass
def exitMethod_member_name(self, ctx):
pass
def enterMethod_member_name2(self, ctx):
pass
def exitMethod_member_name2(self, ctx):
pass
def enterOperator_declaration2(self, ctx):
pass
def exitOperator_declaration2(self, ctx):
pass
def enterInterface_method_declaration2(self, ctx):
pass
def exitInterface_method_declaration2(self, ctx):
pass
def enterInterface_property_declaration2(self, ctx):
pass
def exitInterface_property_declaration2(self, ctx):
pass
def enterInterface_event_declaration2(self, ctx):
pass
def exitInterface_event_declaration2(self, ctx):
pass
def enterInterface_indexer_declaration2(self, ctx):
pass
def exitInterface_indexer_declaration2(self, ctx):
pass
def enterMember_access2(self, ctx):
pass
def exitMember_access2(self, ctx):
pass
def enterMethod_invocation2(self, ctx):
pass
def exitMethod_invocation2(self, ctx):
pass
def enterObject_creation_expression2(self, ctx):
pass
def exitObject_creation_expression2(self, ctx):
pass
def enterType121OF(self, ctx):
pass
def exitType121OF(self, ctx):
pass |
class CSVReader(Reader):
def process(self, fp):
r = csv.DictReader(fp)
return [line for line in r] |
def GetKappa(mol):
res = OrderedDict()
for (k, func) in _Kappa.items():
res.update({k: func(mol)})
return res |
def extract_ans_csv(file):
with open(file, 'r') as fin:
out = []
reader = csv.reader(fin)
next(reader)
for line in reader:
(query, ans) = line[:2]
my_query = os.path.splitext(os.path.split(query)[1])[0]
my_ans = os.path.splitext(os.path.split(ans)[1])[0]
if (my_query in out):
print(('Warning! query %s occured twice' % query))
out.append((my_query, my_ans))
return out |
def test_seg2boundary():
seg = np.array([[]])
text_repr_type = 'quad'
text_score = None
with pytest.raises(AssertionError):
mask_utils.seg2boundary([[]], text_repr_type, text_score)
with pytest.raises(AssertionError):
mask_utils.seg2boundary(seg, 1, text_score)
with pytest.raises(AssertionError):
mask_utils.seg2boundary(seg, text_repr_type, 1.1)
seg = np.array([[1, 1, 1], [1, 1, 1], [1, 1, 1]])
result = mask_utils.seg2boundary(seg, text_repr_type, text_score)
pred_poly = eval_utils.points2polygon(result)
target_poly = eval_utils.points2polygon([2, 2, 0, 2, 0, 0, 2, 0])
assert (eval_utils.poly_iou(pred_poly, target_poly) == 1) |
def gelu_fast(x):
x = tf.convert_to_tensor(x)
coeff1 = tf.cast(0.044715, x.dtype)
coeff2 = tf.cast(0., x.dtype)
return ((0.5 * x) * (1.0 + tf.tanh(((x * coeff2) * (1.0 + ((coeff1 * x) * x)))))) |
()
('--batch_size', type=int, default=4000)
_experiment
def ppo_memorize_digits(ctxt=None, seed=1, batch_size=4000):
set_seed(seed)
with LocalTFRunner(ctxt) as runner:
env = GarageEnv(normalize(gym.make('MemorizeDigits-v0')), is_image=True)
policy = CategoricalCNNPolicy(env_spec=env.spec, filters=((32, (5, 5)), (64, (3, 3)), (64, (2, 2))), strides=(4, 2, 1), padding='VALID', hidden_sizes=(256,))
baseline = GaussianCNNBaseline(env_spec=env.spec, regressor_args=dict(filters=((32, (5, 5)), (64, (3, 3)), (64, (2, 2))), strides=(4, 2, 1), padding='VALID', hidden_sizes=(256,), use_trust_region=True))
algo = PPO(env_spec=env.spec, policy=policy, baseline=baseline, max_path_length=100, discount=0.99, gae_lambda=0.95, lr_clip_range=0.2, policy_ent_coeff=0.0, optimizer_args=dict(batch_size=32, max_epochs=10, learning_rate=0.001), flatten_input=False)
runner.setup(algo, env)
runner.train(n_epochs=1000, batch_size=batch_size) |
class RPN(nn.Module):
def __init__(self):
super(RPN, self).__init__()
def forward(self, z_f, x_f):
raise NotImplementedError |
def register_Ns3FrameCaptureModel_methods(root_module, cls):
cls.add_constructor([])
cls.add_constructor([param('ns3::FrameCaptureModel const &', 'arg0')])
cls.add_method('CaptureNewFrame', 'bool', [param('ns3::Ptr< ns3::Event >', 'currentEvent'), param('ns3::Ptr< ns3::Event >', 'newEvent')], is_pure_virtual=True, is_const=True, is_virtual=True)
cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True)
cls.add_method('IsInCaptureWindow', 'bool', [param('ns3::Time', 'timePreambleDetected')], is_const=True, is_virtual=True)
return |
class MultiSimilarityLoss(nn.Module):
def __init__(self, thresh=0.5, _margin=0.1, scale_pos=2.0, scale_neg=40.0, **kwargs):
super(MultiSimilarityLoss, self).__init__()
self.thresh = thresh
self.margin = _margin
self.scale_pos = scale_pos
self.scale_neg = scale_neg
self.epsilon = 1e-05
def forward(self, feats, labels, device, loss_=None):
assert (feats.size(0) == labels.size(0)), 'feats.size(0): {feats.size(0)} is not equal to labels.size(0): {labels.size(0)}'
batch_size = feats.size(0)
sim_mat = torch.matmul(feats, torch.t(feats))
loss = (loss_ if (loss_ is not None) else torch.tensor(0.0).to(device))
for i in range(batch_size):
pos_pair_ = sim_mat[i][(labels == labels[i])]
pos_pair_ = pos_pair_[(pos_pair_ < (1 - self.epsilon))]
neg_pair_ = sim_mat[i][(labels != labels[i])]
if ((len(neg_pair_) < 1) or (len(pos_pair_) < 1)):
continue
neg_pair = neg_pair_[((neg_pair_ + self.margin) > min(pos_pair_))]
pos_pair = pos_pair_[((pos_pair_ - self.margin) < max(neg_pair_))]
if ((len(neg_pair) < 1) or (len(pos_pair) < 1)):
continue
pos_loss = ((1.0 / self.scale_pos) * torch.log((1 + torch.sum(torch.exp(((- self.scale_pos) * (pos_pair - self.thresh)))))))
neg_loss = ((1.0 / self.scale_neg) * torch.log((1 + torch.sum(torch.exp((self.scale_neg * (neg_pair - self.thresh)))))))
loss += (pos_loss + neg_loss)
if (loss == 0):
return torch.zeros([], requires_grad=True).to(device)
return (loss / batch_size) |
def get_with_answers(recieved):
answers = []
for (_, _, src) in recieved:
tokens = src.split(' ')
answer = []
for token in tokens:
features = token.split('')
word = features[0]
ans_tag = features[1]
if ((ans_tag == 'B') or (ans_tag == 'I')):
answer.append(word)
elif answer:
break
answers.append(' '.join(answer))
return [(recieved[i][0], answers[i], recieved[i][1]) for i in range(len(recieved))] |
def merge_states(x):
x_shape = shape_list(x)
new_x_shape = (x_shape[:(- 2)] + [np.prod(x_shape[(- 2):])])
return tf.reshape(x, new_x_shape) |
.parametrize('num_models', [1, 3])
.parametrize('shadow_model_fn,model_serializer', [(keras_shadow_model_fn, None), (torch_shadow_model_fn, None), (torch_shadow_model_fn, pytest.lazy_fixture('torch_shadow_serializer'))])
def test_shadow_models_are_created_and_data_is_transformed(data, shadow_model_fn, model_serializer, num_models):
((X_train, y_train), _) = data
smb = ShadowModelBundle(shadow_model_fn, shadow_dataset_size=SHADOW_DATASET_SIZE, num_models=num_models, serializer=model_serializer)
assert (not hasattr(smb, 'shadow_models_'))
(X_shadow, y_shadow) = smb.fit_transform(X_train, y_train, fit_kwargs=dict(epochs=5, verbose=False))
assert (len(X_shadow) == len(y_shadow) == ((2 * num_models) * SHADOW_DATASET_SIZE))
assert (X_shadow.shape[1] == (2 * NUM_CLASSES)) |
class Transformer_NonRecursive(Transformer):
def transform(self, tree):
rev_postfix = []
q = [tree]
while q:
t = q.pop()
rev_postfix.append(t)
if isinstance(t, Tree):
q += t.children
stack = []
for x in reversed(rev_postfix):
if isinstance(x, Tree):
size = len(x.children)
if size:
args = stack[(- size):]
del stack[(- size):]
else:
args = []
stack.append(self._call_userfunc(x, args))
else:
stack.append(x)
(t,) = stack
return t |
def extract_melspec(task):
(fps, src_wav, dst_npy) = task
src_wav = src_wav.replace('_left', '').replace('_right', '')
if os.path.exists(dst_npy):
return 1
try:
(y, sr) = librosa.load(src_wav, sr=16000)
hop_length = int(((((1 / 3) * 1) / fps) * 16000))
power = librosa.feature.melspectrogram(y=y, sr=sr, n_fft=512, hop_length=hop_length, win_length=400, n_mels=40)
spec = librosa.core.power_to_db(power)
np.save(dst_npy, spec.transpose())
return 0
except Exception as e:
print('Exception on {}: {}'.format(src_wav, e))
return (- 1) |
def test():
directory = os.path.join(os.path.dirname(os.path.abspath(__file__)), '../../../datasets/images/')
img = Resize((256, 256)).transform(Image(PilImage.open((directory + 'dog_cat.png')).convert('RGB')))
test_instance = img.to_numpy()[0]
svc = init_service(model_tag='vision_explainer:latest', task_type='vision', service_name='vision_explainer')
for runner in svc.runners:
runner.init_local()
predictions = svc.apis['predict'].func(test_instance)
print(predictions)
local_explanations = svc.apis['explain'].func(test_instance, {})
from omnixai.explainers.base import AutoExplainerBase
exp = AutoExplainerBase.parse_explanations_from_json(local_explanations)
for (name, explanation) in exp.items():
explanation.ipython_plot() |
def add_cwe_class(problem_col):
cwe_classes = []
for p in problem_col:
des = str(p).replace("'", '"')
des = json.loads(des)
for cwes in json_normalize(des)['description']:
if (len(cwes) != 0):
cwe_classes.append([cwe_id for cwe_id in json_normalize(cwes)['value']])
else:
cwe_classes.append(['unknown'])
assert (len(problem_col) == len(cwe_classes)), 'Sizes are not equal - Problem occurred while fetching the cwe classification records!'
return cwe_classes |
_decorator(1)
def get_max_num(html):
soup = BeautifulSoup(html, 'lxml')
href_list = soup.find(attrs={'action-type': 'feed_list_page_morelist'}).find_all('a')
return len(href_list) |
class ModelArguments():
model_name_or_path: str = field(default=None, metadata={'help': 'Path to pretrained model or model identifier from huggingface.co/models'})
config_name: Optional[str] = field(default=None, metadata={'help': 'Pretrained config name or path if not the same as model_name'})
tokenizer_name: Optional[str] = field(default=None, metadata={'help': 'Pretrained tokenizer name or path if not the same as model_name'})
cache_dir: Optional[str] = field(default=None, metadata={'help': 'Where to store the pretrained models downloaded from huggingface.co'})
use_fast_tokenizer: bool = field(default=True, metadata={'help': 'Whether to use one of the fast tokenizer (backed by the tokenizers library) or not.'})
model_revision: str = field(default='main', metadata={'help': 'The specific model version to use (can be a branch name, tag name or commit id).'})
use_auth_token: bool = field(default=False, metadata={'help': 'Will use the token generated when running `transformers-cli login` (necessary to use this script with private models).'})
drop_duplicates_in_eval: bool = field(default=True)
use_swed: bool = field(default=False)
swed_context_size: Optional[int] = field(default=None)
attention_window: Optional[int] = field(default=None, metadata={'help': 'The attention window size for models such as LED, will be used in the model config'})
relative_attention_num_buckets: Optional[int] = field(default=None, metadata={'help': 'The relative_attention_num_buckets for T5, will be used in the model config'})
gradient_checkpointing: Optional[bool] = field(default=None, metadata={'help': 'Whether to use gradient checkpointing in models such ash LED'})
remove_global_attention: Optional[bool] = field(default=None, metadata={'help': 'Whether to remove global attention weight matrices in LED'}) |
def train(model, data_loader, optimizer, tokenizer, epoch, warmup_steps, device, scheduler, config):
model.train()
metric_logger = utils.MetricLogger(delimiter=' ')
metric_logger.add_meter('lr', utils.SmoothedValue(window_size=50, fmt='{value:.6f}'))
metric_logger.add_meter('loss_mlm', utils.SmoothedValue(window_size=50, fmt='{value:.4f}'))
metric_logger.add_meter('loss_ita', utils.SmoothedValue(window_size=50, fmt='{value:.4f}'))
metric_logger.add_meter('loss_itm', utils.SmoothedValue(window_size=50, fmt='{value:.4f}'))
header = 'Train Epoch: [{}]'.format(epoch)
print_freq = 50
step_size = 100
warmup_iterations = (warmup_steps * step_size)
if args.distributed:
data_loader.sampler.set_epoch(epoch)
for (i, (image, text)) in enumerate(metric_logger.log_every(data_loader, print_freq, header)):
optimizer.zero_grad()
image = image.to(device, non_blocking=True)
text_input = tokenizer(text, padding='longest', truncation=True, max_length=25, return_tensors='pt').to(device)
if (epoch > 0):
alpha = config['alpha']
else:
alpha = (config['alpha'] * min(1, (i / len(data_loader))))
(loss_mlm, loss_ita, loss_itm) = model(image, text_input, alpha=alpha)
loss = ((loss_mlm + loss_ita) + loss_itm)
loss.backward()
optimizer.step()
metric_logger.update(loss_mlm=loss_mlm.item())
metric_logger.update(loss_ita=loss_ita.item())
metric_logger.update(loss_itm=loss_itm.item())
metric_logger.update(lr=optimizer.param_groups[0]['lr'])
if ((epoch == 0) and ((i % step_size) == 0) and (i <= warmup_iterations)):
scheduler.step((i // step_size))
metric_logger.synchronize_between_processes()
print('Averaged stats:', metric_logger.global_avg())
return {k: '{:.3f}'.format(meter.global_avg) for (k, meter) in metric_logger.meters.items()} |
def tangent_jacobians_chain_rule(expr: T.Element, args: T.Sequence[T.Element]) -> T.List[sf.Matrix]:
jacobians = []
expr_storage = sf.M(StorageOps.to_storage(expr))
expr_tangent_D_storage = LieGroupOps.tangent_D_storage(expr)
for arg in args:
expr_storage_D_arg_storage = expr_storage.jacobian(StorageOps.to_storage(arg))
arg_jacobian = (expr_tangent_D_storage * (expr_storage_D_arg_storage * LieGroupOps.storage_D_tangent(arg)))
jacobians.append(arg_jacobian)
return jacobians |
def main():
output_dir = '{}/wav{}/{}/{}'.format(args.tgt_dir, args.sample_rate, args.mode, args.part)
if os.path.exists(output_dir):
raise ValueError('Warning: {} already exists, please check!'.format(output_dir))
else:
os.makedirs(output_dir)
wav_dir = '{}/wav{}/{}/{}'.format(args.src_dir, args.sample_rate, args.mode, args.part)
assert os.path.exists(wav_dir)
for cond in ['s1', 's2', 'mix_clean', 'mix_both', 'mix_single', 'noise']:
if (not os.path.exists('{}/{}'.format(wav_dir, cond))):
continue
filelist = [f for f in os.listdir('{}/{}'.format(wav_dir, cond)) if f.endswith('.wav')]
filelist.sort()
cond_dir = '{}/{}'.format(output_dir, cond)
if (not os.path.exists(cond_dir)):
os.makedirs(cond_dir)
wav_scp_file = open('{}/wav.scp'.format(cond_dir), 'w')
utt2spk_file = open('{}/utt2spk'.format(cond_dir), 'w')
for f in filelist:
uttname = f.strip('.wav')
wav_scp_file.write('{} {}/{}/{}\n'.format(uttname, wav_dir, cond, f))
utt2spk_file.write('{} {}\n'.format(uttname, uttname))
wav_scp_file.close()
utt2spk_file.close()
shutil.copyfile('{}/utt2spk'.format(cond_dir), '{}/spk2utt'.format(cond_dir))
return 0 |
class AndNode(ASTNode):
def __init__(self, data_type, fields):
super().__init__('AND', 'AND', data_type, fields)
def textual_form_core(self):
if (self.fields[0].depth == 0):
return ' '.join([self.fields[0].textual_form(), 'that', self.fields[1].textual_form()])
else:
return ' '.join([self.fields[0].textual_form(), 'and', self.fields[1].textual_form()]) |
def prepare_xlnet_input(args, _, tokenizer, prompt_text):
prompt_text = ((args.padding_text if args.padding_text else PADDING_TEXT) + prompt_text)
return prompt_text |
def get_args():
parser = argparse.ArgumentParser()
parser.add_argument('dump_dir')
parser.add_argument('out_dir')
parser.add_argument('ranker_path')
parser.add_argument('--start', default=0, type=int)
parser.add_argument('--end', default=1, type=int)
parser.add_argument('--nfs', default=False, action='store_true')
return parser.parse_args() |
class GPTSanJapaneseConfig(PretrainedConfig):
model_type = 'gptsan-japanese'
keys_to_ignore_at_inference = ['past_key_values']
attribute_map = {'hidden_size': 'd_model', 'num_attention_heads': 'num_heads', 'num_hidden_layers': 'num_layers'}
def __init__(self, vocab_size=36000, max_position_embeddings=1280, d_model=1024, d_ff=8192, d_ext=4096, d_spout=128, num_switch_layers=10, num_ext_layers=0, num_heads=16, num_experts=16, expert_capacity=128, dropout_rate=0.0, layer_norm_epsilon=1e-05, router_bias=False, router_jitter_noise=0.0, router_dtype='float32', router_ignore_padding_tokens=False, output_hidden_states=False, output_attentions=False, initializer_factor=0.002, output_router_logits=False, use_cache=True, separator_token_id=35998, pad_token_id=35995, eos_token_id=35999, **kwargs):
self.vocab_size = vocab_size
self.max_position_embeddings = max_position_embeddings
self.d_model = d_model
self.d_ff = d_ff
self.d_ext = d_ext
self.d_spout = d_spout
self.num_switch_layers = num_switch_layers
self.num_ext_layers = num_ext_layers
self.num_layers = (num_switch_layers + num_ext_layers)
self.num_heads = num_heads
self.num_experts = num_experts
self.expert_capacity = expert_capacity
self.dropout_rate = dropout_rate
self.layer_norm_epsilon = layer_norm_epsilon
self.router_bias = router_bias
self.router_jitter_noise = router_jitter_noise
self.router_dtype = router_dtype
self.router_ignore_padding_tokens = router_ignore_padding_tokens
self.output_hidden_states = output_hidden_states
self.output_attentions = output_attentions
self.initializer_factor = initializer_factor
self.output_router_logits = output_router_logits
self.use_cache = use_cache
super().__init__(separator_token_id=separator_token_id, pad_token_id=pad_token_id, eos_token_id=eos_token_id, **kwargs) |
def load_datasets(sample=0.1, list_params=None, load_t=(0, (- 6)), valid_split=0.2, test_split=0.2, randomseed=47):
if (list_params is None):
list_params = ['r', 'd', 'o3', 'v', 'ciwc', 'q', 'pv', 'z', 'clwc', 't', 'w', 'vo', 'u', 'cc']
X1 = []
X2 = []
Y = []
storm_ids = []
print('loading from pkls ...')
x_dir = X_DIR
x_dir2 = X_DIR2
y_dir = Y_DIR_D
data = pd.read_csv(Data_stormids_csv)
stormids = np.unique(data['stormid'].values)
for filename in tqdm(stormids):
non_empty_storm = False
if (np.random.random() > sample):
continue
else:
if (0 in load_t):
with open(((x_dir + filename) + '.pkl'), 'rb') as f:
storm_data = pickle.load(f)
if (len(storm_data['grids']) != 0):
non_empty_storm = True
storm_i = []
for storm_t in storm_data['grids'][:]:
grid_allchannels = []
for key in list_params:
grid = storm_t[key]
grid_allchannels.append(grid)
storm_i.append(grid_allchannels)
X1.append(storm_i)
storm_ids.append(filename)
del storm_data
if ((- 6) in load_t):
with open(((x_dir2 + filename) + '.pkl'), 'rb') as f:
storm_data = pickle.load(f)
if (len(storm_data['grids']) != 0):
non_empty_storm = True
storm2_i = []
for storm_t in storm_data['grids'][:]:
grid_allchannels = []
for key in list_params:
grid = storm_t[key]
grid_allchannels.append(grid)
storm2_i.append(grid_allchannels)
X2.append(storm2_i)
del storm_data
for item in load_t:
if (item not in (0, (- 6), (- 12))):
raise ValueError('only support for t, t-6, t-12')
with open(((y_dir + filename) + '.pkl'), 'rb') as f:
y_data = pickle.load(f)
if (non_empty_storm is True):
y_labels = []
n_storms = len(y_data['next_disp'])
for i in range(n_storms):
y_label_i = [y_data['curr_longlat'][i], y_data['curr_longlat'][(i + 1)], y_data['next_disp'][i]]
y_labels.append(y_label_i)
Y.append(y_labels)
num_storm = len(X1)
indices = list(range(num_storm))
num_test = int(np.floor((test_split * num_storm)))
num_valid = int(np.floor((valid_split * num_storm)))
np.random.seed(randomseed)
np.random.shuffle(indices)
(train_idx, valid_idx, test_idx) = (indices[:((- num_valid) - num_test)], indices[((- num_valid) - num_test):(- num_test)], indices[(- num_test):])
trainset = load_foldset(train_idx, storm_ids, Y, X1, X2)
validset = load_foldset(valid_idx, storm_ids, Y, X1, X2)
testset = load_foldset(test_idx, storm_ids, Y, X1, X2)
return (trainset, validset, testset) |
def simSetJointInterval(jointHandle, cyclic, interval):
ret = lib.simSetJointInterval(jointHandle, cyclic, interval)
_check_return(ret) |
(('Python' not in caffe.layer_type_list()), 'Caffe built without Python layer support')
class TestLayerWithParam(unittest.TestCase):
def setUp(self):
net_file = python_param_net_file()
self.net = caffe.Net(net_file, caffe.TRAIN)
os.remove(net_file)
def test_forward(self):
x = 8
self.net.blobs['data'].data[...] = x
self.net.forward()
for y in self.net.blobs['mul2'].data.flat:
self.assertEqual(y, ((2 * 10) * x))
def test_backward(self):
x = 7
self.net.blobs['mul2'].diff[...] = x
self.net.backward()
for y in self.net.blobs['data'].diff.flat:
self.assertEqual(y, ((2 * 10) * x)) |
_grad()
def evaluate_step(model, dataset, task: Tuple[(int, int)], fast: bool=False) -> dict:
(today, tomorrow) = task
assert (tomorrow == (today + 1)), 'Currently support 1 step forword only.'
model.eval()
for t in range(today):
new_batch = get_task_batch(dataset, t, (t + 1), None).clone()
if (t > 0):
new_batch.node_states = batch.node_states
new_batch.node_cells = batch.node_cells
batch = new_batch
(_, _) = model(batch)
cur_batch = get_task_batch(dataset, today, tomorrow, None).clone()
if (today > 0):
cur_batch.node_states = copy.deepcopy(batch.node_states)
cur_batch.node_cells = copy.deepcopy(batch.node_cells)
(pred, true) = model(cur_batch)
(loss, pred_score) = compute_loss(pred, true)
if fast:
return {'loss': loss.item()}
mrr_batch = get_task_batch(dataset, today, tomorrow, None).clone()
if (today > 0):
mrr_batch.node_states = copy.deepcopy(batch.node_states)
mrr_batch.node_cells = copy.deepcopy(batch.node_cells)
(mrr, rck1, rck3, rck10) = train_utils.report_rank_based_eval(mrr_batch, model, num_neg_per_node=cfg.experimental.rank_eval_multiplier)
return {'loss': loss.item(), 'mrr': mrr, 'rck1': rck1, 'rck3': rck3, 'rck10': rck10} |
def getdtype(dtype, a=None, default=None):
if (dtype is None):
try:
newdtype = a.dtype
except AttributeError as e:
if (default is not None):
newdtype = np.dtype(default)
else:
raise TypeError('could not interpret data type') from e
else:
newdtype = np.dtype(dtype)
if (newdtype == np.object_):
raise ValueError('object dtype is not supported by sparse matrices')
return newdtype |
def idx_split(idx, ratio, seed=0):
set_seed(seed)
n = len(idx)
cut = int((n * ratio))
idx_idx_shuffle = torch.randperm(n)
(idx1_idx, idx2_idx) = (idx_idx_shuffle[:cut], idx_idx_shuffle[cut:])
(idx1, idx2) = (idx[idx1_idx], idx[idx2_idx])
return (idx1, idx2) |
class CollectionLengthAssertion(ReferenceAssertion):
def __init__(self, source: vr.Reference, length: int):
super().__init__(source)
self._length = length
def length(self) -> int:
return self._length
def accept(self, visitor: AssertionVisitor) -> None:
visitor.visit_collection_length_assertion(self)
def clone(self, memo: dict[(vr.VariableReference, vr.VariableReference)]) -> CollectionLengthAssertion:
return CollectionLengthAssertion(self.source.clone(memo), self._length)
def __eq__(self, other: Any) -> bool:
return (isinstance(other, CollectionLengthAssertion) and (self._source == other._source) and (self._length == other._length))
def __hash__(self) -> int:
return hash((self._source, self._length))
def __repr__(self):
return f'CollectionLengthAssertion({self._source!r}, {self._length})' |
def CalculateNormalizedMoreauBrotoAutoResidueASA(ProteinSequence):
result = CalculateEachNormalizedMoreauBrotoAuto(ProteinSequence, _ResidueASA, '_ResidueASA')
return result |
def apply_multiple_times(A: dace.float64[(10, 10, 10)]):
for i in range(10):
for j in range(10):
for k in dace.map[0:10]:
A[(k, i, j)] = (((i * 100) + (j * 10)) + k) |
def version_dict():
v = SAGE_VERSION.split('.')
dict = {}
dict['major'] = int(v[0])
dict['minor'] = int(v[1])
dict['tiny'] = 0
dict['prerelease'] = False
try:
int(v[(- 1)])
except ValueError:
dict['prerelease'] = True
if (((len(v) == 3) and (not dict['prerelease'])) or (len(v) > 3)):
dict['tiny'] = int(v[2])
try:
teeny = int(v[3])
dict['tiny'] += (0.1 * teeny)
except (ValueError, IndexError):
pass
return dict |
def test_find_by_status(testdir):
testdir.make_petstore_test('\(endpoint="/pet/findByStatus$")\(max_examples=5, deadline=None)\ndef test_(request, case):\n request.config.HYPOTHESIS_CASES += 1\n assert_list(case.query["status"])\n for item in case.query["status"]:\n assert item in ("available", "pending", "sold")\n assert_requests_call(case)\n')
testdir.assert_petstore() |
(scope='session')
def simple_openapi():
return {'openapi': '3.0.2', 'info': {'title': 'Test', 'description': 'Test', 'version': '0.1.0'}, 'paths': {'/query': {'get': {'parameters': [{'name': 'id', 'in': 'query', 'required': True, 'schema': {'type': 'string', 'minLength': 1}}, {'name': 'value', 'in': 'header', 'required': True, 'schema': {'type': 'string'}}], 'responses': {'200': {'description': 'OK'}}}}}} |
def compute_Ap():
for (i, j, k) in Ap:
Ap[(i, j, k)] = (((((((6.0 * p[(i, j, k)]) - p[((i + 1), j, k)]) - p[((i - 1), j, k)]) - p[(i, (j + 1), k)]) - p[(i, (j - 1), k)]) - p[(i, j, (k + 1))]) - p[(i, j, (k - 1))]) |
class WorkerInfo(object):
__initialized = False
def __init__(self, **kwargs):
for (k, v) in kwargs.items():
setattr(self, k, v)
self.__keys = tuple(kwargs.keys())
self.__initialized = True
def __setattr__(self, key, val):
if self.__initialized:
raise RuntimeError('Cannot assign attributes to {} objects'.format(self.__class__.__name__))
return super(WorkerInfo, self).__setattr__(key, val)
def __repr__(self):
items = []
for k in self.__keys:
items.append('{}={}'.format(k, getattr(self, k)))
return '{}({})'.format(self.__class__.__name__, ', '.join(items)) |
def setup_devices(args):
main_gpu = 0
if (not args['no_cuda']):
if isinstance(args['devices'], tuple):
main_gpu = args['devices'][0]
elif isinstance(args['devices'], int):
main_gpu = args['devices']
elif isinstance(args['devices'], dict):
main_gpu = args['devices'].get('input', 0)
torch.cuda.set_device(main_gpu)
cudnn.benchmark = True
else:
main_gpu = 'cpu'
return main_gpu |
def compute_hessian(f, params):
h = []
for i in params:
h_i = []
for j in params:
grad = torch.autograd.grad(f, j, create_graph=True)
h_ij = torch.autograd.grad(grad, i, allow_unused=True, retain_graph=True)
h_ij = ((torch.tensor(0.0),) if (h_ij[0] is None) else h_ij)
h_i.append(h_ij[0])
h_i = torch.stack(h_i)
h.append(h_i)
h = torch.stack(h)
h = h.reshape((len(params), len(params)))
return h |
def setup(app):
app.add_domain(ScipyOptimizeInterfaceDomain)
return {'parallel_read_safe': True} |
def unpickle(file_path):
with open(file_path, 'rb') as f:
data = pk.load(f)
return data |
class QDQBertForSequenceClassification(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
class SICETrain(SICE):
def __init__(self, dir_data, **kwargs):
super().__init__(dir_data, split='train', **kwargs) |
def test_cast_to_datetime64():
string_value = '2021-02-02'
list_value = [None, np.nan, '2021-02-02']
series_value = pd.Series(['2021-02-02', None, pd.NaT])
string_out = cast_to_datetime64(string_value)
list_out = cast_to_datetime64(list_value)
series_out = cast_to_datetime64(series_value)
expected_string_output = np.datetime64('2021-02-02')
expected_series_output = pd.Series([np.datetime64('2021-02-02'), np.datetime64('NaT'), np.datetime64('NaT')])
expected_list_output = np.array([np.datetime64('NaT'), np.datetime64('NaT'), '2021-02-02'], dtype='datetime64[ns]')
np.testing.assert_array_equal(expected_list_output, list_out)
pd.testing.assert_series_equal(expected_series_output, series_out)
assert (expected_string_output == string_out) |
.parametrize('context, action, description', invalid_input_of_calc_policy_value)
def test_synthetic_continuous_calc_policy_value_using_invalid_inputs(context, action, description):
dataset = SyntheticContinuousBanditDataset()
with pytest.raises(ValueError, match=f'{description}*'):
_ = dataset.calc_ground_truth_policy_value(context=context, action=action) |
class RDB_Conv(nn.Module):
def __init__(self, inChannels, growRate, kSize=3):
super(RDB_Conv, self).__init__()
Cin = inChannels
G = growRate
self.conv = nn.Sequential(*[nn.Conv2d(Cin, G, kSize, padding=((kSize - 1) // 2), stride=1), nn.ReLU()])
def forward(self, x):
out = self.conv(x)
return torch.cat((x, out), 1) |
def valid_loop(net, loader):
net.eval()
epoch_losses = Counter()
with torch.no_grad():
for (iit, batch) in tqdm(enumerate(loader, 1), position=1, total=len(loader)):
for (k, v) in batch.items():
if torch.is_tensor(v):
batch[k] = v.to(device)
losses = net.compute_losses(batch)
for (k, v) in losses.items():
if torch.is_tensor(v):
epoch_losses[k] += (float(v.item()) / len(loader))
else:
epoch_losses[k] += (v / len(loader))
return epoch_losses |
class _vq_wav2vec_codeids_wrapper(torch.nn.Module):
def __init__(self, vq_wav2vec):
super().__init__()
self.vq_wav2vec = vq_wav2vec
self.featurizer = _Featurizer(vq_wav2vec, 'codeids', upstream_device='cpu')
def _indices_to_string(self, sentence_idxs):
return (('<s> ' + ' '.join(('-'.join(map(str, idx.tolist())) for idx in sentence_idxs))) + ' </s>')
def forward(self, wavs):
batch_idxs = self.featurizer(wavs, self.vq_wav2vec(wavs))
strings = [self._indices_to_string(sentence_idxs) for sentence_idxs in batch_idxs]
return strings |
def get_layer_bytes(layer, is_in):
total_bytes = 0
tensors = (layer.in_tensors if is_in else layer.out_tensors)
for tensor in tensors:
tensor_bytes = get_layer_dtype(tensor.dtype)
for s in tensor.shape:
tensor_bytes *= s
total_bytes += tensor_bytes
return total_bytes |
def test_cnn_fit_resample():
cnn = CondensedNearestNeighbour(random_state=RND_SEED)
(X_resampled, y_resampled) = cnn.fit_resample(X, Y)
X_gt = np.array([[(- 0.), (- 0.)], [0., 0.], [0., 0.], [(- 1.), (- 0.)], [0., 0.], [0., 1.], [(- 0.284881), (- 0.)], [0., 0.], [(- 0.), 0.], [0., 0.]])
y_gt = np.array([0, 0, 1, 1, 1, 2, 2, 2, 2, 2])
assert_array_equal(X_resampled, X_gt)
assert_array_equal(y_resampled, y_gt) |
def visualize_matrix(writer, matrix_arr, iteration, title_str):
stage = 'valid'
for i in range(len(matrix_arr)):
C = matrix_arr[i].shape[1]
matrix = matrix_arr[i][0].unsqueeze(0)
matrix = torch.clamp(torch.abs(matrix), max=1)
matrix = torch.cat((torch.ones(1, C, C).cuda(), torch.abs((matrix - 1.0)), torch.abs((matrix - 1.0))), 0)
matrix = vutils.make_grid(matrix, padding=5, normalize=False, range=(0, 1))
writer.add_image(((stage + title_str) + str(i)), matrix, iteration) |
def qexp_eta(ps_ring, prec):
prec = Integer(prec)
if (not (prec > 0)):
raise ValueError('prec must be a positive integer')
v = ([Integer(0)] * prec)
pm = Integer(1)
v[0] = pm
try:
n = 1
while True:
pm = (- pm)
v[((n * ((3 * n) - 1)) // 2)] = pm
v[((n * ((3 * n) + 1)) // 2)] = pm
n += 1
except IndexError:
pass
return ps_ring(v, prec=prec) |
def test_import_normfactor_bounds():
parsed_xml = pyhf.readxml.parse('validation/xmlimport_input2/config/example.xml', 'validation/xmlimport_input2')
ws = pyhf.Workspace(parsed_xml)
assert (('SigXsecOverSM', 'normfactor') in ws.modifiers)
parameters = [p for p in ws.get_measurement(measurement_name='GaussExample')['config']['parameters'] if (p['name'] == 'SigXsecOverSM')]
assert (len(parameters) == 1)
parameter = parameters[0]
assert (parameter['bounds'] == [[0, 10]]) |
def create_argparser():
defaults = dict(num_samples=80000, batch_size=20000, model_path='')
defaults.update(model_and_diffusion_defaults_2d())
parser = argparse.ArgumentParser()
parser.add_argument('--task', type=int, default=0, help='Which dataset to sample from.')
add_dict_to_argparser(parser, defaults)
return parser |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.