code stringlengths 281 23.7M |
|---|
def before_and_after(predicate, it):
it = iter(it)
transition = []
def true_iterator():
for elem in it:
if predicate(elem):
(yield elem)
else:
transition.append(elem)
return
remainder_iterator = chain(transition, it)
ret... |
def cka(k_x: torch.Tensor, k_y: torch.Tensor, centered: bool=False, unbiased: bool=True) -> torch.Tensor:
hsic_xy = hsic(k_x, k_y, centered, unbiased)
hsic_xx = hsic(k_x, k_x, centered, unbiased)
hsic_yy = hsic(k_y, k_y, centered, unbiased)
return (hsic_xy / torch.sqrt((hsic_xx * hsic_yy))) |
def test_unique_name_generator():
unique_names = unique_name_generator(['blah'], suffix_sep='_')
x = vector('blah')
x_name = unique_names(x)
assert (x_name == 'blah_1')
y = vector('blah_1')
y_name = unique_names(y)
assert (y_name == 'blah_1_1')
x_name = unique_names(x)
assert (x_name... |
class SoftHistogram(nn.Module):
def __init__(self, n_features, n_examples, num_bins, quantiles=False):
super(SoftHistogram, self).__init__()
self.in_channels = n_features
self.num_bins = num_bins
self.quantiles = quantiles
self.bin_centers_conv = nn.Conv1d(self.in_channels, (... |
class ValueHolder():
def __init__(self, value):
self._value = value
def value(self):
return self._value
def get(self):
return self._value
def set(self, new_value):
self._value = new_value
def __bool__(self):
return bool(self._value)
def __eq__(self, other)... |
def test_vcc2016_dummy():
data_source = vcc2016.WavFileDataSource('dummy', speakers=['SF1'])
(ValueError)
def __test_invalid_speaker():
vcc2016.WavFileDataSource('dummy', speakers=['test'])
(RuntimeError)
def __test_nodir(data_source):
data_source.collect_files()
__test_invalid_s... |
class GetIfcFL(CallerIfcFL):
def connect(s, other, parent):
if isinstance(other, CallerIfcCL):
m = RecvCL2GiveFL()
if hasattr(parent, 'RecvCL2GiveFL_count'):
count = parent.RecvCL2GiveFL_count
setattr(parent, ('RecvCL2GiveFL_' + str(count)), m)
... |
def _getcommand():
var = (('a', 'a'), ('ab', 'ab'), ('abc', 'abclear'), ('abo', 'aboveleft'), ('al', 'all'), ('ar', 'ar'), ('ar', 'args'), ('arga', 'argadd'), ('argd', 'argdelete'), ('argdo', 'argdo'), ('arge', 'argedit'), ('argg', 'argglobal'), ('argl', 'arglocal'), ('argu', 'argument'), ('as', 'ascii'), ('au', 'a... |
def get_polynomial_decay_schedule_with_warmup(optimizer, num_warmup_steps, num_training_steps, lr_end=1e-07, power=1.0, last_epoch=(- 1)):
lr_init = optimizer.defaults['lr']
if (not (lr_init > lr_end)):
raise ValueError(f'lr_end ({lr_end}) must be be smaller than initial lr ({lr_init})')
lr_lambda =... |
.skipif(pyproj._datadir._USE_GLOBAL_CONTEXT, reason='Global Context not Threadsafe.')
def test_proj_multithread():
trans = Proj('EPSG:3857')
def transform(num):
return trans(1, 2)
with concurrent.futures.ThreadPoolExecutor(max_workers=2) as executor:
for result in executor.map(transform, ran... |
def set_wled_ip(request: WSGIRequest) -> HttpResponse:
(value, response) = extract_value(request.POST)
try:
socket.inet_aton(value)
except socket.error:
return HttpResponseBadRequest('invalid ip')
storage.put('wled_ip', value)
_notify_settings_changed('wled')
return response |
def main():
parser = argparse.ArgumentParser(description='Tool to create a commit list')
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument('--create_new', nargs=2)
group.add_argument('--update_to')
group.add_argument('--stat', action='store_true')
group.add_argument('... |
class PackedArray(BaseRTLIRDataType):
def __init__(s, dim_sizes, sub_dtype):
assert isinstance(sub_dtype, BaseRTLIRDataType), f'non-RTLIR data type {sub_dtype} as sub type of array.'
assert (not isinstance(sub_dtype, PackedArray)), 'nested PackedArray is not allowed!'
assert (len(dim_sizes) ... |
def load_language(dataset, task, dataset_key, model_args, extractor, subgoal_idx=None, test_split=False):
feat_numpy = dataset.load_features(task, subgoal_idx=subgoal_idx)
if (not test_split):
frames_expert = dataset.load_frames(dataset_key)
model_util.test_extractor(task['root'], extractor, fra... |
class Migration(migrations.Migration):
dependencies = [('api', '0016_auto__1619')]
operations = [migrations.AlterField(model_name='specialsnake', name='images', field=django.contrib.postgres.fields.ArrayField(base_field=models.URLField(), help_text='Images displaying this special snake.', size=None))] |
def main_worker(gpu, ngpus_per_node, args):
global best_acc1
global best_acc2
args.gpu = gpu
if (args.gpu is not None):
print('Use GPU: {} for training'.format(args.gpu))
if args.distributed:
if ((args.dist_url == 'env://') and (args.rank == (- 1))):
args.rank = int(os.en... |
class DlrmSparseNetwork(BaseNetwork):
def __init__(self, categorical_features, numerical_features, multivalue_features, attention_features, loss_ctr, loss_cvr, ptype='mean', hidden_sizes=[512, 512, 512], scope_name='dlrm2_network', save_model_mode='placeholder', save_task_id=0, masks_dir=None):
self._catego... |
class FakeSongsMenuPlugin(SongsMenuPlugin):
PLUGIN_NAME = 'Fake Songs Menu Plugin'
PLUGIN_ID = 'SongsMunger'
MAX_INVOCATIONS = 50
def __init__(self, songs, library):
super().__init__(songs, library)
self.total = 0
def plugin_song(self, song):
self.total += 1
if (self.... |
.parametrize('enabled', [True, False])
def test_auto_input_impedance_enabled(enabled):
with expected_protocol(HP34401A, [('INP:IMP:AUTO?', ('1' if enabled else '0')), (f'INP:IMP:AUTO {(1 if enabled else 0)}', None)]) as inst:
assert (enabled == inst.auto_input_impedance_enabled)
inst.auto_input_impe... |
class PwnLookup(object):
def __init__(self, spi1, spi2, dc=4, cs1=16, rst=17, cs2=5, rotation=270):
self.display = Display(spi1, dc=Pin(dc), cs=Pin(cs1), rst=Pin(rst), width=320, height=240, rotation=rotation)
self.unispace = XglcdFont('fonts/Unispace12x24.c', 12, 24)
self.keyboard = TouchKe... |
.mosaiqdb
def test_get_patient_name(connection: pymedphys.mosaiq.Connection):
mocks.create_mock_patients()
result_all = pymedphys.mosaiq.execute(connection, '\n SELECT\n Pat_Id1,\n First_Name,\n Last_Name\n FROM Patient\n ')
for patient in result_all:
... |
class F19_Realm(KickstartCommand):
removedKeywords = KickstartCommand.removedKeywords
removedAttrs = KickstartCommand.removedAttrs
def __init__(self, writePriority=0, *args, **kwargs):
KickstartCommand.__init__(self, writePriority, *args, **kwargs)
self.join_realm = None
self.join_ar... |
def test_reuters():
random.seed(time.time())
if (random.random() > 0.8):
((x_train, y_train), (x_test, y_test)) = reuters.load_data()
assert (len(x_train) == len(y_train))
assert (len(x_test) == len(y_test))
assert ((len(x_train) + len(x_test)) == 11228)
((x_train, y_trai... |
def test_from_recap_with_cyclic_reference():
converter = ProtobufConverter()
linked_list_node_type = StructType(fields=[IntType(bits=32, name='value'), ProxyType(alias='build.recap.LinkedListNode', registry=converter.registry, name='next')], alias='build.recap.LinkedListNode')
result = converter.from_recap(... |
def process_kym_files(kym_phashes_file):
kym_phashes_by_meme_dic = {}
kym_images_dic = {}
kym_images_dic_reverse = {}
kym_meme_name = {}
print('[i] process_kym_files', kym_phashes_file)
with open(kym_phashes_file) as fd:
for (idx, line) in enumerate(fd.readlines()):
if (idx =... |
class MasterIfcRTL(Interface):
def construct(s, ReqType, RespType):
s.ReqType = ReqType
s.RespType = RespType
s.req = RecvIfcRTL(Type=ReqType)
s.resp = SendIfcRTL(Type=RespType)
def __str__(s):
return f'{s.req}|{s.resp}'
def connect(s, other, parent):
if isins... |
class ModelArguments():
model_name_or_path: Optional[str] = field(default=None, metadata={'help': "The model checkpoint for weights initialization.Don't set if you want to train a model from scratch."})
config_name: Optional[str] = field(default=None, metadata={'help': 'Pretrained config name or path if not the... |
class DbmsLob(DirectoryManagement):
def __init__(self, args):
logging.debug('DbmsLob object created')
DirectoryManagement.__init__(self, args)
self.__setDirectoryName__()
def getFile(self, remotePath, remoteNameFile, localFile):
data = ''
logging.info('Copy the {0} remote... |
class MultiEncodingWeights(WeightLayer):
def __init__(self, weight_mode: str, init='glorot_uniform'):
self.weight_mode = weight_mode
self.init = init
def apply(self, is_train, x, mask=None):
init = get_keras_initialization(self.init)
keys_shape = x.shape.as_list()
if (sel... |
def configureLogging2(args):
logformatNoColor = '%(levelname)-3s -: %(message)s'
datefmt = '%H:%M:%S'
if ('verbose' in args):
if (args['verbose'] == 0):
level = logging.WARNING
elif (args['verbose'] == 1):
level = logging.INFO
elif (args['verbose'] == 2):
... |
class LoginRequiredMixin(DjangoLoginRequiredMixin):
redirect_unauthenticated_users = True
def handle_no_permission(self):
response = redirect_to_login(self.request.get_full_path(), self.get_login_url(), self.get_redirect_field_name())
if self.raise_exception:
if (self.redirect_unauth... |
def get_local_addresses():
global retries
addresses = []
if retries:
try:
from netifaces import interfaces, ifaddresses
for interface in interfaces():
addrs = ifaddresses(interface)
for i in addrs:
if ('addr' in i):
... |
def test(rtlsdrtcp, use_numpy):
from utils import generic_test
port = 1235
while True:
try:
server = rtlsdrtcp.RtlSdrTcpServer(port=port)
server.run()
except socket.error as e:
if (e.errno != errno.EADDRINUSE):
raise
server = No... |
def my_status(task):
if task['disabled']:
return u''
if task['last_failed_count']:
return (u'%d,...' % task['last_failed_count'])
if ((task['last_failed'] or 0) > (task['last_success'] or 0)):
return u''
if ((task['success_count'] == 0) and (task['failed_count'] == 0) and task['n... |
class HorizontalLineDecorator(ChartDecorator, SimpleLegendItem):
def __init__(self, y: ScalarType, color: str='k', key: str=None, **plot_settings: Any):
ChartDecorator.__init__(self, key)
SimpleLegendItem.__init__(self)
self._y = y
self._color = color
self.plot_settings = plo... |
def td_format(td_object):
seconds = int(td_object.total_seconds())
periods = [('y', (((60 * 60) * 24) * 365)), ('m', (((60 * 60) * 24) * 30)), ('d', ((60 * 60) * 24)), ('h', (60 * 60)), ('m', 60), ('s', 1)]
ret = ''
for (period_name, period_seconds) in periods:
if (seconds > period_seconds):
... |
def ElemwiseOpTime(N, script=False, loops=1000):
x = vector('x')
np.random.seed(1235)
v = np.random.random(N).astype(config.floatX)
f = pytensor.function([x], ((2 * x) + (x * x)))
f1 = pytensor.function([x], tanh(x))
f.trust_input = True
f1.trust_input = True
if (not script):
if ... |
class SSSResponseControl(ResponseControl):
controlType = '1.2.840.113556.1.4.474'
def __init__(self, criticality=False):
ResponseControl.__init__(self, self.controlType, criticality)
def decodeControlValue(self, encoded):
(p, rest) = decoder.decode(encoded, asn1Spec=SortResultType())
... |
class SEModule(nn.Module):
def __init__(self, channels, rd_ratio=(1.0 / 16), rd_channels=None, rd_divisor=8, add_maxpool=False, bias=True, act_layer=nn.ReLU, norm_layer=None, gate_layer='sigmoid'):
super(SEModule, self).__init__()
self.add_maxpool = add_maxpool
if (not rd_channels):
... |
class TableWidget(QtWidgets.QTableWidget):
def __init__(self, *args, **kwds):
QtWidgets.QTableWidget.__init__(self, *args)
self.itemClass = TableWidgetItem
self.setVerticalScrollMode(self.ScrollMode.ScrollPerPixel)
self.setSelectionMode(QtWidgets.QAbstractItemView.SelectionMode.Conti... |
def evaluate_stack(s):
(op, num_args) = (s.pop(), 0)
if isinstance(op, tuple):
(op, num_args) = op
if (op == 'unary -'):
return (- evaluate_stack(s))
if (op in '+-*/^'):
op2 = evaluate_stack(s)
op1 = evaluate_stack(s)
return opn[op](op1, op2)
elif (op == 'PI')... |
class XLISCalendarTestCase(EuronextCalendarTestBase, TestCase):
answer_key_filename = 'xlis'
calendar_class = XLISExchangeCalendar
MAX_SESSION_HOURS = 8.5
TIMEDELTA_TO_NORMAL_CLOSE = pd.Timedelta(hours=16, minutes=30)
TIMEDELTA_TO_EARLY_CLOSE = pd.Timedelta(hours=13, minutes=5)
TZ = 'Europe/Lisb... |
class Meter(object):
def __init__(self, name, val, avg):
self.name = name
self.val = val
self.avg = avg
def __repr__(self):
return '{name}: {val:.6f} ({avg:.6f})'.format(name=self.name, val=self.val, avg=self.avg)
def __format__(self, *tuples, **kwargs):
return self._... |
class AccountSessionHandler(object):
def __init__(self, account):
self.account = account
def get(self, sessid=None):
global _SESSIONS
if (not _SESSIONS):
from evennia.server.sessionhandler import SESSIONS as _SESSIONS
if sessid:
return make_iter(_SESSIONS.... |
_module
class RepeatDataset(object):
def __init__(self, dataset, times):
self.dataset = dataset
self.times = times
self.CLASSES = dataset.CLASSES
if hasattr(self.dataset, 'flag'):
self.flag = np.tile(self.dataset.flag, times)
self._ori_len = len(self.dataset)
... |
class DCSourceGenerator(SourceGenerator):
depth_min = Float.T(default=0.0)
depth_max = Float.T(default=(30 * km))
strike = Float.T(optional=True)
dip = Float.T(optional=True)
rake = Float.T(optional=True)
perturbation_angle_std = Float.T(optional=True)
def get_source(self, ievent):
r... |
def linear_dequantize(input, scale, zero_point, inplace=False):
if (len(input.shape) == 4):
scale = scale.view((- 1), 1, 1, 1)
zero_point = zero_point.view((- 1), 1, 1, 1)
elif (len(input.shape) == 2):
scale = scale.view((- 1), 1)
zero_point = zero_point.view((- 1), 1)
if inp... |
def prepare_CHB_MIT_dataloader(args):
seed = 12345
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
np.random.seed(seed)
root = '/srv/local/data/physionet.org/files/chbmit/1.0.0/clean_segments'
train_files = os.listdir(os.path.join(root, 'train'))
val... |
def extract_qa_p(path='../data/msmarco-qa/train_v2.1.json', output='../data/msmarco-qa/train.txt'):
data = json.load(open(path))
data_to_save = []
for (id_, answers) in data['answers'].items():
if (answers[0] != 'No Answer Present.'):
passages = data['passages'][id_]
query = ... |
def test_path_completion_no_text(cmd2_app):
text = ''
line = 'shell ls {}'.format(text)
endidx = len(line)
begidx = (endidx - len(text))
completions_no_text = cmd2_app.path_complete(text, line, begidx, endidx)
text = (os.getcwd() + os.path.sep)
line = 'shell ls {}'.format(text)
endidx = ... |
def test_directed_tripartition_indices():
assert (directed_tripartition_indices(0) == [])
assert (directed_tripartition_indices(2) == [((0, 1), (), ()), ((0,), (1,), ()), ((0,), (), (1,)), ((1,), (0,), ()), ((), (0, 1), ()), ((), (0,), (1,)), ((1,), (), (0,)), ((), (1,), (0,)), ((), (), (0, 1))]) |
class TFSegformerDropPath(tf.keras.layers.Layer):
def __init__(self, drop_path, **kwargs):
super().__init__(**kwargs)
self.drop_path = drop_path
def call(self, x, training=None):
if training:
keep_prob = (1 - self.drop_path)
shape = ((tf.shape(x)[0],) + ((1,) * (l... |
def _read_from_init(initcontent, initname):
metadata = []
i = 0
lines = initcontent.split('\n')
while (i < len(lines)):
if re.search('def\\s+([^\\(]+)', lines[i]):
k = re.search('def\\s+([^\\(]+)', lines[i]).groups()[0]
i += 1
while ((i < len(lines)) and (line... |
class CalcChangeProjectedDroneAmountCommand(wx.Command):
def __init__(self, fitID, itemID, amount):
wx.Command.__init__(self, True, 'Change Projected Drone Amount')
self.fitID = fitID
self.itemID = itemID
self.amount = amount
self.savedDroneInfo = None
def Do(self):
... |
_fixtures(FieldFixture)
def test_min_length_constraint(fixture):
min_required_length = 5
min_length_constraint = MinLengthConstraint(min_length=min_required_length)
assert (min_length_constraint.parameters == ('%s' % min_required_length))
with expected(NoException):
min_length_constraint.validat... |
class Seq2SeqSequenceClassifierOutput(ModelOutput):
loss: Optional[torch.FloatTensor] = None
logits: torch.FloatTensor = None
past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None
decoder_hidden_states: Optional[Tuple[torch.FloatTensor]] = None
decoder_attentions: Optional[Tuple[torch.Fl... |
def get_ts(url):
data = m3u8.load(url)
key_link = get_key(data)
ts_content = b''
key = None
for (i, segment) in enumerate(data.segments):
decrypt_func = (lambda x: x)
if (segment.key.method == 'AES-128'):
if (not key):
key_uri = segment.key.uri
... |
def transform_take(a, indices, axis):
a = pytensor.tensor.as_tensor_variable(a)
indices = pytensor.tensor.as_tensor_variable(indices)
if (indices.ndim == 1):
if (axis == 0):
return advanced_subtensor1(a, indices)
else:
shuffle = list(range(a.ndim))
shuffle... |
def _expand_paths_by_content_type(base_paths: Union[(str, List[str])], base_urls: List[S3Url], content_type_provider: Callable[([str], ContentType)], path_type: S3PathType, user_fs: Optional[Union[(S3FileSystem, s3fs.S3FileSystem)]], resolved_fs: S3FileSystem, **s3_client_kwargs) -> Tuple[(Dict[(ContentType, List[str])... |
class Processor(Iface, TProcessor):
def __init__(self, handler):
self._handler = handler
self._processMap = {}
self._processMap['is_healthy'] = Processor.process_is_healthy
self._on_message_begin = None
def on_message_begin(self, func):
self._on_message_begin = func
d... |
class Effect11426(BaseEffect):
type = 'passive'
def handler(fit, container, context, projectionRange, **kwargs):
fit.drones.filteredItemBoost((lambda drone: drone.item.requiresSkill('Drones')), 'damageMultiplier', container.getModifiedItemAttr('shipBonusAB'), skill='Amarr Battleship', **kwargs) |
def html_parse(parse, viols=False, use_caps=False, use_html=True, between_words=' ', between_sylls='.', line_id='ID'):
last_word = None
output = ''
for pos in parse.positions:
violated = pos.violated
if (viols and violated):
viol_str = ' '.join([rename_constraint(c) for c in viol... |
def read_engine_configs() -> dict:
all_configs = {}
engines_config_dir = os.path.join(ROOT_DIR, 'experiments', 'configurations')
config_files = glob.glob(os.path.join(engines_config_dir, '*.json'))
for config_file in config_files:
with open(config_file, 'r') as fd:
configs = json.loa... |
def MenuBlockAsControls(menuItems, parentage=None):
if (parentage is None):
parentage = []
blocks = []
curBlock = []
for item in menuItems:
itemAsCtrl = MenuItemAsControl(item)
if parentage:
itemPath = ('%s->%s' % ('->'.join(parentage), item['text']))
else:
... |
class MSMRDiffusion(BaseParticle):
def __init__(self, param, domain, options, phase='primary', x_average=False):
super().__init__(param, domain, options, phase)
self.x_average = x_average
pybamm.citations.register('Baker2018')
pybamm.citations.register('Verbrugge2017')
def get_fu... |
def smart_text(s, encoding='utf-8', errors='strict'):
if isinstance(s, six.text_type):
return s
if (not isinstance(s, six.string_types)):
if six.PY3:
if isinstance(s, bytes):
s = six.text_type(s, encoding, errors)
else:
s = six.text_type(s)... |
def Hamming(term, *others):
if isinstance(term, types.GeneratorType):
term = [l for l in term]
elif (len(others) > 0):
term = list(((term,) + others))
lists = [flatten(l) for l in term]
assert (all((checkType(l, [Variable]) for l in lists)) and (len(lists) == 2) and (len(lists[0]) == len... |
class CmdLink(COMMAND_DEFAULT_CLASS):
key = 'link'
locks = 'cmd:perm(link) or perm(Builder)'
help_category = 'Building'
def func(self):
caller = self.caller
if (not self.args):
caller.msg('Usage: link[/twoway] <object> = <target>')
return
object_name = sel... |
class outconv(nn.Module):
def __init__(self, in_ch, out_ch):
super(outconv, self).__init__()
self.conv = nn.Conv2d(in_ch, out_ch, 1)
self.conv2 = nn.Conv2d(in_ch, out_ch, 3, padding=1)
def forward(self, x):
x1 = self.conv(x)
x2 = self.conv2(x)
return (x1 + x2) |
class _AEADCipherContext(AEADCipherContext):
_ctx: (_BackendCipherContext | None)
_tag: (bytes | None)
def __init__(self, ctx: _BackendCipherContext) -> None:
self._ctx = ctx
self._bytes_processed = 0
self._aad_bytes_processed = 0
self._tag = None
self._updated = Fals... |
def getMeshObject(analysis_object):
isPresent = False
meshObj = []
if analysis_object:
members = analysis_object.Group
else:
members = FreeCAD.activeDocument().Objects
for i in members:
if (hasattr(i, 'Proxy') and hasattr(i.Proxy, 'Type') and ((i.Proxy.Type == 'FemMeshGmsh') ... |
class Conv2dSamePadding(nn.Conv2d):
def __init__(self, image_size, in_channels, out_channels, kernel_size, **kernel_wargs):
super().__init__(in_channels, out_channels, kernel_size, **kernel_wargs)
(image_h, image_w) = image_size
(kernel_h, kernel_w) = self.weight.size()[(- 2):]
(stri... |
class GRU_Head(nn.Module):
def __init__(self, input_dim, hidden_dim, n_class=8):
super(GRU_Head, self).__init__()
self._name = 'Head'
self.GRU_layer = nn.GRU(input_dim, hidden_dim, batch_first=True, bidirectional=True)
self.fc_1 = nn.Linear((hidden_dim * 2), n_class)
def forward(... |
class ExportStaticFiles(ProductionCommand):
keyword = 'exportstatics'
def assemble(self):
super().assemble()
self.parser.add_argument('destination_directory', type=str, help='the destination directory to export to')
def execute(self, args):
super().execute(args)
if os.path.ex... |
class ObjectModel():
def __init__(self):
self._instance = None
def __repr__(self):
result = []
cname = type(self).__name__
string = '%(cname)s(%(fields)s)'
alignment = (len(cname) + 1)
for field in sorted(self.attributes()):
width = ((80 - len(field)) ... |
.parametrize('molecule, n_rotatables', [pytest.param('bace0.pdb', 2, id='bace0pdb'), pytest.param('butane.pdb', 1, id='butanepdb'), pytest.param('biphenyl.pdb', 1, id='biphenylpdb')])
def test_find_rotatable_bonds_n_rotatables(molecule, n_rotatables):
mol = Ligand.from_file(get_data(molecule))
assert (len(mol.f... |
class BiSeNetOutput(nn.Module):
def __init__(self, in_chan, mid_chan, n_classes, *args, **kwargs):
super(BiSeNetOutput, self).__init__()
self.conv = ConvBNReLU(in_chan, mid_chan, ks=3, stride=1, padding=1)
self.conv_out = nn.Conv2d(mid_chan, n_classes, kernel_size=1, bias=False)
self... |
class Light():
location: str = ''
level: int = 0
def __init__(self, location: str):
self.location = location
def on(self) -> None:
self.level = 100
print(f'{self.location} light is on')
def off(self) -> None:
self.level = 0
print(f'{self.location} light is off... |
class ZeroShotCoTMethod(PromptMethod):
def __init__(self, **kwargs: Any):
super().__init__(**kwargs)
def run(self, x: Union[(str, Dict)], in_context_examples: List[Dict]=None, prompt_file_path: Optional[str]=None, **kwargs: Any) -> Union[(str, List[str])]:
if isinstance(x, str):
rais... |
def main(args):
with open(args.parsed_ace_roles) as f:
parsed_ace_roles = json.load(f)
name_to_ontology = {parsed['name']: parsed for parsed in parsed_ace_roles}
print('Ontology loaded.')
with open(('.'.join(args.parsed_ace_roles.split('.')[:(- 1)]) + '.py')) as f:
ace_roles_full_context... |
def getItemAttrs(typeid):
attrs = {}
cursor.execute(QUERY_TYPEID_ATTRIBS, (typeid,))
for row in cursor:
attrs[row[0]] = row[1]
cursor.execute(QUERY_TYPEID_BASEATTRIBS, (typeid,))
for row in cursor:
if (row[0] is not None):
attrs['volume'] = row[0]
if (row[1] is no... |
def get_contractreceivechannelsettled_data_from_event(chain_state: ChainState, event: DecodedEvent) -> Optional[ChannelSettleState]:
args = event.event_data['args']
token_network_address = TokenNetworkAddress(event.originating_contract)
channel_identifier = args['channel_identifier']
participant1 = args... |
def _train(args, device):
print('==> Loading data generator... ')
(train_gen_list, elmo, char_vocab) = get_all_datasets(args)
if (args.model_type == 'ETModel'):
print('==> ETModel')
model = models.ETModel(args, constant.ANSWER_NUM_DICT[args.goal])
else:
print(('ERROR: Invalid mod... |
class ResNetEncoder(nn.Module):
def __init__(self, num_input_channels: int=1, num_features: List=None, verbose: bool=False) -> None:
super().__init__()
if (num_features is None):
num_features = [8, 16, 32, 64, 256]
self.verbose = verbose
self.num_features = ([num_input_ch... |
class ImageNet_hdf5(data.Dataset):
def __init__(self, data_dir, dataidxs=None, train=True, transform=None, target_transform=None, download=False):
self.dataidxs = dataidxs
self.train = train
self.transform = transform
self.target_transform = target_transform
self.download = d... |
def test_archs_default(platform, intercepted_build_args):
main()
options = intercepted_build_args.args[0]
if (platform == 'linux'):
assert (options.globals.architectures == {Architecture.x86_64, Architecture.i686})
elif (platform == 'windows'):
assert (options.globals.architectures == {A... |
class VeloxFunctional(types.ModuleType):
def __init__(self):
super().__init__('torcharrow.velox_rt.functional')
self._populate_udfs()
def create_dispatch_wrapper(op_name: str):
def dispatch(*args):
wrapped_args = []
first_col = next((arg for arg in args if isinsta... |
class MindDataset(Dataset):
def __init__(self, root: str, tokenizer: AutoTokenizer, mode: str='train', split: str='small', news_max_len: int=20, hist_max_len: int=20, seq_max_len: int=300) -> None:
super(MindDataset, self).__init__()
self.data_path = os.path.join(root, split)
self._mode = mo... |
def _uda_concat_dataset(cfg, default_args=None):
from .uda_concat import UDAConcatDataset
img_dir = cfg['img_dir']
ann_dir = cfg.get('ann_dir', None)
split = cfg.get('split', None)
separate_eval = cfg.pop('separate_eval', True)
num_img_dir = (len(img_dir) if isinstance(img_dir, (list, tuple)) el... |
class ClockItem(pg.ItemGroup):
def __init__(self, clock):
pg.ItemGroup.__init__(self)
self.size = clock.size
self.item = QtWidgets.QGraphicsEllipseItem(QtCore.QRectF(0, 0, self.size, self.size))
tr = QtGui.QTransform.fromTranslate(((- self.size) * 0.5), ((- self.size) * 0.5))
... |
def clean_up(molecule, delete_input=True, delete_output=False):
input_file = (molecule.filename + '.inp')
output_file = (molecule.filename + '.out')
run_directory = os.getcwd()
for local_file in os.listdir(run_directory):
if local_file.endswith('.clean'):
os.remove(((run_directory + ... |
def add_common_options(parser):
parser.add_option('--show_defaults', '-d', action='store_false', help='Show the default values of command options. Must be typed before help option.')
parser.add_option('--plot_velocity', '-v', action='store_true', help='Plot the velocity traces also.', default=False)
parser.... |
def collate_fn_all(batch):
(obj_point_list, obj_label_list) = ([], [])
(rel_point_list, rel_label_list) = ([], [])
edge_indices = []
for i in batch:
obj_point_list.append(i[0])
obj_label_list.append(i[3])
rel_point_list.append(i[2])
rel_label_list.append(i[4])
edg... |
def add_flops_counting_methods(net_main_module):
net_main_module.start_flops_count = start_flops_count.__get__(net_main_module)
net_main_module.stop_flops_count = stop_flops_count.__get__(net_main_module)
net_main_module.reset_flops_count = reset_flops_count.__get__(net_main_module)
net_main_module.comp... |
def test_decorator_of_context_manager():
data = []
class Context():
def __init__(self, key):
self.key = key
def __enter__(self):
data.append(('enter %s' % self.key))
def __exit__(self, *args):
data.append(('exit %s' % self.key))
decorator = decorat... |
class LeafPattern(BasePattern):
def __init__(self, type=None, content=None, name=None):
if (type is not None):
assert (0 <= type < 256), type
if (content is not None):
assert isinstance(content, str), repr(content)
self.type = type
self.content = content
... |
def valid_pypi_name(package_spec: str) -> Optional[str]:
try:
package_req = Requirement(package_spec)
except InvalidRequirement:
return None
if (package_req.url or package_req.name.endswith(ARCHIVE_EXTENSIONS)):
return None
return canonicalize_name(package_req.name) |
def test_sink(input_dataframe, feature_set):
client = SparkClient()
client.conn.conf.set('spark.sql.sources.partitionOverwriteMode', 'dynamic')
feature_set_df = feature_set.construct(input_dataframe, client)
target_latest_df = OnlineFeatureStoreWriter.filter_latest(feature_set_df, id_columns=[key.name f... |
class PointnetSAModuleCenters(nn.Module):
def __init__(self, *, mlp: List[int], npoint: int=None, radius: float=None, nsample: int=None, bn: bool=True, use_xyz: bool=True, pooling: str='max', sigma: float=None, normalize_xyz: bool=False, sample_uniformly: bool=False, ret_unique_cnt: bool=False):
super().__i... |
class QlColoredFormatter(QlBaseFormatter):
__level_color = {'WARNING': COLOR.YELLOW, 'INFO': COLOR.BLUE, 'DEBUG': COLOR.MAGENTA, 'CRITICAL': COLOR.CRIMSON, 'ERROR': COLOR.RED}
def get_level_tag(self, level: str) -> str:
s = super().get_level_tag(level)
return f'{self.__level_color[level]}{s}{COL... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.