body
stringlengths 26
98.2k
| body_hash
int64 -9,222,864,604,528,158,000
9,221,803,474B
| docstring
stringlengths 1
16.8k
| path
stringlengths 5
230
| name
stringlengths 1
96
| repository_name
stringlengths 7
89
| lang
stringclasses 1
value | body_without_docstring
stringlengths 20
98.2k
|
---|---|---|---|---|---|---|---|
@classmethod
def build_model(cls, args, task):
'Build a new model instance.'
base_architecture(args)
if (not hasattr(args, 'max_source_positions')):
args.max_source_positions = DEFAULT_MAX_SOURCE_POSITIONS
if (not hasattr(args, 'max_target_positions')):
args.max_target_positions = DEFAULT_MAX_TARGET_POSITIONS
(src_dict, tgt_dict) = (task.source_dictionary, task.target_dictionary)
if (len(task.datasets) > 0):
src_berttokenizer = next(iter(task.datasets.values())).berttokenizer
else:
src_berttokenizer = BertTokenizer.from_pretrained(args.bert_model_name)
def build_embedding(dictionary, embed_dim, path=None):
num_embeddings = len(dictionary)
padding_idx = dictionary.pad()
emb = Embedding(num_embeddings, embed_dim, padding_idx)
if path:
embed_dict = utils.parse_embedding(path)
utils.load_embedding(embed_dict, dictionary, emb)
return emb
if args.share_all_embeddings:
if (src_dict != tgt_dict):
raise ValueError('--share-all-embeddings requires a joined dictionary')
if (args.encoder_embed_dim != args.decoder_embed_dim):
raise ValueError('--share-all-embeddings requires --encoder-embed-dim to match --decoder-embed-dim')
if (args.decoder_embed_path and (args.decoder_embed_path != args.encoder_embed_path)):
raise ValueError('--share-all-embeddings not compatible with --decoder-embed-path')
encoder_embed_tokens = build_embedding(src_dict, args.encoder_embed_dim, args.encoder_embed_path)
decoder_embed_tokens = encoder_embed_tokens
args.share_decoder_input_output_embed = True
else:
encoder_embed_tokens = build_embedding(src_dict, args.encoder_embed_dim, args.encoder_embed_path)
decoder_embed_tokens = build_embedding(tgt_dict, args.decoder_embed_dim, args.decoder_embed_path)
bertencoder = BertModel.from_pretrained(args.bert_model_name)
args.bert_out_dim = bertencoder.hidden_size
encoder = cls.build_encoder(args, src_dict, encoder_embed_tokens)
decoder = cls.build_decoder(args, tgt_dict, decoder_embed_tokens)
return TransformerModel(encoder, decoder, bertencoder, src_berttokenizer, args.mask_cls_sep) | 2,152,914,506,224,695,600 | Build a new model instance. | models/transformer.py | build_model | NCTUMLlab/Adversarial-Masking-Transformers-for-Language-Understanding | python | @classmethod
def build_model(cls, args, task):
base_architecture(args)
if (not hasattr(args, 'max_source_positions')):
args.max_source_positions = DEFAULT_MAX_SOURCE_POSITIONS
if (not hasattr(args, 'max_target_positions')):
args.max_target_positions = DEFAULT_MAX_TARGET_POSITIONS
(src_dict, tgt_dict) = (task.source_dictionary, task.target_dictionary)
if (len(task.datasets) > 0):
src_berttokenizer = next(iter(task.datasets.values())).berttokenizer
else:
src_berttokenizer = BertTokenizer.from_pretrained(args.bert_model_name)
def build_embedding(dictionary, embed_dim, path=None):
num_embeddings = len(dictionary)
padding_idx = dictionary.pad()
emb = Embedding(num_embeddings, embed_dim, padding_idx)
if path:
embed_dict = utils.parse_embedding(path)
utils.load_embedding(embed_dict, dictionary, emb)
return emb
if args.share_all_embeddings:
if (src_dict != tgt_dict):
raise ValueError('--share-all-embeddings requires a joined dictionary')
if (args.encoder_embed_dim != args.decoder_embed_dim):
raise ValueError('--share-all-embeddings requires --encoder-embed-dim to match --decoder-embed-dim')
if (args.decoder_embed_path and (args.decoder_embed_path != args.encoder_embed_path)):
raise ValueError('--share-all-embeddings not compatible with --decoder-embed-path')
encoder_embed_tokens = build_embedding(src_dict, args.encoder_embed_dim, args.encoder_embed_path)
decoder_embed_tokens = encoder_embed_tokens
args.share_decoder_input_output_embed = True
else:
encoder_embed_tokens = build_embedding(src_dict, args.encoder_embed_dim, args.encoder_embed_path)
decoder_embed_tokens = build_embedding(tgt_dict, args.decoder_embed_dim, args.decoder_embed_path)
bertencoder = BertModel.from_pretrained(args.bert_model_name)
args.bert_out_dim = bertencoder.hidden_size
encoder = cls.build_encoder(args, src_dict, encoder_embed_tokens)
decoder = cls.build_decoder(args, tgt_dict, decoder_embed_tokens)
return TransformerModel(encoder, decoder, bertencoder, src_berttokenizer, args.mask_cls_sep) |
def forward(self, src_tokens, src_lengths):
"\n Args:\n src_tokens (LongTensor): tokens in the source language of shape\n `(batch, src_len)`\n src_lengths (torch.LongTensor): lengths of each source sentence of\n shape `(batch)`\n\n Returns:\n dict:\n - **encoder_out** (Tensor): the last encoder layer's output of\n shape `(src_len, batch, embed_dim)`\n - **encoder_padding_mask** (ByteTensor): the positions of\n padding elements of shape `(batch, src_len)`\n "
x = (self.embed_scale * self.embed_tokens(src_tokens))
if (self.embed_positions is not None):
x += self.embed_positions(src_tokens)
x = F.dropout(x, p=self.dropout, training=self.training)
x = x.transpose(0, 1)
encoder_padding_mask = src_tokens.eq(self.padding_idx)
if (not encoder_padding_mask.any()):
encoder_padding_mask = None
for layer in self.layers:
x = layer(x, encoder_padding_mask)
if self.layer_norm:
x = self.layer_norm(x)
return {'encoder_out': x, 'encoder_padding_mask': encoder_padding_mask} | 8,721,051,598,448,000,000 | Args:
src_tokens (LongTensor): tokens in the source language of shape
`(batch, src_len)`
src_lengths (torch.LongTensor): lengths of each source sentence of
shape `(batch)`
Returns:
dict:
- **encoder_out** (Tensor): the last encoder layer's output of
shape `(src_len, batch, embed_dim)`
- **encoder_padding_mask** (ByteTensor): the positions of
padding elements of shape `(batch, src_len)` | models/transformer.py | forward | NCTUMLlab/Adversarial-Masking-Transformers-for-Language-Understanding | python | def forward(self, src_tokens, src_lengths):
"\n Args:\n src_tokens (LongTensor): tokens in the source language of shape\n `(batch, src_len)`\n src_lengths (torch.LongTensor): lengths of each source sentence of\n shape `(batch)`\n\n Returns:\n dict:\n - **encoder_out** (Tensor): the last encoder layer's output of\n shape `(src_len, batch, embed_dim)`\n - **encoder_padding_mask** (ByteTensor): the positions of\n padding elements of shape `(batch, src_len)`\n "
x = (self.embed_scale * self.embed_tokens(src_tokens))
if (self.embed_positions is not None):
x += self.embed_positions(src_tokens)
x = F.dropout(x, p=self.dropout, training=self.training)
x = x.transpose(0, 1)
encoder_padding_mask = src_tokens.eq(self.padding_idx)
if (not encoder_padding_mask.any()):
encoder_padding_mask = None
for layer in self.layers:
x = layer(x, encoder_padding_mask)
if self.layer_norm:
x = self.layer_norm(x)
return {'encoder_out': x, 'encoder_padding_mask': encoder_padding_mask} |
def reorder_encoder_out(self, encoder_out, bert_outs, new_order):
'\n Reorder encoder output according to *new_order*.\n\n Args:\n encoder_out: output from the ``forward()`` method\n new_order (LongTensor): desired order\n\n Returns:\n *encoder_out* rearranged according to *new_order*\n '
if (encoder_out['encoder_out'] is not None):
encoder_out['encoder_out'] = encoder_out['encoder_out'].index_select(1, new_order)
if (encoder_out['encoder_padding_mask'] is not None):
encoder_out['encoder_padding_mask'] = encoder_out['encoder_padding_mask'].index_select(0, new_order)
if (bert_outs['bert_encoder_out'] is not None):
bert_outs['bert_encoder_out'] = bert_outs['bert_encoder_out'].index_select(1, new_order)
if (bert_outs['bert_encoder_padding_mask'] is not None):
bert_outs['bert_encoder_padding_mask'] = bert_outs['bert_encoder_padding_mask'].index_select(0, new_order)
return (encoder_out, bert_outs) | -4,539,497,251,350,111,000 | Reorder encoder output according to *new_order*.
Args:
encoder_out: output from the ``forward()`` method
new_order (LongTensor): desired order
Returns:
*encoder_out* rearranged according to *new_order* | models/transformer.py | reorder_encoder_out | NCTUMLlab/Adversarial-Masking-Transformers-for-Language-Understanding | python | def reorder_encoder_out(self, encoder_out, bert_outs, new_order):
'\n Reorder encoder output according to *new_order*.\n\n Args:\n encoder_out: output from the ``forward()`` method\n new_order (LongTensor): desired order\n\n Returns:\n *encoder_out* rearranged according to *new_order*\n '
if (encoder_out['encoder_out'] is not None):
encoder_out['encoder_out'] = encoder_out['encoder_out'].index_select(1, new_order)
if (encoder_out['encoder_padding_mask'] is not None):
encoder_out['encoder_padding_mask'] = encoder_out['encoder_padding_mask'].index_select(0, new_order)
if (bert_outs['bert_encoder_out'] is not None):
bert_outs['bert_encoder_out'] = bert_outs['bert_encoder_out'].index_select(1, new_order)
if (bert_outs['bert_encoder_padding_mask'] is not None):
bert_outs['bert_encoder_padding_mask'] = bert_outs['bert_encoder_padding_mask'].index_select(0, new_order)
return (encoder_out, bert_outs) |
def max_positions(self):
'Maximum input length supported by the encoder.'
if (self.embed_positions is None):
return self.max_source_positions
return min(self.max_source_positions, self.embed_positions.max_positions()) | -5,228,954,016,557,509,000 | Maximum input length supported by the encoder. | models/transformer.py | max_positions | NCTUMLlab/Adversarial-Masking-Transformers-for-Language-Understanding | python | def max_positions(self):
if (self.embed_positions is None):
return self.max_source_positions
return min(self.max_source_positions, self.embed_positions.max_positions()) |
def upgrade_state_dict_named(self, state_dict, name):
'Upgrade a (possibly old) state dict for new versions of fairseq.'
if isinstance(self.embed_positions, SinusoidalPositionalEmbedding):
weights_key = '{}.embed_positions.weights'.format(name)
if (weights_key in state_dict):
del state_dict[weights_key]
state_dict['{}.embed_positions._float_tensor'.format(name)] = torch.FloatTensor(1)
for i in range(len(self.layers)):
self.layers[i].upgrade_state_dict_named(state_dict, '{}.layers.{}'.format(name, i))
version_key = '{}.version'.format(name)
if (utils.item(state_dict.get(version_key, torch.Tensor([1]))[0]) < 2):
self.layer_norm = None
self.normalize = False
state_dict[version_key] = torch.Tensor([1])
return state_dict | 6,001,696,072,670,587,000 | Upgrade a (possibly old) state dict for new versions of fairseq. | models/transformer.py | upgrade_state_dict_named | NCTUMLlab/Adversarial-Masking-Transformers-for-Language-Understanding | python | def upgrade_state_dict_named(self, state_dict, name):
if isinstance(self.embed_positions, SinusoidalPositionalEmbedding):
weights_key = '{}.embed_positions.weights'.format(name)
if (weights_key in state_dict):
del state_dict[weights_key]
state_dict['{}.embed_positions._float_tensor'.format(name)] = torch.FloatTensor(1)
for i in range(len(self.layers)):
self.layers[i].upgrade_state_dict_named(state_dict, '{}.layers.{}'.format(name, i))
version_key = '{}.version'.format(name)
if (utils.item(state_dict.get(version_key, torch.Tensor([1]))[0]) < 2):
self.layer_norm = None
self.normalize = False
state_dict[version_key] = torch.Tensor([1])
return state_dict |
def forward(self, src_tokens, src_lengths, bert_encoder_out):
"\n Args:\n src_tokens (LongTensor): tokens in the source language of shape\n `(batch, src_len)`\n src_lengths (torch.LongTensor): lengths of each source sentence of\n shape `(batch)`\n\n Returns:\n dict:\n - **encoder_out** (Tensor): the last encoder layer's output of\n shape `(src_len, batch, embed_dim)`\n - **encoder_padding_mask** (ByteTensor): the positions of\n padding elements of shape `(batch, src_len)`\n "
x = (self.embed_scale * self.embed_tokens(src_tokens))
if (self.embed_positions is not None):
x += self.embed_positions(src_tokens)
x = F.dropout(x, p=self.dropout, training=self.training)
'\n mask_output = self.mask(src_tokens , x)\n p = mask_output\n p = p.transpose(0, 1)\n t_p = torch.argsort(p,dim=1)\n ratio = 0.2\n self.ratio = ratio\n p_mask = torch.where(t_p<t_p.size(1)*ratio,torch.zeros_like(p),torch.ones_like(p))\n self.p_mask = p_mask\n p_mask = p_mask.unsqueeze(-1).transpose(0,1)\n\n self.mask_output = p\n \n \n if self.training:\n x = x * p_mask.detach()\n else:\n x = x\n ###########\n ###########\n ###########\n # t_p[t_p>t_p.size*ratio] = 1\n # t_p[t_p<=t_p.size*ratio] = 0\n # t_p.permute(1,0)\n \n \n # model.encoder.mask_output \n '
x = x.transpose(0, 1)
encoder_padding_mask = src_tokens.eq(self.padding_idx)
if (not encoder_padding_mask.any()):
encoder_padding_mask = None
for layer in self.layers:
x = layer(x, encoder_padding_mask, bert_encoder_out['bert_encoder_out'], bert_encoder_out['bert_encoder_padding_mask'])
if self.layer_norm:
x = self.layer_norm(x)
'\n self.encoder_vocab_output = self.encodeMLM(src_tokens, src_lengths, bert_encoder_out)\n '
'\n ##########################\n if self.i%1==0:\n import scipy.io as scio\n self.encoder_vocab_output = self.encodeMLM(src_tokens, src_lengths, bert_encoder_out)\n scio.savemat("/home/iojhui/bert-nmt/data"+str(self.i)+".mat", {\'mask_output\':self.mask_output.detach().cpu().numpy(),"src_tokens":src_tokens.cpu().numpy()})\n \n\n\n self.i+=1\n ########################\n '
return {'encoder_out': x, 'encoder_padding_mask': encoder_padding_mask} | 546,859,358,158,450,940 | Args:
src_tokens (LongTensor): tokens in the source language of shape
`(batch, src_len)`
src_lengths (torch.LongTensor): lengths of each source sentence of
shape `(batch)`
Returns:
dict:
- **encoder_out** (Tensor): the last encoder layer's output of
shape `(src_len, batch, embed_dim)`
- **encoder_padding_mask** (ByteTensor): the positions of
padding elements of shape `(batch, src_len)` | models/transformer.py | forward | NCTUMLlab/Adversarial-Masking-Transformers-for-Language-Understanding | python | def forward(self, src_tokens, src_lengths, bert_encoder_out):
"\n Args:\n src_tokens (LongTensor): tokens in the source language of shape\n `(batch, src_len)`\n src_lengths (torch.LongTensor): lengths of each source sentence of\n shape `(batch)`\n\n Returns:\n dict:\n - **encoder_out** (Tensor): the last encoder layer's output of\n shape `(src_len, batch, embed_dim)`\n - **encoder_padding_mask** (ByteTensor): the positions of\n padding elements of shape `(batch, src_len)`\n "
x = (self.embed_scale * self.embed_tokens(src_tokens))
if (self.embed_positions is not None):
x += self.embed_positions(src_tokens)
x = F.dropout(x, p=self.dropout, training=self.training)
'\n mask_output = self.mask(src_tokens , x)\n p = mask_output\n p = p.transpose(0, 1)\n t_p = torch.argsort(p,dim=1)\n ratio = 0.2\n self.ratio = ratio\n p_mask = torch.where(t_p<t_p.size(1)*ratio,torch.zeros_like(p),torch.ones_like(p))\n self.p_mask = p_mask\n p_mask = p_mask.unsqueeze(-1).transpose(0,1)\n\n self.mask_output = p\n \n \n if self.training:\n x = x * p_mask.detach()\n else:\n x = x\n ###########\n ###########\n ###########\n # t_p[t_p>t_p.size*ratio] = 1\n # t_p[t_p<=t_p.size*ratio] = 0\n # t_p.permute(1,0)\n \n \n # model.encoder.mask_output \n '
x = x.transpose(0, 1)
encoder_padding_mask = src_tokens.eq(self.padding_idx)
if (not encoder_padding_mask.any()):
encoder_padding_mask = None
for layer in self.layers:
x = layer(x, encoder_padding_mask, bert_encoder_out['bert_encoder_out'], bert_encoder_out['bert_encoder_padding_mask'])
if self.layer_norm:
x = self.layer_norm(x)
'\n self.encoder_vocab_output = self.encodeMLM(src_tokens, src_lengths, bert_encoder_out)\n '
'\n ##########################\n if self.i%1==0:\n import scipy.io as scio\n self.encoder_vocab_output = self.encodeMLM(src_tokens, src_lengths, bert_encoder_out)\n scio.savemat("/home/iojhui/bert-nmt/data"+str(self.i)+".mat", {\'mask_output\':self.mask_output.detach().cpu().numpy(),"src_tokens":src_tokens.cpu().numpy()})\n \n\n\n self.i+=1\n ########################\n '
return {'encoder_out': x, 'encoder_padding_mask': encoder_padding_mask} |
def encodeMLM(self, src_tokens, src_lengths, bert_encoder_out):
"\n Args:\n src_tokens (LongTensor): tokens in the source language of shape\n `(batch, src_len)`\n src_lengths (torch.LongTensor): lengths of each source sentence of\n shape `(batch)`\n\n Returns:\n dict:\n - **encoder_out** (Tensor): the last encoder layer's output of\n shape `(src_len, batch, embed_dim)`\n - **encoder_padding_mask** (ByteTensor): the positions of\n padding elements of shape `(batch, src_len)`\n "
self.src_tokens = src_tokens
x = (self.embed_scale * self.embed_tokens(src_tokens))
'\n ratio = 0.3\n mask = np.random.choice(src_tokens.size()[1], (int(src_tokens.size()[1] * ratio), ),replace = False)\n \n \n if mask is not None:\n '
'\n if x.size(1)<10:\n mask = [4]\n else:\n mask = [7,9]\n x[:, mask] = self.mask_embedding\n \n '
mask_output = self.mask(src_tokens, x)
p = mask_output
p = p
t_p = torch.argsort(p, dim=1)
ratio = 0.2
self.ratio = ratio
p_mask = torch.where((t_p < (t_p.size(1) * ratio)), torch.zeros_like(p), torch.ones_like(p))
self.p_mask = p_mask
p_mask = p_mask.unsqueeze((- 1))
self.mask_output = p
x = (x * p_mask.detach())
if (self.embed_positions is not None):
x += self.embed_positions(src_tokens)
x = F.dropout(x, p=self.dropout, training=self.training)
x = x.transpose(0, 1)
encoder_padding_mask = src_tokens.eq(self.padding_idx)
if (not encoder_padding_mask.any()):
encoder_padding_mask = None
for layer in self.layers:
x = layer(x, encoder_padding_mask, bert_encoder_out['bert_encoder_out'], bert_encoder_out['bert_encoder_padding_mask'])
if self.layer_norm:
x = self.layer_norm(x)
encoder_vocab_output = self.output_vocab_linear(x)
self.encoder_vocab_output2 = torch.nn.functional.softmax(encoder_vocab_output, dim=(- 1))
self.token = src_tokens
return encoder_vocab_output | -6,241,553,142,829,516,000 | Args:
src_tokens (LongTensor): tokens in the source language of shape
`(batch, src_len)`
src_lengths (torch.LongTensor): lengths of each source sentence of
shape `(batch)`
Returns:
dict:
- **encoder_out** (Tensor): the last encoder layer's output of
shape `(src_len, batch, embed_dim)`
- **encoder_padding_mask** (ByteTensor): the positions of
padding elements of shape `(batch, src_len)` | models/transformer.py | encodeMLM | NCTUMLlab/Adversarial-Masking-Transformers-for-Language-Understanding | python | def encodeMLM(self, src_tokens, src_lengths, bert_encoder_out):
"\n Args:\n src_tokens (LongTensor): tokens in the source language of shape\n `(batch, src_len)`\n src_lengths (torch.LongTensor): lengths of each source sentence of\n shape `(batch)`\n\n Returns:\n dict:\n - **encoder_out** (Tensor): the last encoder layer's output of\n shape `(src_len, batch, embed_dim)`\n - **encoder_padding_mask** (ByteTensor): the positions of\n padding elements of shape `(batch, src_len)`\n "
self.src_tokens = src_tokens
x = (self.embed_scale * self.embed_tokens(src_tokens))
'\n ratio = 0.3\n mask = np.random.choice(src_tokens.size()[1], (int(src_tokens.size()[1] * ratio), ),replace = False)\n \n \n if mask is not None:\n '
'\n if x.size(1)<10:\n mask = [4]\n else:\n mask = [7,9]\n x[:, mask] = self.mask_embedding\n \n '
mask_output = self.mask(src_tokens, x)
p = mask_output
p = p
t_p = torch.argsort(p, dim=1)
ratio = 0.2
self.ratio = ratio
p_mask = torch.where((t_p < (t_p.size(1) * ratio)), torch.zeros_like(p), torch.ones_like(p))
self.p_mask = p_mask
p_mask = p_mask.unsqueeze((- 1))
self.mask_output = p
x = (x * p_mask.detach())
if (self.embed_positions is not None):
x += self.embed_positions(src_tokens)
x = F.dropout(x, p=self.dropout, training=self.training)
x = x.transpose(0, 1)
encoder_padding_mask = src_tokens.eq(self.padding_idx)
if (not encoder_padding_mask.any()):
encoder_padding_mask = None
for layer in self.layers:
x = layer(x, encoder_padding_mask, bert_encoder_out['bert_encoder_out'], bert_encoder_out['bert_encoder_padding_mask'])
if self.layer_norm:
x = self.layer_norm(x)
encoder_vocab_output = self.output_vocab_linear(x)
self.encoder_vocab_output2 = torch.nn.functional.softmax(encoder_vocab_output, dim=(- 1))
self.token = src_tokens
return encoder_vocab_output |
def reorder_encoder_out(self, encoder_out, bert_outs, new_order):
'\n Reorder encoder output according to *new_order*.\n\n Args:\n encoder_out: output from the ``forward()`` method\n new_order (LongTensor): desired order\n\n Returns:\n *encoder_out* rearranged according to *new_order*\n '
if (encoder_out['encoder_out'] is not None):
encoder_out['encoder_out'] = encoder_out['encoder_out'].index_select(1, new_order)
if (encoder_out['encoder_padding_mask'] is not None):
encoder_out['encoder_padding_mask'] = encoder_out['encoder_padding_mask'].index_select(0, new_order)
if (bert_outs['bert_encoder_out'] is not None):
bert_outs['bert_encoder_out'] = bert_outs['bert_encoder_out'].index_select(1, new_order)
if (bert_outs['bert_encoder_padding_mask'] is not None):
bert_outs['bert_encoder_padding_mask'] = bert_outs['bert_encoder_padding_mask'].index_select(0, new_order)
return (encoder_out, bert_outs) | -4,539,497,251,350,111,000 | Reorder encoder output according to *new_order*.
Args:
encoder_out: output from the ``forward()`` method
new_order (LongTensor): desired order
Returns:
*encoder_out* rearranged according to *new_order* | models/transformer.py | reorder_encoder_out | NCTUMLlab/Adversarial-Masking-Transformers-for-Language-Understanding | python | def reorder_encoder_out(self, encoder_out, bert_outs, new_order):
'\n Reorder encoder output according to *new_order*.\n\n Args:\n encoder_out: output from the ``forward()`` method\n new_order (LongTensor): desired order\n\n Returns:\n *encoder_out* rearranged according to *new_order*\n '
if (encoder_out['encoder_out'] is not None):
encoder_out['encoder_out'] = encoder_out['encoder_out'].index_select(1, new_order)
if (encoder_out['encoder_padding_mask'] is not None):
encoder_out['encoder_padding_mask'] = encoder_out['encoder_padding_mask'].index_select(0, new_order)
if (bert_outs['bert_encoder_out'] is not None):
bert_outs['bert_encoder_out'] = bert_outs['bert_encoder_out'].index_select(1, new_order)
if (bert_outs['bert_encoder_padding_mask'] is not None):
bert_outs['bert_encoder_padding_mask'] = bert_outs['bert_encoder_padding_mask'].index_select(0, new_order)
return (encoder_out, bert_outs) |
def max_positions(self):
'Maximum input length supported by the encoder.'
if (self.embed_positions is None):
return self.max_source_positions
return min(self.max_source_positions, self.embed_positions.max_positions()) | -5,228,954,016,557,509,000 | Maximum input length supported by the encoder. | models/transformer.py | max_positions | NCTUMLlab/Adversarial-Masking-Transformers-for-Language-Understanding | python | def max_positions(self):
if (self.embed_positions is None):
return self.max_source_positions
return min(self.max_source_positions, self.embed_positions.max_positions()) |
def upgrade_state_dict_named(self, state_dict, name):
'Upgrade a (possibly old) state dict for new versions of fairseq.'
if isinstance(self.embed_positions, SinusoidalPositionalEmbedding):
weights_key = '{}.embed_positions.weights'.format(name)
if (weights_key in state_dict):
del state_dict[weights_key]
state_dict['{}.embed_positions._float_tensor'.format(name)] = torch.FloatTensor(1)
for i in range(len(self.layers)):
self.layers[i].upgrade_state_dict_named(state_dict, '{}.layers.{}'.format(name, i))
version_key = '{}.version'.format(name)
if (utils.item(state_dict.get(version_key, torch.Tensor([1]))[0]) < 2):
self.layer_norm = None
self.normalize = False
state_dict[version_key] = torch.Tensor([1])
return state_dict | 6,001,696,072,670,587,000 | Upgrade a (possibly old) state dict for new versions of fairseq. | models/transformer.py | upgrade_state_dict_named | NCTUMLlab/Adversarial-Masking-Transformers-for-Language-Understanding | python | def upgrade_state_dict_named(self, state_dict, name):
if isinstance(self.embed_positions, SinusoidalPositionalEmbedding):
weights_key = '{}.embed_positions.weights'.format(name)
if (weights_key in state_dict):
del state_dict[weights_key]
state_dict['{}.embed_positions._float_tensor'.format(name)] = torch.FloatTensor(1)
for i in range(len(self.layers)):
self.layers[i].upgrade_state_dict_named(state_dict, '{}.layers.{}'.format(name, i))
version_key = '{}.version'.format(name)
if (utils.item(state_dict.get(version_key, torch.Tensor([1]))[0]) < 2):
self.layer_norm = None
self.normalize = False
state_dict[version_key] = torch.Tensor([1])
return state_dict |
def forward(self, prev_output_tokens, encoder_out=None, bert_encoder_out=None, incremental_state=None, **unused):
"\n Args:\n prev_output_tokens (LongTensor): previous decoder outputs of shape\n `(batch, tgt_len)`, for input feeding/teacher forcing\n encoder_out (Tensor, optional): output from the encoder, used for\n encoder-side attention\n incremental_state (dict): dictionary used for storing state during\n :ref:`Incremental decoding`\n\n Returns:\n tuple:\n - the decoder's output of shape `(batch, tgt_len, vocab)`\n - a dictionary with any model-specific outputs\n "
(x, extra) = self.extract_features(prev_output_tokens, encoder_out, bert_encoder_out, incremental_state)
x = self.output_layer(x)
return (x, extra) | 8,584,525,393,747,568,000 | Args:
prev_output_tokens (LongTensor): previous decoder outputs of shape
`(batch, tgt_len)`, for input feeding/teacher forcing
encoder_out (Tensor, optional): output from the encoder, used for
encoder-side attention
incremental_state (dict): dictionary used for storing state during
:ref:`Incremental decoding`
Returns:
tuple:
- the decoder's output of shape `(batch, tgt_len, vocab)`
- a dictionary with any model-specific outputs | models/transformer.py | forward | NCTUMLlab/Adversarial-Masking-Transformers-for-Language-Understanding | python | def forward(self, prev_output_tokens, encoder_out=None, bert_encoder_out=None, incremental_state=None, **unused):
"\n Args:\n prev_output_tokens (LongTensor): previous decoder outputs of shape\n `(batch, tgt_len)`, for input feeding/teacher forcing\n encoder_out (Tensor, optional): output from the encoder, used for\n encoder-side attention\n incremental_state (dict): dictionary used for storing state during\n :ref:`Incremental decoding`\n\n Returns:\n tuple:\n - the decoder's output of shape `(batch, tgt_len, vocab)`\n - a dictionary with any model-specific outputs\n "
(x, extra) = self.extract_features(prev_output_tokens, encoder_out, bert_encoder_out, incremental_state)
x = self.output_layer(x)
return (x, extra) |
def extract_features(self, prev_output_tokens, encoder_out=None, bert_encoder_out=None, incremental_state=None, **unused):
"\n Similar to *forward* but only return features.\n\n Returns:\n tuple:\n - the decoder's features of shape `(batch, tgt_len, embed_dim)`\n - a dictionary with any model-specific outputs\n "
positions = (self.embed_positions(prev_output_tokens, incremental_state=incremental_state) if (self.embed_positions is not None) else None)
if (incremental_state is not None):
prev_output_tokens = prev_output_tokens[:, (- 1):]
if (positions is not None):
positions = positions[:, (- 1):]
x = (self.embed_scale * self.embed_tokens(prev_output_tokens))
if (self.project_in_dim is not None):
x = self.project_in_dim(x)
if (positions is not None):
x += positions
x = F.dropout(x, p=self.dropout, training=self.training)
x = x.transpose(0, 1)
attn = None
inner_states = [x]
for layer in self.layers:
(x, attn) = layer(x, (encoder_out['encoder_out'] if (encoder_out is not None) else None), (encoder_out['encoder_padding_mask'] if (encoder_out is not None) else None), bert_encoder_out['bert_encoder_out'], bert_encoder_out['bert_encoder_padding_mask'], incremental_state, self_attn_mask=(self.buffered_future_mask(x) if (incremental_state is None) else None))
inner_states.append(x)
if self.layer_norm:
x = self.layer_norm(x)
x = x.transpose(0, 1)
if (self.project_out_dim is not None):
x = self.project_out_dim(x)
return (x, {'attn': attn, 'inner_states': inner_states}) | -1,850,262,369,369,789,400 | Similar to *forward* but only return features.
Returns:
tuple:
- the decoder's features of shape `(batch, tgt_len, embed_dim)`
- a dictionary with any model-specific outputs | models/transformer.py | extract_features | NCTUMLlab/Adversarial-Masking-Transformers-for-Language-Understanding | python | def extract_features(self, prev_output_tokens, encoder_out=None, bert_encoder_out=None, incremental_state=None, **unused):
"\n Similar to *forward* but only return features.\n\n Returns:\n tuple:\n - the decoder's features of shape `(batch, tgt_len, embed_dim)`\n - a dictionary with any model-specific outputs\n "
positions = (self.embed_positions(prev_output_tokens, incremental_state=incremental_state) if (self.embed_positions is not None) else None)
if (incremental_state is not None):
prev_output_tokens = prev_output_tokens[:, (- 1):]
if (positions is not None):
positions = positions[:, (- 1):]
x = (self.embed_scale * self.embed_tokens(prev_output_tokens))
if (self.project_in_dim is not None):
x = self.project_in_dim(x)
if (positions is not None):
x += positions
x = F.dropout(x, p=self.dropout, training=self.training)
x = x.transpose(0, 1)
attn = None
inner_states = [x]
for layer in self.layers:
(x, attn) = layer(x, (encoder_out['encoder_out'] if (encoder_out is not None) else None), (encoder_out['encoder_padding_mask'] if (encoder_out is not None) else None), bert_encoder_out['bert_encoder_out'], bert_encoder_out['bert_encoder_padding_mask'], incremental_state, self_attn_mask=(self.buffered_future_mask(x) if (incremental_state is None) else None))
inner_states.append(x)
if self.layer_norm:
x = self.layer_norm(x)
x = x.transpose(0, 1)
if (self.project_out_dim is not None):
x = self.project_out_dim(x)
return (x, {'attn': attn, 'inner_states': inner_states}) |
def output_layer(self, features, **kwargs):
'Project features to the vocabulary size.'
if (self.adaptive_softmax is None):
if self.share_input_output_embed:
return F.linear(features, self.embed_tokens.weight)
else:
return F.linear(features, self.embed_out)
else:
return features | -3,345,116,721,218,766,300 | Project features to the vocabulary size. | models/transformer.py | output_layer | NCTUMLlab/Adversarial-Masking-Transformers-for-Language-Understanding | python | def output_layer(self, features, **kwargs):
if (self.adaptive_softmax is None):
if self.share_input_output_embed:
return F.linear(features, self.embed_tokens.weight)
else:
return F.linear(features, self.embed_out)
else:
return features |
def max_positions(self):
'Maximum output length supported by the decoder.'
if (self.embed_positions is None):
return self.max_target_positions
return min(self.max_target_positions, self.embed_positions.max_positions()) | -778,445,331,605,681,300 | Maximum output length supported by the decoder. | models/transformer.py | max_positions | NCTUMLlab/Adversarial-Masking-Transformers-for-Language-Understanding | python | def max_positions(self):
if (self.embed_positions is None):
return self.max_target_positions
return min(self.max_target_positions, self.embed_positions.max_positions()) |
def upgrade_state_dict_named(self, state_dict, name):
'Upgrade a (possibly old) state dict for new versions of fairseq.'
if isinstance(self.embed_positions, SinusoidalPositionalEmbedding):
weights_key = '{}.embed_positions.weights'.format(name)
if (weights_key in state_dict):
del state_dict[weights_key]
state_dict['{}.embed_positions._float_tensor'.format(name)] = torch.FloatTensor(1)
for i in range(len(self.layers)):
layer_norm_map = {'0': 'self_attn_layer_norm', '1': 'encoder_attn_layer_norm', '2': 'final_layer_norm'}
for (old, new) in layer_norm_map.items():
for m in ('weight', 'bias'):
k = '{}.layers.{}.layer_norms.{}.{}'.format(name, i, old, m)
if (k in state_dict):
state_dict['{}.layers.{}.{}.{}'.format(name, i, new, m)] = state_dict[k]
del state_dict[k]
version_key = '{}.version'.format(name)
if (utils.item(state_dict.get(version_key, torch.Tensor([1]))[0]) < 2):
self.layer_norm = None
self.normalize = False
state_dict[version_key] = torch.Tensor([1])
return state_dict | -8,691,086,455,940,025,000 | Upgrade a (possibly old) state dict for new versions of fairseq. | models/transformer.py | upgrade_state_dict_named | NCTUMLlab/Adversarial-Masking-Transformers-for-Language-Understanding | python | def upgrade_state_dict_named(self, state_dict, name):
if isinstance(self.embed_positions, SinusoidalPositionalEmbedding):
weights_key = '{}.embed_positions.weights'.format(name)
if (weights_key in state_dict):
del state_dict[weights_key]
state_dict['{}.embed_positions._float_tensor'.format(name)] = torch.FloatTensor(1)
for i in range(len(self.layers)):
layer_norm_map = {'0': 'self_attn_layer_norm', '1': 'encoder_attn_layer_norm', '2': 'final_layer_norm'}
for (old, new) in layer_norm_map.items():
for m in ('weight', 'bias'):
k = '{}.layers.{}.layer_norms.{}.{}'.format(name, i, old, m)
if (k in state_dict):
state_dict['{}.layers.{}.{}.{}'.format(name, i, new, m)] = state_dict[k]
del state_dict[k]
version_key = '{}.version'.format(name)
if (utils.item(state_dict.get(version_key, torch.Tensor([1]))[0]) < 2):
self.layer_norm = None
self.normalize = False
state_dict[version_key] = torch.Tensor([1])
return state_dict |
def forward(self, prev_output_tokens, encoder_out=None, bert_encoder_out=None, incremental_state=None, **unused):
"\n Args:\n prev_output_tokens (LongTensor): previous decoder outputs of shape\n `(batch, tgt_len)`, for input feeding/teacher forcing\n encoder_out (Tensor, optional): output from the encoder, used for\n encoder-side attention\n incremental_state (dict): dictionary used for storing state during\n :ref:`Incremental decoding`\n\n Returns:\n tuple:\n - the decoder's output of shape `(batch, tgt_len, vocab)`\n - a dictionary with any model-specific outputs\n "
(x, extra) = self.extract_features(prev_output_tokens, encoder_out, bert_encoder_out, incremental_state)
x = self.output_layer(x)
return (x, extra) | 8,584,525,393,747,568,000 | Args:
prev_output_tokens (LongTensor): previous decoder outputs of shape
`(batch, tgt_len)`, for input feeding/teacher forcing
encoder_out (Tensor, optional): output from the encoder, used for
encoder-side attention
incremental_state (dict): dictionary used for storing state during
:ref:`Incremental decoding`
Returns:
tuple:
- the decoder's output of shape `(batch, tgt_len, vocab)`
- a dictionary with any model-specific outputs | models/transformer.py | forward | NCTUMLlab/Adversarial-Masking-Transformers-for-Language-Understanding | python | def forward(self, prev_output_tokens, encoder_out=None, bert_encoder_out=None, incremental_state=None, **unused):
"\n Args:\n prev_output_tokens (LongTensor): previous decoder outputs of shape\n `(batch, tgt_len)`, for input feeding/teacher forcing\n encoder_out (Tensor, optional): output from the encoder, used for\n encoder-side attention\n incremental_state (dict): dictionary used for storing state during\n :ref:`Incremental decoding`\n\n Returns:\n tuple:\n - the decoder's output of shape `(batch, tgt_len, vocab)`\n - a dictionary with any model-specific outputs\n "
(x, extra) = self.extract_features(prev_output_tokens, encoder_out, bert_encoder_out, incremental_state)
x = self.output_layer(x)
return (x, extra) |
def extract_features(self, prev_output_tokens, encoder_out=None, bert_encoder_out=None, incremental_state=None, **unused):
"\n Similar to *forward* but only return features.\n\n Returns:\n tuple:\n - the decoder's features of shape `(batch, tgt_len, embed_dim)`\n - a dictionary with any model-specific outputs\n "
positions = (self.embed_positions(prev_output_tokens, incremental_state=incremental_state) if (self.embed_positions is not None) else None)
if (incremental_state is not None):
prev_output_tokens = prev_output_tokens[:, (- 1):]
if (positions is not None):
positions = positions[:, (- 1):]
x = (self.embed_scale * self.embed_tokens(prev_output_tokens))
if (self.project_in_dim is not None):
x = self.project_in_dim(x)
if (positions is not None):
x += positions
x = F.dropout(x, p=self.dropout, training=self.training)
x = x.transpose(0, 1)
attn = None
inner_states = [x]
for layer in self.layers:
(x, attn) = layer(x, (encoder_out['encoder_out'] if (encoder_out is not None) else None), (encoder_out['encoder_padding_mask'] if (encoder_out is not None) else None), bert_encoder_out['bert_encoder_out'], bert_encoder_out['bert_encoder_padding_mask'], incremental_state, self_attn_mask=(self.buffered_future_mask(x) if (incremental_state is None) else None))
inner_states.append(x)
if self.layer_norm:
x = self.layer_norm(x)
x = x.transpose(0, 1)
if (self.project_out_dim is not None):
x = self.project_out_dim(x)
return (x, {'attn': attn, 'inner_states': inner_states}) | -1,850,262,369,369,789,400 | Similar to *forward* but only return features.
Returns:
tuple:
- the decoder's features of shape `(batch, tgt_len, embed_dim)`
- a dictionary with any model-specific outputs | models/transformer.py | extract_features | NCTUMLlab/Adversarial-Masking-Transformers-for-Language-Understanding | python | def extract_features(self, prev_output_tokens, encoder_out=None, bert_encoder_out=None, incremental_state=None, **unused):
"\n Similar to *forward* but only return features.\n\n Returns:\n tuple:\n - the decoder's features of shape `(batch, tgt_len, embed_dim)`\n - a dictionary with any model-specific outputs\n "
positions = (self.embed_positions(prev_output_tokens, incremental_state=incremental_state) if (self.embed_positions is not None) else None)
if (incremental_state is not None):
prev_output_tokens = prev_output_tokens[:, (- 1):]
if (positions is not None):
positions = positions[:, (- 1):]
x = (self.embed_scale * self.embed_tokens(prev_output_tokens))
if (self.project_in_dim is not None):
x = self.project_in_dim(x)
if (positions is not None):
x += positions
x = F.dropout(x, p=self.dropout, training=self.training)
x = x.transpose(0, 1)
attn = None
inner_states = [x]
for layer in self.layers:
(x, attn) = layer(x, (encoder_out['encoder_out'] if (encoder_out is not None) else None), (encoder_out['encoder_padding_mask'] if (encoder_out is not None) else None), bert_encoder_out['bert_encoder_out'], bert_encoder_out['bert_encoder_padding_mask'], incremental_state, self_attn_mask=(self.buffered_future_mask(x) if (incremental_state is None) else None))
inner_states.append(x)
if self.layer_norm:
x = self.layer_norm(x)
x = x.transpose(0, 1)
if (self.project_out_dim is not None):
x = self.project_out_dim(x)
return (x, {'attn': attn, 'inner_states': inner_states}) |
def output_layer(self, features, **kwargs):
'Project features to the vocabulary size.'
if (self.adaptive_softmax is None):
if self.share_input_output_embed:
return F.linear(features, self.embed_tokens.weight)
else:
return F.linear(features, self.embed_out)
else:
return features | -3,345,116,721,218,766,300 | Project features to the vocabulary size. | models/transformer.py | output_layer | NCTUMLlab/Adversarial-Masking-Transformers-for-Language-Understanding | python | def output_layer(self, features, **kwargs):
if (self.adaptive_softmax is None):
if self.share_input_output_embed:
return F.linear(features, self.embed_tokens.weight)
else:
return F.linear(features, self.embed_out)
else:
return features |
def max_positions(self):
'Maximum output length supported by the decoder.'
if (self.embed_positions is None):
return self.max_target_positions
return min(self.max_target_positions, self.embed_positions.max_positions()) | -778,445,331,605,681,300 | Maximum output length supported by the decoder. | models/transformer.py | max_positions | NCTUMLlab/Adversarial-Masking-Transformers-for-Language-Understanding | python | def max_positions(self):
if (self.embed_positions is None):
return self.max_target_positions
return min(self.max_target_positions, self.embed_positions.max_positions()) |
def upgrade_state_dict_named(self, state_dict, name):
'Upgrade a (possibly old) state dict for new versions of fairseq.'
if isinstance(self.embed_positions, SinusoidalPositionalEmbedding):
weights_key = '{}.embed_positions.weights'.format(name)
if (weights_key in state_dict):
del state_dict[weights_key]
state_dict['{}.embed_positions._float_tensor'.format(name)] = torch.FloatTensor(1)
for i in range(len(self.layers)):
layer_norm_map = {'0': 'self_attn_layer_norm', '1': 'encoder_attn_layer_norm', '2': 'final_layer_norm'}
for (old, new) in layer_norm_map.items():
for m in ('weight', 'bias'):
k = '{}.layers.{}.layer_norms.{}.{}'.format(name, i, old, m)
if (k in state_dict):
state_dict['{}.layers.{}.{}.{}'.format(name, i, new, m)] = state_dict[k]
del state_dict[k]
version_key = '{}.version'.format(name)
if (utils.item(state_dict.get(version_key, torch.Tensor([1]))[0]) < 2):
self.layer_norm = None
self.normalize = False
state_dict[version_key] = torch.Tensor([1])
return state_dict | -8,691,086,455,940,025,000 | Upgrade a (possibly old) state dict for new versions of fairseq. | models/transformer.py | upgrade_state_dict_named | NCTUMLlab/Adversarial-Masking-Transformers-for-Language-Understanding | python | def upgrade_state_dict_named(self, state_dict, name):
if isinstance(self.embed_positions, SinusoidalPositionalEmbedding):
weights_key = '{}.embed_positions.weights'.format(name)
if (weights_key in state_dict):
del state_dict[weights_key]
state_dict['{}.embed_positions._float_tensor'.format(name)] = torch.FloatTensor(1)
for i in range(len(self.layers)):
layer_norm_map = {'0': 'self_attn_layer_norm', '1': 'encoder_attn_layer_norm', '2': 'final_layer_norm'}
for (old, new) in layer_norm_map.items():
for m in ('weight', 'bias'):
k = '{}.layers.{}.layer_norms.{}.{}'.format(name, i, old, m)
if (k in state_dict):
state_dict['{}.layers.{}.{}.{}'.format(name, i, new, m)] = state_dict[k]
del state_dict[k]
version_key = '{}.version'.format(name)
if (utils.item(state_dict.get(version_key, torch.Tensor([1]))[0]) < 2):
self.layer_norm = None
self.normalize = False
state_dict[version_key] = torch.Tensor([1])
return state_dict |
def upgrade_state_dict_named(self, state_dict, name):
'\n Rename layer norm states from `...layer_norms.0.weight` to\n `...self_attn_layer_norm.weight` and `...layer_norms.1.weight` to\n `...final_layer_norm.weight`\n '
layer_norm_map = {'0': 'self_attn_layer_norm', '1': 'final_layer_norm'}
for (old, new) in layer_norm_map.items():
for m in ('weight', 'bias'):
k = '{}.layer_norms.{}.{}'.format(name, old, m)
if (k in state_dict):
state_dict['{}.{}.{}'.format(name, new, m)] = state_dict[k]
del state_dict[k] | -3,313,760,067,142,762,500 | Rename layer norm states from `...layer_norms.0.weight` to
`...self_attn_layer_norm.weight` and `...layer_norms.1.weight` to
`...final_layer_norm.weight` | models/transformer.py | upgrade_state_dict_named | NCTUMLlab/Adversarial-Masking-Transformers-for-Language-Understanding | python | def upgrade_state_dict_named(self, state_dict, name):
'\n Rename layer norm states from `...layer_norms.0.weight` to\n `...self_attn_layer_norm.weight` and `...layer_norms.1.weight` to\n `...final_layer_norm.weight`\n '
layer_norm_map = {'0': 'self_attn_layer_norm', '1': 'final_layer_norm'}
for (old, new) in layer_norm_map.items():
for m in ('weight', 'bias'):
k = '{}.layer_norms.{}.{}'.format(name, old, m)
if (k in state_dict):
state_dict['{}.{}.{}'.format(name, new, m)] = state_dict[k]
del state_dict[k] |
def forward(self, x, encoder_padding_mask):
'\n Args:\n x (Tensor): input to the layer of shape `(seq_len, batch, embed_dim)`\n encoder_padding_mask (ByteTensor): binary ByteTensor of shape\n `(batch, src_len)` where padding elements are indicated by ``1``.\n\n Returns:\n encoded output of shape `(batch, src_len, embed_dim)`\n '
residual = x
x = self.maybe_layer_norm(self.self_attn_layer_norm, x, before=True)
(x, attn_weight) = self.self_attn(query=x, key=x, value=x, key_padding_mask=encoder_padding_mask)
x = F.dropout(x, p=self.dropout, training=self.training)
x = (residual + x)
x = self.maybe_layer_norm(self.self_attn_layer_norm, x, after=True)
self.attn_weight = attn_weight
residual = x
x = self.maybe_layer_norm(self.final_layer_norm, x, before=True)
x = self.activation_fn(self.fc1(x))
x = F.dropout(x, p=self.activation_dropout, training=self.training)
x = self.fc2(x)
x = F.dropout(x, p=self.dropout, training=self.training)
x = (residual + x)
x = self.maybe_layer_norm(self.final_layer_norm, x, after=True)
return x | -4,786,362,497,684,975,000 | Args:
x (Tensor): input to the layer of shape `(seq_len, batch, embed_dim)`
encoder_padding_mask (ByteTensor): binary ByteTensor of shape
`(batch, src_len)` where padding elements are indicated by ``1``.
Returns:
encoded output of shape `(batch, src_len, embed_dim)` | models/transformer.py | forward | NCTUMLlab/Adversarial-Masking-Transformers-for-Language-Understanding | python | def forward(self, x, encoder_padding_mask):
'\n Args:\n x (Tensor): input to the layer of shape `(seq_len, batch, embed_dim)`\n encoder_padding_mask (ByteTensor): binary ByteTensor of shape\n `(batch, src_len)` where padding elements are indicated by ``1``.\n\n Returns:\n encoded output of shape `(batch, src_len, embed_dim)`\n '
residual = x
x = self.maybe_layer_norm(self.self_attn_layer_norm, x, before=True)
(x, attn_weight) = self.self_attn(query=x, key=x, value=x, key_padding_mask=encoder_padding_mask)
x = F.dropout(x, p=self.dropout, training=self.training)
x = (residual + x)
x = self.maybe_layer_norm(self.self_attn_layer_norm, x, after=True)
self.attn_weight = attn_weight
residual = x
x = self.maybe_layer_norm(self.final_layer_norm, x, before=True)
x = self.activation_fn(self.fc1(x))
x = F.dropout(x, p=self.activation_dropout, training=self.training)
x = self.fc2(x)
x = F.dropout(x, p=self.dropout, training=self.training)
x = (residual + x)
x = self.maybe_layer_norm(self.final_layer_norm, x, after=True)
return x |
def upgrade_state_dict_named(self, state_dict, name):
'\n Rename layer norm states from `...layer_norms.0.weight` to\n `...self_attn_layer_norm.weight` and `...layer_norms.1.weight` to\n `...final_layer_norm.weight`\n '
layer_norm_map = {'0': 'self_attn_layer_norm', '1': 'final_layer_norm'}
for (old, new) in layer_norm_map.items():
for m in ('weight', 'bias'):
k = '{}.layer_norms.{}.{}'.format(name, old, m)
if (k in state_dict):
state_dict['{}.{}.{}'.format(name, new, m)] = state_dict[k]
del state_dict[k] | -3,313,760,067,142,762,500 | Rename layer norm states from `...layer_norms.0.weight` to
`...self_attn_layer_norm.weight` and `...layer_norms.1.weight` to
`...final_layer_norm.weight` | models/transformer.py | upgrade_state_dict_named | NCTUMLlab/Adversarial-Masking-Transformers-for-Language-Understanding | python | def upgrade_state_dict_named(self, state_dict, name):
'\n Rename layer norm states from `...layer_norms.0.weight` to\n `...self_attn_layer_norm.weight` and `...layer_norms.1.weight` to\n `...final_layer_norm.weight`\n '
layer_norm_map = {'0': 'self_attn_layer_norm', '1': 'final_layer_norm'}
for (old, new) in layer_norm_map.items():
for m in ('weight', 'bias'):
k = '{}.layer_norms.{}.{}'.format(name, old, m)
if (k in state_dict):
state_dict['{}.{}.{}'.format(name, new, m)] = state_dict[k]
del state_dict[k] |
def forward(self, x, encoder_padding_mask, bert_encoder_out, bert_encoder_padding_mask):
'\n Args:\n x (Tensor): input to the layer of shape `(seq_len, batch, embed_dim)`\n encoder_padding_mask (ByteTensor): binary ByteTensor of shape\n `(batch, src_len)` where padding elements are indicated by ``1``.\n\n Returns:\n encoded output of shape `(batch, src_len, embed_dim)`\n '
residual = x
x = self.maybe_layer_norm(self.self_attn_layer_norm, x, before=True)
(x1, _) = self.self_attn(query=x, key=x, value=x, key_padding_mask=encoder_padding_mask)
(x2, _) = self.bert_attn(query=x, key=bert_encoder_out, value=bert_encoder_out, key_padding_mask=bert_encoder_padding_mask)
x1 = F.dropout(x1, p=self.dropout, training=self.training)
x2 = F.dropout(x2, p=self.dropout, training=self.training)
ratios = self.get_ratio()
x = ((residual + (ratios[0] * x1)) + (ratios[1] * x2))
x = self.maybe_layer_norm(self.self_attn_layer_norm, x, after=True)
residual = x
x = self.maybe_layer_norm(self.final_layer_norm, x, before=True)
x = self.activation_fn(self.fc1(x))
x = F.dropout(x, p=self.activation_dropout, training=self.training)
x = self.fc2(x)
x = F.dropout(x, p=self.dropout, training=self.training)
x = (residual + x)
x = self.maybe_layer_norm(self.final_layer_norm, x, after=True)
return x | -6,319,351,232,305,081,000 | Args:
x (Tensor): input to the layer of shape `(seq_len, batch, embed_dim)`
encoder_padding_mask (ByteTensor): binary ByteTensor of shape
`(batch, src_len)` where padding elements are indicated by ``1``.
Returns:
encoded output of shape `(batch, src_len, embed_dim)` | models/transformer.py | forward | NCTUMLlab/Adversarial-Masking-Transformers-for-Language-Understanding | python | def forward(self, x, encoder_padding_mask, bert_encoder_out, bert_encoder_padding_mask):
'\n Args:\n x (Tensor): input to the layer of shape `(seq_len, batch, embed_dim)`\n encoder_padding_mask (ByteTensor): binary ByteTensor of shape\n `(batch, src_len)` where padding elements are indicated by ``1``.\n\n Returns:\n encoded output of shape `(batch, src_len, embed_dim)`\n '
residual = x
x = self.maybe_layer_norm(self.self_attn_layer_norm, x, before=True)
(x1, _) = self.self_attn(query=x, key=x, value=x, key_padding_mask=encoder_padding_mask)
(x2, _) = self.bert_attn(query=x, key=bert_encoder_out, value=bert_encoder_out, key_padding_mask=bert_encoder_padding_mask)
x1 = F.dropout(x1, p=self.dropout, training=self.training)
x2 = F.dropout(x2, p=self.dropout, training=self.training)
ratios = self.get_ratio()
x = ((residual + (ratios[0] * x1)) + (ratios[1] * x2))
x = self.maybe_layer_norm(self.self_attn_layer_norm, x, after=True)
residual = x
x = self.maybe_layer_norm(self.final_layer_norm, x, before=True)
x = self.activation_fn(self.fc1(x))
x = F.dropout(x, p=self.activation_dropout, training=self.training)
x = self.fc2(x)
x = F.dropout(x, p=self.dropout, training=self.training)
x = (residual + x)
x = self.maybe_layer_norm(self.final_layer_norm, x, after=True)
return x |
def forward(self, x, encoder_out=None, encoder_padding_mask=None, bert_encoder_out=None, bert_encoder_padding_mask=None, incremental_state=None, prev_self_attn_state=None, prev_attn_state=None, self_attn_mask=None, self_attn_padding_mask=None):
'\n Args:\n x (Tensor): input to the layer of shape `(seq_len, batch, embed_dim)`\n encoder_padding_mask (ByteTensor): binary ByteTensor of shape\n `(batch, src_len)` where padding elements are indicated by ``1``.\n\n Returns:\n encoded output of shape `(batch, src_len, embed_dim)`\n '
residual = x
x = self.maybe_layer_norm(self.self_attn_layer_norm, x, before=True)
if (prev_self_attn_state is not None):
if (incremental_state is None):
incremental_state = {}
(prev_key, prev_value) = prev_self_attn_state
saved_state = {'prev_key': prev_key, 'prev_value': prev_value}
self.self_attn._set_input_buffer(incremental_state, saved_state)
(x, attn) = self.self_attn(query=x, key=x, value=x, key_padding_mask=self_attn_padding_mask, incremental_state=incremental_state, need_weights=False, attn_mask=self_attn_mask)
x = F.dropout(x, p=self.dropout, training=self.training)
x = (residual + x)
x = self.maybe_layer_norm(self.self_attn_layer_norm, x, after=True)
if (self.encoder_attn is not None):
residual = x
x = self.maybe_layer_norm(self.encoder_attn_layer_norm, x, before=True)
if (prev_attn_state is not None):
if (incremental_state is None):
incremental_state = {}
(prev_key, prev_value) = prev_attn_state
saved_state = {'prev_key': prev_key, 'prev_value': prev_value}
self.encoder_attn._set_input_buffer(incremental_state, saved_state)
(x1, attn) = self.encoder_attn(query=x, key=encoder_out, value=encoder_out, key_padding_mask=encoder_padding_mask, incremental_state=incremental_state, static_kv=True, need_weights=((not self.training) and self.need_attn))
(x2, _) = self.bert_attn(query=x, key=bert_encoder_out, value=bert_encoder_out, key_padding_mask=bert_encoder_padding_mask, incremental_state=incremental_state, static_kv=True, need_weights=((not self.training) and self.need_attn))
x1 = F.dropout(x1, p=self.dropout, training=self.training)
x2 = F.dropout(x2, p=self.dropout, training=self.training)
ratios = self.get_ratio()
x = ((residual + (ratios[0] * x1)) + (ratios[1] * x2))
x = self.maybe_layer_norm(self.encoder_attn_layer_norm, x, after=True)
residual = x
x = self.maybe_layer_norm(self.final_layer_norm, x, before=True)
x = self.activation_fn(self.fc1(x))
x = F.dropout(x, p=self.activation_dropout, training=self.training)
x = self.fc2(x)
x = F.dropout(x, p=self.dropout, training=self.training)
x = (residual + x)
x = self.maybe_layer_norm(self.final_layer_norm, x, after=True)
if (self.onnx_trace and (incremental_state is not None)):
saved_state = self.self_attn._get_input_buffer(incremental_state)
self_attn_state = (saved_state['prev_key'], saved_state['prev_value'])
return (x, attn, self_attn_state)
return (x, attn) | 4,665,933,914,785,590,000 | Args:
x (Tensor): input to the layer of shape `(seq_len, batch, embed_dim)`
encoder_padding_mask (ByteTensor): binary ByteTensor of shape
`(batch, src_len)` where padding elements are indicated by ``1``.
Returns:
encoded output of shape `(batch, src_len, embed_dim)` | models/transformer.py | forward | NCTUMLlab/Adversarial-Masking-Transformers-for-Language-Understanding | python | def forward(self, x, encoder_out=None, encoder_padding_mask=None, bert_encoder_out=None, bert_encoder_padding_mask=None, incremental_state=None, prev_self_attn_state=None, prev_attn_state=None, self_attn_mask=None, self_attn_padding_mask=None):
'\n Args:\n x (Tensor): input to the layer of shape `(seq_len, batch, embed_dim)`\n encoder_padding_mask (ByteTensor): binary ByteTensor of shape\n `(batch, src_len)` where padding elements are indicated by ``1``.\n\n Returns:\n encoded output of shape `(batch, src_len, embed_dim)`\n '
residual = x
x = self.maybe_layer_norm(self.self_attn_layer_norm, x, before=True)
if (prev_self_attn_state is not None):
if (incremental_state is None):
incremental_state = {}
(prev_key, prev_value) = prev_self_attn_state
saved_state = {'prev_key': prev_key, 'prev_value': prev_value}
self.self_attn._set_input_buffer(incremental_state, saved_state)
(x, attn) = self.self_attn(query=x, key=x, value=x, key_padding_mask=self_attn_padding_mask, incremental_state=incremental_state, need_weights=False, attn_mask=self_attn_mask)
x = F.dropout(x, p=self.dropout, training=self.training)
x = (residual + x)
x = self.maybe_layer_norm(self.self_attn_layer_norm, x, after=True)
if (self.encoder_attn is not None):
residual = x
x = self.maybe_layer_norm(self.encoder_attn_layer_norm, x, before=True)
if (prev_attn_state is not None):
if (incremental_state is None):
incremental_state = {}
(prev_key, prev_value) = prev_attn_state
saved_state = {'prev_key': prev_key, 'prev_value': prev_value}
self.encoder_attn._set_input_buffer(incremental_state, saved_state)
(x1, attn) = self.encoder_attn(query=x, key=encoder_out, value=encoder_out, key_padding_mask=encoder_padding_mask, incremental_state=incremental_state, static_kv=True, need_weights=((not self.training) and self.need_attn))
(x2, _) = self.bert_attn(query=x, key=bert_encoder_out, value=bert_encoder_out, key_padding_mask=bert_encoder_padding_mask, incremental_state=incremental_state, static_kv=True, need_weights=((not self.training) and self.need_attn))
x1 = F.dropout(x1, p=self.dropout, training=self.training)
x2 = F.dropout(x2, p=self.dropout, training=self.training)
ratios = self.get_ratio()
x = ((residual + (ratios[0] * x1)) + (ratios[1] * x2))
x = self.maybe_layer_norm(self.encoder_attn_layer_norm, x, after=True)
residual = x
x = self.maybe_layer_norm(self.final_layer_norm, x, before=True)
x = self.activation_fn(self.fc1(x))
x = F.dropout(x, p=self.activation_dropout, training=self.training)
x = self.fc2(x)
x = F.dropout(x, p=self.dropout, training=self.training)
x = (residual + x)
x = self.maybe_layer_norm(self.final_layer_norm, x, after=True)
if (self.onnx_trace and (incremental_state is not None)):
saved_state = self.self_attn._get_input_buffer(incremental_state)
self_attn_state = (saved_state['prev_key'], saved_state['prev_value'])
return (x, attn, self_attn_state)
return (x, attn) |
def forward(self, x, encoder_out=None, encoder_padding_mask=None, bert_encoder_out=None, bert_encoder_padding_mask=None, incremental_state=None, prev_self_attn_state=None, prev_attn_state=None, self_attn_mask=None, self_attn_padding_mask=None):
'\n Args:\n x (Tensor): input to the layer of shape `(seq_len, batch, embed_dim)`\n encoder_padding_mask (ByteTensor): binary ByteTensor of shape\n `(batch, src_len)` where padding elements are indicated by ``1``.\n\n Returns:\n encoded output of shape `(batch, src_len, embed_dim)`\n '
residual = x
x = self.maybe_layer_norm(self.self_attn_layer_norm, x, before=True)
if (prev_self_attn_state is not None):
if (incremental_state is None):
incremental_state = {}
(prev_key, prev_value) = prev_self_attn_state
saved_state = {'prev_key': prev_key, 'prev_value': prev_value}
self.self_attn._set_input_buffer(incremental_state, saved_state)
(x, attn) = self.self_attn(query=x, key=x, value=x, key_padding_mask=self_attn_padding_mask, incremental_state=incremental_state, need_weights=False, attn_mask=self_attn_mask)
x = F.dropout(x, p=self.dropout, training=self.training)
x = (residual + x)
x = self.maybe_layer_norm(self.self_attn_layer_norm, x, after=True)
if (self.encoder_attn is not None):
residual = x
x = self.maybe_layer_norm(self.encoder_attn_layer_norm, x, before=True)
if (prev_attn_state is not None):
if (incremental_state is None):
incremental_state = {}
(prev_key, prev_value) = prev_attn_state
saved_state = {'prev_key': prev_key, 'prev_value': prev_value}
self.encoder_attn._set_input_buffer(incremental_state, saved_state)
(x1, attn) = self.encoder_attn(query=x, key=encoder_out, value=encoder_out, key_padding_mask=encoder_padding_mask, incremental_state=incremental_state, static_kv=True, need_weights=((not self.training) and self.need_attn))
x1 = F.dropout(x1, p=self.dropout, training=self.training)
x = (residual + x1)
x = self.maybe_layer_norm(self.encoder_attn_layer_norm, x, after=True)
residual = x
x = self.maybe_layer_norm(self.final_layer_norm, x, before=True)
x = self.activation_fn(self.fc1(x))
x = F.dropout(x, p=self.activation_dropout, training=self.training)
x = self.fc2(x)
x = F.dropout(x, p=self.dropout, training=self.training)
x = (residual + x)
x = self.maybe_layer_norm(self.final_layer_norm, x, after=True)
if (self.onnx_trace and (incremental_state is not None)):
saved_state = self.self_attn._get_input_buffer(incremental_state)
self_attn_state = (saved_state['prev_key'], saved_state['prev_value'])
return (x, attn, self_attn_state)
return (x, attn) | -4,948,189,932,445,657,000 | Args:
x (Tensor): input to the layer of shape `(seq_len, batch, embed_dim)`
encoder_padding_mask (ByteTensor): binary ByteTensor of shape
`(batch, src_len)` where padding elements are indicated by ``1``.
Returns:
encoded output of shape `(batch, src_len, embed_dim)` | models/transformer.py | forward | NCTUMLlab/Adversarial-Masking-Transformers-for-Language-Understanding | python | def forward(self, x, encoder_out=None, encoder_padding_mask=None, bert_encoder_out=None, bert_encoder_padding_mask=None, incremental_state=None, prev_self_attn_state=None, prev_attn_state=None, self_attn_mask=None, self_attn_padding_mask=None):
'\n Args:\n x (Tensor): input to the layer of shape `(seq_len, batch, embed_dim)`\n encoder_padding_mask (ByteTensor): binary ByteTensor of shape\n `(batch, src_len)` where padding elements are indicated by ``1``.\n\n Returns:\n encoded output of shape `(batch, src_len, embed_dim)`\n '
residual = x
x = self.maybe_layer_norm(self.self_attn_layer_norm, x, before=True)
if (prev_self_attn_state is not None):
if (incremental_state is None):
incremental_state = {}
(prev_key, prev_value) = prev_self_attn_state
saved_state = {'prev_key': prev_key, 'prev_value': prev_value}
self.self_attn._set_input_buffer(incremental_state, saved_state)
(x, attn) = self.self_attn(query=x, key=x, value=x, key_padding_mask=self_attn_padding_mask, incremental_state=incremental_state, need_weights=False, attn_mask=self_attn_mask)
x = F.dropout(x, p=self.dropout, training=self.training)
x = (residual + x)
x = self.maybe_layer_norm(self.self_attn_layer_norm, x, after=True)
if (self.encoder_attn is not None):
residual = x
x = self.maybe_layer_norm(self.encoder_attn_layer_norm, x, before=True)
if (prev_attn_state is not None):
if (incremental_state is None):
incremental_state = {}
(prev_key, prev_value) = prev_attn_state
saved_state = {'prev_key': prev_key, 'prev_value': prev_value}
self.encoder_attn._set_input_buffer(incremental_state, saved_state)
(x1, attn) = self.encoder_attn(query=x, key=encoder_out, value=encoder_out, key_padding_mask=encoder_padding_mask, incremental_state=incremental_state, static_kv=True, need_weights=((not self.training) and self.need_attn))
x1 = F.dropout(x1, p=self.dropout, training=self.training)
x = (residual + x1)
x = self.maybe_layer_norm(self.encoder_attn_layer_norm, x, after=True)
residual = x
x = self.maybe_layer_norm(self.final_layer_norm, x, before=True)
x = self.activation_fn(self.fc1(x))
x = F.dropout(x, p=self.activation_dropout, training=self.training)
x = self.fc2(x)
x = F.dropout(x, p=self.dropout, training=self.training)
x = (residual + x)
x = self.maybe_layer_norm(self.final_layer_norm, x, after=True)
if (self.onnx_trace and (incremental_state is not None)):
saved_state = self.self_attn._get_input_buffer(incremental_state)
self_attn_state = (saved_state['prev_key'], saved_state['prev_value'])
return (x, attn, self_attn_state)
return (x, attn) |
def forward(self, x, encoder_out=None, encoder_padding_mask=None, bert_encoder_out=None, bert_encoder_padding_mask=None, incremental_state=None, prev_self_attn_state=None, prev_attn_state=None, self_attn_mask=None, self_attn_padding_mask=None):
'\n Args:\n x (Tensor): input to the layer of shape `(seq_len, batch, embed_dim)`\n encoder_padding_mask (ByteTensor): binary ByteTensor of shape\n `(batch, src_len)` where padding elements are indicated by ``1``.\n Returns:\n encoded output of shape `(batch, src_len, embed_dim)`\n '
residual = x
x = self.maybe_layer_norm(self.self_attn_layer_norm, x, before=True)
if (prev_self_attn_state is not None):
if (incremental_state is None):
incremental_state = {}
(prev_key, prev_value) = prev_self_attn_state
saved_state = {'prev_key': prev_key, 'prev_value': prev_value}
self.self_attn._set_input_buffer(incremental_state, saved_state)
(x, attn) = self.self_attn(query=x, key=x, value=x, key_padding_mask=self_attn_padding_mask, incremental_state=incremental_state, need_weights=False, attn_mask=self_attn_mask)
x = F.dropout(x, p=self.dropout, training=self.training)
x = (residual + x)
x = self.maybe_layer_norm(self.self_attn_layer_norm, x, after=True)
if (self.encoder_attn is not None):
if (prev_attn_state is not None):
if (incremental_state is None):
incremental_state = {}
(prev_key, prev_value) = prev_attn_state
saved_state = {'prev_key': prev_key, 'prev_value': prev_value}
self.encoder_attn._set_input_buffer(incremental_state, saved_state)
def sinattn(attnlayer, x, layer_norm, keyorvalue, key_padding, incremental_state):
residual = x
x = self.maybe_layer_norm(layer_norm, x, before=True)
(x, attn) = attnlayer(query=x, key=keyorvalue, value=keyorvalue, key_padding_mask=key_padding, incremental_state=incremental_state, static_kv=True, need_weights=((not self.training) and self.need_attn))
x = F.dropout(x, p=self.dropout, training=self.training)
x = (residual + x)
x = self.maybe_layer_norm(layer_norm, x, after=True)
return (x, attn)
if self.bert_first:
(x, attn) = sinattn(self.bert_attn, x, self.bert_attn_layer_norm, bert_encoder_out, bert_encoder_padding_mask, incremental_state)
(x, attn) = sinattn(self.encoder_attn, x, self.encoder_attn_layer_norm, encoder_out, encoder_padding_mask, incremental_state)
else:
(x, attn) = sinattn(self.encoder_attn, x, self.encoder_attn_layer_norm, encoder_out, encoder_padding_mask, incremental_state)
(x, attn) = sinattn(self.bert_attn, x, self.bert_attn_layer_norm, bert_encoder_out, bert_encoder_padding_mask, incremental_state)
residual = x
x = self.maybe_layer_norm(self.final_layer_norm, x, before=True)
x = self.activation_fn(self.fc1(x))
x = F.dropout(x, p=self.activation_dropout, training=self.training)
x = self.fc2(x)
x = F.dropout(x, p=self.dropout, training=self.training)
x = (residual + x)
x = self.maybe_layer_norm(self.final_layer_norm, x, after=True)
if (self.onnx_trace and (incremental_state is not None)):
saved_state = self.self_attn._get_input_buffer(incremental_state)
self_attn_state = (saved_state['prev_key'], saved_state['prev_value'])
return (x, attn, self_attn_state)
return (x, attn) | 4,853,743,620,221,757,000 | Args:
x (Tensor): input to the layer of shape `(seq_len, batch, embed_dim)`
encoder_padding_mask (ByteTensor): binary ByteTensor of shape
`(batch, src_len)` where padding elements are indicated by ``1``.
Returns:
encoded output of shape `(batch, src_len, embed_dim)` | models/transformer.py | forward | NCTUMLlab/Adversarial-Masking-Transformers-for-Language-Understanding | python | def forward(self, x, encoder_out=None, encoder_padding_mask=None, bert_encoder_out=None, bert_encoder_padding_mask=None, incremental_state=None, prev_self_attn_state=None, prev_attn_state=None, self_attn_mask=None, self_attn_padding_mask=None):
'\n Args:\n x (Tensor): input to the layer of shape `(seq_len, batch, embed_dim)`\n encoder_padding_mask (ByteTensor): binary ByteTensor of shape\n `(batch, src_len)` where padding elements are indicated by ``1``.\n Returns:\n encoded output of shape `(batch, src_len, embed_dim)`\n '
residual = x
x = self.maybe_layer_norm(self.self_attn_layer_norm, x, before=True)
if (prev_self_attn_state is not None):
if (incremental_state is None):
incremental_state = {}
(prev_key, prev_value) = prev_self_attn_state
saved_state = {'prev_key': prev_key, 'prev_value': prev_value}
self.self_attn._set_input_buffer(incremental_state, saved_state)
(x, attn) = self.self_attn(query=x, key=x, value=x, key_padding_mask=self_attn_padding_mask, incremental_state=incremental_state, need_weights=False, attn_mask=self_attn_mask)
x = F.dropout(x, p=self.dropout, training=self.training)
x = (residual + x)
x = self.maybe_layer_norm(self.self_attn_layer_norm, x, after=True)
if (self.encoder_attn is not None):
if (prev_attn_state is not None):
if (incremental_state is None):
incremental_state = {}
(prev_key, prev_value) = prev_attn_state
saved_state = {'prev_key': prev_key, 'prev_value': prev_value}
self.encoder_attn._set_input_buffer(incremental_state, saved_state)
def sinattn(attnlayer, x, layer_norm, keyorvalue, key_padding, incremental_state):
residual = x
x = self.maybe_layer_norm(layer_norm, x, before=True)
(x, attn) = attnlayer(query=x, key=keyorvalue, value=keyorvalue, key_padding_mask=key_padding, incremental_state=incremental_state, static_kv=True, need_weights=((not self.training) and self.need_attn))
x = F.dropout(x, p=self.dropout, training=self.training)
x = (residual + x)
x = self.maybe_layer_norm(layer_norm, x, after=True)
return (x, attn)
if self.bert_first:
(x, attn) = sinattn(self.bert_attn, x, self.bert_attn_layer_norm, bert_encoder_out, bert_encoder_padding_mask, incremental_state)
(x, attn) = sinattn(self.encoder_attn, x, self.encoder_attn_layer_norm, encoder_out, encoder_padding_mask, incremental_state)
else:
(x, attn) = sinattn(self.encoder_attn, x, self.encoder_attn_layer_norm, encoder_out, encoder_padding_mask, incremental_state)
(x, attn) = sinattn(self.bert_attn, x, self.bert_attn_layer_norm, bert_encoder_out, bert_encoder_padding_mask, incremental_state)
residual = x
x = self.maybe_layer_norm(self.final_layer_norm, x, before=True)
x = self.activation_fn(self.fc1(x))
x = F.dropout(x, p=self.activation_dropout, training=self.training)
x = self.fc2(x)
x = F.dropout(x, p=self.dropout, training=self.training)
x = (residual + x)
x = self.maybe_layer_norm(self.final_layer_norm, x, after=True)
if (self.onnx_trace and (incremental_state is not None)):
saved_state = self.self_attn._get_input_buffer(incremental_state)
self_attn_state = (saved_state['prev_key'], saved_state['prev_value'])
return (x, attn, self_attn_state)
return (x, attn) |
def __init__(self, graph, session, y, x, tmp_ckpt_path='/tmp/guided_backprop_ckpt'):
'Constructs a GuidedBackprop SaliencyMask.'
super(GuidedBackprop, self).__init__(graph, session, y, x)
self.x = x
if (GuidedBackprop.GuidedReluRegistered is False):
@tf.RegisterGradient('GuidedRelu')
def _GuidedReluGrad(op, grad):
gate_g = tf.cast((grad > 0), 'float32')
gate_y = tf.cast((op.outputs[0] > 0), 'float32')
return ((gate_y * gate_g) * grad)
GuidedBackprop.GuidedReluRegistered = True
with graph.as_default():
saver = tf.train.Saver()
saver.save(session, tmp_ckpt_path)
graph_def = graph.as_graph_def()
self.guided_graph = tf.Graph()
with self.guided_graph.as_default():
self.guided_sess = tf.Session(graph=self.guided_graph)
with self.guided_graph.gradient_override_map({'Relu': 'GuidedRelu'}):
tf.import_graph_def(graph_def, name='')
saver.restore(self.guided_sess, tmp_ckpt_path)
imported_y = self.guided_graph.get_tensor_by_name(y.name)
imported_x = self.guided_graph.get_tensor_by_name(x.name)
self.guided_grads_node = tf.gradients(imported_y, imported_x)[0] | 7,949,305,015,942,975,000 | Constructs a GuidedBackprop SaliencyMask. | saliency/guided_backprop.py | __init__ | aliabd/history-of-interpretation | python | def __init__(self, graph, session, y, x, tmp_ckpt_path='/tmp/guided_backprop_ckpt'):
super(GuidedBackprop, self).__init__(graph, session, y, x)
self.x = x
if (GuidedBackprop.GuidedReluRegistered is False):
@tf.RegisterGradient('GuidedRelu')
def _GuidedReluGrad(op, grad):
gate_g = tf.cast((grad > 0), 'float32')
gate_y = tf.cast((op.outputs[0] > 0), 'float32')
return ((gate_y * gate_g) * grad)
GuidedBackprop.GuidedReluRegistered = True
with graph.as_default():
saver = tf.train.Saver()
saver.save(session, tmp_ckpt_path)
graph_def = graph.as_graph_def()
self.guided_graph = tf.Graph()
with self.guided_graph.as_default():
self.guided_sess = tf.Session(graph=self.guided_graph)
with self.guided_graph.gradient_override_map({'Relu': 'GuidedRelu'}):
tf.import_graph_def(graph_def, name=)
saver.restore(self.guided_sess, tmp_ckpt_path)
imported_y = self.guided_graph.get_tensor_by_name(y.name)
imported_x = self.guided_graph.get_tensor_by_name(x.name)
self.guided_grads_node = tf.gradients(imported_y, imported_x)[0] |
def GetMask(self, x_value, feed_dict={}):
'Returns a GuidedBackprop mask.'
with self.guided_graph.as_default():
guided_feed_dict = {}
for tensor in feed_dict:
guided_feed_dict[tensor.name] = feed_dict[tensor]
guided_feed_dict[self.x.name] = [x_value]
return self.guided_sess.run(self.guided_grads_node, feed_dict=guided_feed_dict)[0] | 1,790,101,936,076,309,000 | Returns a GuidedBackprop mask. | saliency/guided_backprop.py | GetMask | aliabd/history-of-interpretation | python | def GetMask(self, x_value, feed_dict={}):
with self.guided_graph.as_default():
guided_feed_dict = {}
for tensor in feed_dict:
guided_feed_dict[tensor.name] = feed_dict[tensor]
guided_feed_dict[self.x.name] = [x_value]
return self.guided_sess.run(self.guided_grads_node, feed_dict=guided_feed_dict)[0] |
def validate_url(url):
'\n Auxiliary method to validate an urllib\n :param url: An url to be validated\n :type url: string\n :returns: True if the url is valid\n :rtype: bool\n '
scheme = url.split('://')[0].lower()
if (scheme not in url_schemes):
return False
if (not bool(url_regex.search(url))):
return False
return True | 2,019,927,503,990,452,000 | Auxiliary method to validate an urllib
:param url: An url to be validated
:type url: string
:returns: True if the url is valid
:rtype: bool | app/utils/onelogin/saml2/settings.py | validate_url | nycrecords/intranet | python | def validate_url(url):
'\n Auxiliary method to validate an urllib\n :param url: An url to be validated\n :type url: string\n :returns: True if the url is valid\n :rtype: bool\n '
scheme = url.split('://')[0].lower()
if (scheme not in url_schemes):
return False
if (not bool(url_regex.search(url))):
return False
return True |
def __init__(self, settings=None, custom_base_path=None, sp_validation_only=False):
'\n Initializes the settings:\n - Sets the paths of the different folders\n - Loads settings info from settings file or array/object provided\n\n :param settings: SAML Toolkit Settings\n :type settings: dict\n\n :param custom_base_path: Path where are stored the settings file and the cert folder\n :type custom_base_path: string\n\n :param sp_validation_only: Avoid the IdP validation\n :type sp_validation_only: boolean\n '
self.__sp_validation_only = sp_validation_only
self.__paths = {}
self.__strict = False
self.__debug = False
self.__sp = {}
self.__idp = {}
self.__security = {}
self.__contacts = {}
self.__organization = {}
self.__errors = []
self.__load_paths(base_path=custom_base_path)
self.__update_paths(settings)
if (settings is None):
try:
valid = self.__load_settings_from_file()
except Exception as e:
raise e
if (not valid):
raise OneLogin_Saml2_Error('Invalid dict settings at the file: %s', OneLogin_Saml2_Error.SETTINGS_INVALID, ','.join(self.__errors))
elif isinstance(settings, dict):
if (not self.__load_settings_from_dict(settings)):
raise OneLogin_Saml2_Error('Invalid dict settings: %s', OneLogin_Saml2_Error.SETTINGS_INVALID, ','.join(self.__errors))
else:
raise OneLogin_Saml2_Error('Unsupported settings object', OneLogin_Saml2_Error.UNSUPPORTED_SETTINGS_OBJECT)
self.format_idp_cert()
if ('x509certMulti' in self.__idp):
self.format_idp_cert_multi()
self.format_sp_cert()
if ('x509certNew' in self.__sp):
self.format_sp_cert_new()
self.format_sp_key() | -4,102,128,884,988,414,500 | Initializes the settings:
- Sets the paths of the different folders
- Loads settings info from settings file or array/object provided
:param settings: SAML Toolkit Settings
:type settings: dict
:param custom_base_path: Path where are stored the settings file and the cert folder
:type custom_base_path: string
:param sp_validation_only: Avoid the IdP validation
:type sp_validation_only: boolean | app/utils/onelogin/saml2/settings.py | __init__ | nycrecords/intranet | python | def __init__(self, settings=None, custom_base_path=None, sp_validation_only=False):
'\n Initializes the settings:\n - Sets the paths of the different folders\n - Loads settings info from settings file or array/object provided\n\n :param settings: SAML Toolkit Settings\n :type settings: dict\n\n :param custom_base_path: Path where are stored the settings file and the cert folder\n :type custom_base_path: string\n\n :param sp_validation_only: Avoid the IdP validation\n :type sp_validation_only: boolean\n '
self.__sp_validation_only = sp_validation_only
self.__paths = {}
self.__strict = False
self.__debug = False
self.__sp = {}
self.__idp = {}
self.__security = {}
self.__contacts = {}
self.__organization = {}
self.__errors = []
self.__load_paths(base_path=custom_base_path)
self.__update_paths(settings)
if (settings is None):
try:
valid = self.__load_settings_from_file()
except Exception as e:
raise e
if (not valid):
raise OneLogin_Saml2_Error('Invalid dict settings at the file: %s', OneLogin_Saml2_Error.SETTINGS_INVALID, ','.join(self.__errors))
elif isinstance(settings, dict):
if (not self.__load_settings_from_dict(settings)):
raise OneLogin_Saml2_Error('Invalid dict settings: %s', OneLogin_Saml2_Error.SETTINGS_INVALID, ','.join(self.__errors))
else:
raise OneLogin_Saml2_Error('Unsupported settings object', OneLogin_Saml2_Error.UNSUPPORTED_SETTINGS_OBJECT)
self.format_idp_cert()
if ('x509certMulti' in self.__idp):
self.format_idp_cert_multi()
self.format_sp_cert()
if ('x509certNew' in self.__sp):
self.format_sp_cert_new()
self.format_sp_key() |
def __load_paths(self, base_path=None):
'\n Set the paths of the different folders\n '
if (base_path is None):
base_path = dirname(dirname(dirname(__file__)))
if (not base_path.endswith(sep)):
base_path += sep
self.__paths = {'base': base_path, 'cert': ((base_path + 'certs') + sep), 'lib': ((base_path + 'lib') + sep), 'extlib': ((base_path + 'extlib') + sep)} | -7,425,753,098,019,775,000 | Set the paths of the different folders | app/utils/onelogin/saml2/settings.py | __load_paths | nycrecords/intranet | python | def __load_paths(self, base_path=None):
'\n \n '
if (base_path is None):
base_path = dirname(dirname(dirname(__file__)))
if (not base_path.endswith(sep)):
base_path += sep
self.__paths = {'base': base_path, 'cert': ((base_path + 'certs') + sep), 'lib': ((base_path + 'lib') + sep), 'extlib': ((base_path + 'extlib') + sep)} |
def __update_paths(self, settings):
'\n Set custom paths if necessary\n '
if (not isinstance(settings, dict)):
return
if ('custom_base_path' in settings):
base_path = settings['custom_base_path']
base_path = join(dirname(__file__), base_path)
self.__load_paths(base_path) | -851,702,267,590,710,300 | Set custom paths if necessary | app/utils/onelogin/saml2/settings.py | __update_paths | nycrecords/intranet | python | def __update_paths(self, settings):
'\n \n '
if (not isinstance(settings, dict)):
return
if ('custom_base_path' in settings):
base_path = settings['custom_base_path']
base_path = join(dirname(__file__), base_path)
self.__load_paths(base_path) |
def get_base_path(self):
'\n Returns base path\n\n :return: The base toolkit folder path\n :rtype: string\n '
return self.__paths['base'] | -3,251,405,120,382,975,500 | Returns base path
:return: The base toolkit folder path
:rtype: string | app/utils/onelogin/saml2/settings.py | get_base_path | nycrecords/intranet | python | def get_base_path(self):
'\n Returns base path\n\n :return: The base toolkit folder path\n :rtype: string\n '
return self.__paths['base'] |
def get_cert_path(self):
'\n Returns cert path\n\n :return: The cert folder path\n :rtype: string\n '
return self.__paths['cert'] | -2,868,438,709,607,504,400 | Returns cert path
:return: The cert folder path
:rtype: string | app/utils/onelogin/saml2/settings.py | get_cert_path | nycrecords/intranet | python | def get_cert_path(self):
'\n Returns cert path\n\n :return: The cert folder path\n :rtype: string\n '
return self.__paths['cert'] |
def get_lib_path(self):
'\n Returns lib path\n\n :return: The library folder path\n :rtype: string\n '
return self.__paths['lib'] | -3,343,954,377,221,302,300 | Returns lib path
:return: The library folder path
:rtype: string | app/utils/onelogin/saml2/settings.py | get_lib_path | nycrecords/intranet | python | def get_lib_path(self):
'\n Returns lib path\n\n :return: The library folder path\n :rtype: string\n '
return self.__paths['lib'] |
def get_ext_lib_path(self):
'\n Returns external lib path\n\n :return: The external library folder path\n :rtype: string\n '
return self.__paths['extlib'] | -7,216,888,168,113,255,000 | Returns external lib path
:return: The external library folder path
:rtype: string | app/utils/onelogin/saml2/settings.py | get_ext_lib_path | nycrecords/intranet | python | def get_ext_lib_path(self):
'\n Returns external lib path\n\n :return: The external library folder path\n :rtype: string\n '
return self.__paths['extlib'] |
def get_schemas_path(self):
'\n Returns schema path\n\n :return: The schema folder path\n :rtype: string\n '
return (self.__paths['lib'] + 'schemas/') | -4,632,891,345,904,846,000 | Returns schema path
:return: The schema folder path
:rtype: string | app/utils/onelogin/saml2/settings.py | get_schemas_path | nycrecords/intranet | python | def get_schemas_path(self):
'\n Returns schema path\n\n :return: The schema folder path\n :rtype: string\n '
return (self.__paths['lib'] + 'schemas/') |
def __load_settings_from_dict(self, settings):
'\n Loads settings info from a settings Dict\n\n :param settings: SAML Toolkit Settings\n :type settings: dict\n\n :returns: True if the settings info is valid\n :rtype: boolean\n '
errors = self.check_settings(settings)
if (len(errors) == 0):
self.__errors = []
self.__sp = settings['sp']
self.__idp = settings.get('idp', {})
self.__strict = settings.get('strict', False)
self.__debug = settings.get('debug', False)
self.__security = settings.get('security', {})
self.__contacts = settings.get('contactPerson', {})
self.__organization = settings.get('organization', {})
self.__add_default_values()
return True
self.__errors = errors
return False | 9,101,060,825,214,802,000 | Loads settings info from a settings Dict
:param settings: SAML Toolkit Settings
:type settings: dict
:returns: True if the settings info is valid
:rtype: boolean | app/utils/onelogin/saml2/settings.py | __load_settings_from_dict | nycrecords/intranet | python | def __load_settings_from_dict(self, settings):
'\n Loads settings info from a settings Dict\n\n :param settings: SAML Toolkit Settings\n :type settings: dict\n\n :returns: True if the settings info is valid\n :rtype: boolean\n '
errors = self.check_settings(settings)
if (len(errors) == 0):
self.__errors = []
self.__sp = settings['sp']
self.__idp = settings.get('idp', {})
self.__strict = settings.get('strict', False)
self.__debug = settings.get('debug', False)
self.__security = settings.get('security', {})
self.__contacts = settings.get('contactPerson', {})
self.__organization = settings.get('organization', {})
self.__add_default_values()
return True
self.__errors = errors
return False |
def __load_settings_from_file(self):
'\n Loads settings info from the settings json file\n\n :returns: True if the settings info is valid\n :rtype: boolean\n '
filename = (self.get_base_path() + 'settings.json')
if (not exists(filename)):
raise OneLogin_Saml2_Error('Settings file not found: %s', OneLogin_Saml2_Error.SETTINGS_FILE_NOT_FOUND, filename)
with open(filename, 'r') as json_data:
settings = json.loads(json_data.read())
advanced_filename = (self.get_base_path() + 'advanced_settings.json')
if exists(advanced_filename):
with open(advanced_filename, 'r') as json_data:
settings.update(json.loads(json_data.read()))
return self.__load_settings_from_dict(settings) | 3,696,009,825,667,300,400 | Loads settings info from the settings json file
:returns: True if the settings info is valid
:rtype: boolean | app/utils/onelogin/saml2/settings.py | __load_settings_from_file | nycrecords/intranet | python | def __load_settings_from_file(self):
'\n Loads settings info from the settings json file\n\n :returns: True if the settings info is valid\n :rtype: boolean\n '
filename = (self.get_base_path() + 'settings.json')
if (not exists(filename)):
raise OneLogin_Saml2_Error('Settings file not found: %s', OneLogin_Saml2_Error.SETTINGS_FILE_NOT_FOUND, filename)
with open(filename, 'r') as json_data:
settings = json.loads(json_data.read())
advanced_filename = (self.get_base_path() + 'advanced_settings.json')
if exists(advanced_filename):
with open(advanced_filename, 'r') as json_data:
settings.update(json.loads(json_data.read()))
return self.__load_settings_from_dict(settings) |
def __add_default_values(self):
'\n Add default values if the settings info is not complete\n '
self.__sp.setdefault('assertionConsumerService', {})
self.__sp['assertionConsumerService'].setdefault('binding', OneLogin_Saml2_Constants.BINDING_HTTP_POST)
self.__sp.setdefault('attributeConsumingService', {})
self.__sp.setdefault('singleLogoutService', {})
self.__sp['singleLogoutService'].setdefault('binding', OneLogin_Saml2_Constants.BINDING_HTTP_REDIRECT)
self.__idp.setdefault('singleLogoutService', {})
self.__sp.setdefault('NameIDFormat', OneLogin_Saml2_Constants.NAMEID_UNSPECIFIED)
self.__security.setdefault('nameIdEncrypted', False)
self.__security.setdefault('metadataValidUntil', None)
self.__security.setdefault('metadataCacheDuration', None)
self.__security.setdefault('authnRequestsSigned', False)
self.__security.setdefault('logoutRequestSigned', False)
self.__security.setdefault('logoutResponseSigned', False)
self.__security.setdefault('signMetadata', False)
self.__security.setdefault('wantMessagesSigned', False)
self.__security.setdefault('wantAssertionsSigned', False)
self.__security.setdefault('wantNameId', True)
self.__security.setdefault('wantAssertionsEncrypted', False)
self.__security.setdefault('wantNameIdEncrypted', False)
self.__security.setdefault('signatureAlgorithm', OneLogin_Saml2_Constants.RSA_SHA1)
self.__security.setdefault('digestAlgorithm', OneLogin_Saml2_Constants.SHA1)
self.__security.setdefault('wantAttributeStatement', True)
self.__idp.setdefault('x509cert', '')
self.__idp.setdefault('certFingerprint', '')
self.__idp.setdefault('certFingerprintAlgorithm', 'sha1')
self.__sp.setdefault('x509cert', '')
self.__sp.setdefault('privateKey', '')
self.__security.setdefault('requestedAuthnContext', True)
self.__security.setdefault('failOnAuthnContextMismatch', False) | 8,789,121,310,913,046,000 | Add default values if the settings info is not complete | app/utils/onelogin/saml2/settings.py | __add_default_values | nycrecords/intranet | python | def __add_default_values(self):
'\n \n '
self.__sp.setdefault('assertionConsumerService', {})
self.__sp['assertionConsumerService'].setdefault('binding', OneLogin_Saml2_Constants.BINDING_HTTP_POST)
self.__sp.setdefault('attributeConsumingService', {})
self.__sp.setdefault('singleLogoutService', {})
self.__sp['singleLogoutService'].setdefault('binding', OneLogin_Saml2_Constants.BINDING_HTTP_REDIRECT)
self.__idp.setdefault('singleLogoutService', {})
self.__sp.setdefault('NameIDFormat', OneLogin_Saml2_Constants.NAMEID_UNSPECIFIED)
self.__security.setdefault('nameIdEncrypted', False)
self.__security.setdefault('metadataValidUntil', None)
self.__security.setdefault('metadataCacheDuration', None)
self.__security.setdefault('authnRequestsSigned', False)
self.__security.setdefault('logoutRequestSigned', False)
self.__security.setdefault('logoutResponseSigned', False)
self.__security.setdefault('signMetadata', False)
self.__security.setdefault('wantMessagesSigned', False)
self.__security.setdefault('wantAssertionsSigned', False)
self.__security.setdefault('wantNameId', True)
self.__security.setdefault('wantAssertionsEncrypted', False)
self.__security.setdefault('wantNameIdEncrypted', False)
self.__security.setdefault('signatureAlgorithm', OneLogin_Saml2_Constants.RSA_SHA1)
self.__security.setdefault('digestAlgorithm', OneLogin_Saml2_Constants.SHA1)
self.__security.setdefault('wantAttributeStatement', True)
self.__idp.setdefault('x509cert', )
self.__idp.setdefault('certFingerprint', )
self.__idp.setdefault('certFingerprintAlgorithm', 'sha1')
self.__sp.setdefault('x509cert', )
self.__sp.setdefault('privateKey', )
self.__security.setdefault('requestedAuthnContext', True)
self.__security.setdefault('failOnAuthnContextMismatch', False) |
def check_settings(self, settings):
'\n Checks the settings info.\n\n :param settings: Dict with settings data\n :type settings: dict\n\n :returns: Errors found on the settings data\n :rtype: list\n '
assert isinstance(settings, dict)
errors = []
if ((not isinstance(settings, dict)) or (len(settings) == 0)):
errors.append('invalid_syntax')
else:
if (not self.__sp_validation_only):
errors += self.check_idp_settings(settings)
sp_errors = self.check_sp_settings(settings)
errors += sp_errors
return errors | 6,683,541,287,288,272,000 | Checks the settings info.
:param settings: Dict with settings data
:type settings: dict
:returns: Errors found on the settings data
:rtype: list | app/utils/onelogin/saml2/settings.py | check_settings | nycrecords/intranet | python | def check_settings(self, settings):
'\n Checks the settings info.\n\n :param settings: Dict with settings data\n :type settings: dict\n\n :returns: Errors found on the settings data\n :rtype: list\n '
assert isinstance(settings, dict)
errors = []
if ((not isinstance(settings, dict)) or (len(settings) == 0)):
errors.append('invalid_syntax')
else:
if (not self.__sp_validation_only):
errors += self.check_idp_settings(settings)
sp_errors = self.check_sp_settings(settings)
errors += sp_errors
return errors |
def check_idp_settings(self, settings):
'\n Checks the IdP settings info.\n :param settings: Dict with settings data\n :type settings: dict\n :returns: Errors found on the IdP settings data\n :rtype: list\n '
assert isinstance(settings, dict)
errors = []
if ((not isinstance(settings, dict)) or (len(settings) == 0)):
errors.append('invalid_syntax')
elif (not settings.get('idp')):
errors.append('idp_not_found')
else:
idp = settings['idp']
if (not idp.get('entityId')):
errors.append('idp_entityId_not_found')
if (not idp.get('singleSignOnService', {}).get('url')):
errors.append('idp_sso_not_found')
elif (not validate_url(idp['singleSignOnService']['url'])):
errors.append('idp_sso_url_invalid')
slo_url = idp.get('singleLogoutService', {}).get('url')
if (slo_url and (not validate_url(slo_url))):
errors.append('idp_slo_url_invalid')
if ('security' in settings):
security = settings['security']
exists_x509 = bool(idp.get('x509cert'))
exists_fingerprint = bool(idp.get('certFingerprint'))
exists_multix509sign = (('x509certMulti' in idp) and ('signing' in idp['x509certMulti']) and idp['x509certMulti']['signing'])
exists_multix509enc = (('x509certMulti' in idp) and ('encryption' in idp['x509certMulti']) and idp['x509certMulti']['encryption'])
want_assert_sign = bool(security.get('wantAssertionsSigned'))
want_mes_signed = bool(security.get('wantMessagesSigned'))
nameid_enc = bool(security.get('nameIdEncrypted'))
if ((want_assert_sign or want_mes_signed) and (not (exists_x509 or exists_fingerprint or exists_multix509sign))):
errors.append('idp_cert_or_fingerprint_not_found_and_required')
if (nameid_enc and (not (exists_x509 or exists_multix509enc))):
errors.append('idp_cert_not_found_and_required')
return errors | 8,715,893,815,939,197,000 | Checks the IdP settings info.
:param settings: Dict with settings data
:type settings: dict
:returns: Errors found on the IdP settings data
:rtype: list | app/utils/onelogin/saml2/settings.py | check_idp_settings | nycrecords/intranet | python | def check_idp_settings(self, settings):
'\n Checks the IdP settings info.\n :param settings: Dict with settings data\n :type settings: dict\n :returns: Errors found on the IdP settings data\n :rtype: list\n '
assert isinstance(settings, dict)
errors = []
if ((not isinstance(settings, dict)) or (len(settings) == 0)):
errors.append('invalid_syntax')
elif (not settings.get('idp')):
errors.append('idp_not_found')
else:
idp = settings['idp']
if (not idp.get('entityId')):
errors.append('idp_entityId_not_found')
if (not idp.get('singleSignOnService', {}).get('url')):
errors.append('idp_sso_not_found')
elif (not validate_url(idp['singleSignOnService']['url'])):
errors.append('idp_sso_url_invalid')
slo_url = idp.get('singleLogoutService', {}).get('url')
if (slo_url and (not validate_url(slo_url))):
errors.append('idp_slo_url_invalid')
if ('security' in settings):
security = settings['security']
exists_x509 = bool(idp.get('x509cert'))
exists_fingerprint = bool(idp.get('certFingerprint'))
exists_multix509sign = (('x509certMulti' in idp) and ('signing' in idp['x509certMulti']) and idp['x509certMulti']['signing'])
exists_multix509enc = (('x509certMulti' in idp) and ('encryption' in idp['x509certMulti']) and idp['x509certMulti']['encryption'])
want_assert_sign = bool(security.get('wantAssertionsSigned'))
want_mes_signed = bool(security.get('wantMessagesSigned'))
nameid_enc = bool(security.get('nameIdEncrypted'))
if ((want_assert_sign or want_mes_signed) and (not (exists_x509 or exists_fingerprint or exists_multix509sign))):
errors.append('idp_cert_or_fingerprint_not_found_and_required')
if (nameid_enc and (not (exists_x509 or exists_multix509enc))):
errors.append('idp_cert_not_found_and_required')
return errors |
def check_sp_settings(self, settings):
'\n Checks the SP settings info.\n :param settings: Dict with settings data\n :type settings: dict\n :returns: Errors found on the SP settings data\n :rtype: list\n '
assert isinstance(settings, dict)
errors = []
if ((not isinstance(settings, dict)) or (not settings)):
errors.append('invalid_syntax')
else:
if (not settings.get('sp')):
errors.append('sp_not_found')
else:
old_sp = self.__sp
self.__sp = settings['sp']
sp = settings['sp']
security = settings.get('security', {})
if (not sp.get('entityId')):
errors.append('sp_entityId_not_found')
if (not sp.get('assertionConsumerService', {}).get('url')):
errors.append('sp_acs_not_found')
elif (not validate_url(sp['assertionConsumerService']['url'])):
errors.append('sp_acs_url_invalid')
if sp.get('attributeConsumingService'):
attributeConsumingService = sp['attributeConsumingService']
if ('serviceName' not in attributeConsumingService):
errors.append('sp_attributeConsumingService_serviceName_not_found')
elif (not isinstance(attributeConsumingService['serviceName'], basestring)):
errors.append('sp_attributeConsumingService_serviceName_type_invalid')
if ('requestedAttributes' not in attributeConsumingService):
errors.append('sp_attributeConsumingService_requestedAttributes_not_found')
elif (not isinstance(attributeConsumingService['requestedAttributes'], list)):
errors.append('sp_attributeConsumingService_serviceName_type_invalid')
else:
for req_attrib in attributeConsumingService['requestedAttributes']:
if ('name' not in req_attrib):
errors.append('sp_attributeConsumingService_requestedAttributes_name_not_found')
if (('name' in req_attrib) and (not req_attrib['name'].strip())):
errors.append('sp_attributeConsumingService_requestedAttributes_name_invalid')
if (('attributeValue' in req_attrib) and (type(req_attrib['attributeValue']) != list)):
errors.append('sp_attributeConsumingService_requestedAttributes_attributeValue_type_invalid')
if (('isRequired' in req_attrib) and (type(req_attrib['isRequired']) != bool)):
errors.append('sp_attributeConsumingService_requestedAttributes_isRequired_type_invalid')
if (('serviceDescription' in attributeConsumingService) and (not isinstance(attributeConsumingService['serviceDescription'], basestring))):
errors.append('sp_attributeConsumingService_serviceDescription_type_invalid')
slo_url = sp.get('singleLogoutService', {}).get('url')
if (slo_url and (not validate_url(slo_url))):
errors.append('sp_sls_url_invalid')
if (('signMetadata' in security) and isinstance(security['signMetadata'], dict)):
if (('keyFileName' not in security['signMetadata']) or ('certFileName' not in security['signMetadata'])):
errors.append('sp_signMetadata_invalid')
authn_sign = bool(security.get('authnRequestsSigned'))
logout_req_sign = bool(security.get('logoutRequestSigned'))
logout_res_sign = bool(security.get('logoutResponseSigned'))
want_assert_enc = bool(security.get('wantAssertionsEncrypted'))
want_nameid_enc = bool(security.get('wantNameIdEncrypted'))
if (not self.check_sp_certs()):
if (authn_sign or logout_req_sign or logout_res_sign or want_assert_enc or want_nameid_enc):
errors.append('sp_cert_not_found_and_required')
if ('contactPerson' in settings):
types = settings['contactPerson']
valid_types = ['technical', 'support', 'administrative', 'billing', 'other']
for c_type in types:
if (c_type not in valid_types):
errors.append('contact_type_invalid')
break
for c_type in settings['contactPerson']:
contact = settings['contactPerson'][c_type]
if ((('givenName' not in contact) or (len(contact['givenName']) == 0)) or (('emailAddress' not in contact) or (len(contact['emailAddress']) == 0))):
errors.append('contact_not_enought_data')
break
if ('organization' in settings):
for org in settings['organization']:
organization = settings['organization'][org]
if ((('name' not in organization) or (len(organization['name']) == 0)) or (('displayname' not in organization) or (len(organization['displayname']) == 0)) or (('url' not in organization) or (len(organization['url']) == 0))):
errors.append('organization_not_enought_data')
break
if ('old_sp' in locals()):
self.__sp = old_sp
return errors | -2,496,403,301,086,345,700 | Checks the SP settings info.
:param settings: Dict with settings data
:type settings: dict
:returns: Errors found on the SP settings data
:rtype: list | app/utils/onelogin/saml2/settings.py | check_sp_settings | nycrecords/intranet | python | def check_sp_settings(self, settings):
'\n Checks the SP settings info.\n :param settings: Dict with settings data\n :type settings: dict\n :returns: Errors found on the SP settings data\n :rtype: list\n '
assert isinstance(settings, dict)
errors = []
if ((not isinstance(settings, dict)) or (not settings)):
errors.append('invalid_syntax')
else:
if (not settings.get('sp')):
errors.append('sp_not_found')
else:
old_sp = self.__sp
self.__sp = settings['sp']
sp = settings['sp']
security = settings.get('security', {})
if (not sp.get('entityId')):
errors.append('sp_entityId_not_found')
if (not sp.get('assertionConsumerService', {}).get('url')):
errors.append('sp_acs_not_found')
elif (not validate_url(sp['assertionConsumerService']['url'])):
errors.append('sp_acs_url_invalid')
if sp.get('attributeConsumingService'):
attributeConsumingService = sp['attributeConsumingService']
if ('serviceName' not in attributeConsumingService):
errors.append('sp_attributeConsumingService_serviceName_not_found')
elif (not isinstance(attributeConsumingService['serviceName'], basestring)):
errors.append('sp_attributeConsumingService_serviceName_type_invalid')
if ('requestedAttributes' not in attributeConsumingService):
errors.append('sp_attributeConsumingService_requestedAttributes_not_found')
elif (not isinstance(attributeConsumingService['requestedAttributes'], list)):
errors.append('sp_attributeConsumingService_serviceName_type_invalid')
else:
for req_attrib in attributeConsumingService['requestedAttributes']:
if ('name' not in req_attrib):
errors.append('sp_attributeConsumingService_requestedAttributes_name_not_found')
if (('name' in req_attrib) and (not req_attrib['name'].strip())):
errors.append('sp_attributeConsumingService_requestedAttributes_name_invalid')
if (('attributeValue' in req_attrib) and (type(req_attrib['attributeValue']) != list)):
errors.append('sp_attributeConsumingService_requestedAttributes_attributeValue_type_invalid')
if (('isRequired' in req_attrib) and (type(req_attrib['isRequired']) != bool)):
errors.append('sp_attributeConsumingService_requestedAttributes_isRequired_type_invalid')
if (('serviceDescription' in attributeConsumingService) and (not isinstance(attributeConsumingService['serviceDescription'], basestring))):
errors.append('sp_attributeConsumingService_serviceDescription_type_invalid')
slo_url = sp.get('singleLogoutService', {}).get('url')
if (slo_url and (not validate_url(slo_url))):
errors.append('sp_sls_url_invalid')
if (('signMetadata' in security) and isinstance(security['signMetadata'], dict)):
if (('keyFileName' not in security['signMetadata']) or ('certFileName' not in security['signMetadata'])):
errors.append('sp_signMetadata_invalid')
authn_sign = bool(security.get('authnRequestsSigned'))
logout_req_sign = bool(security.get('logoutRequestSigned'))
logout_res_sign = bool(security.get('logoutResponseSigned'))
want_assert_enc = bool(security.get('wantAssertionsEncrypted'))
want_nameid_enc = bool(security.get('wantNameIdEncrypted'))
if (not self.check_sp_certs()):
if (authn_sign or logout_req_sign or logout_res_sign or want_assert_enc or want_nameid_enc):
errors.append('sp_cert_not_found_and_required')
if ('contactPerson' in settings):
types = settings['contactPerson']
valid_types = ['technical', 'support', 'administrative', 'billing', 'other']
for c_type in types:
if (c_type not in valid_types):
errors.append('contact_type_invalid')
break
for c_type in settings['contactPerson']:
contact = settings['contactPerson'][c_type]
if ((('givenName' not in contact) or (len(contact['givenName']) == 0)) or (('emailAddress' not in contact) or (len(contact['emailAddress']) == 0))):
errors.append('contact_not_enought_data')
break
if ('organization' in settings):
for org in settings['organization']:
organization = settings['organization'][org]
if ((('name' not in organization) or (len(organization['name']) == 0)) or (('displayname' not in organization) or (len(organization['displayname']) == 0)) or (('url' not in organization) or (len(organization['url']) == 0))):
errors.append('organization_not_enought_data')
break
if ('old_sp' in locals()):
self.__sp = old_sp
return errors |
def check_sp_certs(self):
'\n Checks if the x509 certs of the SP exists and are valid.\n :returns: If the x509 certs of the SP exists and are valid\n :rtype: boolean\n '
key = self.get_sp_key()
cert = self.get_sp_cert()
return ((key is not None) and (cert is not None)) | -7,812,650,226,965,906,000 | Checks if the x509 certs of the SP exists and are valid.
:returns: If the x509 certs of the SP exists and are valid
:rtype: boolean | app/utils/onelogin/saml2/settings.py | check_sp_certs | nycrecords/intranet | python | def check_sp_certs(self):
'\n Checks if the x509 certs of the SP exists and are valid.\n :returns: If the x509 certs of the SP exists and are valid\n :rtype: boolean\n '
key = self.get_sp_key()
cert = self.get_sp_cert()
return ((key is not None) and (cert is not None)) |
def get_sp_key(self):
'\n Returns the x509 private key of the SP.\n :returns: SP private key\n :rtype: string or None\n '
key = self.__sp.get('privateKey')
key_file_name = (self.__paths['cert'] + 'sp.key')
if ((not key) and exists(key_file_name)):
with open(key_file_name) as f:
key = f.read()
return (key or None) | -4,037,297,485,836,650,000 | Returns the x509 private key of the SP.
:returns: SP private key
:rtype: string or None | app/utils/onelogin/saml2/settings.py | get_sp_key | nycrecords/intranet | python | def get_sp_key(self):
'\n Returns the x509 private key of the SP.\n :returns: SP private key\n :rtype: string or None\n '
key = self.__sp.get('privateKey')
key_file_name = (self.__paths['cert'] + 'sp.key')
if ((not key) and exists(key_file_name)):
with open(key_file_name) as f:
key = f.read()
return (key or None) |
def get_sp_cert(self):
'\n Returns the x509 public cert of the SP.\n :returns: SP public cert\n :rtype: string or None\n '
cert = self.__sp.get('x509cert')
cert_file_name = (self.__paths['cert'] + 'sp.crt')
if ((not cert) and exists(cert_file_name)):
with open(cert_file_name) as f:
cert = f.read()
return (cert or None) | 3,085,101,086,525,962,000 | Returns the x509 public cert of the SP.
:returns: SP public cert
:rtype: string or None | app/utils/onelogin/saml2/settings.py | get_sp_cert | nycrecords/intranet | python | def get_sp_cert(self):
'\n Returns the x509 public cert of the SP.\n :returns: SP public cert\n :rtype: string or None\n '
cert = self.__sp.get('x509cert')
cert_file_name = (self.__paths['cert'] + 'sp.crt')
if ((not cert) and exists(cert_file_name)):
with open(cert_file_name) as f:
cert = f.read()
return (cert or None) |
def get_sp_cert_new(self):
'\n Returns the x509 public of the SP planned\n to be used soon instead the other public cert\n :returns: SP public cert new\n :rtype: string or None\n '
cert = self.__sp.get('x509certNew')
cert_file_name = (self.__paths['cert'] + 'sp_new.crt')
if ((not cert) and exists(cert_file_name)):
with open(cert_file_name) as f:
cert = f.read()
return (cert or None) | -1,498,846,491,623,402,500 | Returns the x509 public of the SP planned
to be used soon instead the other public cert
:returns: SP public cert new
:rtype: string or None | app/utils/onelogin/saml2/settings.py | get_sp_cert_new | nycrecords/intranet | python | def get_sp_cert_new(self):
'\n Returns the x509 public of the SP planned\n to be used soon instead the other public cert\n :returns: SP public cert new\n :rtype: string or None\n '
cert = self.__sp.get('x509certNew')
cert_file_name = (self.__paths['cert'] + 'sp_new.crt')
if ((not cert) and exists(cert_file_name)):
with open(cert_file_name) as f:
cert = f.read()
return (cert or None) |
def get_idp_cert(self):
'\n Returns the x509 public cert of the IdP.\n :returns: IdP public cert\n :rtype: string\n '
return self.__idp.get('x509cert') | 4,088,177,130,043,971,000 | Returns the x509 public cert of the IdP.
:returns: IdP public cert
:rtype: string | app/utils/onelogin/saml2/settings.py | get_idp_cert | nycrecords/intranet | python | def get_idp_cert(self):
'\n Returns the x509 public cert of the IdP.\n :returns: IdP public cert\n :rtype: string\n '
return self.__idp.get('x509cert') |
def get_idp_data(self):
'\n Gets the IdP data.\n\n :returns: IdP info\n :rtype: dict\n '
return self.__idp | -3,116,901,750,163,315,000 | Gets the IdP data.
:returns: IdP info
:rtype: dict | app/utils/onelogin/saml2/settings.py | get_idp_data | nycrecords/intranet | python | def get_idp_data(self):
'\n Gets the IdP data.\n\n :returns: IdP info\n :rtype: dict\n '
return self.__idp |
def get_sp_data(self):
'\n Gets the SP data.\n\n :returns: SP info\n :rtype: dict\n '
return self.__sp | -7,802,741,565,788,101,000 | Gets the SP data.
:returns: SP info
:rtype: dict | app/utils/onelogin/saml2/settings.py | get_sp_data | nycrecords/intranet | python | def get_sp_data(self):
'\n Gets the SP data.\n\n :returns: SP info\n :rtype: dict\n '
return self.__sp |
def get_security_data(self):
'\n Gets security data.\n\n :returns: Security info\n :rtype: dict\n '
return self.__security | 1,365,572,923,322,081,000 | Gets security data.
:returns: Security info
:rtype: dict | app/utils/onelogin/saml2/settings.py | get_security_data | nycrecords/intranet | python | def get_security_data(self):
'\n Gets security data.\n\n :returns: Security info\n :rtype: dict\n '
return self.__security |
def get_contacts(self):
'\n Gets contact data.\n\n :returns: Contacts info\n :rtype: dict\n '
return self.__contacts | -8,828,376,608,204,893,000 | Gets contact data.
:returns: Contacts info
:rtype: dict | app/utils/onelogin/saml2/settings.py | get_contacts | nycrecords/intranet | python | def get_contacts(self):
'\n Gets contact data.\n\n :returns: Contacts info\n :rtype: dict\n '
return self.__contacts |
def get_organization(self):
'\n Gets organization data.\n\n :returns: Organization info\n :rtype: dict\n '
return self.__organization | 7,596,810,709,364,819,000 | Gets organization data.
:returns: Organization info
:rtype: dict | app/utils/onelogin/saml2/settings.py | get_organization | nycrecords/intranet | python | def get_organization(self):
'\n Gets organization data.\n\n :returns: Organization info\n :rtype: dict\n '
return self.__organization |
def get_sp_metadata(self):
'\n Gets the SP metadata. The XML representation.\n :returns: SP metadata (xml)\n :rtype: string\n '
metadata = OneLogin_Saml2_Metadata.builder(self.__sp, self.__security['authnRequestsSigned'], self.__security['wantAssertionsSigned'], self.__security['metadataValidUntil'], self.__security['metadataCacheDuration'], self.get_contacts(), self.get_organization())
add_encryption = (self.__security['wantNameIdEncrypted'] or self.__security['wantAssertionsEncrypted'])
cert_new = self.get_sp_cert_new()
metadata = OneLogin_Saml2_Metadata.add_x509_key_descriptors(metadata, cert_new, add_encryption)
cert = self.get_sp_cert()
metadata = OneLogin_Saml2_Metadata.add_x509_key_descriptors(metadata, cert, add_encryption)
if (('signMetadata' in self.__security) and (self.__security['signMetadata'] is not False)):
if (self.__security['signMetadata'] is True):
if (not cert):
raise OneLogin_Saml2_Error('Cannot sign metadata: missing SP public key certificate.', OneLogin_Saml2_Error.PUBLIC_CERT_FILE_NOT_FOUND)
cert_metadata = cert
key_metadata = self.get_sp_key()
if (not key_metadata):
raise OneLogin_Saml2_Error('Cannot sign metadata: missing SP private key.', OneLogin_Saml2_Error.PRIVATE_KEY_FILE_NOT_FOUND)
else:
if (('keyFileName' not in self.__security['signMetadata']) or ('certFileName' not in self.__security['signMetadata'])):
raise OneLogin_Saml2_Error('Invalid Setting: signMetadata value of the sp is not valid', OneLogin_Saml2_Error.SETTINGS_INVALID_SYNTAX)
key_file_name = self.__security['signMetadata']['keyFileName']
cert_file_name = self.__security['signMetadata']['certFileName']
key_metadata_file = (self.__paths['cert'] + key_file_name)
cert_metadata_file = (self.__paths['cert'] + cert_file_name)
try:
with open(key_metadata_file, 'r') as f_metadata_key:
key_metadata = f_metadata_key.read()
except IOError:
raise OneLogin_Saml2_Error('Private key file not readable: %s', OneLogin_Saml2_Error.PRIVATE_KEY_FILE_NOT_FOUND, key_metadata_file)
try:
with open(cert_metadata_file, 'r') as f_metadata_cert:
cert_metadata = f_metadata_cert.read()
except IOError:
raise OneLogin_Saml2_Error('Public cert file not readable: %s', OneLogin_Saml2_Error.PUBLIC_CERT_FILE_NOT_FOUND, cert_metadata_file)
signature_algorithm = self.__security['signatureAlgorithm']
digest_algorithm = self.__security['digestAlgorithm']
metadata = OneLogin_Saml2_Metadata.sign_metadata(metadata, key_metadata, cert_metadata, signature_algorithm, digest_algorithm)
return metadata | -4,473,593,141,927,607,300 | Gets the SP metadata. The XML representation.
:returns: SP metadata (xml)
:rtype: string | app/utils/onelogin/saml2/settings.py | get_sp_metadata | nycrecords/intranet | python | def get_sp_metadata(self):
'\n Gets the SP metadata. The XML representation.\n :returns: SP metadata (xml)\n :rtype: string\n '
metadata = OneLogin_Saml2_Metadata.builder(self.__sp, self.__security['authnRequestsSigned'], self.__security['wantAssertionsSigned'], self.__security['metadataValidUntil'], self.__security['metadataCacheDuration'], self.get_contacts(), self.get_organization())
add_encryption = (self.__security['wantNameIdEncrypted'] or self.__security['wantAssertionsEncrypted'])
cert_new = self.get_sp_cert_new()
metadata = OneLogin_Saml2_Metadata.add_x509_key_descriptors(metadata, cert_new, add_encryption)
cert = self.get_sp_cert()
metadata = OneLogin_Saml2_Metadata.add_x509_key_descriptors(metadata, cert, add_encryption)
if (('signMetadata' in self.__security) and (self.__security['signMetadata'] is not False)):
if (self.__security['signMetadata'] is True):
if (not cert):
raise OneLogin_Saml2_Error('Cannot sign metadata: missing SP public key certificate.', OneLogin_Saml2_Error.PUBLIC_CERT_FILE_NOT_FOUND)
cert_metadata = cert
key_metadata = self.get_sp_key()
if (not key_metadata):
raise OneLogin_Saml2_Error('Cannot sign metadata: missing SP private key.', OneLogin_Saml2_Error.PRIVATE_KEY_FILE_NOT_FOUND)
else:
if (('keyFileName' not in self.__security['signMetadata']) or ('certFileName' not in self.__security['signMetadata'])):
raise OneLogin_Saml2_Error('Invalid Setting: signMetadata value of the sp is not valid', OneLogin_Saml2_Error.SETTINGS_INVALID_SYNTAX)
key_file_name = self.__security['signMetadata']['keyFileName']
cert_file_name = self.__security['signMetadata']['certFileName']
key_metadata_file = (self.__paths['cert'] + key_file_name)
cert_metadata_file = (self.__paths['cert'] + cert_file_name)
try:
with open(key_metadata_file, 'r') as f_metadata_key:
key_metadata = f_metadata_key.read()
except IOError:
raise OneLogin_Saml2_Error('Private key file not readable: %s', OneLogin_Saml2_Error.PRIVATE_KEY_FILE_NOT_FOUND, key_metadata_file)
try:
with open(cert_metadata_file, 'r') as f_metadata_cert:
cert_metadata = f_metadata_cert.read()
except IOError:
raise OneLogin_Saml2_Error('Public cert file not readable: %s', OneLogin_Saml2_Error.PUBLIC_CERT_FILE_NOT_FOUND, cert_metadata_file)
signature_algorithm = self.__security['signatureAlgorithm']
digest_algorithm = self.__security['digestAlgorithm']
metadata = OneLogin_Saml2_Metadata.sign_metadata(metadata, key_metadata, cert_metadata, signature_algorithm, digest_algorithm)
return metadata |
def validate_metadata(self, xml):
"\n Validates an XML SP Metadata.\n\n :param xml: Metadata's XML that will be validate\n :type xml: string\n\n :returns: The list of found errors\n :rtype: list\n "
assert isinstance(xml, compat.text_types)
if (len(xml) == 0):
raise Exception('Empty string supplied as input')
errors = []
root = OneLogin_Saml2_XML.validate_xml(xml, 'saml-schema-metadata-2.0.xsd', self.__debug)
if isinstance(root, str):
errors.append(root)
elif (root.tag != ('{%s}EntityDescriptor' % OneLogin_Saml2_Constants.NS_MD)):
errors.append('noEntityDescriptor_xml')
elif (len(root.findall('.//md:SPSSODescriptor', namespaces=OneLogin_Saml2_Constants.NSMAP)) != 1):
errors.append('onlySPSSODescriptor_allowed_xml')
else:
(valid_until, cache_duration) = (root.get('validUntil'), root.get('cacheDuration'))
if valid_until:
valid_until = OneLogin_Saml2_Utils.parse_SAML_to_time(valid_until)
expire_time = OneLogin_Saml2_Utils.get_expire_time(cache_duration, valid_until)
if ((expire_time is not None) and (int(time()) > int(expire_time))):
errors.append('expired_xml')
return errors | 3,210,722,307,556,125,000 | Validates an XML SP Metadata.
:param xml: Metadata's XML that will be validate
:type xml: string
:returns: The list of found errors
:rtype: list | app/utils/onelogin/saml2/settings.py | validate_metadata | nycrecords/intranet | python | def validate_metadata(self, xml):
"\n Validates an XML SP Metadata.\n\n :param xml: Metadata's XML that will be validate\n :type xml: string\n\n :returns: The list of found errors\n :rtype: list\n "
assert isinstance(xml, compat.text_types)
if (len(xml) == 0):
raise Exception('Empty string supplied as input')
errors = []
root = OneLogin_Saml2_XML.validate_xml(xml, 'saml-schema-metadata-2.0.xsd', self.__debug)
if isinstance(root, str):
errors.append(root)
elif (root.tag != ('{%s}EntityDescriptor' % OneLogin_Saml2_Constants.NS_MD)):
errors.append('noEntityDescriptor_xml')
elif (len(root.findall('.//md:SPSSODescriptor', namespaces=OneLogin_Saml2_Constants.NSMAP)) != 1):
errors.append('onlySPSSODescriptor_allowed_xml')
else:
(valid_until, cache_duration) = (root.get('validUntil'), root.get('cacheDuration'))
if valid_until:
valid_until = OneLogin_Saml2_Utils.parse_SAML_to_time(valid_until)
expire_time = OneLogin_Saml2_Utils.get_expire_time(cache_duration, valid_until)
if ((expire_time is not None) and (int(time()) > int(expire_time))):
errors.append('expired_xml')
return errors |
def format_idp_cert(self):
'\n Formats the IdP cert.\n '
self.__idp['x509cert'] = OneLogin_Saml2_Utils.format_cert(self.__idp['x509cert']) | 154,846,901,795,047,100 | Formats the IdP cert. | app/utils/onelogin/saml2/settings.py | format_idp_cert | nycrecords/intranet | python | def format_idp_cert(self):
'\n \n '
self.__idp['x509cert'] = OneLogin_Saml2_Utils.format_cert(self.__idp['x509cert']) |
def format_idp_cert_multi(self):
'\n Formats the Multple IdP certs.\n '
if ('x509certMulti' in self.__idp):
if ('signing' in self.__idp['x509certMulti']):
for idx in range(len(self.__idp['x509certMulti']['signing'])):
self.__idp['x509certMulti']['signing'][idx] = OneLogin_Saml2_Utils.format_cert(self.__idp['x509certMulti']['signing'][idx])
if ('encryption' in self.__idp['x509certMulti']):
for idx in range(len(self.__idp['x509certMulti']['encryption'])):
self.__idp['x509certMulti']['encryption'][idx] = OneLogin_Saml2_Utils.format_cert(self.__idp['x509certMulti']['encryption'][idx]) | -5,308,441,926,965,280,000 | Formats the Multple IdP certs. | app/utils/onelogin/saml2/settings.py | format_idp_cert_multi | nycrecords/intranet | python | def format_idp_cert_multi(self):
'\n \n '
if ('x509certMulti' in self.__idp):
if ('signing' in self.__idp['x509certMulti']):
for idx in range(len(self.__idp['x509certMulti']['signing'])):
self.__idp['x509certMulti']['signing'][idx] = OneLogin_Saml2_Utils.format_cert(self.__idp['x509certMulti']['signing'][idx])
if ('encryption' in self.__idp['x509certMulti']):
for idx in range(len(self.__idp['x509certMulti']['encryption'])):
self.__idp['x509certMulti']['encryption'][idx] = OneLogin_Saml2_Utils.format_cert(self.__idp['x509certMulti']['encryption'][idx]) |
def format_sp_cert(self):
'\n Formats the SP cert.\n '
self.__sp['x509cert'] = OneLogin_Saml2_Utils.format_cert(self.__sp['x509cert']) | -8,799,753,653,561,585,000 | Formats the SP cert. | app/utils/onelogin/saml2/settings.py | format_sp_cert | nycrecords/intranet | python | def format_sp_cert(self):
'\n \n '
self.__sp['x509cert'] = OneLogin_Saml2_Utils.format_cert(self.__sp['x509cert']) |
def format_sp_cert_new(self):
'\n Formats the SP cert.\n '
self.__sp['x509certNew'] = OneLogin_Saml2_Utils.format_cert(self.__sp['x509certNew']) | -4,849,810,101,938,704,000 | Formats the SP cert. | app/utils/onelogin/saml2/settings.py | format_sp_cert_new | nycrecords/intranet | python | def format_sp_cert_new(self):
'\n \n '
self.__sp['x509certNew'] = OneLogin_Saml2_Utils.format_cert(self.__sp['x509certNew']) |
def format_sp_key(self):
'\n Formats the private key.\n '
self.__sp['privateKey'] = OneLogin_Saml2_Utils.format_private_key(self.__sp['privateKey']) | 240,490,718,022,734,240 | Formats the private key. | app/utils/onelogin/saml2/settings.py | format_sp_key | nycrecords/intranet | python | def format_sp_key(self):
'\n \n '
self.__sp['privateKey'] = OneLogin_Saml2_Utils.format_private_key(self.__sp['privateKey']) |
def get_errors(self):
'\n Returns an array with the errors, the array is empty when the settings is ok.\n\n :returns: Errors\n :rtype: list\n '
return self.__errors | -450,769,031,362,331,000 | Returns an array with the errors, the array is empty when the settings is ok.
:returns: Errors
:rtype: list | app/utils/onelogin/saml2/settings.py | get_errors | nycrecords/intranet | python | def get_errors(self):
'\n Returns an array with the errors, the array is empty when the settings is ok.\n\n :returns: Errors\n :rtype: list\n '
return self.__errors |
def set_strict(self, value):
'\n Activates or deactivates the strict mode.\n\n :param value: Strict parameter\n :type value: boolean\n '
assert isinstance(value, bool)
self.__strict = value | -1,835,184,990,267,616,000 | Activates or deactivates the strict mode.
:param value: Strict parameter
:type value: boolean | app/utils/onelogin/saml2/settings.py | set_strict | nycrecords/intranet | python | def set_strict(self, value):
'\n Activates or deactivates the strict mode.\n\n :param value: Strict parameter\n :type value: boolean\n '
assert isinstance(value, bool)
self.__strict = value |
def is_strict(self):
"\n Returns if the 'strict' mode is active.\n\n :returns: Strict parameter\n :rtype: boolean\n "
return self.__strict | -5,834,133,523,043,742,000 | Returns if the 'strict' mode is active.
:returns: Strict parameter
:rtype: boolean | app/utils/onelogin/saml2/settings.py | is_strict | nycrecords/intranet | python | def is_strict(self):
"\n Returns if the 'strict' mode is active.\n\n :returns: Strict parameter\n :rtype: boolean\n "
return self.__strict |
def is_debug_active(self):
'\n Returns if the debug is active.\n\n :returns: Debug parameter\n :rtype: boolean\n '
return self.__debug | 2,389,600,388,186,807,000 | Returns if the debug is active.
:returns: Debug parameter
:rtype: boolean | app/utils/onelogin/saml2/settings.py | is_debug_active | nycrecords/intranet | python | def is_debug_active(self):
'\n Returns if the debug is active.\n\n :returns: Debug parameter\n :rtype: boolean\n '
return self.__debug |
@pytest.mark.ui
def test_apply_mag_field_view1(exopy_qtbot, root_view, task_workbench):
'Test ApplyMagFieldView widget outisde of a LoopTask.\n\n '
task = ApplyMagFieldTask(name='Test')
root_view.task.add_child_task(0, task)
show_and_close_widget(exopy_qtbot, ApplyMagFieldView(task=task, root=root_view)) | 8,545,179,322,454,801,000 | Test ApplyMagFieldView widget outisde of a LoopTask. | tests/tasks/tasks/instr/test_apply_mag_field_task.py | test_apply_mag_field_view1 | Qcircuits/exopy_hqc_legacy | python | @pytest.mark.ui
def test_apply_mag_field_view1(exopy_qtbot, root_view, task_workbench):
'\n\n '
task = ApplyMagFieldTask(name='Test')
root_view.task.add_child_task(0, task)
show_and_close_widget(exopy_qtbot, ApplyMagFieldView(task=task, root=root_view)) |
@pytest.mark.ui
def test_apply_mag_field_view2(exopy_qtbot, root_view, task_workbench):
'Test ApplyMagFieldView widget inside of a LoopTask.\n\n '
task = ApplyMagFieldTask(name='Test')
loop = LoopTask(name='r', task=task)
root_view.task.add_child_task(0, loop)
show_and_close_widget(exopy_qtbot, LoopView(task=loop, root=root_view)) | 4,429,556,137,842,436,600 | Test ApplyMagFieldView widget inside of a LoopTask. | tests/tasks/tasks/instr/test_apply_mag_field_task.py | test_apply_mag_field_view2 | Qcircuits/exopy_hqc_legacy | python | @pytest.mark.ui
def test_apply_mag_field_view2(exopy_qtbot, root_view, task_workbench):
'\n\n '
task = ApplyMagFieldTask(name='Test')
loop = LoopTask(name='r', task=task)
root_view.task.add_child_task(0, loop)
show_and_close_widget(exopy_qtbot, LoopView(task=loop, root=root_view)) |
def test_check1(self):
'Simply test that everything is ok if field can be evaluated.\n\n '
self.task.field = '3.0'
(test, traceback) = self.task.check(test_instr=True)
assert test
assert (not traceback)
assert (self.task.get_from_database('Test_field') == 3.0) | 3,313,670,270,641,834,000 | Simply test that everything is ok if field can be evaluated. | tests/tasks/tasks/instr/test_apply_mag_field_task.py | test_check1 | Qcircuits/exopy_hqc_legacy | python | def test_check1(self):
'\n\n '
self.task.field = '3.0'
(test, traceback) = self.task.check(test_instr=True)
assert test
assert (not traceback)
assert (self.task.get_from_database('Test_field') == 3.0) |
def test_check2(self):
'Check handling a wrong field.\n\n '
self.task.field = '*1.0*'
(test, traceback) = self.task.check(test_instr=True)
assert (not test)
assert (len(traceback) == 1)
assert ('root/Test-field' in traceback)
assert (self.task.get_from_database('Test_field') == 0.01) | 7,797,678,657,480,563,000 | Check handling a wrong field. | tests/tasks/tasks/instr/test_apply_mag_field_task.py | test_check2 | Qcircuits/exopy_hqc_legacy | python | def test_check2(self):
'\n\n '
self.task.field = '*1.0*'
(test, traceback) = self.task.check(test_instr=True)
assert (not test)
assert (len(traceback) == 1)
assert ('root/Test-field' in traceback)
assert (self.task.get_from_database('Test_field') == 0.01) |
def test_perform1(self):
'Simple test when everything is right.\n\n '
self.task.field = '2.0'
self.root.prepare()
self.task.perform()
assert (self.root.get_from_database('Test_field') == 2.0) | -9,060,059,394,285,495,000 | Simple test when everything is right. | tests/tasks/tasks/instr/test_apply_mag_field_task.py | test_perform1 | Qcircuits/exopy_hqc_legacy | python | def test_perform1(self):
'\n\n '
self.task.field = '2.0'
self.root.prepare()
self.task.perform()
assert (self.root.get_from_database('Test_field') == 2.0) |
def _skip_date_tokens(tokens):
'\n Based on RFC 3164 + RFC 5424 and real-world logs\n '
if (tokens and tokens[0].startswith('<')):
tokens.pop(0)
while (tokens and ((not tokens[0]) or tokens[0][:1].isdigit())):
tokens.pop(0) | -6,881,443,272,031,541,000 | Based on RFC 3164 + RFC 5424 and real-world logs | syslog.py | _skip_date_tokens | Bun/ha-syslog-devtracker | python | def _skip_date_tokens(tokens):
'\n \n '
if (tokens and tokens[0].startswith('<')):
tokens.pop(0)
while (tokens and ((not tokens[0]) or tokens[0][:1].isdigit())):
tokens.pop(0) |
def parse_syslog_line(line):
'Parses lines created by hostapd and dnsmasq DHCP'
tokens = line.split(' ')
_skip_date_tokens(tokens)
process = _find_process(tokens)
if ((not process) or (not tokens)):
_LOGGER.debug('Unable to process line: %r', line)
return
if (process == 'hostapd'):
if (len(tokens) == 3):
if (tokens[1] == 'AP-STA-CONNECTED'):
return Event(tokens[2], 'home', True, tokens[1])
elif (tokens[1] == 'AP-STA-DISCONNECTED'):
return Event(tokens[2], 'timeout', True, tokens[1])
elif ((len(tokens) > 4) and (tokens[1] == 'STA')):
suffix = ' '.join(_remove_param(tokens[3:]))
for (consider, status) in STA_EVENTS.items():
if suffix.endswith(consider):
if (status == ''):
return
return Event(tokens[2], status, True, suffix)
_LOGGER.warning('Unhandled line: %r', line)
elif (process == 'dnsmasq-dhcp'):
if (len(tokens) >= 3):
if tokens[0].startswith('DHCPACK('):
return Event(tokens[2], 'home', False, tokens[0]) | -6,569,647,656,581,431,000 | Parses lines created by hostapd and dnsmasq DHCP | syslog.py | parse_syslog_line | Bun/ha-syslog-devtracker | python | def parse_syslog_line(line):
tokens = line.split(' ')
_skip_date_tokens(tokens)
process = _find_process(tokens)
if ((not process) or (not tokens)):
_LOGGER.debug('Unable to process line: %r', line)
return
if (process == 'hostapd'):
if (len(tokens) == 3):
if (tokens[1] == 'AP-STA-CONNECTED'):
return Event(tokens[2], 'home', True, tokens[1])
elif (tokens[1] == 'AP-STA-DISCONNECTED'):
return Event(tokens[2], 'timeout', True, tokens[1])
elif ((len(tokens) > 4) and (tokens[1] == 'STA')):
suffix = ' '.join(_remove_param(tokens[3:]))
for (consider, status) in STA_EVENTS.items():
if suffix.endswith(consider):
if (status == ):
return
return Event(tokens[2], status, True, suffix)
_LOGGER.warning('Unhandled line: %r', line)
elif (process == 'dnsmasq-dhcp'):
if (len(tokens) >= 3):
if tokens[0].startswith('DHCPACK('):
return Event(tokens[2], 'home', False, tokens[0]) |
def _add_conv_fc_branch(self, num_branch_convs, num_branch_fcs, in_channels, is_shared=False):
'Add shared or separable branch.\n\n convs -> avg pool (optional) -> fcs\n '
last_layer_dim = in_channels
branch_convs = nn.ModuleList()
if (num_branch_convs > 0):
for i in range(num_branch_convs):
conv_in_channels = (last_layer_dim if (i == 0) else self.conv_out_channels)
branch_convs.append(ConvModule(conv_in_channels, self.conv_out_channels, 3, padding=1, conv_cfg=self.conv_cfg, norm_cfg=self.norm_cfg))
last_layer_dim = self.conv_out_channels
branch_fcs = nn.ModuleList()
if (num_branch_fcs > 0):
if ((is_shared or (self.num_shared_fcs == 0)) and (not self.with_avg_pool)):
last_layer_dim *= self.roi_feat_area
for i in range(num_branch_fcs):
fc_in_channels = (last_layer_dim if (i == 0) else self.fc_out_channels)
branch_fcs.append(nn.Linear(fc_in_channels, self.fc_out_channels))
last_layer_dim = self.fc_out_channels
return (branch_convs, branch_fcs, last_layer_dim) | -8,176,502,878,514,245,000 | Add shared or separable branch.
convs -> avg pool (optional) -> fcs | mmdet/models/roi_heads/bbox_heads/convfc_bbox_head.py | _add_conv_fc_branch | marcovalenti/mmdetection | python | def _add_conv_fc_branch(self, num_branch_convs, num_branch_fcs, in_channels, is_shared=False):
'Add shared or separable branch.\n\n convs -> avg pool (optional) -> fcs\n '
last_layer_dim = in_channels
branch_convs = nn.ModuleList()
if (num_branch_convs > 0):
for i in range(num_branch_convs):
conv_in_channels = (last_layer_dim if (i == 0) else self.conv_out_channels)
branch_convs.append(ConvModule(conv_in_channels, self.conv_out_channels, 3, padding=1, conv_cfg=self.conv_cfg, norm_cfg=self.norm_cfg))
last_layer_dim = self.conv_out_channels
branch_fcs = nn.ModuleList()
if (num_branch_fcs > 0):
if ((is_shared or (self.num_shared_fcs == 0)) and (not self.with_avg_pool)):
last_layer_dim *= self.roi_feat_area
for i in range(num_branch_fcs):
fc_in_channels = (last_layer_dim if (i == 0) else self.fc_out_channels)
branch_fcs.append(nn.Linear(fc_in_channels, self.fc_out_channels))
last_layer_dim = self.fc_out_channels
return (branch_convs, branch_fcs, last_layer_dim) |
def get_targets(self, sampling_results, gt_bboxes, gt_labels, rcnn_train_cfg, reference_labels, classes, concat=True):
"Calculate the ground truth for all samples in a batch according to\n the sampling_results.\n Almost the same as the implementation in bbox_head, we passed\n additional parameters pos_inds_list and neg_inds_list to\n `_get_target_single` function.\n Args:\n sampling_results (List[obj:SamplingResults]): Assign results of\n all images in a batch after sampling.\n gt_bboxes (list[Tensor]): Gt_bboxes of all images in a batch,\n each tensor has shape (num_gt, 4), the last dimension 4\n represents [tl_x, tl_y, br_x, br_y].\n gt_labels (list[Tensor]): Gt_labels of all images in a batch,\n each tensor has shape (num_gt,).\n rcnn_train_cfg (obj:ConfigDict): `train_cfg` of RCNN.\n concat (bool): Whether to concatenate the results of all\n the images in a single batch.\n Returns:\n Tuple[Tensor]: Ground truth for proposals in a single image.\n Containing the following list of Tensors:\n - labels (list[Tensor],Tensor): Gt_labels for all\n proposals in a batch, each tensor in list has\n shape (num_proposals,) when `concat=False`, otherwise\n just a single tensor has shape (num_all_proposals,).\n - label_weights (list[Tensor]): Labels_weights for\n all proposals in a batch, each tensor in list has\n shape (num_proposals,) when `concat=False`, otherwise\n just a single tensor has shape (num_all_proposals,).\n - bbox_targets (list[Tensor],Tensor): Regression target\n for all proposals in a batch, each tensor in list\n has shape (num_proposals, 4) when `concat=False`,\n otherwise just a single tensor has shape\n (num_all_proposals, 4), the last dimension 4 represents\n [tl_x, tl_y, br_x, br_y].\n - bbox_weights (list[tensor],Tensor): Regression weights for\n all proposals in a batch, each tensor in list has shape\n (num_proposals, 4) when `concat=False`, otherwise just a\n single tensor has shape (num_all_proposals, 4).\n - dis_targets (list[tensor], Tensor): Gt_dis for all\n proposal in a batch, each tensor in list has\n shape (num_proposal,) when 'concat=False`, otherwise\n just a single tensor has shape (num_all_proposals,).\n "
pos_bboxes_list = [res.pos_bboxes for res in sampling_results]
neg_bboxes_list = [res.neg_bboxes for res in sampling_results]
pos_gt_bboxes_list = [res.pos_gt_bboxes for res in sampling_results]
pos_gt_labels_list = [res.pos_gt_labels for res in sampling_results]
(labels, label_weights, bbox_targets, bbox_weights) = multi_apply(self._get_target_single, pos_bboxes_list, neg_bboxes_list, pos_gt_bboxes_list, pos_gt_labels_list, cfg=rcnn_train_cfg)
iou_calculator = dict(type='BboxOverlaps2D')
iou_calculator = build_iou_calculator(iou_calculator)
isolation_thr = 0.45
dis_targets = []
for (i, res) in enumerate(sampling_results):
ref_grap_list = []
ref_leav_list = []
ref_grap_dis_list = []
ref_leav_dis_list = []
for (j, bbox) in enumerate(gt_bboxes[i]):
if (self.dis_selector == 0):
if (('grappolo' in classes[gt_labels[i][j]]) and (gt_labels[i][j] != reference_labels['grappolo_vite'])):
ref_grap_dis_list.append(bbox)
elif ((('foglia' in classes[gt_labels[i][j]]) or (classes[gt_labels[i][j]] == 'malattia_esca') or (classes[gt_labels[i][j]] == 'virosi_pinot_grigio')) and (gt_labels[i][j] != reference_labels['foglia_vite'])):
ref_leav_dis_list.append(bbox)
elif (self.dis_selector == 1):
if (gt_labels[i][j] == reference_labels['grappolo_vite']):
ref_grap_list.append(bbox)
elif (gt_labels[i][j] == reference_labels['foglia_vite']):
ref_leav_list.append(bbox)
elif (self.dis_selector == 2):
if (gt_labels[i][j] == reference_labels['grappolo_vite']):
ref_grap_list.append(bbox)
elif (gt_labels[i][j] == reference_labels['foglia_vite']):
ref_leav_list.append(bbox)
elif ('grappolo' in classes[gt_labels[i][j]]):
ref_grap_dis_list.append(bbox)
elif (('foglia' in classes[gt_labels[i][j]]) or (classes[gt_labels[i][j]] == 'malattia_esca') or (classes[gt_labels[i][j]] == 'virosi_pinot_grigio')):
ref_leav_dis_list.append(bbox)
"\n if 'grappolo' in classes[gt_labels[i][j]] and gt_labels[i][j] != reference_labels['grappolo_vite']:\n ref_grap_dis_list.append(bbox)\n elif (('foglia' in classes[gt_labels[i][j]] or classes[gt_labels[i][j]] == 'malattia_esca' or classes[gt_labels[i][j]] == 'virosi_pinot_grigio')\n and gt_labels[i][j] != reference_labels['foglia_vite']):\n ref_leav_dis_list.append(bbox)\n "
if (len(ref_grap_list) > 0):
ref_grap_tensor = torch.cat(ref_grap_list)
ref_grap_tensor = torch.reshape(ref_grap_tensor, (len(ref_grap_list), 4))
if (len(ref_leav_list) > 0):
ref_leav_tensor = torch.cat(ref_leav_list)
ref_leav_tensor = torch.reshape(ref_leav_tensor, (len(ref_leav_list), 4))
if (len(ref_grap_dis_list) > 0):
ref_grap_dis_tensor = torch.cat(ref_grap_dis_list)
ref_grap_dis_tensor = torch.reshape(ref_grap_dis_tensor, (len(ref_grap_dis_list), 4))
if (len(ref_leav_dis_list) > 0):
ref_leav_dis_tensor = torch.cat(ref_leav_dis_list)
ref_leav_dis_tensor = torch.reshape(ref_leav_dis_tensor, (len(ref_leav_dis_list), 4))
num_pos = res.pos_bboxes.size(0)
num_neg = res.neg_bboxes.size(0)
num_samples = (num_pos + num_neg)
dis_tensor = res.pos_bboxes.new_full((num_samples,), (- 1), dtype=torch.long)
dis_list = []
for (j, bbox) in enumerate(res.pos_bboxes):
bbox = bbox.unsqueeze(0)
if (res.pos_gt_labels[j] == reference_labels['grappolo_vite']):
if (self.dis_selector == 0):
dis_list.append((- 1))
elif ((self.dis_selector == 1) or (self.dis_selector == 2)):
if (len(ref_grap_dis_list) > 0):
overlaps = iou_calculator(ref_grap_dis_tensor, bbox, mode='iof')
overlaps = (overlaps < isolation_thr)
if overlaps.all():
dis_list.append(0)
else:
dis_list.append(1)
else:
dis_list.append(0)
elif (res.pos_gt_labels[j] == reference_labels['foglia_vite']):
if (self.dis_selector == 0):
dis_list.append((- 1))
elif ((self.dis_selector == 1) or (self.dis_selector == 2)):
if (len(ref_leav_dis_list) > 0):
overlaps = iou_calculator(ref_leav_dis_tensor, bbox, mode='iof')
overlaps = (overlaps < isolation_thr)
if overlaps.all():
dis_list.append(0)
else:
dis_list.append(1)
else:
dis_list.append(0)
elif (('grappolo' in classes[res.pos_gt_labels[j]]) and (res.pos_gt_labels[j] != reference_labels['grappolo_vite'])):
if (self.dis_selector == 1):
dis_list.append((- 1))
elif (self.dis_selector == 0):
if (len(ref_grap_list) > 0):
overlaps = iou_calculator(bbox, ref_grap_tensor, mode='iof')
overlaps = (overlaps < isolation_thr)
if overlaps.all():
dis_list.append(0)
else:
dis_list.append(1)
else:
dis_list.append(0)
elif (self.dis_selector == 2):
if (len(ref_grap_list) > 0):
overlaps = iou_calculator(bbox, ref_grap_tensor, mode='iof')
overlaps = (overlaps < isolation_thr)
if overlaps.all():
dis_list.append(2)
else:
dis_list.append(3)
else:
dis_list.append(2)
elif ((('foglia' in classes[res.pos_gt_labels[j]]) or (classes[res.pos_gt_labels[j]] == 'malattia_esca') or (classes[res.pos_gt_labels[j]] == 'virosi_pinot_grigio')) and (res.pos_gt_labels[j] != reference_labels['foglia_vite'])):
if (self.dis_selector == 1):
dis_list.append((- 1))
elif (self.dis_selector == 0):
if (len(ref_leav_list) > 0):
overlaps = iou_calculator(bbox, ref_leav_tensor, mode='iof')
overlaps = (overlaps < isolation_thr)
if overlaps.all():
dis_list.append(0)
else:
dis_list.append(1)
else:
dis_list.append(0)
elif (self.dis_selector == 2):
if (len(ref_leav_list) > 0):
overlaps = iou_calculator(bbox, ref_leav_tensor, mode='iof')
overlaps = (overlaps < isolation_thr)
if overlaps.all():
dis_list.append(2)
else:
dis_list.append(3)
else:
dis_list.append(2)
dis_tensor[:num_pos] = torch.tensor(dis_list)
dis_targets.append(dis_tensor)
if concat:
labels = torch.cat(labels, 0)
label_weights = torch.cat(label_weights, 0)
bbox_targets = torch.cat(bbox_targets, 0)
bbox_weights = torch.cat(bbox_weights, 0)
dis_targets = torch.cat(dis_targets, 0)
return (labels, label_weights, bbox_targets, bbox_weights, dis_targets) | -50,011,819,819,159,050 | Calculate the ground truth for all samples in a batch according to
the sampling_results.
Almost the same as the implementation in bbox_head, we passed
additional parameters pos_inds_list and neg_inds_list to
`_get_target_single` function.
Args:
sampling_results (List[obj:SamplingResults]): Assign results of
all images in a batch after sampling.
gt_bboxes (list[Tensor]): Gt_bboxes of all images in a batch,
each tensor has shape (num_gt, 4), the last dimension 4
represents [tl_x, tl_y, br_x, br_y].
gt_labels (list[Tensor]): Gt_labels of all images in a batch,
each tensor has shape (num_gt,).
rcnn_train_cfg (obj:ConfigDict): `train_cfg` of RCNN.
concat (bool): Whether to concatenate the results of all
the images in a single batch.
Returns:
Tuple[Tensor]: Ground truth for proposals in a single image.
Containing the following list of Tensors:
- labels (list[Tensor],Tensor): Gt_labels for all
proposals in a batch, each tensor in list has
shape (num_proposals,) when `concat=False`, otherwise
just a single tensor has shape (num_all_proposals,).
- label_weights (list[Tensor]): Labels_weights for
all proposals in a batch, each tensor in list has
shape (num_proposals,) when `concat=False`, otherwise
just a single tensor has shape (num_all_proposals,).
- bbox_targets (list[Tensor],Tensor): Regression target
for all proposals in a batch, each tensor in list
has shape (num_proposals, 4) when `concat=False`,
otherwise just a single tensor has shape
(num_all_proposals, 4), the last dimension 4 represents
[tl_x, tl_y, br_x, br_y].
- bbox_weights (list[tensor],Tensor): Regression weights for
all proposals in a batch, each tensor in list has shape
(num_proposals, 4) when `concat=False`, otherwise just a
single tensor has shape (num_all_proposals, 4).
- dis_targets (list[tensor], Tensor): Gt_dis for all
proposal in a batch, each tensor in list has
shape (num_proposal,) when 'concat=False`, otherwise
just a single tensor has shape (num_all_proposals,). | mmdet/models/roi_heads/bbox_heads/convfc_bbox_head.py | get_targets | marcovalenti/mmdetection | python | def get_targets(self, sampling_results, gt_bboxes, gt_labels, rcnn_train_cfg, reference_labels, classes, concat=True):
"Calculate the ground truth for all samples in a batch according to\n the sampling_results.\n Almost the same as the implementation in bbox_head, we passed\n additional parameters pos_inds_list and neg_inds_list to\n `_get_target_single` function.\n Args:\n sampling_results (List[obj:SamplingResults]): Assign results of\n all images in a batch after sampling.\n gt_bboxes (list[Tensor]): Gt_bboxes of all images in a batch,\n each tensor has shape (num_gt, 4), the last dimension 4\n represents [tl_x, tl_y, br_x, br_y].\n gt_labels (list[Tensor]): Gt_labels of all images in a batch,\n each tensor has shape (num_gt,).\n rcnn_train_cfg (obj:ConfigDict): `train_cfg` of RCNN.\n concat (bool): Whether to concatenate the results of all\n the images in a single batch.\n Returns:\n Tuple[Tensor]: Ground truth for proposals in a single image.\n Containing the following list of Tensors:\n - labels (list[Tensor],Tensor): Gt_labels for all\n proposals in a batch, each tensor in list has\n shape (num_proposals,) when `concat=False`, otherwise\n just a single tensor has shape (num_all_proposals,).\n - label_weights (list[Tensor]): Labels_weights for\n all proposals in a batch, each tensor in list has\n shape (num_proposals,) when `concat=False`, otherwise\n just a single tensor has shape (num_all_proposals,).\n - bbox_targets (list[Tensor],Tensor): Regression target\n for all proposals in a batch, each tensor in list\n has shape (num_proposals, 4) when `concat=False`,\n otherwise just a single tensor has shape\n (num_all_proposals, 4), the last dimension 4 represents\n [tl_x, tl_y, br_x, br_y].\n - bbox_weights (list[tensor],Tensor): Regression weights for\n all proposals in a batch, each tensor in list has shape\n (num_proposals, 4) when `concat=False`, otherwise just a\n single tensor has shape (num_all_proposals, 4).\n - dis_targets (list[tensor], Tensor): Gt_dis for all\n proposal in a batch, each tensor in list has\n shape (num_proposal,) when 'concat=False`, otherwise\n just a single tensor has shape (num_all_proposals,).\n "
pos_bboxes_list = [res.pos_bboxes for res in sampling_results]
neg_bboxes_list = [res.neg_bboxes for res in sampling_results]
pos_gt_bboxes_list = [res.pos_gt_bboxes for res in sampling_results]
pos_gt_labels_list = [res.pos_gt_labels for res in sampling_results]
(labels, label_weights, bbox_targets, bbox_weights) = multi_apply(self._get_target_single, pos_bboxes_list, neg_bboxes_list, pos_gt_bboxes_list, pos_gt_labels_list, cfg=rcnn_train_cfg)
iou_calculator = dict(type='BboxOverlaps2D')
iou_calculator = build_iou_calculator(iou_calculator)
isolation_thr = 0.45
dis_targets = []
for (i, res) in enumerate(sampling_results):
ref_grap_list = []
ref_leav_list = []
ref_grap_dis_list = []
ref_leav_dis_list = []
for (j, bbox) in enumerate(gt_bboxes[i]):
if (self.dis_selector == 0):
if (('grappolo' in classes[gt_labels[i][j]]) and (gt_labels[i][j] != reference_labels['grappolo_vite'])):
ref_grap_dis_list.append(bbox)
elif ((('foglia' in classes[gt_labels[i][j]]) or (classes[gt_labels[i][j]] == 'malattia_esca') or (classes[gt_labels[i][j]] == 'virosi_pinot_grigio')) and (gt_labels[i][j] != reference_labels['foglia_vite'])):
ref_leav_dis_list.append(bbox)
elif (self.dis_selector == 1):
if (gt_labels[i][j] == reference_labels['grappolo_vite']):
ref_grap_list.append(bbox)
elif (gt_labels[i][j] == reference_labels['foglia_vite']):
ref_leav_list.append(bbox)
elif (self.dis_selector == 2):
if (gt_labels[i][j] == reference_labels['grappolo_vite']):
ref_grap_list.append(bbox)
elif (gt_labels[i][j] == reference_labels['foglia_vite']):
ref_leav_list.append(bbox)
elif ('grappolo' in classes[gt_labels[i][j]]):
ref_grap_dis_list.append(bbox)
elif (('foglia' in classes[gt_labels[i][j]]) or (classes[gt_labels[i][j]] == 'malattia_esca') or (classes[gt_labels[i][j]] == 'virosi_pinot_grigio')):
ref_leav_dis_list.append(bbox)
"\n if 'grappolo' in classes[gt_labels[i][j]] and gt_labels[i][j] != reference_labels['grappolo_vite']:\n ref_grap_dis_list.append(bbox)\n elif (('foglia' in classes[gt_labels[i][j]] or classes[gt_labels[i][j]] == 'malattia_esca' or classes[gt_labels[i][j]] == 'virosi_pinot_grigio')\n and gt_labels[i][j] != reference_labels['foglia_vite']):\n ref_leav_dis_list.append(bbox)\n "
if (len(ref_grap_list) > 0):
ref_grap_tensor = torch.cat(ref_grap_list)
ref_grap_tensor = torch.reshape(ref_grap_tensor, (len(ref_grap_list), 4))
if (len(ref_leav_list) > 0):
ref_leav_tensor = torch.cat(ref_leav_list)
ref_leav_tensor = torch.reshape(ref_leav_tensor, (len(ref_leav_list), 4))
if (len(ref_grap_dis_list) > 0):
ref_grap_dis_tensor = torch.cat(ref_grap_dis_list)
ref_grap_dis_tensor = torch.reshape(ref_grap_dis_tensor, (len(ref_grap_dis_list), 4))
if (len(ref_leav_dis_list) > 0):
ref_leav_dis_tensor = torch.cat(ref_leav_dis_list)
ref_leav_dis_tensor = torch.reshape(ref_leav_dis_tensor, (len(ref_leav_dis_list), 4))
num_pos = res.pos_bboxes.size(0)
num_neg = res.neg_bboxes.size(0)
num_samples = (num_pos + num_neg)
dis_tensor = res.pos_bboxes.new_full((num_samples,), (- 1), dtype=torch.long)
dis_list = []
for (j, bbox) in enumerate(res.pos_bboxes):
bbox = bbox.unsqueeze(0)
if (res.pos_gt_labels[j] == reference_labels['grappolo_vite']):
if (self.dis_selector == 0):
dis_list.append((- 1))
elif ((self.dis_selector == 1) or (self.dis_selector == 2)):
if (len(ref_grap_dis_list) > 0):
overlaps = iou_calculator(ref_grap_dis_tensor, bbox, mode='iof')
overlaps = (overlaps < isolation_thr)
if overlaps.all():
dis_list.append(0)
else:
dis_list.append(1)
else:
dis_list.append(0)
elif (res.pos_gt_labels[j] == reference_labels['foglia_vite']):
if (self.dis_selector == 0):
dis_list.append((- 1))
elif ((self.dis_selector == 1) or (self.dis_selector == 2)):
if (len(ref_leav_dis_list) > 0):
overlaps = iou_calculator(ref_leav_dis_tensor, bbox, mode='iof')
overlaps = (overlaps < isolation_thr)
if overlaps.all():
dis_list.append(0)
else:
dis_list.append(1)
else:
dis_list.append(0)
elif (('grappolo' in classes[res.pos_gt_labels[j]]) and (res.pos_gt_labels[j] != reference_labels['grappolo_vite'])):
if (self.dis_selector == 1):
dis_list.append((- 1))
elif (self.dis_selector == 0):
if (len(ref_grap_list) > 0):
overlaps = iou_calculator(bbox, ref_grap_tensor, mode='iof')
overlaps = (overlaps < isolation_thr)
if overlaps.all():
dis_list.append(0)
else:
dis_list.append(1)
else:
dis_list.append(0)
elif (self.dis_selector == 2):
if (len(ref_grap_list) > 0):
overlaps = iou_calculator(bbox, ref_grap_tensor, mode='iof')
overlaps = (overlaps < isolation_thr)
if overlaps.all():
dis_list.append(2)
else:
dis_list.append(3)
else:
dis_list.append(2)
elif ((('foglia' in classes[res.pos_gt_labels[j]]) or (classes[res.pos_gt_labels[j]] == 'malattia_esca') or (classes[res.pos_gt_labels[j]] == 'virosi_pinot_grigio')) and (res.pos_gt_labels[j] != reference_labels['foglia_vite'])):
if (self.dis_selector == 1):
dis_list.append((- 1))
elif (self.dis_selector == 0):
if (len(ref_leav_list) > 0):
overlaps = iou_calculator(bbox, ref_leav_tensor, mode='iof')
overlaps = (overlaps < isolation_thr)
if overlaps.all():
dis_list.append(0)
else:
dis_list.append(1)
else:
dis_list.append(0)
elif (self.dis_selector == 2):
if (len(ref_leav_list) > 0):
overlaps = iou_calculator(bbox, ref_leav_tensor, mode='iof')
overlaps = (overlaps < isolation_thr)
if overlaps.all():
dis_list.append(2)
else:
dis_list.append(3)
else:
dis_list.append(2)
dis_tensor[:num_pos] = torch.tensor(dis_list)
dis_targets.append(dis_tensor)
if concat:
labels = torch.cat(labels, 0)
label_weights = torch.cat(label_weights, 0)
bbox_targets = torch.cat(bbox_targets, 0)
bbox_weights = torch.cat(bbox_weights, 0)
dis_targets = torch.cat(dis_targets, 0)
return (labels, label_weights, bbox_targets, bbox_weights, dis_targets) |
def test_publisher_structure():
'\n The module.publisher itself is a bit of a skeleton...\n '
params = {'1': 1, '2': 2, 'channel_name': 'test'}
test_publisher = Publisher(params)
assert (test_publisher.get_parameters() == {'1': 1, '2': 2, 'channel_name': 'test'})
test_publisher.set_data_block('example')
assert (test_publisher.get_data_block() == 'example')
assert (test_publisher._consumes == {})
test_publisher.publish()
test_publisher.publish(data_block='asdf')
test_publisher.shutdown() | 2,516,664,684,722,745,000 | The module.publisher itself is a bit of a skeleton... | src/decisionengine/framework/modules/tests/test_Publisher.py | test_publisher_structure | BrunoCoimbra/decisionengine | python | def test_publisher_structure():
'\n \n '
params = {'1': 1, '2': 2, 'channel_name': 'test'}
test_publisher = Publisher(params)
assert (test_publisher.get_parameters() == {'1': 1, '2': 2, 'channel_name': 'test'})
test_publisher.set_data_block('example')
assert (test_publisher.get_data_block() == 'example')
assert (test_publisher._consumes == {})
test_publisher.publish()
test_publisher.publish(data_block='asdf')
test_publisher.shutdown() |
def create_dataset_from_tf_record_files(input_file_pattern, pre_batch_size, batch_size, is_training=True):
'Creates dataset from (tf)records files for training/evaluation.'
files = tf.data.Dataset.list_files(input_file_pattern, shuffle=is_training)
def make_dataset(files_dataset, shard_index):
'Returns dataset for sharded tf record files.'
if (pre_batch_size != batch_size):
raise ValueError('Pre-batch ({}) size is not equal to batch size ({})'.format(pre_batch_size, batch_size))
files_dataset = files_dataset.shard(NUM_SHARDS, shard_index)
dataset = files_dataset.interleave(tf.data.TFRecordDataset)
decode_fn = functools.partial(data_pipeline.DatasetManager.deserialize, batch_size=pre_batch_size, is_training=is_training)
dataset = dataset.map(decode_fn, num_parallel_calls=tf.data.experimental.AUTOTUNE)
return dataset
dataset = tf.data.Dataset.range(NUM_SHARDS)
map_fn = functools.partial(make_dataset, files)
dataset = dataset.interleave(map_fn, cycle_length=NUM_SHARDS, num_parallel_calls=tf.data.experimental.AUTOTUNE)
dataset = dataset.prefetch(tf.data.experimental.AUTOTUNE)
return dataset | -4,105,225,009,478,872,600 | Creates dataset from (tf)records files for training/evaluation. | examples/benchmark/utils/recommendation/ncf_input_pipeline.py | create_dataset_from_tf_record_files | Ezra-H/autodist | python | def create_dataset_from_tf_record_files(input_file_pattern, pre_batch_size, batch_size, is_training=True):
files = tf.data.Dataset.list_files(input_file_pattern, shuffle=is_training)
def make_dataset(files_dataset, shard_index):
'Returns dataset for sharded tf record files.'
if (pre_batch_size != batch_size):
raise ValueError('Pre-batch ({}) size is not equal to batch size ({})'.format(pre_batch_size, batch_size))
files_dataset = files_dataset.shard(NUM_SHARDS, shard_index)
dataset = files_dataset.interleave(tf.data.TFRecordDataset)
decode_fn = functools.partial(data_pipeline.DatasetManager.deserialize, batch_size=pre_batch_size, is_training=is_training)
dataset = dataset.map(decode_fn, num_parallel_calls=tf.data.experimental.AUTOTUNE)
return dataset
dataset = tf.data.Dataset.range(NUM_SHARDS)
map_fn = functools.partial(make_dataset, files)
dataset = dataset.interleave(map_fn, cycle_length=NUM_SHARDS, num_parallel_calls=tf.data.experimental.AUTOTUNE)
dataset = dataset.prefetch(tf.data.experimental.AUTOTUNE)
return dataset |
def create_dataset_from_data_producer(producer, params):
'Return dataset online-generating data.'
def preprocess_train_input(features, labels):
'Pre-process the training data.\n\n This is needed because\n - The label needs to be extended to be used in the loss fn\n - We need the same inputs for training and eval so adding fake inputs\n for DUPLICATE_MASK in training data.\n\n Args:\n features: Dictionary of features for training.\n labels: Training labels.\n\n Returns:\n Processed training features.\n '
fake_dup_mask = tf.zeros_like(features[movielens.USER_COLUMN])
features[rconst.DUPLICATE_MASK] = fake_dup_mask
features[rconst.TRAIN_LABEL_KEY] = labels
return features
train_input_fn = producer.make_input_fn(is_training=True)
train_input_dataset = train_input_fn(params).map(preprocess_train_input)
def preprocess_eval_input(features):
'Pre-process the eval data.\n\n This is needed because:\n - The label needs to be extended to be used in the loss fn\n - We need the same inputs for training and eval so adding fake inputs\n for VALID_PT_MASK in eval data.\n\n Args:\n features: Dictionary of features for evaluation.\n\n Returns:\n Processed evaluation features.\n '
labels = tf.cast(tf.zeros_like(features[movielens.USER_COLUMN]), tf.bool)
fake_valid_pt_mask = tf.cast(tf.zeros_like(features[movielens.USER_COLUMN]), tf.bool)
features[rconst.VALID_POINT_MASK] = fake_valid_pt_mask
features[rconst.TRAIN_LABEL_KEY] = labels
return features
eval_input_fn = producer.make_input_fn(is_training=False)
eval_input_dataset = eval_input_fn(params).map(preprocess_eval_input)
return (train_input_dataset, eval_input_dataset) | -7,371,762,913,903,107,000 | Return dataset online-generating data. | examples/benchmark/utils/recommendation/ncf_input_pipeline.py | create_dataset_from_data_producer | Ezra-H/autodist | python | def create_dataset_from_data_producer(producer, params):
def preprocess_train_input(features, labels):
'Pre-process the training data.\n\n This is needed because\n - The label needs to be extended to be used in the loss fn\n - We need the same inputs for training and eval so adding fake inputs\n for DUPLICATE_MASK in training data.\n\n Args:\n features: Dictionary of features for training.\n labels: Training labels.\n\n Returns:\n Processed training features.\n '
fake_dup_mask = tf.zeros_like(features[movielens.USER_COLUMN])
features[rconst.DUPLICATE_MASK] = fake_dup_mask
features[rconst.TRAIN_LABEL_KEY] = labels
return features
train_input_fn = producer.make_input_fn(is_training=True)
train_input_dataset = train_input_fn(params).map(preprocess_train_input)
def preprocess_eval_input(features):
'Pre-process the eval data.\n\n This is needed because:\n - The label needs to be extended to be used in the loss fn\n - We need the same inputs for training and eval so adding fake inputs\n for VALID_PT_MASK in eval data.\n\n Args:\n features: Dictionary of features for evaluation.\n\n Returns:\n Processed evaluation features.\n '
labels = tf.cast(tf.zeros_like(features[movielens.USER_COLUMN]), tf.bool)
fake_valid_pt_mask = tf.cast(tf.zeros_like(features[movielens.USER_COLUMN]), tf.bool)
features[rconst.VALID_POINT_MASK] = fake_valid_pt_mask
features[rconst.TRAIN_LABEL_KEY] = labels
return features
eval_input_fn = producer.make_input_fn(is_training=False)
eval_input_dataset = eval_input_fn(params).map(preprocess_eval_input)
return (train_input_dataset, eval_input_dataset) |
def create_ncf_input_data(params, producer=None, input_meta_data=None, strategy=None):
'Creates NCF training/evaluation dataset.\n\n Args:\n params: Dictionary containing parameters for train/evaluation data.\n producer: Instance of BaseDataConstructor that generates data online. Must\n not be None when params[\'train_dataset_path\'] or\n params[\'eval_dataset_path\'] is not specified.\n input_meta_data: A dictionary of input metadata to be used when reading data\n from tf record files. Must be specified when params["train_input_dataset"]\n is specified.\n strategy: Distribution strategy used for distributed training. If specified,\n used to assert that evaluation batch size is correctly a multiple of\n total number of devices used.\n\n Returns:\n (training dataset, evaluation dataset, train steps per epoch,\n eval steps per epoch)\n\n Raises:\n ValueError: If data is being generated online for when using TPU\'s.\n '
num_devices = (strategy.num_replicas_in_sync if strategy else 1)
if (params['eval_batch_size'] % (num_devices * (1 + rconst.NUM_EVAL_NEGATIVES))):
raise ValueError('Evaluation batch size must be divisible by {} times {}'.format(num_devices, (1 + rconst.NUM_EVAL_NEGATIVES)))
if params['train_dataset_path']:
assert params['eval_dataset_path']
train_dataset = create_dataset_from_tf_record_files(params['train_dataset_path'], input_meta_data['train_prebatch_size'], params['batch_size'], is_training=True)
eval_dataset = create_dataset_from_tf_record_files(params['eval_dataset_path'], input_meta_data['eval_prebatch_size'], params['eval_batch_size'], is_training=False)
num_train_steps = int(input_meta_data['num_train_steps'])
num_eval_steps = int(input_meta_data['num_eval_steps'])
else:
if params['use_tpu']:
raise ValueError('TPU training does not support data producer yet. Use pre-processed data.')
assert producer
(train_dataset, eval_dataset) = create_dataset_from_data_producer(producer, params)
num_train_steps = producer.train_batches_per_epoch
num_eval_steps = producer.eval_batches_per_epoch
return (train_dataset, eval_dataset, num_train_steps, num_eval_steps) | -6,474,459,502,976,197,000 | Creates NCF training/evaluation dataset.
Args:
params: Dictionary containing parameters for train/evaluation data.
producer: Instance of BaseDataConstructor that generates data online. Must
not be None when params['train_dataset_path'] or
params['eval_dataset_path'] is not specified.
input_meta_data: A dictionary of input metadata to be used when reading data
from tf record files. Must be specified when params["train_input_dataset"]
is specified.
strategy: Distribution strategy used for distributed training. If specified,
used to assert that evaluation batch size is correctly a multiple of
total number of devices used.
Returns:
(training dataset, evaluation dataset, train steps per epoch,
eval steps per epoch)
Raises:
ValueError: If data is being generated online for when using TPU's. | examples/benchmark/utils/recommendation/ncf_input_pipeline.py | create_ncf_input_data | Ezra-H/autodist | python | def create_ncf_input_data(params, producer=None, input_meta_data=None, strategy=None):
'Creates NCF training/evaluation dataset.\n\n Args:\n params: Dictionary containing parameters for train/evaluation data.\n producer: Instance of BaseDataConstructor that generates data online. Must\n not be None when params[\'train_dataset_path\'] or\n params[\'eval_dataset_path\'] is not specified.\n input_meta_data: A dictionary of input metadata to be used when reading data\n from tf record files. Must be specified when params["train_input_dataset"]\n is specified.\n strategy: Distribution strategy used for distributed training. If specified,\n used to assert that evaluation batch size is correctly a multiple of\n total number of devices used.\n\n Returns:\n (training dataset, evaluation dataset, train steps per epoch,\n eval steps per epoch)\n\n Raises:\n ValueError: If data is being generated online for when using TPU\'s.\n '
num_devices = (strategy.num_replicas_in_sync if strategy else 1)
if (params['eval_batch_size'] % (num_devices * (1 + rconst.NUM_EVAL_NEGATIVES))):
raise ValueError('Evaluation batch size must be divisible by {} times {}'.format(num_devices, (1 + rconst.NUM_EVAL_NEGATIVES)))
if params['train_dataset_path']:
assert params['eval_dataset_path']
train_dataset = create_dataset_from_tf_record_files(params['train_dataset_path'], input_meta_data['train_prebatch_size'], params['batch_size'], is_training=True)
eval_dataset = create_dataset_from_tf_record_files(params['eval_dataset_path'], input_meta_data['eval_prebatch_size'], params['eval_batch_size'], is_training=False)
num_train_steps = int(input_meta_data['num_train_steps'])
num_eval_steps = int(input_meta_data['num_eval_steps'])
else:
if params['use_tpu']:
raise ValueError('TPU training does not support data producer yet. Use pre-processed data.')
assert producer
(train_dataset, eval_dataset) = create_dataset_from_data_producer(producer, params)
num_train_steps = producer.train_batches_per_epoch
num_eval_steps = producer.eval_batches_per_epoch
return (train_dataset, eval_dataset, num_train_steps, num_eval_steps) |
def make_dataset(files_dataset, shard_index):
'Returns dataset for sharded tf record files.'
if (pre_batch_size != batch_size):
raise ValueError('Pre-batch ({}) size is not equal to batch size ({})'.format(pre_batch_size, batch_size))
files_dataset = files_dataset.shard(NUM_SHARDS, shard_index)
dataset = files_dataset.interleave(tf.data.TFRecordDataset)
decode_fn = functools.partial(data_pipeline.DatasetManager.deserialize, batch_size=pre_batch_size, is_training=is_training)
dataset = dataset.map(decode_fn, num_parallel_calls=tf.data.experimental.AUTOTUNE)
return dataset | -8,816,612,933,234,172,000 | Returns dataset for sharded tf record files. | examples/benchmark/utils/recommendation/ncf_input_pipeline.py | make_dataset | Ezra-H/autodist | python | def make_dataset(files_dataset, shard_index):
if (pre_batch_size != batch_size):
raise ValueError('Pre-batch ({}) size is not equal to batch size ({})'.format(pre_batch_size, batch_size))
files_dataset = files_dataset.shard(NUM_SHARDS, shard_index)
dataset = files_dataset.interleave(tf.data.TFRecordDataset)
decode_fn = functools.partial(data_pipeline.DatasetManager.deserialize, batch_size=pre_batch_size, is_training=is_training)
dataset = dataset.map(decode_fn, num_parallel_calls=tf.data.experimental.AUTOTUNE)
return dataset |
def preprocess_train_input(features, labels):
'Pre-process the training data.\n\n This is needed because\n - The label needs to be extended to be used in the loss fn\n - We need the same inputs for training and eval so adding fake inputs\n for DUPLICATE_MASK in training data.\n\n Args:\n features: Dictionary of features for training.\n labels: Training labels.\n\n Returns:\n Processed training features.\n '
fake_dup_mask = tf.zeros_like(features[movielens.USER_COLUMN])
features[rconst.DUPLICATE_MASK] = fake_dup_mask
features[rconst.TRAIN_LABEL_KEY] = labels
return features | 1,766,241,002,850,631,000 | Pre-process the training data.
This is needed because
- The label needs to be extended to be used in the loss fn
- We need the same inputs for training and eval so adding fake inputs
for DUPLICATE_MASK in training data.
Args:
features: Dictionary of features for training.
labels: Training labels.
Returns:
Processed training features. | examples/benchmark/utils/recommendation/ncf_input_pipeline.py | preprocess_train_input | Ezra-H/autodist | python | def preprocess_train_input(features, labels):
'Pre-process the training data.\n\n This is needed because\n - The label needs to be extended to be used in the loss fn\n - We need the same inputs for training and eval so adding fake inputs\n for DUPLICATE_MASK in training data.\n\n Args:\n features: Dictionary of features for training.\n labels: Training labels.\n\n Returns:\n Processed training features.\n '
fake_dup_mask = tf.zeros_like(features[movielens.USER_COLUMN])
features[rconst.DUPLICATE_MASK] = fake_dup_mask
features[rconst.TRAIN_LABEL_KEY] = labels
return features |
def preprocess_eval_input(features):
'Pre-process the eval data.\n\n This is needed because:\n - The label needs to be extended to be used in the loss fn\n - We need the same inputs for training and eval so adding fake inputs\n for VALID_PT_MASK in eval data.\n\n Args:\n features: Dictionary of features for evaluation.\n\n Returns:\n Processed evaluation features.\n '
labels = tf.cast(tf.zeros_like(features[movielens.USER_COLUMN]), tf.bool)
fake_valid_pt_mask = tf.cast(tf.zeros_like(features[movielens.USER_COLUMN]), tf.bool)
features[rconst.VALID_POINT_MASK] = fake_valid_pt_mask
features[rconst.TRAIN_LABEL_KEY] = labels
return features | 5,271,456,008,588,656,000 | Pre-process the eval data.
This is needed because:
- The label needs to be extended to be used in the loss fn
- We need the same inputs for training and eval so adding fake inputs
for VALID_PT_MASK in eval data.
Args:
features: Dictionary of features for evaluation.
Returns:
Processed evaluation features. | examples/benchmark/utils/recommendation/ncf_input_pipeline.py | preprocess_eval_input | Ezra-H/autodist | python | def preprocess_eval_input(features):
'Pre-process the eval data.\n\n This is needed because:\n - The label needs to be extended to be used in the loss fn\n - We need the same inputs for training and eval so adding fake inputs\n for VALID_PT_MASK in eval data.\n\n Args:\n features: Dictionary of features for evaluation.\n\n Returns:\n Processed evaluation features.\n '
labels = tf.cast(tf.zeros_like(features[movielens.USER_COLUMN]), tf.bool)
fake_valid_pt_mask = tf.cast(tf.zeros_like(features[movielens.USER_COLUMN]), tf.bool)
features[rconst.VALID_POINT_MASK] = fake_valid_pt_mask
features[rconst.TRAIN_LABEL_KEY] = labels
return features |
def playbook_path(playbook_name):
'\n Get the path to the named playbook. To allow for\n as much brevity as possible in the given playbook\n name, we will attempt to search under:\n - oct/playbooks\n - openshift-ansible/playbooks\n\n :param playbook_name: the name of the playbook\n :type playbook_name: str\n\n :return: the path to the playbook\n :rtype: str\n\n :raises ClickException: when no playbook is found\n '
from ..oct import __file__ as root_path
for parent_repo in ['oct', 'openshift-ansible']:
playbook_file = join(abspath(dirname(root_path)), 'ansible', parent_repo, 'playbooks', (playbook_name + '.yml'))
if exists(playbook_file):
return playbook_file
raise ClickException('No playbook named {} found!'.format(playbook_name)) | -6,925,699,650,955,053,000 | Get the path to the named playbook. To allow for
as much brevity as possible in the given playbook
name, we will attempt to search under:
- oct/playbooks
- openshift-ansible/playbooks
:param playbook_name: the name of the playbook
:type playbook_name: str
:return: the path to the playbook
:rtype: str
:raises ClickException: when no playbook is found | oct/util/playbook.py | playbook_path | DennisPeriquet/origin-ci-tool | python | def playbook_path(playbook_name):
'\n Get the path to the named playbook. To allow for\n as much brevity as possible in the given playbook\n name, we will attempt to search under:\n - oct/playbooks\n - openshift-ansible/playbooks\n\n :param playbook_name: the name of the playbook\n :type playbook_name: str\n\n :return: the path to the playbook\n :rtype: str\n\n :raises ClickException: when no playbook is found\n '
from ..oct import __file__ as root_path
for parent_repo in ['oct', 'openshift-ansible']:
playbook_file = join(abspath(dirname(root_path)), 'ansible', parent_repo, 'playbooks', (playbook_name + '.yml'))
if exists(playbook_file):
return playbook_file
raise ClickException('No playbook named {} found!'.format(playbook_name)) |
def test_location_handles_reused(instance, monkeypatch, grpc_server_registry):
'\n verifies that only one repository location is created when two queued runs from the same\n location are dequeued in the same iteration\n '
create_run(instance, run_id='queued-run', status=PipelineRunStatus.QUEUED)
create_run(instance, run_id='queued-run-2', status=PipelineRunStatus.QUEUED)
original_method = GrpcServerRepositoryLocationHandle.__init__
method_calls = []
def mocked_handle_init(self, origin, host=None, port=None, socket=None, server_id=None, heartbeat=False, watch_server=True):
method_calls.append(origin)
return original_method(self, origin, host, port, socket, server_id, heartbeat, watch_server)
monkeypatch.setattr(GrpcServerRepositoryLocationHandle, '__init__', mocked_handle_init)
coordinator = QueuedRunCoordinatorDaemon(interval_seconds=5, max_concurrent_runs=10)
list(coordinator.run_iteration(instance, grpc_server_registry))
assert (get_run_ids(instance.run_launcher.queue()) == ['queued-run', 'queued-run-2'])
assert (len(method_calls) == 1) | 7,905,741,415,444,816,000 | verifies that only one repository location is created when two queued runs from the same
location are dequeued in the same iteration | python_modules/dagster/dagster_tests/daemon_tests/test_queued_run_coordinator_daemon.py | test_location_handles_reused | PenguinToast/dagster | python | def test_location_handles_reused(instance, monkeypatch, grpc_server_registry):
'\n verifies that only one repository location is created when two queued runs from the same\n location are dequeued in the same iteration\n '
create_run(instance, run_id='queued-run', status=PipelineRunStatus.QUEUED)
create_run(instance, run_id='queued-run-2', status=PipelineRunStatus.QUEUED)
original_method = GrpcServerRepositoryLocationHandle.__init__
method_calls = []
def mocked_handle_init(self, origin, host=None, port=None, socket=None, server_id=None, heartbeat=False, watch_server=True):
method_calls.append(origin)
return original_method(self, origin, host, port, socket, server_id, heartbeat, watch_server)
monkeypatch.setattr(GrpcServerRepositoryLocationHandle, '__init__', mocked_handle_init)
coordinator = QueuedRunCoordinatorDaemon(interval_seconds=5, max_concurrent_runs=10)
list(coordinator.run_iteration(instance, grpc_server_registry))
assert (get_run_ids(instance.run_launcher.queue()) == ['queued-run', 'queued-run-2'])
assert (len(method_calls) == 1) |
def _update_dag_tasks(function_name, caller_line, dependencies, depends_logic, args=None, template_name=None, step_name=None):
'\n A task in DAG of Argo YAML contains name, related template and parameters.\n Here we insert a single task into the global tasks.\n '
if (step_name is None):
function_id = utils.invocation_name(function_name, caller_line)
else:
function_id = step_name
task_template = states.workflow.get_dag_task(function_id)
if (task_template is None):
task_template = OrderedDict({'name': function_id})
if ((dependencies is not None) and isinstance(dependencies, list)):
if ('dependencies' in task_template):
task_template['dependencies'].extend(dependencies)
else:
task_template['dependencies'] = dependencies
if (depends_logic is not None):
task_template['depends'] = depends_logic
if (template_name is None):
task_template['template'] = function_name
else:
task_template['template'] = template_name
if (args is not None):
(parameters, artifacts) = _get_params_and_artifacts_from_args(args, function_name, prefix='tasks')
if (len(parameters) > 0):
task_template['arguments'] = OrderedDict()
task_template['arguments']['parameters'] = parameters
if (len(artifacts) > 0):
if ('arguments' not in task_template):
task_template['arguments'] = OrderedDict()
task_template['arguments']['artifacts'] = artifacts
else:
if (dependencies is not None):
if ('dependencies' in task_template):
task_template['dependencies'].extend(dependencies)
else:
task_template['dependencies'] = [dependencies]
if (depends_logic is not None):
task_template['depends'] = depends_logic
t_name = (function_name if (template_name is None) else template_name)
step = Step(name=function_id, template=t_name)
if states._exit_handler_enable:
if (states._when_prefix is not None):
step.when = states._when_prefix
if (function_id in states.workflow.exit_handler_step):
states.workflow.exit_handler_step.get(function_id).append(step.to_dict())
else:
states.workflow.exit_handler_step[function_id] = [step.to_dict()]
elif (states._when_prefix is not None):
step.when = states._when_prefix
if (step.name not in states.workflow.dag_tasks.keys()):
step_spec = step.to_dict()
step_spec['dependencies'] = [states._when_task]
states.workflow.dag_tasks[step.name] = step_spec
else:
states.workflow.update_dag_task(function_id, task_template)
return function_id | 2,822,368,232,564,738,600 | A task in DAG of Argo YAML contains name, related template and parameters.
Here we insert a single task into the global tasks. | couler/core/step_update_utils.py | _update_dag_tasks | javoweb/couler | python | def _update_dag_tasks(function_name, caller_line, dependencies, depends_logic, args=None, template_name=None, step_name=None):
'\n A task in DAG of Argo YAML contains name, related template and parameters.\n Here we insert a single task into the global tasks.\n '
if (step_name is None):
function_id = utils.invocation_name(function_name, caller_line)
else:
function_id = step_name
task_template = states.workflow.get_dag_task(function_id)
if (task_template is None):
task_template = OrderedDict({'name': function_id})
if ((dependencies is not None) and isinstance(dependencies, list)):
if ('dependencies' in task_template):
task_template['dependencies'].extend(dependencies)
else:
task_template['dependencies'] = dependencies
if (depends_logic is not None):
task_template['depends'] = depends_logic
if (template_name is None):
task_template['template'] = function_name
else:
task_template['template'] = template_name
if (args is not None):
(parameters, artifacts) = _get_params_and_artifacts_from_args(args, function_name, prefix='tasks')
if (len(parameters) > 0):
task_template['arguments'] = OrderedDict()
task_template['arguments']['parameters'] = parameters
if (len(artifacts) > 0):
if ('arguments' not in task_template):
task_template['arguments'] = OrderedDict()
task_template['arguments']['artifacts'] = artifacts
else:
if (dependencies is not None):
if ('dependencies' in task_template):
task_template['dependencies'].extend(dependencies)
else:
task_template['dependencies'] = [dependencies]
if (depends_logic is not None):
task_template['depends'] = depends_logic
t_name = (function_name if (template_name is None) else template_name)
step = Step(name=function_id, template=t_name)
if states._exit_handler_enable:
if (states._when_prefix is not None):
step.when = states._when_prefix
if (function_id in states.workflow.exit_handler_step):
states.workflow.exit_handler_step.get(function_id).append(step.to_dict())
else:
states.workflow.exit_handler_step[function_id] = [step.to_dict()]
elif (states._when_prefix is not None):
step.when = states._when_prefix
if (step.name not in states.workflow.dag_tasks.keys()):
step_spec = step.to_dict()
step_spec['dependencies'] = [states._when_task]
states.workflow.dag_tasks[step.name] = step_spec
else:
states.workflow.update_dag_task(function_id, task_template)
return function_id |
def _update_steps(function_name, caller_line, args=None, template_name=None):
'\n A step in Argo YAML contains name, related template and parameters.\n Here we insert a single step into the global steps.\n '
function_id = utils.invocation_name(function_name, caller_line)
if states._update_steps_lock:
name = function_id
if states._run_concurrent_lock:
_id = utils.invocation_name(template_name, caller_line)
name = ('%s-%s' % (_id, states._concurrent_func_id))
if (states._sub_steps is not None):
states._concurrent_func_id = (states._concurrent_func_id + 1)
t_name = (function_name if (template_name is None) else template_name)
step = Step(name=name, template=t_name)
if (states._when_prefix is not None):
step.when = states._when_prefix
if (args is not None):
(parameters, artifacts) = _get_params_and_artifacts_from_args(args, (template_name if states._run_concurrent_lock else function_name), prefix='steps')
if (len(parameters) > 0):
step.arguments = OrderedDict()
step.arguments['parameters'] = parameters
if (len(artifacts) > 0):
if (step.arguments is None):
step.arguments = OrderedDict()
step.arguments['artifacts'] = artifacts
if (states._condition_id is not None):
function_id = states._condition_id
if states._while_lock:
if (function_id in states._while_steps):
states._while_steps.get(function_id).append(step.to_dict())
else:
states._while_steps[function_id] = [step.to_dict()]
elif (states._sub_steps is not None):
if (function_id in states._sub_steps):
states._sub_steps.get(function_id).append(step.to_dict())
else:
states._sub_steps[function_id] = [step.to_dict()]
elif (states._exit_handler_enable is True):
if (function_id in states.workflow.exit_handler_step):
states.workflow.exit_handler_step.get(function_id).append(step.to_dict())
else:
states.workflow.exit_handler_step[function_id] = [step.to_dict()]
else:
states.workflow.add_step(function_id, step)
return step.name
else:
return function_id | -1,058,683,839,742,048,800 | A step in Argo YAML contains name, related template and parameters.
Here we insert a single step into the global steps. | couler/core/step_update_utils.py | _update_steps | javoweb/couler | python | def _update_steps(function_name, caller_line, args=None, template_name=None):
'\n A step in Argo YAML contains name, related template and parameters.\n Here we insert a single step into the global steps.\n '
function_id = utils.invocation_name(function_name, caller_line)
if states._update_steps_lock:
name = function_id
if states._run_concurrent_lock:
_id = utils.invocation_name(template_name, caller_line)
name = ('%s-%s' % (_id, states._concurrent_func_id))
if (states._sub_steps is not None):
states._concurrent_func_id = (states._concurrent_func_id + 1)
t_name = (function_name if (template_name is None) else template_name)
step = Step(name=name, template=t_name)
if (states._when_prefix is not None):
step.when = states._when_prefix
if (args is not None):
(parameters, artifacts) = _get_params_and_artifacts_from_args(args, (template_name if states._run_concurrent_lock else function_name), prefix='steps')
if (len(parameters) > 0):
step.arguments = OrderedDict()
step.arguments['parameters'] = parameters
if (len(artifacts) > 0):
if (step.arguments is None):
step.arguments = OrderedDict()
step.arguments['artifacts'] = artifacts
if (states._condition_id is not None):
function_id = states._condition_id
if states._while_lock:
if (function_id in states._while_steps):
states._while_steps.get(function_id).append(step.to_dict())
else:
states._while_steps[function_id] = [step.to_dict()]
elif (states._sub_steps is not None):
if (function_id in states._sub_steps):
states._sub_steps.get(function_id).append(step.to_dict())
else:
states._sub_steps[function_id] = [step.to_dict()]
elif (states._exit_handler_enable is True):
if (function_id in states.workflow.exit_handler_step):
states.workflow.exit_handler_step.get(function_id).append(step.to_dict())
else:
states.workflow.exit_handler_step[function_id] = [step.to_dict()]
else:
states.workflow.add_step(function_id, step)
return step.name
else:
return function_id |
@contextmanager
def silence_stderr():
' Redirect stderr. '
if DEBUG:
(yield)
else:
with threading.Lock():
stderr = sys.stderr
sys.stderr = StringIO()
(yield)
with threading.Lock():
sys.stderr = stderr | -2,169,894,562,685,810,000 | Redirect stderr. | bundle/python-mode/pymode/utils.py | silence_stderr | Jenkin0603/myvim | python | @contextmanager
def silence_stderr():
' '
if DEBUG:
(yield)
else:
with threading.Lock():
stderr = sys.stderr
sys.stderr = StringIO()
(yield)
with threading.Lock():
sys.stderr = stderr |
def patch_paths():
' Function description. '
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'libs'))
if PY2:
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'libs2'))
else:
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'libs3')) | -1,636,797,612,643,356,200 | Function description. | bundle/python-mode/pymode/utils.py | patch_paths | Jenkin0603/myvim | python | def patch_paths():
' '
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'libs'))
if PY2:
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'libs2'))
else:
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'libs3')) |
@abstractmethod
def eval(self, tokens: List[str]) -> bool:
'If the given tokens sequence matches the given command execute it\n and return True. Otherwise, return False.\n\n Parameters\n ----------\n tokens: list(string)\n List of tokens in the command line\n\n Returns\n -------\n bool\n '
raise NotImplementedError() | -3,451,811,905,667,464,000 | If the given tokens sequence matches the given command execute it
and return True. Otherwise, return False.
Parameters
----------
tokens: list(string)
List of tokens in the command line
Returns
-------
bool | vizier/api/client/cli/command.py | eval | VizierDB/web-api-async | python | @abstractmethod
def eval(self, tokens: List[str]) -> bool:
'If the given tokens sequence matches the given command execute it\n and return True. Otherwise, return False.\n\n Parameters\n ----------\n tokens: list(string)\n List of tokens in the command line\n\n Returns\n -------\n bool\n '
raise NotImplementedError() |
@abstractmethod
def help(self) -> None:
'Print a simple help statement for the command.'
raise NotImplementedError() | 592,158,047,742,548,200 | Print a simple help statement for the command. | vizier/api/client/cli/command.py | help | VizierDB/web-api-async | python | @abstractmethod
def help(self) -> None:
raise NotImplementedError() |
def output(self, rows):
'Output the given rows in tabular format. Each rows is a list of\n string values. All rows are expected to have the sam elength. The first\n row is the table header.\n\n Parameters\n ----------\n rows: list(string)\n List of rows in the table\n '
columns = ([0] * len(rows[0]))
for row in rows:
for col in range(len(columns)):
count = len(row[col])
if (count > columns[col]):
columns[col] = count
format = None
divider = list()
for col_len in columns:
f = (('%-' + str(col_len)) + 's')
if (format is None):
format = f
else:
format += (' | ' + f)
if (len(divider) in [0, (len(columns) - 1)]):
i = 1
else:
i = 2
divider.append(('-' * (col_len + i)))
print((format % tuple(rows[0])))
print('|'.join(divider))
for row in rows[1:]:
print((format % tuple(row))) | 8,790,974,993,255,597,000 | Output the given rows in tabular format. Each rows is a list of
string values. All rows are expected to have the sam elength. The first
row is the table header.
Parameters
----------
rows: list(string)
List of rows in the table | vizier/api/client/cli/command.py | output | VizierDB/web-api-async | python | def output(self, rows):
'Output the given rows in tabular format. Each rows is a list of\n string values. All rows are expected to have the sam elength. The first\n row is the table header.\n\n Parameters\n ----------\n rows: list(string)\n List of rows in the table\n '
columns = ([0] * len(rows[0]))
for row in rows:
for col in range(len(columns)):
count = len(row[col])
if (count > columns[col]):
columns[col] = count
format = None
divider = list()
for col_len in columns:
f = (('%-' + str(col_len)) + 's')
if (format is None):
format = f
else:
format += (' | ' + f)
if (len(divider) in [0, (len(columns) - 1)]):
i = 1
else:
i = 2
divider.append(('-' * (col_len + i)))
print((format % tuple(rows[0])))
print('|'.join(divider))
for row in rows[1:]:
print((format % tuple(row))) |
def ProcessTag(self, line, type):
'\n Process a single string tag.\n \n :param line: an array of lines making a single string tag.\n :param type: the tag type, such as TYPE_STR or TYPE_PLUR\n :return: an array of lines representing the processed tag.\n '
return line | -3,578,550,112,715,211,000 | Process a single string tag.
:param line: an array of lines making a single string tag.
:param type: the tag type, such as TYPE_STR or TYPE_PLUR
:return: an array of lines representing the processed tag. | scripts/translations/base_string_script.py | ProcessTag | 1y445rc/FirebaseUI-Android | python | def ProcessTag(self, line, type):
'\n Process a single string tag.\n \n :param line: an array of lines making a single string tag.\n :param type: the tag type, such as TYPE_STR or TYPE_PLUR\n :return: an array of lines representing the processed tag.\n '
return line |
def ProcessFile(self, file_name):
'\n Process and write a file of string resources.\n \n :param file_name: path to the file to process.\n :return: None.\n '
lines = []
state = self.STATE_SEARCHING
curr_tag = []
pending_process_type = None
with open(file_name, 'r') as myfile:
data = myfile.read()
for line in data.split('\n'):
if (state == self.STATE_SEARCHING):
if (self.START_STR in line):
state = self.STATE_IN_STR
elif (self.START_PLUR in line):
state = self.STATE_IN_PLUR
else:
lines.append(line)
if (state == self.STATE_IN_STR):
curr_tag.append(line)
if (self.END_STR in line):
pending_process_type = self.TYPE_STR
if (state == self.STATE_IN_PLUR):
curr_tag.append(line)
if (self.END_PLUR in line):
pending_process_type = self.TYPE_PLUR
if pending_process_type:
lines += self.ProcessTag(curr_tag, pending_process_type)
pending_process_type = None
state = self.STATE_SEARCHING
curr_tag = []
self.WriteFile(file_name, '\n'.join(lines)) | -1,617,482,522,694,352,400 | Process and write a file of string resources.
:param file_name: path to the file to process.
:return: None. | scripts/translations/base_string_script.py | ProcessFile | 1y445rc/FirebaseUI-Android | python | def ProcessFile(self, file_name):
'\n Process and write a file of string resources.\n \n :param file_name: path to the file to process.\n :return: None.\n '
lines = []
state = self.STATE_SEARCHING
curr_tag = []
pending_process_type = None
with open(file_name, 'r') as myfile:
data = myfile.read()
for line in data.split('\n'):
if (state == self.STATE_SEARCHING):
if (self.START_STR in line):
state = self.STATE_IN_STR
elif (self.START_PLUR in line):
state = self.STATE_IN_PLUR
else:
lines.append(line)
if (state == self.STATE_IN_STR):
curr_tag.append(line)
if (self.END_STR in line):
pending_process_type = self.TYPE_STR
if (state == self.STATE_IN_PLUR):
curr_tag.append(line)
if (self.END_PLUR in line):
pending_process_type = self.TYPE_PLUR
if pending_process_type:
lines += self.ProcessTag(curr_tag, pending_process_type)
pending_process_type = None
state = self.STATE_SEARCHING
curr_tag = []
self.WriteFile(file_name, '\n'.join(lines)) |
def WriteFile(self, file_name, file_contents):
'\n Overwrite the contents of a file.\n \n :param file_name: path to the file to write.\n :param file_contents: string containing new file contents. \n :return: None\n '
with open(file_name, 'w') as myfile:
myfile.write(file_contents) | 3,607,157,379,932,279,000 | Overwrite the contents of a file.
:param file_name: path to the file to write.
:param file_contents: string containing new file contents.
:return: None | scripts/translations/base_string_script.py | WriteFile | 1y445rc/FirebaseUI-Android | python | def WriteFile(self, file_name, file_contents):
'\n Overwrite the contents of a file.\n \n :param file_name: path to the file to write.\n :param file_contents: string containing new file contents. \n :return: None\n '
with open(file_name, 'w') as myfile:
myfile.write(file_contents) |
def __init__(self, config_entry: config_entries.ConfigEntry) -> None:
'Init object.'
self.config_entry = config_entry | -2,559,020,865,665,428,000 | Init object. | homeassistant/components/netgear/config_flow.py | __init__ | 2004happy/core | python | def __init__(self, config_entry: config_entries.ConfigEntry) -> None:
self.config_entry = config_entry |
async def async_step_init(self, user_input=None):
'Manage the options.'
if (user_input is not None):
return self.async_create_entry(title='', data=user_input)
settings_schema = vol.Schema({vol.Optional(CONF_CONSIDER_HOME, default=self.config_entry.options.get(CONF_CONSIDER_HOME, DEFAULT_CONSIDER_HOME.total_seconds())): int})
return self.async_show_form(step_id='init', data_schema=settings_schema) | 6,396,657,444,366,347,000 | Manage the options. | homeassistant/components/netgear/config_flow.py | async_step_init | 2004happy/core | python | async def async_step_init(self, user_input=None):
if (user_input is not None):
return self.async_create_entry(title=, data=user_input)
settings_schema = vol.Schema({vol.Optional(CONF_CONSIDER_HOME, default=self.config_entry.options.get(CONF_CONSIDER_HOME, DEFAULT_CONSIDER_HOME.total_seconds())): int})
return self.async_show_form(step_id='init', data_schema=settings_schema) |
def __init__(self):
'Initialize the netgear config flow.'
self.placeholders = {CONF_HOST: DEFAULT_HOST, CONF_PORT: DEFAULT_PORT, CONF_USERNAME: DEFAULT_USER, CONF_SSL: False}
self.discovered = False | -8,401,081,290,602,939,000 | Initialize the netgear config flow. | homeassistant/components/netgear/config_flow.py | __init__ | 2004happy/core | python | def __init__(self):
self.placeholders = {CONF_HOST: DEFAULT_HOST, CONF_PORT: DEFAULT_PORT, CONF_USERNAME: DEFAULT_USER, CONF_SSL: False}
self.discovered = False |
@staticmethod
@callback
def async_get_options_flow(config_entry: config_entries.ConfigEntry) -> OptionsFlowHandler:
'Get the options flow.'
return OptionsFlowHandler(config_entry) | 46,051,271,963,521,970 | Get the options flow. | homeassistant/components/netgear/config_flow.py | async_get_options_flow | 2004happy/core | python | @staticmethod
@callback
def async_get_options_flow(config_entry: config_entries.ConfigEntry) -> OptionsFlowHandler:
return OptionsFlowHandler(config_entry) |
async def _show_setup_form(self, user_input=None, errors=None):
'Show the setup form to the user.'
if (not user_input):
user_input = {}
if self.discovered:
data_schema = _discovery_schema_with_defaults(user_input)
else:
data_schema = _user_schema_with_defaults(user_input)
return self.async_show_form(step_id='user', data_schema=data_schema, errors=(errors or {}), description_placeholders=self.placeholders) | 5,815,990,346,358,273,000 | Show the setup form to the user. | homeassistant/components/netgear/config_flow.py | _show_setup_form | 2004happy/core | python | async def _show_setup_form(self, user_input=None, errors=None):
if (not user_input):
user_input = {}
if self.discovered:
data_schema = _discovery_schema_with_defaults(user_input)
else:
data_schema = _user_schema_with_defaults(user_input)
return self.async_show_form(step_id='user', data_schema=data_schema, errors=(errors or {}), description_placeholders=self.placeholders) |
async def async_step_ssdp(self, discovery_info: ssdp.SsdpServiceInfo) -> FlowResult:
'Initialize flow from ssdp.'
updated_data: dict[(str, ((str | int) | bool))] = {}
device_url = urlparse(discovery_info.ssdp_location)
if (hostname := device_url.hostname):
hostname = cast(str, hostname)
updated_data[CONF_HOST] = hostname
if (not is_ipv4_address(str(hostname))):
return self.async_abort(reason='not_ipv4_address')
_LOGGER.debug('Netgear ssdp discovery info: %s', discovery_info)
(await self.async_set_unique_id(discovery_info.upnp[ssdp.ATTR_UPNP_SERIAL]))
self._abort_if_unique_id_configured(updates=updated_data)
if (device_url.scheme == 'https'):
updated_data[CONF_SSL] = True
else:
updated_data[CONF_SSL] = False
updated_data[CONF_PORT] = DEFAULT_PORT
for model in MODELS_PORT_80:
if (discovery_info.upnp.get(ssdp.ATTR_UPNP_MODEL_NUMBER, '').startswith(model) or discovery_info.upnp.get(ssdp.ATTR_UPNP_MODEL_NAME, '').startswith(model)):
updated_data[CONF_PORT] = PORT_80
for model in MODELS_PORT_5555:
if (discovery_info.upnp.get(ssdp.ATTR_UPNP_MODEL_NUMBER, '').startswith(model) or discovery_info.upnp.get(ssdp.ATTR_UPNP_MODEL_NAME, '').startswith(model)):
updated_data[CONF_PORT] = PORT_5555
updated_data[CONF_SSL] = True
self.placeholders.update(updated_data)
self.discovered = True
return (await self.async_step_user()) | -1,430,843,196,014,504,200 | Initialize flow from ssdp. | homeassistant/components/netgear/config_flow.py | async_step_ssdp | 2004happy/core | python | async def async_step_ssdp(self, discovery_info: ssdp.SsdpServiceInfo) -> FlowResult:
updated_data: dict[(str, ((str | int) | bool))] = {}
device_url = urlparse(discovery_info.ssdp_location)
if (hostname := device_url.hostname):
hostname = cast(str, hostname)
updated_data[CONF_HOST] = hostname
if (not is_ipv4_address(str(hostname))):
return self.async_abort(reason='not_ipv4_address')
_LOGGER.debug('Netgear ssdp discovery info: %s', discovery_info)
(await self.async_set_unique_id(discovery_info.upnp[ssdp.ATTR_UPNP_SERIAL]))
self._abort_if_unique_id_configured(updates=updated_data)
if (device_url.scheme == 'https'):
updated_data[CONF_SSL] = True
else:
updated_data[CONF_SSL] = False
updated_data[CONF_PORT] = DEFAULT_PORT
for model in MODELS_PORT_80:
if (discovery_info.upnp.get(ssdp.ATTR_UPNP_MODEL_NUMBER, ).startswith(model) or discovery_info.upnp.get(ssdp.ATTR_UPNP_MODEL_NAME, ).startswith(model)):
updated_data[CONF_PORT] = PORT_80
for model in MODELS_PORT_5555:
if (discovery_info.upnp.get(ssdp.ATTR_UPNP_MODEL_NUMBER, ).startswith(model) or discovery_info.upnp.get(ssdp.ATTR_UPNP_MODEL_NAME, ).startswith(model)):
updated_data[CONF_PORT] = PORT_5555
updated_data[CONF_SSL] = True
self.placeholders.update(updated_data)
self.discovered = True
return (await self.async_step_user()) |
async def async_step_user(self, user_input=None):
'Handle a flow initiated by the user.'
errors = {}
if (user_input is None):
return (await self._show_setup_form())
host = user_input.get(CONF_HOST, self.placeholders[CONF_HOST])
port = self.placeholders[CONF_PORT]
ssl = self.placeholders[CONF_SSL]
username = user_input.get(CONF_USERNAME, self.placeholders[CONF_USERNAME])
password = user_input[CONF_PASSWORD]
if (not username):
username = self.placeholders[CONF_USERNAME]
try:
api = (await self.hass.async_add_executor_job(get_api, password, host, username, port, ssl))
except CannotLoginException:
errors['base'] = 'config'
if errors:
return (await self._show_setup_form(user_input, errors))
info = (await self.hass.async_add_executor_job(api.get_info))
(await self.async_set_unique_id(info['SerialNumber'], raise_on_progress=False))
self._abort_if_unique_id_configured()
config_data = {CONF_USERNAME: username, CONF_PASSWORD: password, CONF_HOST: host, CONF_PORT: api.port, CONF_SSL: api.ssl}
if ((info.get('ModelName') is not None) and (info.get('DeviceName') is not None)):
name = f"{info['ModelName']} - {info['DeviceName']}"
else:
name = info.get('ModelName', DEFAULT_NAME)
return self.async_create_entry(title=name, data=config_data) | -6,443,958,358,770,587,000 | Handle a flow initiated by the user. | homeassistant/components/netgear/config_flow.py | async_step_user | 2004happy/core | python | async def async_step_user(self, user_input=None):
errors = {}
if (user_input is None):
return (await self._show_setup_form())
host = user_input.get(CONF_HOST, self.placeholders[CONF_HOST])
port = self.placeholders[CONF_PORT]
ssl = self.placeholders[CONF_SSL]
username = user_input.get(CONF_USERNAME, self.placeholders[CONF_USERNAME])
password = user_input[CONF_PASSWORD]
if (not username):
username = self.placeholders[CONF_USERNAME]
try:
api = (await self.hass.async_add_executor_job(get_api, password, host, username, port, ssl))
except CannotLoginException:
errors['base'] = 'config'
if errors:
return (await self._show_setup_form(user_input, errors))
info = (await self.hass.async_add_executor_job(api.get_info))
(await self.async_set_unique_id(info['SerialNumber'], raise_on_progress=False))
self._abort_if_unique_id_configured()
config_data = {CONF_USERNAME: username, CONF_PASSWORD: password, CONF_HOST: host, CONF_PORT: api.port, CONF_SSL: api.ssl}
if ((info.get('ModelName') is not None) and (info.get('DeviceName') is not None)):
name = f"{info['ModelName']} - {info['DeviceName']}"
else:
name = info.get('ModelName', DEFAULT_NAME)
return self.async_create_entry(title=name, data=config_data) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.