code stringlengths 101 5.91M |
|---|
def MLP(channels, bias=False, nonlin=LeakyReLU(negative_slope=0.2)):
return Seq(*[Seq(Lin(channels[(i - 1)], channels[i], bias=bias), BatchNorm1d(channels[i]), nonlin) for i in range(1, len(channels))]) |
def parse_optional_tags(string, *, return_string_sans_tags=False):
(safe, literals, state) = strip_string_literals(string)
split = safe.split('\n', 1)
if (len(split) > 1):
(first_line, rest) = split
else:
(first_line, rest) = (split[0], None)
sharp_index = first_line.find('#')
if... |
def siren_init_first(**kwargs):
module = kwargs['module']
n = kwargs['n']
if isinstance(module, nn.Linear):
module.weight.data.uniform_(((- 1) / n), (1 / n)) |
()
_context
('--network', 'ckpt_path', help='Network pickle filename', required=True)
('--attr_name', help='choose one of the attr: upper_length or bottom_length', type=str, required=True)
('--trunc', 'truncation', type=float, help='Truncation psi', default=0.8, show_default=True)
('--gen_video', type=bool, default=Tru... |
class Initialized(ExecutionEvent):
schema: dict[(str, Any)]
operations_count: (int | None)
links_count: (int | None)
location: (str | None)
seed: (int | None)
base_url: str
specification_name: str
start_time: float = field(default_factory=time.monotonic)
started_at: str = field(defau... |
def dataset_options(func):
decorators = [click.option('--datasets-dir', default='./data', show_default=True, help='Path to datasets.'), click.option('--dataset', '-d', type=click.Choice(DATASETS), default='imagenet', show_default=True, help='Specify dataset to use in experiment.'), click.option('--augmentation/--no... |
.skipif((get_start_method() != 'fork'), reason='multiprocessing with spawn method is not compatible with pytest.')
def test_mapwrapper_parallel():
in_arg = np.arange(10.0)
out_arg = np.sin(in_arg)
with MapWrapper(2) as p:
out = p(np.sin, in_arg)
assert_equal(list(out), out_arg)
asser... |
def reduce_tau(tau):
assert (tau.imag() > 0)
(a, b) = (ZZ(1), ZZ(0))
(c, d) = (b, a)
k = tau.real().round()
tau -= k
a -= (k * c)
b -= (k * d)
while (tau.abs() < 0.999):
tau = ((- 1) / tau)
(a, b, c, d) = (c, d, (- a), (- b))
k = tau.real().round()
tau -= ... |
class SegformerImageProcessor(BaseImageProcessor):
model_input_names = ['pixel_values']
def __init__(self, do_resize: bool=True, size: Dict[(str, int)]=None, resample: PILImageResampling=PILImageResampling.BILINEAR, do_rescale: bool=True, rescale_factor: Union[(int, float)]=(1 / 255), do_normalize: bool=True, i... |
class HFModelHandler(CommonModelHandler):
def __init__(self, method: GetConfigFrom=GetConfigFrom.HardCoded, *args, **kw):
super().__init__(*args, **kw)
self.pipeline_transformer_config = None
self.method = method
self.tokenizer = None
self.config = None
def _get_normal_mo... |
def MakeUnDir(tspec, *args):
if (type(tspec) == PUNGraph):
return MakeUnDir_PUNGraph(tspec, *args)
if (type(tspec) == PUndirNet):
return MakeUnDir_PUndirNet(tspec, *args)
if (type(tspec) == PDirNet):
return MakeUnDir_PDirNet(tspec, *args)
if (type(tspec) == PNGraph):
retu... |
def _sym_solve(Dinv, A, r1, r2, solve):
r = (r2 + A.dot((Dinv * r1)))
v = solve(r)
u = (Dinv * (A.T.dot(v) - r1))
return (u, v) |
def _get_const(value, desc, arg_name):
if (_is_value(value) and (value.node().kind() not in ('onnx::Constant', 'prim::Constant'))):
raise RuntimeError('ONNX symbolic expected a constant value of the {} argument, got `{}`'.format(arg_name, value))
return _parse_arg(value, desc) |
class CutExecutor(ActionExecutor):
def execute(self, script: Script, state: EnvironmentState, info: ExecutionInfo):
current_line = script[0]
info.set_current_line(current_line)
node = state.get_state_node(current_line.object())
if (node is None):
info.object_found_error()... |
def ComputeErrorRates(label_counts, word_counts, seq_errors, num_seqs):
label_errors = (label_counts.fn + label_counts.fp)
num_labels = (label_counts.truth_count + label_counts.test_count)
return ErrorRates(ComputeErrorRate(label_errors, num_labels), ComputeErrorRate(word_counts.fn, word_counts.truth_count)... |
def create_base_classifier(return_value, return_prob=None):
classifier = MagicMock()
classifier.predict.return_value = return_value
classifier.predict_proba.return_value = return_prob
return classifier |
def _generate_fantasized_model(model: FantasizerModelOrStack, fantasized_data: Dataset) -> (_fantasized_model | PredictJointPredictYModelStack):
if isinstance(model, ModelStack):
observations = tf.split(fantasized_data.observations, model._event_sizes, axis=(- 1))
fmods = []
for (mod, obs, e... |
class DigitalMonstersDataset(data.Dataset):
def __init__(self, root_path, input_height=None, input_width=None, output_height=128, output_width=None, is_gray=False, pokemon=True, digimon=True, nexomon=True):
super(DigitalMonstersDataset, self).__init__()
image_list = []
if pokemon:
... |
def register_Ns3CallbackImpl__Void_Ns3Ptr__lt__const_ns3Packet__gt___Ns3UanAddress_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, cls):
cls.add_constructor([])
cls.add_constructor([param('ns3::CallbackImpl< void, ns3::Ptr< ns3::Packet const >, ns3::UanAddress, ns3::empty, ns... |
class Network():
def __init__(self):
self.graph = tf.Graph()
gpu_options = tf.GPUOptions(allow_growth=True)
tf_config = tf.ConfigProto(gpu_options=gpu_options, allow_soft_placement=True, log_device_placement=False)
self.sess = tf.Session(graph=self.graph, config=tf_config)
def in... |
def keras_train_distributed(classifier, model_params, save, model_meta, FLAGS, train_dataset_fn, val_dataset_fn, is_pai=True):
(cluster, task_type, task_index) = make_distributed_info_without_evaluator(FLAGS)
dump_into_tf_config(cluster, task_type, task_index)
dist_strategy = tf.contrib.distribute.Parameter... |
def do_join(eval_ctx, value, d=u'', attribute=None):
if (attribute is not None):
value = imap(make_attrgetter(eval_ctx.environment, attribute), value)
if (not eval_ctx.autoescape):
return text_type(d).join(imap(text_type, value))
if (not hasattr(d, '__html__')):
value = list(value)
... |
def compute_normal(z, c):
J0 = vec4(1, 0, 0, 0)
J1 = vec4(0, 1, 0, 0)
J2 = vec4(0, 0, 1, 0)
z_curr = z
iterations = 0
while ((z_curr.norm() < max_norm) and (iterations < iters)):
cz = quat_conj(z_curr)
J0 = vec4(tm.dot(J0, cz), tm.dot(J0.xy, z_curr.yx), tm.dot(J0.xz, z_curr.zx), ... |
def get_adafactor_weight_predictor(pred_mem: str, pred_type: str, optimizer, scheduler=None, nag_with_predictor=False, true_weights_storage=None) -> WeightPredictor:
has_weight_decay = any([(pg['weight_decay'] != 0) for pg in optimizer.param_groups])
if has_weight_decay:
pass
if (pred_type == 'msnag... |
def hfft(x, n=None, axis=(- 1), norm=None, overwrite_x=False, workers=None, *, plan=None):
return _execute_1D('hfft', _pocketfft.hfft, x, n=n, axis=axis, norm=norm, overwrite_x=overwrite_x, workers=workers, plan=plan) |
class Pix2pixDataset(BaseDataset):
def modify_commandline_options(parser, is_train):
parser.add_argument('--no_pairing_check', action='store_true', help='If specified, skip sanity check of correct label-image file pairing')
return parser
def initialize(self, opt):
self.opt = opt
... |
def get_type_information_cname(code, dtype, maxdepth=None):
namesuffix = mangle_dtype_name(dtype)
name = ('__Pyx_TypeInfo_%s' % namesuffix)
structinfo_name = ('__Pyx_StructFields_%s' % namesuffix)
if dtype.is_error:
return '<error>'
if (maxdepth is None):
maxdepth = dtype.struct_nest... |
class RenameVar(NodeTransformer):
def __init__(self, oldname: str, newname: str):
self.oldname = oldname
self.newname = newname
def visit_Name_Node(self, node: ast_internal_classes.Name_Node):
return (ast_internal_classes.Name_Node(name=self.newname) if (node.name == self.oldname) else n... |
def clean_ie_pps(df: Union[(pd.DataFrame, dd.DataFrame)], column: str, output_format: str='standard', inplace: bool=False, errors: str='coerce', progress: bool=True) -> pd.DataFrame:
if (output_format not in {'compact', 'standard'}):
raise ValueError(f'output_format {output_format} is invalid. It needs to b... |
class SkipUpBlock2D(nn.Module):
def __init__(self, in_channels: int, prev_output_channel: int, out_channels: int, temb_channels: int, dropout: float=0.0, num_layers: int=1, resnet_eps: float=1e-06, resnet_time_scale_shift: str='default', resnet_act_fn: str='swish', resnet_pre_norm: bool=True, output_scale_factor=np... |
def mod_endpoint(edge, z, end):
if (edge.get_node1() == z):
edge.set_endpoint1(end)
elif (edge.get_node2() == z):
edge.set_endpoint2(end)
else:
raise ValueError('z not in edge') |
def __add_publish_ex3_subprocess(available_detectors: List[str], available_datasets: List[str], subparsers) -> None:
experiment_parser = subparsers.add_parser('ex3', formatter_class=SortingHelpFormatter, help="Experiment 3: Publish potential hits for known misuses to assess a detector's recall when it uses its own ... |
class DirectlyParameterizedNormalDiag(TrackableLayer):
means: Parameter
stds: Parameter
def __init__(self, num_data: int, latent_dim: int, means: Optional[np.ndarray]=None):
super().__init__()
if (means is None):
means = (0.01 * np.random.randn(num_data, latent_dim))
elif... |
def load_from_json(file):
with open(file, 'r') as json_file:
contents = json.load(json_file)
return contents |
def isstringfunction(rout):
if (not isfunction(rout)):
return 0
if ('result' in rout):
a = rout['result']
else:
a = rout['name']
if (a in rout['vars']):
return isstring(rout['vars'][a])
return 0 |
def write_examples(job_id, args):
job_tmp_dir = os.path.join(args.data_dir, 'tmp', ('job_' + str(job_id)))
owt_dir = os.path.join(args.data_dir, 'openwebtext')
def log(*args):
msg = ' '.join(map(str, args))
print('Job {}:'.format(job_id), msg)
log('Creating example writer')
example_w... |
def is_PrimeFiniteField(x):
from sage.misc.superseded import deprecation
deprecation(32664, 'the function is_PrimeFiniteField is deprecated; use isinstance(x, sage.rings.finite_rings.finite_field_base.FiniteField) and x.is_prime_field() instead')
from .finite_field_prime_modn import FiniteField_prime_modn
... |
def v_5_1_BIBD(v, check=True):
v = int(v)
assert (v > 1)
assert (((v % 20) == 5) or ((v % 20) == 1))
if (((v % 5) == 0) and (((v // 5) % 4) == 1) and is_prime_power((v // 5))):
bibd = BIBD_5q_5_for_q_prime_power((v // 5))
elif (v in [21, 41, 61, 81, 141, 161, 281]):
from .difference_... |
class TestFeatureOptimizer(unittest.TestCase):
def setUp(self) -> None:
self.model = tf.keras.Sequential([tf.keras.layers.Input((28, 28, 3)), tf.keras.layers.Conv2D(16, (3, 3)), tf.keras.layers.Conv2D(16, (3, 3)), tf.keras.layers.MaxPool2D((2, 2)), tf.keras.layers.Conv2D(16, (3, 3)), tf.keras.layers.Conv2D(... |
class FlowNetS(nn.Module):
def __init__(self, args, input_channels=12, batchNorm=True):
super(FlowNetS, self).__init__()
self.batchNorm = batchNorm
self.conv1 = conv(self.batchNorm, input_channels, 64, kernel_size=7, stride=2)
self.conv2 = conv(self.batchNorm, 64, 128, kernel_size=5,... |
def redirect_entity(ent, redirects_en):
if (ent is not None):
ent_underscore = ent.replace(' ', '_')
if (ent_underscore in redirects_en):
ent = redirects_en[ent_underscore].replace('_', ' ')
return ent |
def read_keyframes(video_fpath: str, keyframes: FrameTsList, video_stream_idx: int=0) -> FrameList:
try:
with PathManager.open(video_fpath, 'rb') as io:
container = av.open(io)
stream = container.streams.video[video_stream_idx]
frames = []
for pts in keyframes... |
def evaluate(args, model, tokenizer, processor, prefix=''):
(dataset, features) = load_and_cache_examples(args, model, tokenizer, processor, evaluate=True)
if ((not os.path.exists(args.output_dir)) and (args.local_rank in [(- 1), 0])):
os.makedirs(args.output_dir)
args.eval_batch_size = args.per_gpu... |
class CFQ(TextDataset):
URL = '
def tokenize_punctuation(self, text):
text = map((lambda c: ((' %s ' % c) if (c in string.punctuation) else c)), text)
return ' '.join(''.join(text).split())
def preprocess_sparql(self, query):
query = query.replace('count(*)', 'count ( * )')
t... |
def kldiv(x, xp, k=3, base=2):
assert (k <= (len(x) - 1)), 'Set k smaller than num. samples - 1'
assert (k <= (len(xp) - 1)), 'Set k smaller than num. samples - 1'
assert (len(x[0]) == len(xp[0])), 'Two distributions must have same dim.'
d = len(x[0])
n = len(x)
m = len(xp)
const = (log(m) -... |
class NetG(nn.Module):
def __init__(self, opt):
super(NetG, self).__init__()
self.encoder1 = Encoder(opt.isize, opt.nz, opt.nc, opt.ngf, opt.ngpu, opt.extralayers)
self.decoder = Decoder(opt.isize, opt.nz, opt.nc, opt.ngf, opt.ngpu, opt.extralayers)
self.encoder2 = Encoder(opt.isize,... |
def _get_pipeline_hyperparameter(hyperparameters, dataset_name, pipeline_name):
hyperparameters_ = deepcopy(hyperparameters)
if hyperparameters:
hyperparameters_ = (hyperparameters_.get(dataset_name) or hyperparameters_)
hyperparameters_ = (hyperparameters_.get(pipeline_name) or hyperparameters_... |
def conv3x3(in_planes, out_planes, stride=1):
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=True) |
def DMSToDecimal(degrees, minutes, seconds):
d = ((abs(degrees) + (minutes / 60.0)) + (seconds / 3600.0))
if (degrees < 0):
return (- d)
else:
return d |
class WordpieceTokenizer(object):
def __init__(self, vocab, unk_token, max_input_chars_per_word=100):
self.vocab = vocab
self.unk_token = unk_token
self.max_input_chars_per_word = max_input_chars_per_word
def tokenize(self, text):
output_tokens = []
for token in whitespac... |
def compute_metrics(pred):
labels = pred.label_ids
preds = pred.predictions.argmax((- 1))
acc = accuracy_score(labels, preds)
return {'accuracy': acc} |
class CoordinateDescentTuner(Tuner):
def line_search(self, config, cur_param, epsilon, budget, cur_score=0):
(minval, maxval) = self.search_space[cur_param]['range']
Y = (maxval - minval)
delta = (epsilon * Y)
orig_val = config[cur_param]
if (((orig_val + delta) > maxval) and... |
def parse_vec2(s: Union[(str, Tuple[(float, float)])]) -> Tuple[(float, float)]:
if isinstance(s, tuple):
return s
parts = s.split(',')
if (len(parts) == 2):
return (float(parts[0]), float(parts[1]))
raise ValueError(f'cannot parse 2-vector {s}') |
class PhysicallyOffsetPaddle125BreakoutWorld(OffsetPaddleBreakoutWorld):
paddle_class = VisuallyFixedOffsetPaddle
paddle_offset = 125 |
def MODEL(model_name, weight_decay, image, label, lr, epoch, is_training):
network_fn = nets_factory.get_network_fn(model_name, weight_decay=weight_decay)
end_points = network_fn(image, is_training=is_training, lr=lr, val=(not is_training))
losses = []
if is_training:
def scale_grad(x, scale):
... |
class STS16CLEval(STSEval):
def __init__(self, taskpath, seed=1111):
logging.debug('***** Transfer task : STS16CL *****\n\n')
self.seed = seed
self.datasets = ['multisource', 'news']
self.loadFile(taskpath)
def loadFile(self, fpath):
self.data = {}
self.samples = ... |
class OneFormerImageProcessor(metaclass=DummyObject):
_backends = ['vision']
def __init__(self, *args, **kwargs):
requires_backends(self, ['vision']) |
class Pipeline(_ScikitCompat):
default_input_names = None
def __init__(self, model, tokenizer: PreTrainedTokenizer=None, modelcard: ModelCard=None, framework: Optional[str]=None, args_parser: ArgumentHandler=None, device: int=(- 1), binary_output: bool=False):
if (framework is None):
framewo... |
def test_case83():
url = (brokerIp + '/ngsi-ld/v1/entityOperations/upsert')
headers = {'Content-Type': 'application/json', 'Accept': 'application/ld+json', 'Link': '<{{link}}>; rel=" type="application/ld+json"', 'fiware-service': 'openiot', 'fiware-servicepath': 'test'}
r = requests.post(url, data=json.dump... |
class Schema():
def __init__(self, schema, table):
self._schema = schema
self._table = table
self._idMap = self._map(self._schema, self._table)
def schema(self):
return self._schema
def idMap(self):
return self._idMap
def _map(self, schema, table):
column_... |
class SliceObjectAction(BaseAction):
valid_actions = {'SliceObject', 'OpenObject', 'CloseObject'}
def get_reward(self, state, prev_state, expert_plan, goal_idx):
if (state.metadata['lastAction'] not in self.valid_actions):
(reward, done) = (self.rewards['invalid_action'], False)
... |
class IntegralProjectiveCurve_finite_field(IntegralProjectiveCurve):
_point = IntegralProjectiveCurvePoint_finite_field
def places(self, degree=1):
F = self.function_field()
return F.places(degree)
def closed_points(self, degree=1):
F = self.function_field()
places_above = F.... |
def red(x):
if (x < 0.352):
return 0
if ((x >= 0.352) and (x < 0.662)):
return ((822.58 * x) - 289.55)
if ((x >= 0.662) and (x < 0.89)):
return 255
if (x >= 0.89):
return (((- 1159) * x) + 1286.5) |
class BaseDataset(Dataset, metaclass=ABCMeta):
def __init__(self, ann_file, pipeline, data_prefix=None, test_mode=False, multi_class=False, num_classes=None, start_index=1, modality='RGB', sample_by_class=False, power=0, dynamic_length=False):
super().__init__()
self.ann_file = ann_file
self... |
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})')
def lr_lamb... |
def dist_reduce_tensor(tensor):
world_size = get_world_size()
if (world_size < 2):
return tensor
with torch.no_grad():
dist.reduce(tensor, dst=0)
if (get_rank() == 0):
tensor /= world_size
return tensor |
def main():
print(((('\n' + ' SMPLpix Evaluation Loop \n') + '\n') + ' Copyright (c) 2021 - now, Sergey Prokudin (sergey.) '))
args = get_smplpix_arguments()
print('ARGUMENTS:')
pprint.pprint(args)
if (args.checkpoint_path is None):
print('no model checkpoint was specified, looking in the l... |
def test_initialize_unknown_binary_policy(digraph_with_unknown_policy):
with pytest.raises(KeyError):
digraph_with_unknown_policy._initialize_binary_policy() |
def _create_graph(structure_dict):
graph = pydot.Dot()
for node in structure_dict['nodes']:
graph.add_node(pydot.Node(node))
for (node1, node2) in structure_dict['edges']:
graph.add_edge(pydot.Edge(node1, node2))
return graph |
def get_device(args):
args.ngpu = (torch.cuda.device_count() if (args.ngpu == None) else args.ngpu)
cuda = ('cuda:' + str(args.gpu_1st))
device = torch.device((cuda if (torch.cuda.is_available() and (args.ngpu > 0)) else 'cpu'))
multi_gpu = (True if (args.ngpu > 1) else False)
return (device, multi_... |
def corpus_bleu(list_of_references, hypotheses, weights=(0.25, 0.25, 0.25, 0.25), smoothing_function=None, auto_reweigh=False):
p_numerators = Counter()
p_denominators = Counter()
(hyp_lengths, ref_lengths) = (0, 0)
assert (len(list_of_references) == len(hypotheses)), 'The number of hypotheses and their... |
def get_available_gpus():
from tensorflow.python.client import device_lib
local_device_protos = device_lib.list_local_devices()
return [x.name for x in local_device_protos if (x.device_type == 'GPU')] |
class DesAscPredictor():
def __init__(self, question, sql, table, history):
self.sql = sql
self.question = question
self.history = history
self.table = table
def generate_output(self):
for key in self.sql:
if ((key == 'orderBy') and self.sql[key]):
... |
def post_process(out, pb, state, extend=False):
from sfepy.base.base import Struct
dvel = pb.evaluate('ev_diffusion_velocity.i.Omega(m.K, p)', mode='el_avg')
out['dvel'] = Struct(name='output_data', mode='cell', data=dvel, dofs=None)
stress = pb.evaluate('ev_cauchy_stress.i.Omega(m.D, u)', mode='el_avg'... |
def add_stats_to_debug_csv():
row = [multi_stats.get('all', 'tried'), multi_stats.get('all', 'success'), multi_stats.get('all', 'time_spent'), multi_stats.get('is_flickr', 'tried'), multi_stats.get('is_flickr', 'success'), multi_stats.get('is_flickr', 'time_spent'), multi_stats.get('not_flickr', 'tried'), multi_sta... |
class MaskedSoftmax(nn.Module):
def __init__(self):
super(MaskedSoftmax, self).__init__()
self.softmax = nn.Softmax(1)
def forward(self, x, mask=None):
if (mask is not None):
mask = mask.float()
if (mask is not None):
x_masked = ((x * mask) + (1 - (1 / mas... |
class MiniGridWrapper(gym.ObservationWrapper):
def __init__(self, env):
gym.ObservationWrapper.__init__(self, env)
self.observation_space = env.observation_space.spaces['image']
def observation(self, observation):
return observation['image'] |
def rotmat_to_ee(matrix: Union[(torch.Tensor, numpy.ndarray)], convention: str='xyz') -> Union[(torch.Tensor, numpy.ndarray)]:
if ((matrix.shape[(- 1)] != 3) or (matrix.shape[(- 2)] != 3)):
raise ValueError(f'Invalid rotation matrix shape f{matrix.shape}.')
t = Compose([matrix_to_euler_angles])
retu... |
class FunctionFieldDerivation(RingDerivationWithoutTwist):
def __init__(self, parent):
RingDerivationWithoutTwist.__init__(self, parent)
self.__field = parent.domain()
def is_injective(self) -> bool:
return False
def _rmul_(self, factor):
return self._lmul_(factor) |
def test_get_parameter_example_from_properties():
schema: dict[(str, Any)] = {'parameters': [{'name': 'param1', 'in': 'query', 'schema': {'type': 'object', 'properties': {'prop1': {'type': 'string', 'example': 'prop1 example string'}, 'prop2': {'type': 'string', 'example': 'prop2 example string'}, 'noExampleProp': ... |
def test_initialize_mix():
_pos = 'datasets/ToyFather/train/pos.pl'
_neg = 'datasets/ToyFather/train/neg.pl'
_facts = pathlib.Path('datasets/ToyFather/train/facts.pl')
_db = Database.from_files(pos=_pos, neg=_neg, facts=_facts, lazy_load=True)
_db.neg = ['father(harrypotter,ronweasley).']
assert... |
def count_above(errors, epsilon):
above = (errors > epsilon)
total_above = len(errors[above])
above = pd.Series(above)
shift = above.shift(1)
change = (above != shift)
total_consecutive = sum((above & change))
return (total_above, total_consecutive) |
def test_suffix_perturbation():
data_augmenter = DataAugmenter(perturbations=[SuffixPerturbation(suffix='pixel art')])
instance: Instance = Instance(id='id0', input=Input(text='A blue dog'), references=[])
instances: List[Instance] = data_augmenter.generate([instance], include_original=True)
assert (len... |
def _cardinality_subfield(self, jpol):
k = self.base_ring()
p = k.characteristic()
d = k.degree()
jdeg = jpol.degree()
if (jdeg >= d):
raise ValueError('j-invariant does not lie in a subfield')
GFj = GF((p, jdeg), name='j', modulus=jpol)
j = GFj.gen()
if (j == 1728):
retu... |
def make_dataset(dir):
images = []
assert os.path.isdir(dir), ('%s is not a valid directory' % dir)
for (root, _, fnames) in sorted(os.walk(dir)):
for fname in fnames:
if is_image_file(fname):
path = os.path.join(root, fname)
images.append(path)
return... |
def crop_all_images(split_dict, global_product_pair_id_map, root_dir, image_root_dir_split, low_res_image_root, crop_images_save_root, target_image_size):
next_anno_id = 0
next_img_id = 0
all_annotations = {}
all_image_infos = {}
for subset_name in list(split_dict.keys()):
CROP_IMAGES_SAVE_P... |
def chamfer_distance(x, y, metric='l2', direction='bi'):
if (direction == 'y_to_x'):
x_nn = NearestNeighbors(n_neighbors=1, leaf_size=1, algorithm='kd_tree', metric=metric).fit(x)
min_y_to_x = x_nn.kneighbors(y)[0]
chamfer_dist = np.mean(min_y_to_x)
elif (direction == 'x_to_y'):
... |
def all_seld_eval(args, pred_directory, result_path=None):
if args.eval:
with open(args.eval_wav_txt) as f:
wav_file_list = [s.strip() for s in f.readlines()]
wav_dir = os.path.dirname(wav_file_list[0])
elif args.val:
with open(args.val_wav_txt) as f:
wav_file_lis... |
class LayerNormGeneral(nn.Module):
def __init__(self, affine_shape=None, normalized_dim=((- 1),), scale=True, bias=True, eps=1e-05):
super().__init__()
self.normalized_dim = normalized_dim
self.use_scale = scale
self.use_bias = bias
self.weight = (nn.Parameter(torch.ones(affi... |
class TestAflCov(unittest.TestCase):
tmp_file = './tmp_cmd.out'
version_file = '../VERSION'
afl_cov_cmd = '../afl-cov'
single_generator = './afl/afl-cov-generator.sh'
parallel_generator = './afl/afl-cov-generator-parallel.sh'
afl_cov_live = './afl/afl-cov-generator-live.sh'
top_out_dir = './... |
def replace_with_separator(text, separator, regexs):
replacement = (('\\1' + separator) + '\\2')
result = text
for regex in regexs:
result = regex.sub(replacement, result)
return result |
def setup(old_style=False, target_package_name='returnn'):
print('Setup for importing RETURNN as framework/package.')
tmp_env_path_dir = tempfile.mkdtemp()
print('Temp dir:', tmp_env_path_dir)
if old_style:
print('Old-style setup!')
src_dir = _base_dir
else:
src_dir = ('%s/re... |
class LinearLR(_LRScheduler):
def __init__(self, optimizer, total_iter, last_epoch=(- 1)):
self.total_iter = total_iter
super(LinearLR, self).__init__(optimizer, last_epoch)
def get_lr(self):
process = (self.last_epoch / self.total_iter)
weight = (1 - process)
return [(we... |
def recurrent_net(net, cell_net, inputs, initial_cell_inputs, links, timestep=None, scope=None, outputs_with_grads=(0,), recompute_blobs_on_backward=None, forward_only=False):
assert (len(inputs) == 1), 'Only one input blob is supported so far'
input_blobs = [str(i[0]) for i in inputs]
initial_input_blobs =... |
def test_constructors():
(loss, (Nsig, poigen, poieval)) = create_loss()
ToyResult(poigen, poieval)
with pytest.raises(TypeError):
ToyResult(poigen, 'poieval')
with pytest.raises(TypeError):
ToyResult(poieval, poieval)
ToysManager(loss, Minuit()) |
def register_Ns3Ipv4PacketFilter_methods(root_module, cls):
cls.add_constructor([param('ns3::Ipv4PacketFilter const &', 'arg0')])
cls.add_constructor([])
cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True)
cls.add_method('CheckProtocol', 'bool', [param('ns3::Ptr< ns3::QueueDiscItem >', 'item'... |
class RDN(nn.Module):
def __init__(self, args):
super(RDN, self).__init__()
r = args.scale[0]
G0 = args.G0
kSize = args.RDNkSize
(self.D, C, G) = {'A': (20, 6, 32), 'B': (16, 8, 64)}[args.RDNconfig]
self.SFENet1 = nn.Conv2d(args.n_colors, G0, kSize, padding=((kSize - ... |
def volwrite(uri, im, format=None, **kwargs):
imt = type(im)
im = np.asanyarray(im)
if (not np.issubdtype(im.dtype, np.number)):
raise ValueError('Image is not numeric, but {}.'.format(imt.__name__))
elif (im.ndim == 3):
pass
elif ((im.ndim == 4) and (im.shape[3] < 32)):
pass... |
def process_mr_l3cube(paths, short_name):
base_output_path = paths['NER_DATA_DIR']
in_directory = os.path.join(paths['NERBASE'], 'marathi', 'MarathiNLP', 'L3Cube-MahaNER', 'IOB')
input_files = ['train_iob.txt', 'valid_iob.txt', 'test_iob.txt']
input_files = [os.path.join(in_directory, x) for x in input_... |
class BaseModelOutputWithNoAttention(ModelOutput):
last_hidden_state: torch.FloatTensor = None
hidden_states: Optional[Tuple[torch.FloatTensor]] = None |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.